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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import requests
|
| 4 |
+
import time
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import urllib3
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from urllib.parse import urlparse
|
| 11 |
+
|
| 12 |
+
# --- 基础配置 ---
|
| 13 |
+
st.set_page_config(page_title="TMS 影片查询", page_icon="🎬", layout="wide")
|
| 14 |
+
|
| 15 |
+
# 屏蔽 HTTPS 证书警告
|
| 16 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 17 |
+
|
| 18 |
+
# 加载环境变量
|
| 19 |
+
load_dotenv()
|
| 20 |
+
|
| 21 |
+
# --- 工具函数 ---
|
| 22 |
+
|
| 23 |
+
TMS_ORIGIN = "https://tms.hengdianfilm.com"
|
| 24 |
+
TMS_PROXY_URL_ENV = "TMS_CF_WORKER_URL"
|
| 25 |
+
TMS_PROXY_TOKEN_ENV = "TMS_CF_WORKER_TOKEN"
|
| 26 |
+
TMS_PROXY_REGION_ENV = "TMS_PROXY_REGION"
|
| 27 |
+
TMS_DEFAULT_SUPABASE_REGION = "ap-northeast-1"
|
| 28 |
+
TMS_PROXY_TOKEN_HEADER = "X-TMS-Proxy-Token"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def normalize_tms_proxy_base_url(proxy_url=None):
|
| 32 |
+
raw = (proxy_url if proxy_url is not None else os.getenv(TMS_PROXY_URL_ENV, "")).strip()
|
| 33 |
+
if not raw:
|
| 34 |
+
return ""
|
| 35 |
+
if "://" not in raw:
|
| 36 |
+
raw = f"https://{raw}"
|
| 37 |
+
return raw.rstrip("/")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def build_tms_request_url(origin_url, proxy_base_url=""):
|
| 41 |
+
proxy_base_url = normalize_tms_proxy_base_url(proxy_base_url)
|
| 42 |
+
if not proxy_base_url:
|
| 43 |
+
return origin_url
|
| 44 |
+
|
| 45 |
+
parsed = urlparse(origin_url)
|
| 46 |
+
origin = f"{parsed.scheme}://{parsed.netloc}"
|
| 47 |
+
if origin != TMS_ORIGIN:
|
| 48 |
+
return origin_url
|
| 49 |
+
|
| 50 |
+
query = f"?{parsed.query}" if parsed.query else ""
|
| 51 |
+
return f"{proxy_base_url}{parsed.path}{query}"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def with_tms_proxy_auth(headers, proxy_base_url=""):
|
| 55 |
+
headers = dict(headers)
|
| 56 |
+
normalized_proxy_url = normalize_tms_proxy_base_url(proxy_base_url)
|
| 57 |
+
if normalized_proxy_url:
|
| 58 |
+
proxy_token = os.getenv(TMS_PROXY_TOKEN_ENV, "").strip()
|
| 59 |
+
if proxy_token:
|
| 60 |
+
headers[TMS_PROXY_TOKEN_HEADER] = proxy_token
|
| 61 |
+
proxy_region = os.getenv(TMS_PROXY_REGION_ENV, "").strip()
|
| 62 |
+
if not proxy_region and "supabase.co" in normalized_proxy_url:
|
| 63 |
+
proxy_region = TMS_DEFAULT_SUPABASE_REGION
|
| 64 |
+
if proxy_region:
|
| 65 |
+
headers["x-region"] = proxy_region
|
| 66 |
+
return headers
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def fetch_tms_rows_via_combined_proxy(proxy_base_url, app_secret, ticket, theater_id, x_session_id):
|
| 70 |
+
proxy_base_url = normalize_tms_proxy_base_url(proxy_base_url)
|
| 71 |
+
if not proxy_base_url:
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
headers = with_tms_proxy_auth({"Content-Type": "application/json"}, proxy_base_url)
|
| 75 |
+
payload = {
|
| 76 |
+
"appSecret": app_secret,
|
| 77 |
+
"ticket": ticket,
|
| 78 |
+
"theaterId": theater_id,
|
| 79 |
+
"sessionId": x_session_id,
|
| 80 |
+
"pageCapacity": 20,
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
response = None
|
| 84 |
+
for path in ("/tms/dcp-list", "/__tms/dcp-list"):
|
| 85 |
+
response = requests.post(f"{proxy_base_url}{path}", headers=headers, json=payload, timeout=60)
|
| 86 |
+
if response.status_code != 404:
|
| 87 |
+
break
|
| 88 |
+
if response is None or response.status_code == 404:
|
| 89 |
+
return None
|
| 90 |
+
try:
|
| 91 |
+
data = response.json()
|
| 92 |
+
except ValueError as exc:
|
| 93 |
+
raise RuntimeError(format_tms_http_error("TMS 合并代理返回非 JSON 响应", response)) from exc
|
| 94 |
+
|
| 95 |
+
if not response.ok or not data.get("ok"):
|
| 96 |
+
upstream_status = response.headers.get("X-TMS-Upstream-Status") or data.get("upstreamStatus") or "-"
|
| 97 |
+
body_preview = data.get("body") or data.get("error") or response.text[:240]
|
| 98 |
+
raise RuntimeError(
|
| 99 |
+
f"TMS 合并代理失败: HTTP {response.status_code}; "
|
| 100 |
+
f"TMS上游状态={upstream_status}; 响应={body_preview}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return data.get("rows", [])
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def format_tms_http_error(prefix, response):
|
| 107 |
+
if response is None:
|
| 108 |
+
return prefix
|
| 109 |
+
|
| 110 |
+
proxy_error = response.headers.get("X-TMS-Proxy-Error") or "-"
|
| 111 |
+
proxy_region = (
|
| 112 |
+
response.headers.get("X-TMS-Proxy-Region")
|
| 113 |
+
or response.headers.get("X-SB-Edge-Region")
|
| 114 |
+
or "-"
|
| 115 |
+
)
|
| 116 |
+
upstream_status = response.headers.get("X-TMS-Upstream-Status") or "-"
|
| 117 |
+
body_preview = re.sub(r"\s+", " ", response.text or "").strip()[:240] or "-"
|
| 118 |
+
return (
|
| 119 |
+
f"{prefix}: HTTP {response.status_code}; "
|
| 120 |
+
f"代理错误={proxy_error}; 代理区域={proxy_region}; "
|
| 121 |
+
f"TMS上游状态={upstream_status}; 响应={body_preview}"
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_circled_number(hall_name):
|
| 126 |
+
"""
|
| 127 |
+
将影厅数字转换为带圈数字,例如 1 -> ①
|
| 128 |
+
"""
|
| 129 |
+
mapping = {'1': '①', '2': '②', '3': '③', '4': '④', '5': '⑤', '6': '⑥', '7': '⑦', '8': '⑧', '9': '⑨'}
|
| 130 |
+
# 提取字符串中的数字
|
| 131 |
+
num_str = ''.join(filter(str.isdigit, str(hall_name)))
|
| 132 |
+
return mapping.get(num_str, num_str)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def format_play_time(time_str):
|
| 136 |
+
"""
|
| 137 |
+
格式化时长字符串,例如 "01:30" -> 90
|
| 138 |
+
"""
|
| 139 |
+
if not time_str or not isinstance(time_str, str): return None
|
| 140 |
+
try:
|
| 141 |
+
parts = time_str.split(':')
|
| 142 |
+
hours = int(parts[0])
|
| 143 |
+
minutes = int(parts[1])
|
| 144 |
+
return hours * 60 + minutes
|
| 145 |
+
except (ValueError, IndexError):
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def format_content_name_with_explanation(content_name):
|
| 150 |
+
raw = str(content_name or '').strip()
|
| 151 |
+
if not raw:
|
| 152 |
+
return ''
|
| 153 |
+
|
| 154 |
+
lang_map = {
|
| 155 |
+
'CMN': '国语/普通话', 'YUE': '粤语', 'EN': '英语', 'JP': '日语/或简化命名中的加密标记',
|
| 156 |
+
'KO': '韩语', 'FR': '法语', 'ES': '西班牙语', 'TH': '泰语', 'HI': '印地语', 'RU': '俄语',
|
| 157 |
+
'PTH': '普通话', 'GDH': '广东话', 'YS': '原声', 'YZ': '译制', 'SCH': '四川话',
|
| 158 |
+
'NAN': '闽南语', 'WU': '吴语/上海话', 'XX': '无字幕', 'QMS': '简中字幕',
|
| 159 |
+
'QMT': '繁中字幕', 'CCAP': '听障字幕'
|
| 160 |
+
}
|
| 161 |
+
audio_map = {'20': '2.0', '51': '5.1', '71': '7.1', 'ATMOS': 'Dolby Atmos', 'DTSX': 'DTS:X'}
|
| 162 |
+
type_map = {'FTR': '正片', 'TLR': '预告片', 'TSR': '先导预告'}
|
| 163 |
+
pack_map = {'OV': '原始版本包', 'VF': '版本增量包'}
|
| 164 |
+
|
| 165 |
+
notes = []
|
| 166 |
+
parts = raw.split('_')
|
| 167 |
+
first_tokens = parts[0].split('-') if parts else []
|
| 168 |
+
if first_tokens:
|
| 169 |
+
notes.append(f"[片名/标识:{first_tokens[0]}]")
|
| 170 |
+
for token in first_tokens[1:]:
|
| 171 |
+
up = token.upper()
|
| 172 |
+
if up in type_map:
|
| 173 |
+
notes.append(f"[内容类型:{type_map[up]}({token})]")
|
| 174 |
+
elif up in {'2D', '3D'}:
|
| 175 |
+
notes.append(f"[制式:{up}]")
|
| 176 |
+
elif up in {'4FL', '24FPS', '48FPS', '60FPS', '120FPS'}:
|
| 177 |
+
notes.append(f"[技术参数:{token}]")
|
| 178 |
+
elif re.fullmatch(r'\d+', up):
|
| 179 |
+
notes.append(f"[版本号:{token}]")
|
| 180 |
+
else:
|
| 181 |
+
notes.append(f"[{token}]")
|
| 182 |
+
|
| 183 |
+
for token in parts[1:]:
|
| 184 |
+
up = token.upper()
|
| 185 |
+
if '-' in up:
|
| 186 |
+
a, b = up.split('-', 1)
|
| 187 |
+
if a in lang_map and b in lang_map:
|
| 188 |
+
notes.append(f"[音频:{lang_map[a]}({a})]")
|
| 189 |
+
notes.append(f"[字幕:{lang_map[b]}({b})]")
|
| 190 |
+
continue
|
| 191 |
+
if up in {'F', 'S', 'C', 'F-178', 'C-19', '235', '185'}:
|
| 192 |
+
notes.append(f"[画幅:{token}]")
|
| 193 |
+
elif re.fullmatch(r'\d{2,3}M', up):
|
| 194 |
+
notes.append(f"[时长:{token}]")
|
| 195 |
+
elif up in audio_map:
|
| 196 |
+
notes.append(f"[音效:{audio_map[up]}({token})]")
|
| 197 |
+
elif up in {'2K', '4K'}:
|
| 198 |
+
notes.append(f"[分辨率:{up}]")
|
| 199 |
+
elif up in {'SMPTE', 'IOP'}:
|
| 200 |
+
notes.append(f"[封装标准:{up}]")
|
| 201 |
+
elif re.fullmatch(r'\d{8}', up):
|
| 202 |
+
notes.append(f"[打包日期:{token}]")
|
| 203 |
+
elif re.fullmatch(r'\d{4}', up):
|
| 204 |
+
notes.append(f"[月日批次:{token}]")
|
| 205 |
+
elif up in pack_map:
|
| 206 |
+
notes.append(f"[包类型:{pack_map[up]}({up})]")
|
| 207 |
+
elif up in lang_map:
|
| 208 |
+
notes.append(f"[语言/标记:{lang_map[up]}({up})]")
|
| 209 |
+
elif up.startswith('CN'):
|
| 210 |
+
notes.append(f"[地区/分级:{token}]")
|
| 211 |
+
else:
|
| 212 |
+
notes.append(f"[{token}]")
|
| 213 |
+
|
| 214 |
+
return f"{raw} / {' '.join(notes)}"
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def clean_movie_title(raw_title, canonical_names=None):
|
| 218 |
+
"""
|
| 219 |
+
电影名称标准化清洗函数
|
| 220 |
+
"""
|
| 221 |
+
if not isinstance(raw_title, str):
|
| 222 |
+
return raw_title
|
| 223 |
+
|
| 224 |
+
base_name = None
|
| 225 |
+
|
| 226 |
+
# 1. 尝试匹配标准名称
|
| 227 |
+
if canonical_names:
|
| 228 |
+
# 按长度倒序排序,确保最长匹配优先
|
| 229 |
+
sorted_names = sorted(canonical_names, key=len, reverse=True)
|
| 230 |
+
for name in sorted_names:
|
| 231 |
+
if name in raw_title:
|
| 232 |
+
base_name = name
|
| 233 |
+
break
|
| 234 |
+
|
| 235 |
+
# 2. 回退逻辑:如果没传列表或没匹配到,使用空格分割
|
| 236 |
+
if not base_name:
|
| 237 |
+
base_name = raw_title.split(' ', 1)[0]
|
| 238 |
+
|
| 239 |
+
# 3. 后缀追加逻辑
|
| 240 |
+
raw_upper = raw_title.upper()
|
| 241 |
+
suffix = ""
|
| 242 |
+
|
| 243 |
+
if "HDR LED" in raw_upper:
|
| 244 |
+
suffix = "(HDR LED)"
|
| 245 |
+
elif "CINITY" in raw_upper:
|
| 246 |
+
suffix = "(CINITY)"
|
| 247 |
+
elif "杜比" in raw_upper or "DOLBY" in raw_upper:
|
| 248 |
+
suffix = "(杜比视界)"
|
| 249 |
+
elif "IMAX" in raw_upper:
|
| 250 |
+
if "3D" in raw_upper:
|
| 251 |
+
suffix = "(数字IMAX3D)"
|
| 252 |
+
else:
|
| 253 |
+
suffix = "(数字IMAX)"
|
| 254 |
+
elif "巨幕" in raw_upper:
|
| 255 |
+
if "立体" in raw_upper:
|
| 256 |
+
suffix = "(中国巨幕立体)"
|
| 257 |
+
else:
|
| 258 |
+
suffix = "(中国巨幕)"
|
| 259 |
+
elif "3D" in raw_upper:
|
| 260 |
+
suffix = "(数字3D)"
|
| 261 |
+
|
| 262 |
+
# 只有当 base_name 自身不包含该后缀时才添加
|
| 263 |
+
if suffix and suffix not in base_name:
|
| 264 |
+
return f"{base_name}{suffix}"
|
| 265 |
+
|
| 266 |
+
return base_name
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# --- 核心功能模块 ---
|
| 270 |
+
|
| 271 |
+
# @st.cache_data(show_spinner=False, ttl=600)
|
| 272 |
+
def fetch_and_process_server_movies(priority_movie_titles=None, tms_proxy_base_url=""):
|
| 273 |
+
if priority_movie_titles is None: priority_movie_titles = []
|
| 274 |
+
proxy_base_url = normalize_tms_proxy_base_url(tms_proxy_base_url)
|
| 275 |
+
|
| 276 |
+
# 获取环境变量
|
| 277 |
+
app_secret = os.getenv("TMS_APP_SECRET")
|
| 278 |
+
ticket = os.getenv("TMS_TICKET")
|
| 279 |
+
theater_id_str = os.getenv("TMS_THEATER_ID")
|
| 280 |
+
x_session_id = os.getenv("TMS_X_SESSION_ID")
|
| 281 |
+
|
| 282 |
+
# 转换 ID 为整数
|
| 283 |
+
try:
|
| 284 |
+
theater_id = int(theater_id_str) if theater_id_str else 0
|
| 285 |
+
except ValueError:
|
| 286 |
+
st.error("环境变量 TMS_THEATER_ID 格式错误,应为数字。")
|
| 287 |
+
return {}, []
|
| 288 |
+
|
| 289 |
+
if proxy_base_url:
|
| 290 |
+
try:
|
| 291 |
+
all_movies = fetch_tms_rows_via_combined_proxy(
|
| 292 |
+
proxy_base_url,
|
| 293 |
+
app_secret,
|
| 294 |
+
ticket,
|
| 295 |
+
theater_id,
|
| 296 |
+
x_session_id,
|
| 297 |
+
)
|
| 298 |
+
if all_movies is not None:
|
| 299 |
+
return process_tms_movies(all_movies, priority_movie_titles)
|
| 300 |
+
except Exception as e:
|
| 301 |
+
st.warning(f"合并代理查询失败,尝试普通代理转发: {e}")
|
| 302 |
+
|
| 303 |
+
token_headers = {
|
| 304 |
+
'Accept': 'application/json, text/javascript, */*; q=0.01',
|
| 305 |
+
'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
|
| 306 |
+
'Content-Type': 'application/json',
|
| 307 |
+
'Cookie': f'JSESSIONID={x_session_id}',
|
| 308 |
+
'DNT': '1',
|
| 309 |
+
'Origin': 'https://tms.hengdianfilm.com',
|
| 310 |
+
'Priority': 'u=0, i',
|
| 311 |
+
'Referer': f'https://tms.hengdianfilm.com/hd/oalogin?ticket={ticket}',
|
| 312 |
+
'Sec-CH-UA': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"',
|
| 313 |
+
'Sec-CH-UA-Mobile': '?0',
|
| 314 |
+
'Sec-CH-UA-Platform': '"macOS"',
|
| 315 |
+
'Sec-Fetch-Dest': 'empty',
|
| 316 |
+
'Sec-Fetch-Mode': 'cors',
|
| 317 |
+
'Sec-Fetch-Site': 'same-origin',
|
| 318 |
+
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36',
|
| 319 |
+
'X-Requested-With': 'XMLHttpRequest',
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
# 使用变量
|
| 323 |
+
token_json_data = {'appId': 'hd', 'appSecret': app_secret, 'timeStamp': int(time.time() * 1000)}
|
| 324 |
+
# 动态构建 URL
|
| 325 |
+
token_url = build_tms_request_url(
|
| 326 |
+
f'{TMS_ORIGIN}/cinema-api/admin/generateToken?token=hd&murl=?token=hd&murl=ticket={ticket}',
|
| 327 |
+
proxy_base_url,
|
| 328 |
+
)
|
| 329 |
+
token_headers = with_tms_proxy_auth(token_headers, proxy_base_url)
|
| 330 |
+
|
| 331 |
+
try:
|
| 332 |
+
response = requests.post(token_url, headers=token_headers, json=token_json_data, timeout=10)
|
| 333 |
+
response.raise_for_status()
|
| 334 |
+
token_data = response.json()
|
| 335 |
+
if token_data.get('error_code') != '0000':
|
| 336 |
+
raise Exception(f"获取Token失败: {token_data.get('error_desc')}")
|
| 337 |
+
auth_token = token_data['param']
|
| 338 |
+
except requests.exceptions.HTTPError as e:
|
| 339 |
+
st.error(format_tms_http_error("连接 TMS 认证服务失败", e.response))
|
| 340 |
+
return {}, []
|
| 341 |
+
except Exception as e:
|
| 342 |
+
st.error(f"连接 TMS 认证服务失败: {e}")
|
| 343 |
+
return {}, []
|
| 344 |
+
|
| 345 |
+
all_movies, page_index = [], 1
|
| 346 |
+
while True:
|
| 347 |
+
list_headers = {
|
| 348 |
+
'Accept': 'application/json, text/javascript, */*; q=0.01',
|
| 349 |
+
'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
|
| 350 |
+
'Content-Type': 'application/json; charset=UTF-8',
|
| 351 |
+
'Cookie': f'JSESSIONID={x_session_id}',
|
| 352 |
+
'DNT': '1',
|
| 353 |
+
'Origin': 'https://tms.hengdianfilm.com',
|
| 354 |
+
'Priority': 'u=1, i',
|
| 355 |
+
'Referer': f'https://tms.hengdianfilm.com/hd/index?ContentMovie&THEATER_ID={theater_id}&SOURCE=SERVER&ASSERT_TYPE=2&PAGE_CAPACITY=20&PAGE_INDEX=1',
|
| 356 |
+
'Sec-CH-UA': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"',
|
| 357 |
+
'Sec-CH-UA-Mobile': '?0',
|
| 358 |
+
'Sec-CH-UA-Platform': '"macOS"',
|
| 359 |
+
'Sec-Fetch-Dest': 'empty',
|
| 360 |
+
'Sec-Fetch-Mode': 'cors',
|
| 361 |
+
'Sec-Fetch-Site': 'same-origin',
|
| 362 |
+
'Token': auth_token,
|
| 363 |
+
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36',
|
| 364 |
+
'X-Requested-With': 'XMLHttpRequest',
|
| 365 |
+
'X-SESSIONID': x_session_id,
|
| 366 |
+
}
|
| 367 |
+
list_params = {'token': 'hd', 'murl': 'ContentMovie'}
|
| 368 |
+
list_json_data = {'THEATER_ID': theater_id, 'SOURCE': 'SERVER', 'ASSERT_TYPE': 2, 'PAGE_CAPACITY': 20,
|
| 369 |
+
'PAGE_INDEX': page_index}
|
| 370 |
+
|
| 371 |
+
list_url = build_tms_request_url(f'{TMS_ORIGIN}/cinema-api/cinema/server/dcp/list', proxy_base_url)
|
| 372 |
+
list_headers = with_tms_proxy_auth(list_headers, proxy_base_url)
|
| 373 |
+
try:
|
| 374 |
+
response = requests.post(
|
| 375 |
+
list_url,
|
| 376 |
+
params=list_params,
|
| 377 |
+
headers=list_headers,
|
| 378 |
+
json=list_json_data,
|
| 379 |
+
verify=bool(proxy_base_url),
|
| 380 |
+
timeout=15,
|
| 381 |
+
)
|
| 382 |
+
response.raise_for_status()
|
| 383 |
+
movie_data = response.json()
|
| 384 |
+
if movie_data.get("RSPCD") != "000000":
|
| 385 |
+
raise Exception(f"获取影片列表失败: {movie_data.get('RSPMSG')}")
|
| 386 |
+
|
| 387 |
+
body = movie_data.get("BODY", {})
|
| 388 |
+
movies_on_page = body.get("LIST", [])
|
| 389 |
+
if not movies_on_page: break
|
| 390 |
+
all_movies.extend(movies_on_page)
|
| 391 |
+
if len(all_movies) >= body.get("COUNT", 0): break
|
| 392 |
+
page_index += 1
|
| 393 |
+
time.sleep(0.5)
|
| 394 |
+
except requests.exceptions.HTTPError as e:
|
| 395 |
+
st.error(format_tms_http_error(f"��取影片列表页 {page_index} 失败", e.response))
|
| 396 |
+
break
|
| 397 |
+
except Exception as e:
|
| 398 |
+
st.error(f"获取影片列表页 {page_index} 失败: {e}")
|
| 399 |
+
break
|
| 400 |
+
|
| 401 |
+
return process_tms_movies(all_movies, priority_movie_titles)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def process_tms_movies(all_movies, priority_movie_titles=None):
|
| 405 |
+
if priority_movie_titles is None:
|
| 406 |
+
priority_movie_titles = []
|
| 407 |
+
|
| 408 |
+
# 处理数据
|
| 409 |
+
movie_details = {m.get('CONTENT_NAME'): {'assert_name': m.get('ASSERT_NAME'),
|
| 410 |
+
'halls': sorted([h.get('HALL_NAME') for h in m.get('HALL_INFO', [])]),
|
| 411 |
+
'play_time': m.get('PLAY_TIME')} for m in all_movies if
|
| 412 |
+
m.get('CONTENT_NAME')}
|
| 413 |
+
|
| 414 |
+
by_hall = defaultdict(list)
|
| 415 |
+
for content_name, details in movie_details.items():
|
| 416 |
+
for hall_name in details['halls']:
|
| 417 |
+
by_hall[hall_name].append({'content_name': content_name, 'details': details})
|
| 418 |
+
|
| 419 |
+
for hall_name in by_hall:
|
| 420 |
+
by_hall[hall_name].sort(
|
| 421 |
+
key=lambda item: (item['details']['assert_name'] is None or item['details']['assert_name'] == '',
|
| 422 |
+
item['details']['assert_name'] or item['content_name']))
|
| 423 |
+
|
| 424 |
+
view2_list = [{'assert_name': d['assert_name'], 'content_name': c, 'halls': d['halls'], 'play_time': d['play_time']}
|
| 425 |
+
for c, d in movie_details.items() if d.get('assert_name')]
|
| 426 |
+
|
| 427 |
+
priority_list = [item for item in view2_list if
|
| 428 |
+
any(p_title in item['assert_name'] for p_title in priority_movie_titles)]
|
| 429 |
+
other_list_items = [item for item in view2_list if item not in priority_list]
|
| 430 |
+
|
| 431 |
+
priority_list.sort(key=lambda x: x['assert_name'])
|
| 432 |
+
other_list_items.sort(key=lambda x: x['assert_name'])
|
| 433 |
+
final_sorted_list = priority_list + other_list_items
|
| 434 |
+
|
| 435 |
+
return dict(sorted(by_hall.items())), final_sorted_list
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
# --- 主界面 ---
|
| 439 |
+
|
| 440 |
+
def main():
|
| 441 |
+
st.title("🎬 TMS 服务器影片内容查询")
|
| 442 |
+
st.info("查询 TMS 服务器上的 DCP 内容及分布情况。")
|
| 443 |
+
proxy_base_url = normalize_tms_proxy_base_url()
|
| 444 |
+
if proxy_base_url:
|
| 445 |
+
st.caption(f"当前 TMS 请求将通过 Cloudflare Worker 中转:{proxy_base_url}")
|
| 446 |
+
else:
|
| 447 |
+
st.caption(f"当前 TMS 请求为直连;配置 `{TMS_PROXY_URL_ENV}` 后会自动启用 Cloudflare Worker 中转。")
|
| 448 |
+
|
| 449 |
+
# 尝试从 Session State 获取优先显示的影片(如果在主页加载了排片)
|
| 450 |
+
priority_titles = []
|
| 451 |
+
if 'api_df' in st.session_state and not st.session_state.api_df.empty:
|
| 452 |
+
df = st.session_state.api_df
|
| 453 |
+
if '影片名称_清理后' in df.columns:
|
| 454 |
+
priority_titles = df['影片名称_清理后'].unique().tolist()
|
| 455 |
+
elif '影片名称' in df.columns:
|
| 456 |
+
priority_titles = df['影片名称'].apply(lambda x: clean_movie_title(x)).unique().tolist()
|
| 457 |
+
|
| 458 |
+
# 也可以检查 file_df
|
| 459 |
+
elif 'file_df' in st.session_state and not st.session_state.file_df.empty:
|
| 460 |
+
df = st.session_state.file_df
|
| 461 |
+
if '影片名称_清理后' in df.columns:
|
| 462 |
+
priority_titles = df['影片名称_清理后'].unique().tolist()
|
| 463 |
+
elif '影片名称' in df.columns:
|
| 464 |
+
priority_titles = df['影片名称'].apply(lambda x: clean_movie_title(x)).unique().tolist()
|
| 465 |
+
|
| 466 |
+
if st.button('点击查询 TMS 服务器', key="query_tms", type="primary", icon="🔍"):
|
| 467 |
+
with st.spinner("正在从 TMS 服务器获取数据中..."):
|
| 468 |
+
try:
|
| 469 |
+
halls_data, movie_list_sorted = fetch_and_process_server_movies(priority_titles, proxy_base_url)
|
| 470 |
+
|
| 471 |
+
if not movie_list_sorted:
|
| 472 |
+
st.warning("未获取到任何影片数据,请检查 TMS 连接配置。")
|
| 473 |
+
else:
|
| 474 |
+
st.success("TMS 服务器数据获取成功!")
|
| 475 |
+
|
| 476 |
+
# 1. 按影片查看
|
| 477 |
+
st.markdown("### 🎥 按影片查看所在影厅")
|
| 478 |
+
view2_data = [{'影片名称': item['assert_name'],
|
| 479 |
+
'所在影厅': " ".join(sorted([get_circled_number(h) for h in item['halls']])),
|
| 480 |
+
'时长(分钟)': format_play_time(item['play_time']),
|
| 481 |
+
'文件名': format_content_name_with_explanation(item['content_name'])}
|
| 482 |
+
for item in movie_list_sorted]
|
| 483 |
+
st.dataframe(pd.DataFrame(view2_data), hide_index=True, use_container_width=True)
|
| 484 |
+
|
| 485 |
+
st.divider()
|
| 486 |
+
|
| 487 |
+
# 2. 按影厅查看
|
| 488 |
+
st.markdown("### 🏢 按影厅查看影片内容")
|
| 489 |
+
if halls_data:
|
| 490 |
+
hall_tabs = st.tabs(list(halls_data.keys()))
|
| 491 |
+
for tab, hall_name in zip(hall_tabs, halls_data.keys()):
|
| 492 |
+
with tab:
|
| 493 |
+
view1_data = [{'影片名称': item['details']['assert_name'],
|
| 494 |
+
'所在影厅': " ".join(sorted([get_circled_number(h) for h in item['details']['halls']])),
|
| 495 |
+
'时长(分钟)': format_play_time(item['details']['play_time']),
|
| 496 |
+
'文件名': format_content_name_with_explanation(item['content_name'])} for item in
|
| 497 |
+
halls_data[hall_name]]
|
| 498 |
+
st.dataframe(pd.DataFrame(view1_data), hide_index=True, use_container_width=True)
|
| 499 |
+
else:
|
| 500 |
+
st.info("暂无影厅数据。")
|
| 501 |
+
|
| 502 |
+
except Exception as e:
|
| 503 |
+
st.error(f"查询 TMS 服务器时出错: {e}")
|
| 504 |
+
|
| 505 |
+
if __name__ == "__main__":
|
| 506 |
+
main()
|