mirror of
https://github.com/mikumifa/biliTickerBuy.git
synced 2026-11-18 06:23:16 -08:00
fix: preserve embedded signing tickets when selecting dates (#1119)
Co-authored-by: TianYu0820 <212339270+TianYu0820@users.noreply.github.com>
This commit is contained in:
1 parent
1bb9610e05
commit
2003913801
5 files changed
+337
-32
No files matched your search
@@ -469,6 +469,7 @@ def build_ticket_config_from_selection(
|
||||
purchase_context.get("is_hot_project", False),
|
||||
),
|
||||
"sku_id": ticket["id"],
|
||||
"sale_start": ticket.get("sale_start", ""),
|
||||
"order_type": 1,
|
||||
"pay_money": int(ticket["price"]) * len(selected_buyers),
|
||||
"buyer_info": selected_buyers,
|
||||
|
||||
+67
-10
@@ -1,6 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -13,6 +15,33 @@ NEW_PROJECT_DETAIL_PAGE_URL = (
|
||||
OLD_PROJECT_DETAIL_URL = "https://show.bilibili.com/api/ticket/project/getV2"
|
||||
|
||||
|
||||
def _normalize_link_sale_start(ticket, screen):
|
||||
"""Link-goods uses Java Date strings; screen timestamps are Beijing time."""
|
||||
value = ticket.get("sale_start")
|
||||
if isinstance(value, str) and " CST " in value:
|
||||
# Parse explicitly: CST here means China, not US Central time. Avoid
|
||||
# strptime's locale-dependent English month/day names on Windows.
|
||||
parts = value.split()
|
||||
months = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
|
||||
try:
|
||||
return datetime(
|
||||
int(parts[5]),
|
||||
months.index(parts[1]) + 1,
|
||||
int(parts[2]),
|
||||
*map(int, parts[3].split(":")),
|
||||
).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except (ValueError, IndexError, TypeError):
|
||||
pass
|
||||
if value not in (None, ""):
|
||||
return value
|
||||
timestamp = _normalize_epoch_seconds(screen.get("sale_start"))
|
||||
if timestamp > 0:
|
||||
return datetime.fromtimestamp(timestamp, timezone(timedelta(hours=8))).strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def _first_value(payload: dict[str, Any], *keys: str, default: Any = None) -> Any:
|
||||
for key in keys:
|
||||
value = payload.get(key)
|
||||
@@ -356,8 +385,17 @@ def _merge_link_goods(
|
||||
"?project_id={0}&page_type=0".format(project_id)
|
||||
)
|
||||
).json()
|
||||
good_ids = [item["id"] for item in good_list.get("data", {}).get("list", [])]
|
||||
for good_id in good_ids:
|
||||
if good_list.get("errno", good_list.get("code", 0)) != 0:
|
||||
raise RuntimeError(good_list.get("msg") or "内场票列表获取失败")
|
||||
goods = good_list.get("data", {}).get("list", [])
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).warning("获取内场票列表失败: %s", exc)
|
||||
return merged
|
||||
for good in goods:
|
||||
good_id = good.get("id")
|
||||
if not good_id:
|
||||
continue
|
||||
try:
|
||||
detail = request.get(
|
||||
url=(
|
||||
"https://show.bilibili.com/api/ticket/linkgoods/detail"
|
||||
@@ -365,14 +403,21 @@ def _merge_link_goods(
|
||||
)
|
||||
).json()
|
||||
good_data = detail.get("data") or {}
|
||||
if detail.get("errno", detail.get("code", 0)) != 0:
|
||||
raise RuntimeError(detail.get("msg") or "内场票详情获取失败")
|
||||
item_id = good_data.get("item_id")
|
||||
for item in good_data.get("specs_list", []):
|
||||
if not item_id:
|
||||
raise RuntimeError("内场票详情缺少子项目 ID")
|
||||
for item in good_data.get("specs_list") or []:
|
||||
enriched = copy.deepcopy(item)
|
||||
enriched["project_id"] = item_id
|
||||
enriched["link_id"] = good_id
|
||||
for ticket in enriched.get("ticket_list", []):
|
||||
ticket["sale_start"] = _normalize_link_sale_start(ticket, item)
|
||||
merged.append(enriched)
|
||||
except Exception:
|
||||
return merged
|
||||
except Exception as exc:
|
||||
# A broken/removed merchandise entry must not hide later guests.
|
||||
logging.getLogger(__name__).warning("获取内场票 %s 失败: %s", good_id, exc)
|
||||
return merged
|
||||
|
||||
|
||||
@@ -395,11 +440,23 @@ def _fetch_ticket_options(
|
||||
).json()
|
||||
screens = date_payload.get("data", {}).get("screen_list", [])
|
||||
else:
|
||||
screens = _merge_link_goods(
|
||||
request=request,
|
||||
screen_list=project_payload.get("screen_list", []),
|
||||
project_id=project_id,
|
||||
)
|
||||
screens = project_payload.get("screen_list", [])
|
||||
screens = _merge_link_goods(
|
||||
request=request,
|
||||
screen_list=screens,
|
||||
project_id=project_id,
|
||||
)
|
||||
if selected_date:
|
||||
screens = [
|
||||
screen
|
||||
for screen in screens
|
||||
if not screen.get("link_id")
|
||||
or datetime.fromtimestamp(
|
||||
_normalize_epoch_seconds(screen.get("start_time")),
|
||||
timezone(timedelta(hours=8)),
|
||||
).strftime("%Y-%m-%d")
|
||||
== selected_date
|
||||
]
|
||||
|
||||
options: list[dict[str, Any]] = []
|
||||
for screen in screens:
|
||||
|
||||
+47
-20
@@ -17,7 +17,7 @@ import util
|
||||
from loguru import logger
|
||||
|
||||
from interface.common import _format_sale_status
|
||||
from interface.project import fetch_project_payload
|
||||
from interface.project import fetch_project_payload, _merge_link_goods
|
||||
from util import ConfigDB
|
||||
from util import GLOBAL_COOKIE_PATH
|
||||
from util import TEMP_PATH
|
||||
@@ -173,6 +173,34 @@ def _merge_screens(base_screens: list[dict], extra_screens: list[dict]) -> list[
|
||||
return merged
|
||||
|
||||
|
||||
def _fetch_date_screens_with_link_goods(request, project_id, date_str):
|
||||
if date_str == "全部日期":
|
||||
payload = fetch_project_payload(request=request, project_id=project_id)
|
||||
screens = payload.get("screen_list", [])
|
||||
for day in _iter_project_dates(payload["start_time"], payload["end_time"]):
|
||||
try:
|
||||
screens = _merge_screens(
|
||||
screens,
|
||||
_fetch_screens_by_date_with_fallback(request, project_id, day),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(f"获取 {day} 普通票失败,保留其余票档: {exc}")
|
||||
else:
|
||||
screens = _fetch_screens_by_date_with_fallback(request, project_id, date_str)
|
||||
screens = _merge_link_goods(
|
||||
request=request,
|
||||
screen_list=screens,
|
||||
project_id=project_id,
|
||||
)
|
||||
return [
|
||||
screen
|
||||
for screen in screens
|
||||
if date_str == "全部日期"
|
||||
or not screen.get("link_id")
|
||||
or _screen_matches_date(screen, date_str)
|
||||
]
|
||||
|
||||
|
||||
def filename_filter(filename):
|
||||
return re.sub(r'[/:*?"<>|]', "", filename)
|
||||
|
||||
@@ -343,21 +371,11 @@ def on_submit_ticket_id(num):
|
||||
|
||||
data["screen_list"] = _merge_screens(data["screen_list"], daily_screens)
|
||||
|
||||
try:
|
||||
good_list = util.main_request.get(
|
||||
url=f"https://show.bilibili.com/api/ticket/linkgoods/list?project_id={project_id}&page_type=0"
|
||||
).json()
|
||||
ids = [item["id"] for item in good_list["data"]["list"]]
|
||||
for item_id in ids:
|
||||
good_detail = util.main_request.get(
|
||||
url=f"https://show.bilibili.com/api/ticket/linkgoods/detail?link_id={item_id}"
|
||||
).json()
|
||||
for item in good_detail["data"]["specs_list"]:
|
||||
item["project_id"] = good_detail["data"]["item_id"]
|
||||
item["link_id"] = item_id
|
||||
data["screen_list"] += good_detail["data"]["specs_list"]
|
||||
except Exception as exc:
|
||||
logger.warning(f"获取周边商品信息失败: {exc}")
|
||||
data["screen_list"] = _merge_link_goods(
|
||||
request=util.main_request,
|
||||
screen_list=data["screen_list"],
|
||||
project_id=project_id,
|
||||
)
|
||||
|
||||
for screen in data["screen_list"]:
|
||||
if "name" not in screen:
|
||||
@@ -434,7 +452,9 @@ def on_submit_ticket_id(num):
|
||||
),
|
||||
visible=True,
|
||||
),
|
||||
gr.update(choices=sales_dates, visible=True, value=sales_dates[0])
|
||||
gr.update(
|
||||
choices=["全部日期", *sales_dates], visible=True, value="全部日期"
|
||||
)
|
||||
if sales_dates_show
|
||||
else gr.update(choices=[], visible=False, value=None),
|
||||
]
|
||||
@@ -1122,14 +1142,16 @@ def setting_tab(account_change_state=None):
|
||||
global project_id
|
||||
global project_name
|
||||
|
||||
if project_id <= 0 or not _normalize_date_string(_date):
|
||||
if project_id <= 0 or (
|
||||
_date != "全部日期" and not _normalize_date_string(_date)
|
||||
):
|
||||
return [
|
||||
gr.update(choices=[], value=None),
|
||||
gr.update(value="", visible=False),
|
||||
]
|
||||
|
||||
try:
|
||||
screens = _fetch_screens_by_date_with_fallback(
|
||||
screens = _fetch_date_screens_with_link_goods(
|
||||
util.main_request, project_id, _date
|
||||
)
|
||||
|
||||
@@ -1153,6 +1175,8 @@ def setting_tab(account_change_state=None):
|
||||
ticket["screen"] = screen_name
|
||||
ticket["screen_id"] = screen_id
|
||||
ticket["is_hot_project"] = is_hot_project
|
||||
if "link_id" in screen:
|
||||
ticket["link_id"] = screen["link_id"]
|
||||
ticket_str_list.append(
|
||||
_format_ticket_option(
|
||||
screen_name,
|
||||
@@ -1161,7 +1185,10 @@ def setting_tab(account_change_state=None):
|
||||
)
|
||||
)
|
||||
ticket_value.append(
|
||||
{"project_id": project_id, "ticket": ticket}
|
||||
{
|
||||
"project_id": screen.get("project_id", project_id),
|
||||
"ticket": ticket,
|
||||
}
|
||||
)
|
||||
|
||||
return [
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Regression fixture from Chongqing Mengxiang's public linkgoods API."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from pathlib import Path
|
||||
|
||||
from interface import project
|
||||
from tab import settings
|
||||
|
||||
|
||||
SCREEN = {
|
||||
"id": 1024355,
|
||||
"name": "2026/10/03 9:00—17:00",
|
||||
"start_time": 1790989200,
|
||||
"sale_start": 1788080400,
|
||||
"ticket_list": [
|
||||
{
|
||||
"id": 932296,
|
||||
"price": 990,
|
||||
"desc": "纸老虎签售票",
|
||||
"sale_start": "Sun Aug 30 17:00:00 CST 2026",
|
||||
"sale_flag_number": 4,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
|
||||
def json(self):
|
||||
return copy.deepcopy(self.data)
|
||||
|
||||
|
||||
class Request:
|
||||
def get(self, url):
|
||||
if "linkgoods/list" in url:
|
||||
return Response({"errno": 0, "data": {"list": [{"id": 1}, {"id": 3049}]}})
|
||||
if "link_id=1" in url:
|
||||
raise RuntimeError("one removed merchandise entry")
|
||||
if "link_id=3049" in url:
|
||||
return Response(
|
||||
{
|
||||
"errno": 0,
|
||||
"data": {
|
||||
"item_id": 1005095,
|
||||
"specs_list": [SCREEN],
|
||||
},
|
||||
}
|
||||
)
|
||||
if "infoByDate" in url:
|
||||
return Response({"errno": 0, "data": {"screen_list": []}})
|
||||
raise AssertionError(url)
|
||||
|
||||
|
||||
def test_one_bad_entry_does_not_hide_guests_and_sale_time_is_normalized():
|
||||
screens = project._merge_link_goods(
|
||||
request=Request(), screen_list=[], project_id=1004484
|
||||
)
|
||||
assert len(screens) == 1
|
||||
assert screens[0]["project_id"] == 1005095
|
||||
assert screens[0]["link_id"] == 3049
|
||||
assert screens[0]["ticket_list"][0]["sale_start"] == "2026-08-30 17:00:00"
|
||||
assert SCREEN["ticket_list"][0]["sale_start"] == "Sun Aug 30 17:00:00 CST 2026"
|
||||
|
||||
|
||||
def test_date_refresh_includes_matching_guest_even_without_general_tickets(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
settings, "_fetch_screens_by_date_with_fallback", lambda *args: []
|
||||
)
|
||||
screens = settings._fetch_date_screens_with_link_goods(
|
||||
Request(), 1004484, "2026-10-03"
|
||||
)
|
||||
assert len(screens) == 1
|
||||
assert screens[0]["project_id"] == 1005095
|
||||
assert (
|
||||
settings._fetch_date_screens_with_link_goods(Request(), 1004484, "2026-10-02")
|
||||
== []
|
||||
)
|
||||
|
||||
|
||||
def test_interface_date_selection_retains_child_project_and_link():
|
||||
payload = {
|
||||
"id": 1004484,
|
||||
"hotProject": False,
|
||||
"has_eticket": True,
|
||||
"screen_list": [],
|
||||
}
|
||||
options = project._fetch_ticket_options(
|
||||
request=Request(), project_payload=payload, selected_date="2026-10-03"
|
||||
)
|
||||
assert len(options) == 1
|
||||
ticket = options[0]
|
||||
assert (
|
||||
ticket["project_id"],
|
||||
ticket["screen_id"],
|
||||
ticket["id"],
|
||||
ticket["link_id"],
|
||||
) == (1005095, 1024355, 932296, 3049)
|
||||
assert ticket["price"] == 990
|
||||
assert ticket["sale_status"] == "售罄"
|
||||
assert (
|
||||
project._fetch_ticket_options(
|
||||
request=Request(), project_payload=payload, selected_date="2026-10-02"
|
||||
)
|
||||
== []
|
||||
)
|
||||
|
||||
|
||||
def test_missing_sale_start_uses_beijing_screen_timestamp():
|
||||
assert project._normalize_link_sale_start({}, SCREEN) == "2026-08-30 17:00:00"
|
||||
|
||||
|
||||
def test_web_config_generation_preserves_guest_ids_and_time(monkeypatch, tmp_path):
|
||||
settings._reset_ticket_context()
|
||||
payload = {"id": 1004484, "hotProject": False, "has_eticket": True}
|
||||
option = project._fetch_ticket_options(
|
||||
request=Request(),
|
||||
project_payload=payload,
|
||||
selected_date="2026-10-03",
|
||||
)[0]
|
||||
monkeypatch.setattr(
|
||||
settings,
|
||||
"ticket_value",
|
||||
[{"project_id": option["project_id"], "ticket": option}],
|
||||
)
|
||||
monkeypatch.setattr(settings, "ticket_str_list", [option["display"]])
|
||||
monkeypatch.setattr(
|
||||
settings, "buyer_value", [{"name": "TEST", "personal_id": "TEST-ONLY"}]
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
settings,
|
||||
"addr_value",
|
||||
[
|
||||
{
|
||||
"name": "TEST",
|
||||
"phone": "000",
|
||||
"id": 1,
|
||||
"prov": "",
|
||||
"city": "",
|
||||
"area": "",
|
||||
"addr": "TEST",
|
||||
}
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(settings, "TEMP_PATH", str(tmp_path))
|
||||
monkeypatch.setattr(settings.ConfigDB, "insert", lambda *args: None)
|
||||
cookie_manager = SimpleNamespace(
|
||||
get_cookies=lambda: [{"name": "test", "value": "fake"}],
|
||||
get_config_value=lambda *args: "",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
settings.util,
|
||||
"main_request",
|
||||
SimpleNamespace(
|
||||
get_request_name=lambda: "TEST",
|
||||
cookieManager=cookie_manager,
|
||||
),
|
||||
)
|
||||
updates = next(settings.on_submit_all("1004484", 0, [0], "TEST", "000", 0))
|
||||
config = json.loads(Path(updates[1]["value"]).read_text(encoding="utf-8"))
|
||||
assert (
|
||||
config["project_id"],
|
||||
config["screen_id"],
|
||||
config["sku_id"],
|
||||
config["link_id"],
|
||||
) == (1005095, 1024355, 932296, 3049)
|
||||
assert config["sale_start"] == "2026-08-30 17:00:00"
|
||||
assert config["pay_money"] == 990
|
||||
|
||||
|
||||
def test_all_dates_keeps_guest_options(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
settings,
|
||||
"fetch_project_payload",
|
||||
lambda **kwargs: {
|
||||
"screen_list": [],
|
||||
"start_time": 1790989200,
|
||||
"end_time": 1790989200,
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
settings, "_fetch_screens_by_date_with_fallback", lambda *args: []
|
||||
)
|
||||
assert (
|
||||
settings._fetch_date_screens_with_link_goods(Request(), 1004484, "全部日期")[0][
|
||||
"link_id"
|
||||
]
|
||||
== 3049
|
||||
)
|
||||
|
||||
|
||||
def test_guest_config_reaches_order_payload_without_parent_id_substitution(monkeypatch):
|
||||
from task import buy_helpers
|
||||
from tab.go import _parse_sale_start
|
||||
|
||||
config = {
|
||||
"project_id": 1005095,
|
||||
"screen_id": 1024355,
|
||||
"sku_id": 932296,
|
||||
"link_id": 3049,
|
||||
"count": 1,
|
||||
"pay_money": 990,
|
||||
"sale_start": "2026-08-30 17:00:00",
|
||||
"buyer_info": [],
|
||||
}
|
||||
assert _parse_sale_start(config["sale_start"]).hour == 17
|
||||
assert buy_helpers.build_token_payload(config)["project_id"] == 1005095
|
||||
monkeypatch.setattr(
|
||||
buy_helpers,
|
||||
"sim_ctoken_state",
|
||||
lambda **kwargs: SimpleNamespace(generate_create_ctoken=lambda: "TEST"),
|
||||
)
|
||||
url, payload = buy_helpers.prepare_create_request(config, "TEST", False, None, None)
|
||||
assert "project_id=1005095" in url
|
||||
assert payload["link_id"] == 3049
|
||||
assert payload["sku_id"] == 932296
|
||||
# Only construct the payload: no request is sent.
|
||||
@@ -143,8 +143,8 @@ def test_submit_ticket_id_keeps_dates_when_account_data_is_unavailable(monkeypat
|
||||
assert updates[0]["choices"]
|
||||
assert updates[1]["choices"] == []
|
||||
assert updates[2]["choices"] == []
|
||||
assert updates[5]["choices"] == ["2026-07-16"]
|
||||
assert updates[5]["value"] == "2026-07-16"
|
||||
assert updates[5]["choices"] == ["全部日期", "2026-07-16"]
|
||||
assert updates[5]["value"] == "全部日期"
|
||||
assert warnings == [
|
||||
"票档和日期已获取;请先在“账号登录”页重新登录,以加载实名购票人和收货地址。"
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user