Termux之h5


pt站做成h5,然后推送与订阅

一、longpt

from flask import Flask, render_template_string, Response, request, jsonify
import requests
from bs4 import BeautifulSoup
import urllib.parse
import re
import os
import json
import threading
import time
import datetime
import random

# 启动时自动剿灭被龙头像污染的旧缓存文件
for f in ["longpt_official_history.json", "longpt_recent_history.json"]:
    if os.path.exists(f):
        try: os.remove(f)
        except: pass

app = Flask(__name__)

# ================= 必须配置的区域 =================
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Connection': 'close',
    # 【安全提醒】:请把你的 LongPT 长效 Cookie 填在下面
    'Cookie': 'SITE_TOTAL_ID=b06a69304be7b561a043e0a5854d8e72; c_secure_pass=eyJ1c2VyX2lkIjoiMzQyODMiLCJleHBpcmVzIjoxODEzNDk1MjQyfS5lZjAyNTU4NDlkMzlkYjZhNzM4NmM5NTUzZTNlMWFjM2Q4M2VlYjE3NTUwNjI1ZjE3NjRkMzAwNjlmZTlmM2Zj; server_name_session=54eb12fe05fd05ddaaaedf7596b64a03; cf_clearance=q8.jsFZV.ZXKRO2YXJlJqX3ooETUkVOchY7OxTIoARI-1790686222-1.2.1.1-nF9k6YHJS6Ir04vlZvI5Z5RoY.vfJn3WShGqnkO_ah52LmrYTHYxYSS_SJDJOQ2x0kEqPKdPG.C5Xz8Y3aRe37Z61L_6kL_bIRI3Lc91M6CUjySriI38lUmZpwmv6tJn4WmQKvbZVaxpoS1UOD1_vCLNWHm41WdaVs5VH62iTuT9FuefQfLpCaj.SFAQuFECLU16MsYPybyIiw1QK8ZqLUFrjWCwjrtcEV_Nt1C5c1v4diyRDCqvKd3OU9xHHieZoC8DWBkPc2V98d77.xAwgXLiu2KhujJk5kvVZNp1xmHmACPquBhP9yTK_zE_2F86MEpPqzpxckFm5xM0aV_Cp4fQdDNNbEjzBESu65a6dr7zwTx4kenOTDsaImoHDWwyC9ylHDRgxw4.ANMc8hibcyG3Pj3XELHRShyyBV0q.4VlEJJNG2foaSHQgx0AGAKV' 
}

PROXY_URL = ""
PROXIES = {"http": PROXY_URL, "https": PROXY_URL} if PROXY_URL else None
TIMEOUT = 10

BASE_URL = "https://longpt.org"
OFFICIAL_URL = f"{BASE_URL}/torrents.php"
INDEX_URL = f"{BASE_URL}/index.php"
SIGNIN_URL = f"{BASE_URL}/attendance.php"

OFFICIAL_HISTORY_FILE = "longpt_official_history.json"
RECENT_HISTORY_FILE = "longpt_recent_history.json"

# 🚀 三台 qBittorrent 服务器配置(请填入账号密码及各节点中已添加的固定 RSS 订阅源 URL)
QBT_SERVERS = {
    "177": {
        "name": "177 节点 (192.168.2.177)",
        "url": "http://192.168.2.177:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_url": "https://longpt.org/torrentrss.php?passkey=32952e31a75f7f8e25cb90d6fb19a76c&rows=100&cat403=1&cat402=1&cat405=1&cat404=1&cat401=1&tea1=1&tea2=1&tea3=1&tea4=1&tea8=1&linktype=dl"  # 👈 填入177节点里配置的 LongPT RSS 订阅链接
    },
    "188": {
        "name": "188 节点 (192.168.2.188)",
        "url": "http://192.168.2.188:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_url": "https://longpt.org/torrentrss.php?passkey=32952e31a75f7f8e25cb90d6fb19a76c&rows=100&cat403=1&cat402=1&cat405=1&cat404=1&cat401=1&tea1=1&tea2=1&tea3=1&tea4=1&tea8=1&linktype=dl"  # 👈 填入188节点里配置的 LongPT RSS 订阅链接
    },
    "004": {
        "name": "004 节点 (192.168.2.4)",
        "url": "http://192.168.2.4:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_url": "https://longpt.org/torrentrss.php?passkey=32952e31a75f7f8e25cb90d6fb19a76c&rows=100&cat403=1&cat402=1&cat405=1&cat404=1&cat401=1&tea1=1&tea2=1&tea3=1&tea4=1&tea8=1&linktype=dl"  # 👈 填入2.4节点里配置的 LongPT RSS 订阅链接
    }
}
# =================================================

class SafeRequester:
    """防半死连接包装器:强制短连接 + 偶发抖动自动重试"""
    @staticmethod
    def get(url, **kwargs):
        kwargs.setdefault('timeout', (5, 10))
        for i in range(2):
            try:
                with requests.Session() as s:
                    s.headers.update({'Connection': 'close'})
                    return s.get(url, **kwargs)
            except Exception as e:
                if i == 1: raise e

HTTP_SESSION = SafeRequester()
QBT_SESSIONS = {}
MEM_CACHE_OFFICIAL = {}
MEM_CACHE_RECENT = {}
CACHE_LOCK = threading.Lock()

def get_qbt_session(srv_id):
    cfg = QBT_SERVERS.get(srv_id)
    if not cfg:
        return None, None, "未找到该 qB 节点配置"
    base_url = cfg['url'].rstrip('/')
    sess = QBT_SESSIONS.get(srv_id)
    if not sess:
        sess = requests.Session()
        QBT_SESSIONS[srv_id] = sess

    try:
        test_r = sess.get(f"{base_url}/api/v2/app/version", timeout=3)
        if test_r.status_code == 200:
            return sess, base_url, None
    except Exception:
        pass

    for attempt in range(2):
        try:
            sess = requests.Session()
            QBT_SESSIONS[srv_id] = sess
            login_r = sess.post(
                f"{base_url}/api/v2/auth/login",
                data={"username": cfg.get("username", ""), "password": cfg.get("password", "")},
                headers={"Referer": base_url + "/", "Origin": base_url},
                timeout=5
            )
            if login_r.status_code == 200 and "Ok." in login_r.text:
                return sess, base_url, None
        except Exception as e:
            if attempt == 1:
                return None, None, f"无法连接 {base_url}: {str(e)}"
    return None, None, "qB 登录失败,请检查账号密码配置"

def load_cache(cache_type='official'):
    global MEM_CACHE_OFFICIAL, MEM_CACHE_RECENT
    filename = OFFICIAL_HISTORY_FILE if cache_type == 'official' else RECENT_HISTORY_FILE
    target_cache = MEM_CACHE_OFFICIAL if cache_type == 'official' else MEM_CACHE_RECENT
    
    with CACHE_LOCK:
        if not target_cache and os.path.exists(filename):
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    res = {str(item['id']): item for item in data}
                    if cache_type == 'official': MEM_CACHE_OFFICIAL = res
                    else: MEM_CACHE_RECENT = res
                    return res
            except Exception: pass
    return target_cache

def save_cache(cache_dict, cache_type='official'):
    global MEM_CACHE_OFFICIAL, MEM_CACHE_RECENT
    filename = OFFICIAL_HISTORY_FILE if cache_type == 'official' else RECENT_HISTORY_FILE
    with CACHE_LOCK:
        if cache_type == 'official': MEM_CACHE_OFFICIAL = cache_dict.copy()
        else: MEM_CACHE_RECENT = cache_dict.copy()
        
        merged = list(cache_dict.values())
        merged.sort(key=lambda x: int(x['id']), reverse=True)
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(merged[:500], f, ensure_ascii=False, indent=2)
        except Exception: pass

TECH_KEYWORDS = [
    'FREE', '50%', '30%', '2X', '热门', '官方', '中字', '英字', '国语', '粤语', '英语', 
    '简繁', '双语', '杜比', '高帧', '高码', '臻彩MAX', '高分', '完结', '4K', '2160P', '1440P', '1080P', '720P', 
    'WEB-DL', 'BLU-RAY', 'REMUX', 'HDR10+', 'HDR10', 'HDRVIVID', 
    'HDR', 'DOVI', 'DV', 'SDR', '60FPS', 'HFR', 'HQ', 'H.265', 'H.264', 'H265', 'H264', 
    'HEVC', 'AAC', 'DDP', 'ATMOS', '10BIT', '首发', '禁转', '应求', 'DIY', '字幕'
]

def purify_tags(tags):
    valid = []
    for t in tags:
        clean_t = t.upper()
        if '剩余' in clean_t or '🕒' in clean_t:
            valid.append(t)
        elif clean_t in [k.upper() for k in TECH_KEYWORDS] or re.match(r'^[\d]+%$', clean_t):
            valid.append(t)
            
    final_tags = []
    time_tags = [t for t in valid if '剩余' in t]
    best_time = max(time_tags, key=len) if time_tags else None
    
    clock_tags = [t for t in valid if '🕒' in t]
    best_clock = clock_tags[-1] if clock_tags else None
    
    if best_time and best_clock:
        pure_time = re.sub(r'^.*?(?:剩余时间|免费剩余)[::\s]*', '', best_time).strip()
        pure_clock = best_clock.replace('🕒', '').strip()
        if pure_time == pure_clock:
            best_clock = None
            
    for t in valid:
        if '剩余' in t:
            if t == best_time and best_time not in final_tags:
                if not re.match(r'^剩余时间[::\s]*\d+\s*分$', t):
                    final_tags.append(t)
        elif '🕒' in t:
            if t == best_clock and best_clock not in final_tags:
                final_tags.append(t)
        elif t not in final_tags:
            final_tags.append(t)
            
    return final_tags

def merge_tags_list(list_tags, cached_tags):
    res = list(list_tags)
    for t in cached_tags:
        t_up = t.upper()
        is_dynamic = '%' in t_up or '2X' in t_up or t_up in ['FREE', '免费'] or '剩余' in t_up
        if not is_dynamic and t not in res:
            res.append(t)
    return res

def merge_tags_details(details_tags, cached_tags):
    res = list(details_tags)
    has_discount = any('%' in x.upper() or '2X' in x.upper() for x in res)
    has_free = any(x.upper() in ['FREE', '免费'] for x in res)
    has_time = any('剩余' in x for x in res)
    has_clock = any('🕒' in x for x in res)
    
    for t in cached_tags:
        if t in res: continue
        t_up = t.upper()
        if '%' in t_up or '2X' in t_up:
            if not has_discount: res.append(t)
        elif t_up in ['FREE', '免费']:
            if not has_free: res.append(t)
        elif '剩余' in t_up:
            if not has_time: res.append(t)
        elif '🕒' in t_up:
            if not has_clock: res.append(t)
        else:
            res.append(t)
    return res

def auto_extract_tags(text, current_tags):
    en_matches = re.findall(r'(?i)\b(4K|2160P|1440P|1080P|720P|WEB-DL|BLU-RAY|REMUX|HDR10\+|HDR10|HDRVIVID|HDR|DOVI|DV|SDR|60FPS|HFR|HQ|H\.?265|H\.?264|HEVC|AAC|DDP|ATMOS|10BIT)\b', text)
    cn_matches = re.findall(r'(杜比|高帧|高码|臻彩MAX|高分|完结|国语|中字|英字|粤语|英语|简繁|双语|官方|首发)', text)
    disc_matches = re.findall(r'(50%|30%|2X)', text.upper())
    
    all_new = [m.upper() for m in en_matches] + cn_matches + disc_matches
    for tag in all_new:
        tag_up = tag.upper()
        if not any(tag_up in t.upper() or t.upper() in tag_up for t in current_tags):
            current_tags.append(tag)
    return current_tags

def sort_tags(tags):
    top_pri, top_sec, bot_disc, bot_pri, bot_sec = [], [], [], [], []
    remaining = list(tags)
    
    t_res = ['4K', '2160P', '1440P', '1080P', '720P']
    t_hdr = ['HDRVIVID', 'HDR10+', 'HDR10', 'HDR', 'DOVI', 'DV', 'SDR']
    t_fps = ['60FPS', 'HFR', '高帧', '臻彩MAX', 'BLU-RAY', 'REMUX']
    t_enc = ['WEB-DL', 'H.265', 'H.264', 'H265', 'H264', 'HEVC', 'AAC', 'DDP', 'ATMOS', '杜比', '10BIT', 'HQ', '高码']
    
    for t in list(remaining):
        t_upper = t.upper()
        if '%' in t_upper or '2X' in t_upper or t_upper in ['免费', 'FREE', '30%', '50%']:
            if t_upper not in ['FREE', '免费']:
                bot_disc.append(t)
            remaining.remove(t)
    
    t_status = ['热门', '完结', '首发', '高分', 'DIY']
    t_lang = ['国语', '中字', '英字', '粤语', '英语', '简繁', '双语', '官方', '字幕']
    
    for kw in t_res + t_hdr + t_fps:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                top_pri.append(t)
                remaining.remove(t)
                
    for kw in t_enc:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                top_sec.append(t)
                remaining.remove(t)
                
    for kw in t_status:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                bot_pri.append(t)
                remaining.remove(t)
                
    for kw in t_lang:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                bot_sec.append(t)
                remaining.remove(t)
                
    for t in list(remaining):
        bot_pri.append(t)
        
    return top_pri, top_sec, bot_disc, bot_pri, bot_sec

def fetch_details_info(tid):
    try:
        r = HTTP_SESSION.get(f"{BASE_URL}/details.php?id={tid}", headers=HEADERS, proxies=PROXIES)
        raw_html = r.text
        soup = BeautifulSoup(raw_html, 'html.parser')
        extra_tags = []

        time_match = re.search(r'(?:免费剩余时间|免费剩余|优惠剩余时间|剩余时间|还有|剩余)[^\d<]{0,30}(?:<[^>]+>)*\s*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', raw_html)
        if time_match:
            extra_tags.append(f"剩余时间: {time_match.group(1).strip()}")
        else:
            text_clean = soup.get_text(separator=' ')
            tm2 = re.search(r'(?:免费剩余时间|免费剩余|优惠剩余时间|剩余时间|还有|剩余)[::\s]+(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', text_clean)
            if tm2: extra_tags.append(f"剩余时间: {tm2.group(1).strip()}")

        img_src = ""
        descr_div = soup.find('div', id='kdescr')
        if descr_div:
            img = descr_div.find('img')
            if img: 
                img_src = img.get('data-src') or img.get('src') or ""
                if img_src and not img_src.startswith('http'):
                    img_src = f"{BASE_URL}/" + img_src

        size = "未知"
        size_match = re.search(r'大小.*?([\d\.]+\s*[KMGTP]B)', raw_html, re.IGNORECASE)
        if size_match: size = size_match.group(1)

        h1 = soup.find('h1')
        release_group = ""
        h1_text = ""
        if h1:
            h1_text = h1.get_text(strip=True)
            for kw in ['免费', 'FREE', '50%', '30%', '2X']:
                if kw in h1_text.upper():
                    if kw in ['免费', 'FREE']:
                        if 'Free' not in extra_tags: extra_tags.append('Free')
                    else:
                        if kw not in extra_tags: extra_tags.append(kw)
            
            for span in h1.find_all('span', class_=re.compile(r'tag|label|badge', re.I)):
                text = span.get_text(strip=True).replace('[', '').replace(']', '').strip()
                if text.upper() in ['FREE', '免费'] and 'Free' not in extra_tags: extra_tags.append('Free')
                elif text and text not in extra_tags and len(text) <= 15: extra_tags.append(text)
                    
            group_match = re.search(r'-([A-Za-z0-9@_]+)$', h1_text)
            if group_match: release_group = group_match.group(1).upper()

        sub_td = soup.find('td', class_='rowhead', string=re.compile('副标题|副標題'))
        sub_text = ""
        if sub_td:
            sub_text = sub_td.find_next_sibling('td').get_text(strip=True)
            
        extra_tags = auto_extract_tags(h1_text + " " + sub_text, extra_tags)
        
        page_clean_text = soup.get_text(separator=' ')
        pub_exact = re.search(r'(?:发布时间|添加时间|上传时间|创建时间)[^\d]*(\d{4}-\d{2}-\d{2}\s*\d{2}:\d{2}(?::\d{2})?)', page_clean_text)
        if pub_exact:
            extra_tags.append(f"🕒 {pub_exact.group(1)}")
        else:
            pub_rel = re.search(r'发布于\s*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)\s*前', page_clean_text)
            if pub_rel:
                extra_tags.append(f"🕒 {re.sub(r'\s+', '', pub_rel.group(1))}前")
        
        return img_src, size, purify_tags(extra_tags), release_group
    except Exception:
        return "", "未知", [], ""

def is_real_sticky(row):
    for img in row.find_all('img'):
        src = img.get('src', '').lower()
        alt = img.get('alt', '').lower()
        title = img.get('title', '').lower()
        cls = ' '.join(img.get('class', [])).lower()
        if 'sticky' in cls: return True
        if alt in ['sticky', '置顶'] or title in ['sticky', '置顶']: return True
        if any(x in src for x in ['sticky.gif', 'pin.gif', 'pro_sticky.gif']): return True
    for tag in row.find_all(['span', 'font', 'b']):
        t = tag.get_text(strip=True).upper()
        if t in ['[置顶]', '置顶', '[STICKY]', 'STICKY']: return True
        if 'sticky' in ' '.join(tag.get('class', [])).lower(): return True
    tr_cls = ' '.join(row.get('class', [])).lower()
    if any(x in tr_cls for x in ['sticky_bg', 'sticky_blank', 'pro_sticky']): return True
    return False

def parse_torrents_page(target_url_base, seen_ids, is_search=False, skip_sticky=False, start_page=0, max_pages=1):
    torrents = []
    try:
        for page in range(start_page, start_page + max_pages):
            url = f"{target_url_base}&page={page}" if "?" in target_url_base else f"{target_url_base}?page={page}"
            resp = HTTP_SESSION.get(url, headers=HEADERS, proxies=PROXIES)
            
            if "登录" in resp.text and "torrents.php" not in resp.url: return None, "⚠️ Cookie 已失效!请更新。"
            if resp.status_code != 200: break

            soup = BeautifulSoup(resp.text, 'html.parser')
            for row in soup.find_all('tr'):
                if skip_sticky and is_real_sticky(row): continue

                tds = row.find_all('td')
                if len(tds) < 6: continue
                title_a = row.find('a', href=lambda h: h and h.startswith('details.php?id='))
                if not title_a: continue
                
                tid = re.search(r'id=(\d+)', title_a['href']).group(1)
                title = title_a.get('title') or title_a.get_text(strip=True)
                if not title and title_a.find('b'): title = title_a.find('b').get_text(strip=True)
                if not title or tid in seen_ids: continue
                seen_ids.add(tid)
                link = f"{BASE_URL}/" + title_a['href']
                
                release_group = ""
                group_match = re.search(r'-([A-Za-z0-9@_]+)$', title.strip())
                if group_match: release_group = group_match.group(1)
                
                try: 
                    size = tds[-5].get_text(strip=True)
                    seeders = tds[-4].get_text(strip=True)
                    leechers = tds[-3].get_text(strip=True)
                    time_col_td = tds[-6]
                except: 
                    size, seeders, leechers, time_col_td = "未知", "-", "-", None

                img_src = ""
                td = title_a.find_parent('td')
                tags = []
                
                if time_col_td:
                    time_span = time_col_td.find('span', title=re.compile(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'))
                    t_text = time_span.get_text(separator='', strip=True) if time_span else time_col_td.get_text(separator='', strip=True)
                    if t_text and any(x in t_text for x in ['年', '月', '周', '天', '时', '分', '秒']):
                        clean_t = re.sub(r'\s+', '', t_text)
                        if not clean_t.endswith('前') and not re.search(r'\d{4}-\d{2}-\d{2}', clean_t):
                            clean_t += '前'
                        tags.append(f"🕒 {clean_t}")
                    elif re.search(r'\d{4}-\d{2}-\d{2}', t_text):
                        tags.append(f"🕒 {t_text.strip()}")
                
                subtitle = ""
                if td:
                    raw_html = str(td)
                    
                    if not any('🕒' in t for t in tags):
                        t_match = re.search(r'\b(20\d{2}-\d{2}-\d{2}\s+\d{2}:\d{2}(?::\d{2})?)\b', raw_html)
                        if t_match: tags.append(f"🕒 {t_match.group(1)}")

                    time_matches = re.finditer(r'(?:免费剩余时间|免费剩余|剩余时间|剩余)[::\s]*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', raw_html)
                    for tm in time_matches: tags.append(f"剩余时间: {tm.group(1).strip()}")

                    for icon in td.find_all('img'):
                        alt = str(icon.get('alt') or '')
                        title_attr = str(icon.get('title') or '')
                        combined_text = alt + " " + title_attr
                        if '免费' in combined_text or 'Free' in combined_text:
                            if 'Free' not in tags: tags.append('Free')
                        if icon.get('src', '') != img_src: 
                            icon.replace_with(soup.new_tag("span", string=f" [{alt}] "))
                    
                    for span in td.find_all('span'):
                        text = span.get_text(strip=True)
                        title_attr = str(span.get('title') or '')
                        combined = (text + " " + title_attr).upper()
                        if 'FREE' in combined or '免费' in combined:
                            if 'Free' not in tags: tags.append('Free')
                        for disc in ['50%', '30%', '2X']:
                            if disc in combined and disc not in tags: tags.append(disc)
                                
                        text_clean = text.replace('[', '').replace(']', '').strip()
                        if not text_clean: continue
                        span_class = ' '.join(span.get('class', [])).lower()
                        if bool(re.search(r'tag|label|badge', span_class)) or text_clean.upper() in [k.upper() for k in TECH_KEYWORDS] or re.match(r'^[\d]+%$', text_clean):
                            if text_clean not in tags: tags.append(text_clean)
                            span.replace_with(soup.new_tag("span", string=f" [{text_clean}] "))
                    
                    subtitle = td.get_text(separator=' | ', strip=True).replace(title, '').strip(' | ')
                    subtitle = re.sub(r'(?i)\[?(?:Sticky|置顶|poster)\]?[\s\|]*', '', subtitle)
                    
                    inline_time = re.search(r'\[?(?:剩余时间)[::\s]*\]?[\s\|]*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', subtitle)
                    if inline_time:
                        t_str = f"剩余时间: {inline_time.group(1).strip()}"
                        if t_str not in tags: tags.append(t_str)
                        subtitle = subtitle.replace(inline_time.group(0), '')
                    
                    clean_sub = subtitle
                    for m in re.finditer(r'\[(.*?)\]', subtitle):
                        tag = m.group(1).strip(' |[]')
                        if tag.upper() in [k.upper() for k in TECH_KEYWORDS] or re.match(r'^[\d]+%$', tag) or tag.upper() in ['热门']:
                            if tag not in tags: tags.append(tag)
                            clean_sub = clean_sub.replace(m.group(0), '')
                        else: clean_sub = clean_sub.replace(m.group(0), tag)
                    
                    clean_sub = re.sub(r'热门|免费', '', clean_sub)
                    parts = [p.strip() for p in clean_sub.split('|') if p.strip()]
                    kept_sub = []
                    for p in parts:
                        clean_p = re.sub(r'^[()\[\]\-|\s]+|[()\[\]\-|\s]+$', '', p)
                        if not clean_p: continue
                        if clean_p.upper() in [k.upper() for k in TECH_KEYWORDS]:
                            if clean_p not in tags: tags.append(clean_p)
                        else: kept_sub.append(p)
                    subtitle = ' | '.join(kept_sub)
                
                tags = auto_extract_tags(title + " " + subtitle, tags)
                tags = purify_tags(tags)

                torrents.append({
                    'id': tid, 'title': title, 'link': link, 'subtitle': subtitle, 'img': img_src,
                    'seeders': seeders, 'leechers': leechers, 'size': size, 'tags': tags, 'group': release_group
                })
                
                if len(torrents) >= 50 and max_pages > 1: break
            if len(torrents) >= 50 and max_pages > 1: break
        return torrents, None
    except Exception as e:
        return None, f"网络请求异常: {str(e)}"

def parse_index_page(seen_ids):
    torrents = []
    try:
        resp = HTTP_SESSION.get(INDEX_URL, headers=HEADERS, proxies=PROXIES)
        if "登录" in resp.text and "index.php" not in resp.url: return None, "⚠️ Cookie 已失效!"
        
        if resp.status_code == 200:
            soup = BeautifulSoup(resp.text, 'html.parser')
            cached_recent = load_cache('recent')
            
            for title_a in soup.find_all('a', href=lambda h: h and h.startswith('details.php?id=')):
                tid_m = re.search(r'id=(\d+)', title_a['href'])
                if not tid_m: continue
                tid = tid_m.group(1)
                if tid in seen_ids: continue
                
                title = title_a.get('title') or title_a.get_text(strip=True)
                if not title and title_a.find('img'): title = title_a.find('img').get('alt') or title_a.find('img').get('title')
                if not title: continue
                seen_ids.add(tid)
                
                link = f"{BASE_URL}/details.php?id={tid}"
                container = title_a.find_parent('tr') or title_a.find_parent('div')
                
                img_src, subtitle, seeders, leechers, size = "", "", "-", "-", "加载中..."
                tags = []
                release_group = ""
                
                group_match = re.search(r'-([A-Za-z0-9@_]+)$', title.strip())
                if group_match: release_group = group_match.group(1)
                    
                if container:
                    if container.name == 'tr':
                        tds = container.find_all('td')
                        if len(tds) >= 3:
                            seeders, leechers = tds[-2].get_text(strip=True), tds[-1].get_text(strip=True)
                            for td in tds:
                                txt = td.get_text(strip=True)
                                if re.match(r'^\d+(\.\d+)?\s*[KMGTP]B$', txt, re.I):
                                    size = txt
                                    break
                            
                    subtitle = container.get_text(separator=' | ', strip=True).replace(title, '').strip(' | ')
                    if seeders != "-" and subtitle.endswith(leechers): subtitle = subtitle.rsplit('|', 2)[0].strip(' | ')
                    subtitle = re.sub(r'(?i)\[?(?:Sticky|置顶|poster)\]?[\s\|]*', '', subtitle)
                    subtitle = re.sub(r'(?i)^\s*\[?新\]?\s*\|\s*', '', subtitle)

                    text_clean = container.get_text(separator=' ', strip=True)
                    t_match = re.search(r'\b(20\d{2}-\d{2}-\d{2}\s+\d{2}:\d{2}(?::\d{2})?)\b', text_clean)
                    if t_match: tags.append(f"🕒 {t_match.group(1)}")
                    else:
                        rel_m = re.search(r'(?:发布于)?\s*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)\s*前', text_clean)
                        if rel_m: tags.append(f"🕒 {re.sub(r'\s+', '', rel_m.group(1))}前")

                tags = auto_extract_tags(title + " " + subtitle, tags)
                
                tid_str = str(tid)
                if tid_str in cached_recent:
                    cached_item = cached_recent[tid_str]
                    tags = merge_tags_details(tags, cached_item.get('tags', []))
                    if cached_item.get('img') and 'data:image/svg+xml' not in cached_item['img']: img_src = cached_item['img']
                    if cached_item.get('size') and cached_item.get('size') not in ['未知', '加载中...']: size = cached_item['size']
                
                tags = purify_tags(tags)
                torrents.append({
                    'id': tid, 'title': title, 'link': link, 'subtitle': subtitle, 'img': img_src,
                    'seeders': seeders, 'leechers': leechers, 'size': size, 'tags': tags, 'group': release_group
                })
            return torrents, None
        return None, f"获取最新种子失败,状态码: {resp.status_code}"
    except Exception as e:
        return None, f"网络请求异常: {str(e)}"

def background_monitor():
    last_sign_date = None
    last_draw_date = None
    while True:
        try:
            current_time = datetime.datetime.now()
            current_date_str = current_time.strftime("%Y-%m-%d")
            
            if last_sign_date != current_date_str:
                r_sign = HTTP_SESSION.get(SIGNIN_URL, headers=HEADERS, proxies=PROXIES)
                r_sign.encoding = 'utf-8'
                if any(kw in r_sign.text for kw in ["已经签到", "请明天再来", "签到成功", "魔力值", "次签到", "退下", "已经", "这是您的第"]):
                    last_sign_date = current_date_str

            if last_draw_date != current_date_str:
                h = current_time.hour
                m = current_time.minute
                if (h == 0 and m >= 45) or (h == 1 and m <= 30):
                    time.sleep(random.randint(1, 300))
                    try:
                        HTTP_SESSION.get(f"{BASE_URL}/pt-api/v1/lucky/pluginsPrizeReceiptRecord/join", headers=HEADERS, proxies=PROXIES, timeout=5)
                        last_draw_date = current_date_str
                    except: pass
        except Exception: pass

        try:
            current_off, err = parse_torrents_page(OFFICIAL_URL, set(), skip_sticky=False, max_pages=2)
            if current_off:
                off_dict = load_cache('official')
                for item in current_off[:5]:
                    tid_str = str(item['id'])
                    if tid_str not in off_dict or not off_dict[tid_str].get('img') or 'data:image/svg+xml' in off_dict[tid_str]['img'] or off_dict[tid_str].get('size') in ['未知', '加载中...']:
                        det_img, det_size, det_tags, det_group = fetch_details_info(item['id'])
                        if det_img: item['img'] = det_img
                        if det_size and det_size != "未知": item['size'] = det_size
                        if det_group and not item.get('group'): item['group'] = det_group
                        if det_tags:
                            item['tags'] = purify_tags(merge_tags_details(det_tags, item.get('tags', [])))

                    if tid_str in off_dict:
                        cached = off_dict[tid_str]
                        if cached.get('img') and 'data:image/svg+xml' not in cached['img']: item['img'] = cached['img']
                        if cached.get('size') not in ['未知', '加载中...']: item['size'] = cached['size']
                        if not item.get('group') and cached.get('group'): item['group'] = cached['group']
                        item['tags'] = purify_tags(merge_tags_list(item.get('tags', []), cached.get('tags', [])))
                        
                    off_dict[tid_str] = item
                save_cache(off_dict, 'official')
        except Exception: pass

        try:
            current_rec, err = parse_index_page(set())
            if current_rec:
                rec_dict = load_cache('recent')
                for item in current_rec:
                    tid_str = str(item['id'])
                    if tid_str not in rec_dict or not rec_dict[tid_str].get('img') or 'data:image/svg+xml' in rec_dict[tid_str]['img'] or rec_dict[tid_str].get('size') in ['未知', '加载中...']:
                        det_img, det_size, det_tags, det_group = fetch_details_info(item['id'])
                        if det_img: item['img'] = det_img
                        if det_size and det_size != "未知": item['size'] = det_size
                        if det_group and not item.get('group'): item['group'] = det_group
                        if det_tags:
                            item['tags'] = purify_tags(merge_tags_details(det_tags, item.get('tags', [])))

                    if tid_str in rec_dict:
                        cached = rec_dict[tid_str]
                        if cached.get('img') and 'data:image/svg+xml' not in cached['img']: item['img'] = cached['img']
                        if cached.get('size') not in ['未知', '加载中...']: item['size'] = cached['size']
                        if not item.get('group') and cached.get('group'): item['group'] = cached['group']
                        item['tags'] = purify_tags(merge_tags_details(item.get('tags', []), cached.get('tags', [])))
                        
                    rec_dict[tid_str] = item
                save_cache(rec_dict, 'recent')
        except Exception: pass

        time.sleep(900)

threading.Thread(target=background_monitor, daemon=True).start()

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>LongPT 手机端</title>
    <style>
        :root { --bg-color: #f7f7f7; --card-bg: #ffffff; --text-main: #333333; --text-sub: #888888; --border-color: #eeeeee; --topbar-bg: #ffffff; --icon-bg: #f0f0f5; --primary-color: #2563eb; }
        [data-theme="dark"] { --bg-color: #121212; --card-bg: #1e1e1e; --text-main: #eeeeee; --text-sub: #aaaaaa; --border-color: #333333; --topbar-bg: #1e1e1e; --icon-bg: #333333; --primary-color: #3b82f6; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background-color: var(--bg-color); color: var(--text-main); margin: 0; padding: 0; padding-top: 55px; transition: background-color 0.3s; }
        
        .top-bar { position: fixed; top: 0; left: 0; right: 0; height: 50px; background: var(--topbar-bg); display: flex; align-items: center; justify-content: space-between; padding: 0 15px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); z-index: 100; transition: background 0.3s; }
        .menu-btn { width: 22px; height: 16px; position: relative; cursor: pointer; display: flex; flex-direction: column; justify-content: space-between; padding: 0; }
        .menu-btn span { display: block; height: 2px; width: 100%; background: var(--text-main); border-radius: 2px; transition: all 0.3s ease; }
        .menu-btn.open span:nth-child(1) { transform: translateY(7px) rotate(45deg); }
        .menu-btn.open span:nth-child(2) { opacity: 0; }
        .menu-btn.open span:nth-child(3) { transform: translateY(-7px) rotate(-45deg); }

        .logo { font-weight: 800; font-size: 20px; color: var(--text-main); letter-spacing: 1px; }
        .theme-half-circle { width: 24px; height: 24px; cursor: pointer; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: transform 0.35s ease; color: var(--text-main); user-select: none; }
        [data-theme="dark"] .theme-half-circle { transform: rotate(180deg); }

        .sidebar { position: fixed; top: 0; left: -260px; bottom: 0; width: 260px; background: var(--card-bg); z-index: 1001; transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 2px 0 10px rgba(0,0,0,0.1); padding-top: 60px; display: flex; flex-direction: column; }
        .sidebar.open { left: 0; }
        .menu-item { padding: 16px 24px; font-size: 16px; font-weight: 500; color: var(--text-main); text-decoration: none; display: block; border-bottom: 1px solid var(--border-color); }
        .menu-item.active { color: var(--primary-color); border-left: 4px solid var(--primary-color); padding-left: 20px; background: rgba(37,99,235,0.05); }
        .overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1000; opacity: 0; pointer-events: none; transition: opacity 0.3s; }
        .overlay.open { opacity: 1; pointer-events: auto; }

        .container { padding: 5px 10px 10px 10px; }
        .global-search-container { display: flex; gap: 8px; margin: 5px 5px 15px 5px; align-items: center; background: var(--card-bg); padding: 5px; border-radius: 20px; border: 1px solid var(--border-color); }
        .search-input { flex: 1; padding: 8px 15px; border: none; outline: none; font-size: 14px; background: transparent; color: var(--text-main); }
        .search-btn { background: rgba(37,99,235,0.1); color: var(--primary-color); border: none; width: 36px; height: 36px; border-radius: 18px; font-weight: bold; font-size: 16px; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        
        .list-item { display: flex; gap: 12px; padding: 15px 5px; border-bottom: 1px solid var(--border-color); }
        .poster-wrapper { position: relative; flex-shrink: 0; width: 100px; height: 140px; }
        .poster { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; background-color: #e0e0e0; }
        .tag-free { position: absolute; top: 0; left: 0; background: #22c55e; color: #fff; font-size: 10px; font-weight: bold; padding: 2px 6px; border-radius: 8px 0 8px 0; z-index: 10; }
        
        .info { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; justify-content: space-between; padding-bottom: 2px; }
        .title { font-size: 15px; font-weight: bold; margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height: 1.3; cursor: pointer; }
        .subtitle { font-size: 12px; color: var(--text-sub); line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; margin-bottom: 4px; }
        .subtitle:empty { display: none; margin: 0; }
        
        .stats-and-download { display: flex; justify-content: space-between; align-items: center; gap: 8px; width: 100%; margin-bottom: 4px; }
        .stats-row { font-size: 12px; color: var(--text-sub); display: flex; align-items: center; gap: 6px; overflow-x: auto; white-space: nowrap; scrollbar-width: none; flex: 1; min-width: 0; }
        .stats-row::-webkit-scrollbar { display: none; }
        .stat-item { display: flex; align-items: center; gap: 2px; flex-shrink: 0; }
        .seed-icon { color: #22c55e; font-size: 10px; }
        .leech-icon { color: #ef4444; font-size: 10px; }
        
        .tags-wrapper { display: flex; flex-direction: column; gap: 6px; margin-top: auto; width: 100%; overflow: hidden; padding-top: 2px; }
        .tags-top, .tags-bottom { display: flex; gap: 6px; overflow-x: auto; white-space: nowrap; scrollbar-width: none; align-items: center; }
        .tags-top:empty, .tags-bottom:empty { display: none; }
        .secondary-tag { display: none !important; }
        .show-extra .secondary-tag { display: inline-flex !important; }
        .badge-toggle { background: #e5e7eb; color: #6b7280; font-size: 10px; padding: 2px 8px; border-radius: 4px; flex-shrink: 0; cursor: pointer; font-weight: bold; }
        [data-theme="dark"] .badge-toggle { background: #374151; color: #9ca3af; }
        
        .badge { background: #8b5cf6; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-discount { background: #ef4444; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-tech { background: #0ea5e9; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-lang { background: #10b981; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-group { background: #ec4899; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; font-weight: bold; } 
        .badge-longweb { background: linear-gradient(135deg, #2563eb 0%, #06b6d4 100%); color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; font-weight: bold; }

        .download-btn { background: var(--primary-color); color: #fff; font-size: 11px; padding: 3px 9px; border-radius: 4px; font-weight: bold; border: none; cursor: pointer; flex-shrink: 0; }

        /* 底部滑出式多功能面板(单集推送 + 精准RSS建规则) */
        .qbt-modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.55); z-index: 2000; opacity: 0; pointer-events: none; transition: opacity 0.25s; }
        .qbt-modal-mask.open { opacity: 1; pointer-events: auto; }
        .qbt-sheet { position: fixed; left: 0; right: 0; bottom: -100%; background: var(--card-bg); border-radius: 16px 16px 0 0; padding: 16px 16px 24px 16px; z-index: 2001; transition: bottom 0.28s cubic-bezier(0.2, 0.8, 0.2, 1); max-height: 86vh; overflow-y: auto; box-shadow: 0 -4px 20px rgba(0,0,0,0.18); }
        .qbt-sheet.open { bottom: 0; }
        .qbt-sheet-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .qbt-sheet-title { font-size: 14px; font-weight: bold; color: var(--text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 88%; }
        .qbt-close { font-size: 20px; color: var(--text-sub); cursor: pointer; padding: 0 4px; }
        
        /* 模式切换分段器 */
        .mode-tabs { display: flex; background: var(--bg-color); padding: 4px; border-radius: 10px; border: 1px solid var(--border-color); margin-bottom: 10px; }
        .mode-tab { flex: 1; text-align: center; padding: 7px 0; font-size: 13px; font-weight: bold; border-radius: 7px; cursor: pointer; color: var(--text-sub); transition: all 0.2s; }
        .mode-tab.active { background: var(--primary-color); color: #fff; box-shadow: 0 2px 6px rgba(37,99,235,0.25); }

        .qbt-sec-lbl { font-size: 12px; font-weight: bold; color: var(--text-sub); margin: 11px 0 5px 0; display: flex; justify-content: space-between; align-items: center; }
        .qbt-pills { display: flex; flex-wrap: wrap; gap: 7px; }
        .qbt-pill { font-size: 12px; padding: 5px 11px; border-radius: 15px; background: var(--bg-color); color: var(--text-main); border: 1px solid var(--border-color); cursor: pointer; user-select: none; }
        .qbt-pill.active { background: var(--primary-color); color: #fff; border-color: var(--primary-color); font-weight: bold; }
        .qbt-pill.spec-pill.active { background: #0ea5e9; border-color: #0ea5e9; }
        .qbt-input { width: 100%; box-sizing: border-box; padding: 8px 11px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-color); color: var(--text-main); font-size: 12px; margin-top: 4px; outline: none; font-family: monospace; }
        .qbt-check-row { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; font-size: 12px; color: var(--text-main); background: var(--bg-color); padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); }
        .qbt-actions { display: flex; gap: 10px; margin-top: 16px; }
        .qbt-submit-btn { flex: 1; background: var(--primary-color); color: #fff; border: none; padding: 11px; border-radius: 8px; font-size: 14px; font-weight: bold; cursor: pointer; }
        .qbt-direct-link { padding: 11px 14px; border-radius: 8px; background: var(--bg-color); color: var(--text-sub); font-size: 13px; text-decoration: none; border: 1px solid var(--border-color); text-align: center; font-weight: 500; }

        /* RSS 规则列表卡片样式 */
        .rss-card { background: var(--card-bg); border-radius: 10px; padding: 14px; margin-bottom: 10px; border: 1px solid var(--border-color); }
        .rss-card-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
        .rss-rule-name { font-size: 15px; font-weight: bold; color: var(--text-main); }
        .rss-meta { font-size: 12px; color: var(--text-sub); line-height: 1.6; word-break: break-all; }
        .rss-regex-box { background: var(--bg-color); padding: 6px 8px; border-radius: 6px; font-family: monospace; font-size: 11px; color: var(--primary-color); margin: 6px 0; border: 1px solid var(--border-color); word-break: break-all; }
        .rss-del-btn { background: #fee2e2; color: #dc2626; border: none; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: bold; cursor: pointer; }
        .rss-toggle-btn { background: #dcfce7; color: #15803d; border: none; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: bold; cursor: pointer; margin-right: 6px; }
        .rss-toggle-btn.off { background: #f4f4f5; color: #71717a; }

        .account-box { background: var(--card-bg); border-radius: 12px; padding: 20px; text-align: center; border: 1px solid var(--border-color); }
        .avatar { width: 70px; height: 70px; background: var(--primary-color); color: #fff; border-radius: 35px; line-height: 70px; font-size: 24px; margin: 0 auto 10px; }
        .account-name { font-size: 18px; font-weight: bold; }
        .stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 20px; }
        .stat-val { font-size: 18px; font-weight: bold; color: var(--primary-color); margin-bottom: 4px; }
        .stat-lbl { font-size: 12px; color: var(--text-sub); }
        .btn-signin { background: #22c55e; color: #fff; width: 100%; padding: 12px; font-size: 16px; border-radius: 8px; font-weight: bold; margin-top: 25px; border: none; cursor: pointer; }
        .btn-lottery { background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%); color: #fff; width: 100%; padding: 12px; font-size: 16px; border-radius: 8px; font-weight: bold; margin-top: 15px; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <script>
        function setTheme(theme) {
            const html = document.documentElement;
            if (theme === 'dark') { html.setAttribute('data-theme', 'dark'); }
            else if (theme === 'light') { html.removeAttribute('data-theme'); }
            else { 
                if (window.matchMedia('(prefers-color-scheme: dark)').matches) html.setAttribute('data-theme', 'dark');
                else html.removeAttribute('data-theme');
            }
        }
        let currentTheme = localStorage.getItem('longpt_theme') || 'auto';
        setTheme(currentTheme);
        
        window.toggleTags = function(btn) {
            const wrapper = btn.closest('.tags-wrapper');
            wrapper.classList.toggle('show-extra');
            btn.innerText = wrapper.classList.contains('show-extra') ? '收起 ▴' : '... ▾';
        };
    </script>

    <div class="top-bar">
        <div class="menu-btn" id="menuBtn" onclick="toggleMenu()">
            <span></span><span></span><span></span>
        </div>
        <div class="logo">🌟 LongPT</div>
        <div class="theme-half-circle" onclick="cycleTheme()" title="切换深浅模式">
            <svg viewBox="0 0 24 24" width="20" height="20">
                <circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/>
                <path d="M 12 3 A 9 9 0 0 0 12 21 Z" fill="currentColor"/>
            </svg>
        </div>
    </div>

    <div class="overlay" id="overlay" onclick="toggleMenu()"></div>
    <div class="sidebar" id="sidebar">
        <a href="/?tab=official" class="menu-item {% if tab == 'official' %}active{% endif %}">官方发布</a>
        <a href="/?tab=recent" class="menu-item {% if tab == 'recent' %}active{% endif %}">最近发布</a>
        <a href="/?tab=rss" class="menu-item {% if tab == 'rss' %}active{% endif %}">📡 RSS 订阅规则</a>
        <a href="/?tab=account" class="menu-item {% if tab == 'account' %}active{% endif %}">我的帐号</a>
    </div>

    <!-- 🚀 底部多功能面板:单集直推 + 精准 RSS 自动追剧规则生成器 -->
    <div class="qbt-modal-mask" id="qbtMask" onclick="closeQbtModal()"></div>
    <div class="qbt-sheet" id="qbtSheet">
        <div class="qbt-sheet-header">
            <div class="qbt-sheet-title" id="qbtSheetTitle">操作面板</div>
            <div class="qbt-close" onclick="closeQbtModal()">✕</div>
        </div>

        <div class="mode-tabs">
            <div class="mode-tab active" id="modeTabPush" onclick="switchModalMode('push')">🚀 单集立即推送</div>
            <div class="mode-tab" id="modeTabRss" onclick="switchModalMode('rss')">📡 精准 RSS 追更</div>
        </div>

        <div class="qbt-sec-lbl">
            <span>1. 选择目标 qBittorrent 节点</span>
            <span id="qbtConnStatus" style="font-weight:normal; font-size:11px;"></span>
        </div>
        <div class="qbt-pills" id="qbtServerPills">
            {% for sid, scfg in qbt_servers.items() %}
            <div class="qbt-pill" data-srv="{{ sid }}" onclick="selectQbtServer('{{ sid }}')">{{ scfg.name }}</div>
            {% endfor %}
        </div>

        <div class="qbt-sec-lbl">
            <span>2. 选择分类 (自动同步所选节点)</span>
            <span id="qbtCatPath" style="font-weight:normal; font-size:11px; max-width:52%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"></span>
        </div>
        <div class="qbt-pills" id="qbtCatPills">
            <div class="qbt-pill active" data-cat="" onclick="selectQbtCat('', '')">不设分类(默认路径)</div>
        </div>

        <div class="qbt-sec-lbl"><span>3. 附加标签 (默认洗码,可点选追加)</span></div>
        <div class="qbt-pills" id="qbtTagPills"></div>
        <input type="text" id="qbtCustomTags" class="qbt-input" value="洗码" oninput="isTagsManuallyEdited = true">

        <!-- 📡 RSS 专属精准过滤配置区 -->
        <div id="rssConfigZone" style="display:none;">
            <div class="qbt-sec-lbl"><span>4. 规则名称 & 剧名/季数锁定 (自动剥离集数)</span></div>
            <input type="text" id="rssRuleName" class="qbt-input" placeholder="规则显示名称">
            <input type="text" id="rssShowCore" class="qbt-input" placeholder="剧名+季数核心,如: Shang Gong Zhu.*S01" oninput="rebuildRssRegex()">

            <div class="qbt-sec-lbl"><span>5. 精准画质/编码/制作组锁定 (点击切换必须包含项)</span></div>
            <div class="qbt-pills" id="rssSpecPills"></div>

            <div class="qbt-sec-lbl"><span>6. 最终正则预览 (mustContain,支持手动微调)</span></div>
            <input type="text" id="rssFinalRegex" class="qbt-input" placeholder="自动生成的精准正则">

            <div class="qbt-sec-lbl"><span>7. 排除关键词 (mustNotContain,防洗版/防合集包)</span></div>
            <input type="text" id="rssExcludeRegex" class="qbt-input" value="合集|Complete|Pack|全集|招募">

            <div class="qbt-check-row">
                <span>启用智能集数过滤 (Smart Filter 防同集重下)</span>
                <input type="checkbox" id="rssSmartFilter" style="width:18px; height:18px;">
            </div>
            <div class="qbt-check-row">
                <span>绑定该节点配置的固定 RSS 订阅源</span>
                <span id="rssFeedHint" style="font-size:11px; color:var(--primary-color); max-width:45%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"></span>
            </div>
        </div>

        <div class="qbt-actions">
            <button class="qbt-submit-btn" id="qbtSubmitBtn" onclick="handleModalSubmit()">🚀 立即推送到 qB</button>
            <a id="qbtDirectBtn" href="#" class="qbt-direct-link">原文件</a>
        </div>
    </div>

    <div class="container" id="list-container">
        {% if tab in ['official', 'recent', 'search'] %}
        <form class="global-search-container" action="/" method="GET">
            <input type="hidden" name="tab" value="search">
            <input type="text" name="q" class="search-input" placeholder="输入关键词搜全站..." value="{{ query }}">
            <button type="submit" class="search-btn">🔍</button>
        </form>
        {% endif %}

        {% if error %}<div style="text-align:center; color:#ef4444; margin-top:30px; font-weight:bold;">{{ error }}</div>{% endif %}

        {% if tab == 'rss' %}
            <div style="margin: 8px 4px 12px 4px;">
                <div style="font-size:13px; font-weight:bold; color:var(--text-sub); margin-bottom:8px;">选择要查看的 qBittorrent 节点:</div>
                <div class="qbt-pills" id="rssManageNodes">
                    {% for sid, scfg in qbt_servers.items() %}
                    <div class="qbt-pill {% if loop.first %}active{% endif %}" data-srv="{{ sid }}" onclick="loadNodeRssRules('{{ sid }}')">{{ scfg.name }}</div>
                    {% endfor %}
                </div>
            </div>
            <div id="rssRulesContainer" style="margin-top:10px;">
                <div style="text-align:center; padding:30px; color:var(--text-sub);">正在加载节点订阅规则...</div>
            </div>
            <script>
                document.addEventListener("DOMContentLoaded", function() {
                    const savedSrv = localStorage.getItem('longpt_qbt_srv') || '177';
                    loadNodeRssRules(savedSrv);
                });
                function loadNodeRssRules(srvId) {
                    localStorage.setItem('longpt_qbt_srv', srvId);
                    document.querySelectorAll('#rssManageNodes .qbt-pill').forEach(el => {
                        el.classList.toggle('active', el.getAttribute('data-srv') === srvId);
                    });
                    const box = document.getElementById('rssRulesContainer');
                    box.innerHTML = '<div style="text-align:center; padding:30px; color:var(--text-sub);">正在读取 qB RSS 规则...</div>';
                    fetch('/api/qbt/rss/rules?server=' + encodeURIComponent(srvId))
                        .then(r => r.json())
                        .then(d => {
                            if (!d.ok) {
                                box.innerHTML = `<div style="text-align:center; color:#ef4444; padding:20px;">⚠️ ${d.msg}</div>`;
                                return;
                            }
                            const rules = d.rules || [];
                            if (rules.length === 0) {
                                box.innerHTML = `<div style="text-align:center; color:var(--text-sub); padding:30px;">该节点暂无 RSS 自动下载规则<br><span style="font-size:12px;">去种子列表点击“推送” -> 切换到“RSS 追更”即可一键创建</span></div>`;
                                return;
                            }
                            let html = '';
                            rules.forEach(r => {
                                const safeName = r.name.replace(/'/g, "\\'");
                                html += `
                                <div class="rss-card">
                                    <div class="rss-card-top">
                                        <div class="rss-rule-name">${r.enabled ? '🟢' : '⏸️'} ${r.name}</div>
                                        <div>
                                            <button class="rss-toggle-btn ${r.enabled ? '' : 'off'}" onclick="toggleRssRule('${srvId}', '${safeName}', ${!r.enabled})">${r.enabled ? '运行中' : '已暂停'}</button>
                                            <button class="rss-del-btn" onclick="deleteRssRule('${srvId}', '${safeName}')">删除</button>
                                        </div>
                                    </div>
                                    <div class="rss-meta">
                                        📁 分类: <b>${r.assignedCategory || '未设'}</b> &nbsp;|&nbsp; 🏷️ 标签: <b>${(r.torrentParams && r.torrentParams.tags ? r.torrentParams.tags.join(',') : '') || '无'}</b>
                                    </div>
                                    <div class="rss-regex-box">匹配: ${r.mustContain || '(空)'}</div>
                                    ${r.mustNotContain ? `<div class="rss-meta" style="font-size:11px;">🚫 排除: ${r.mustNotContain}</div>` : ''}
                                    <div class="rss-meta" style="font-size:11px; margin-top:4px;">
                                        📌 智能集数过滤: ${r.smartFilter ? '开启' : '关闭'} &nbsp;|&nbsp; 历史命中: ${(r.previouslyMatchedEpisodes || []).length} 集
                                    </div>
                                </div>`;
                            });
                            box.innerHTML = html;
                        });
                }
                function toggleRssRule(srvId, ruleName, targetState) {
                    fetch('/api/qbt/rss/toggle', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({server: srvId, name: ruleName, enabled: targetState})
                    }).then(r => r.json()).then(d => {
                        if (d.ok) loadNodeRssRules(srvId);
                        else alert('❌ ' + d.msg);
                    });
                }
                function deleteRssRule(srvId, ruleName) {
                    if (!confirm('确定要删除追剧规则【' + ruleName + '】吗?')) return;
                    fetch('/api/qbt/rss/delete', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({server: srvId, name: ruleName})
                    }).then(r => r.json()).then(d => {
                        if (d.ok) loadNodeRssRules(srvId);
                        else alert('❌ ' + d.msg);
                    });
                }
            </script>

        {% elif tab == 'account' and user_info %}
        <div class="account-box">
            <div class="avatar">{{ user_info.username[:1] | upper }}</div>
            <div class="account-name">{{ user_info.username }}</div>
            <div class="stat-grid">
                <div><div class="stat-val">{{ user_info.bonus }}</div><div class="stat-lbl">魔力值</div></div>
                <div><div class="stat-val">{{ user_info.ratio }}</div><div class="stat-lbl">分享率</div></div>
                <div><div class="stat-val">{{ user_info.upload }}</div><div class="stat-lbl">总上传</div></div>
                <div><div class="stat-val">{{ user_info.download }}</div><div class="stat-lbl">总下载</div></div>
            </div>
            <button id="signinBtn" class="btn-signin" onclick="doSignIn()">✅ 每日签到</button>
            <button id="lotteryBtn" class="btn-lottery" onclick="doLottery()">🎰 立即参与抽奖</button>
        </div>
        <script>
            function doSignIn() {
                const btn = document.getElementById('signinBtn');
                btn.innerText = '打卡中...'; btn.disabled = true;
                fetch('/api/signin').then(r => r.json()).then(data => {
                    alert(data.msg); btn.innerText = '✅ 每日签到'; btn.disabled = false;
                }).catch(e => { alert('请求失败'); btn.innerText = '✅ 每日签到'; btn.disabled = false; });
            }
            function doLottery() {
                const btn = document.getElementById('lotteryBtn');
                btn.innerText = '参与中...'; btn.disabled = true;
                fetch('/api/lottery').then(r => r.json()).then(data => {
                    alert(data.msg); btn.innerText = '🎰 立即参与抽奖'; btn.disabled = false;
                }).catch(e => { alert('请求失败'); btn.innerText = '🎰 立即参与抽奖'; btn.disabled = false; });
            }
        </script>
        
        {% elif tab not in ['account', 'rss'] %}
            {% for item in torrents %}
            <div class="list-item" id="item-{{ item.id }}">
                <div class="poster-wrapper">
                    {% set needs_lazy = not item.img or ('data:image/svg+xml' in item.img) %}
                    <img class="poster {% if needs_lazy %}lazy-load{% endif %}" 
                         src="{{ item.img if item.img else 'data:image/svg+xml;utf8,<svg xmlns=\\'http://www.w3.org/2000/svg\\' width=\\'100\\' height=\\'140\\'><rect width=\\'100%\\' height=\\'100%\\' fill=\\'%23e6e6e6\\'/><text x=\\'50%\\' y=\\'50%\\' fill=\\'%23999\\' font-size=\\'12\\' font-family=\\'sans-serif\\' text-anchor=\\'middle\\' dominant-baseline=\\'middle\\'>加载海报</text></svg>' }}" 
                         {% if needs_lazy %}data-tid="{{ item.id }}"{% endif %}
                         referrerpolicy="no-referrer" alt="海报" onclick="window.open('{{ item.link }}', '_blank')">
                    {% if 'FREE' in item.tags|join(' ')|upper %}
                        <div class="tag-free">FREE</div>
                    {% endif %}
                </div>
                <div class="info">
                    <div class="title" onclick="window.open('{{ item.link }}', '_blank')">{{ item.title }}</div>
                    <div class="subtitle">{{ item.subtitle }}</div>
                    
                    <div class="stats-and-download">
                        <div class="stats-row">
                            <span class="stat-item" id="size-{{ item.id }}">📄 {{ item.size }}</span>
                            <span class="stat-item"><span class="seed-icon">▲</span> {{ item.seeders }}</span>
                            <span class="stat-item"><span class="leech-icon">▼</span> {{ item.leechers }}</span>
                            {% if item.group %}
                                {% if item.group|upper == 'LONGWEB' %}
                                    <span class="badge-longweb">💎</span>
                                {% else %}
                                    <span class="badge-group">{{ item.group }}</span>
                                {% endif %}
                            {% endif %}
                        </div>
                        <button type="button" class="download-btn" data-tid="{{ item.id }}" data-title="{{ item.title|e }}" data-sub="{{ item.subtitle|e }}" data-grp="{{ item.group|e }}" onclick="openQbtFromBtn(this)">推送</button>
                    </div>

                    <div class="tags-wrapper">
                        <div class="tags-top">
                            {% for tag in item.top_pri %}<span class="badge-tech">{{ tag }}</span>{% endfor %}
                            {% for tag in item.top_sec %}<span class="badge-tech secondary-tag">{{ tag }}</span>{% endfor %}
                        </div>
                        <div class="tags-bottom">
                            {% if item.time_tag %}<span class="badge-discount">{{ item.time_tag }}</span>{% endif %}
                            {% if item.clock_tag %}<span class="badge" style="background:#64748b;">{{ item.clock_tag }}</span>{% endif %}
                            {% for tag in item.bot_disc %}<span class="badge-discount">{{ tag }}</span>{% endfor %}
                            {% for tag in item.bot_pri %}<span class="badge">{{ tag }}</span>{% endfor %}
                            {% for tag in item.bot_sec %}<span class="badge-lang secondary-tag">{{ tag }}</span>{% endfor %}
                            {% if item.top_sec|length > 0 or item.bot_sec|length > 0 %}
                                <span class="badge-toggle" onclick="toggleTags(this)">... ▾</span>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
            
            {% if tab == 'search' and not torrents and query %}
                <div style="text-align:center; color:var(--text-sub); margin-top:30px;">找到 0 个结果</div>
            {% elif tab in ['recent', 'official', 'search'] and not error %}
                <div id="load-more-sentinel" style="text-align:center; padding: 20px; color:var(--text-sub); font-size:12px; clear:both;">
                    向下划动,无痕加载更多... ⚡
                </div>
            {% endif %}
        {% endif %}
    </div>

    <script>
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        const menuBtn = document.getElementById('menuBtn');

        function toggleMenu() { 
            sidebar.classList.toggle('open'); 
            overlay.classList.toggle('open'); 
            menuBtn.classList.toggle('open');
        }

        function cycleTheme() {
            if (currentTheme === 'dark') currentTheme = 'light';
            else currentTheme = 'dark';
            localStorage.setItem('longpt_theme', currentTheme);
            setTheme(currentTheme);
        }

        // 🚀 底部面板状态控制(支持单集推送 & 精准RSS追剧建规则)
        let currentModalMode = 'push';
        let currentPushTid = null;
        let currentQbtServer = localStorage.getItem('longpt_qbt_srv') || '177';
        let currentQbtCat = localStorage.getItem('longpt_qbt_cat_' + currentQbtServer) || '';
        let rssSpecState = [];
        let rssBaseCnName = '';
        let isTagsManuallyEdited = false;
        let rssSeasonStr = '';

        function switchModalMode(mode) {
            currentModalMode = mode;
            document.getElementById('modeTabPush').classList.toggle('active', mode === 'push');
            document.getElementById('modeTabRss').classList.toggle('active', mode === 'rss');
            document.getElementById('rssConfigZone').style.display = (mode === 'rss') ? 'block' : 'none';
            document.getElementById('qbtSubmitBtn').innerText = (mode === 'rss') ? '📡 保存并下发 RSS 追更规则' : '🚀 立即推送到 qB';
        }

        function parseTitleForRss(title, sub, grp) {
            const BS = String.fromCharCode(92);

            // 1. 提取纯中文剧名
            let cnName = '';
            if (sub) {
                const skipWords = /^(分集|完结|官种|官方|国语|中字|粤语|英语|双语|简繁|热门|首发|禁转|DIY|4K|HDR|DV|HQ|SDR|杜比|高帧|高码)$/i;
                const parts = sub.split('|').map(s => s.trim()).filter(Boolean);
                for (let p of parts) {
                    if (!skipWords.test(p) && /[\u4e00-\u9fa5]/.test(p)) {
                        let cleaned = p.replace(/^.*?[::]/, '').split('/')[0].trim();
                        cleaned = cleaned.replace(/\s*(?:第\s*[一二三四五六七八九十百\d]+(?:\s*-\s*\d+)?\s*[集期话季]|更新至\s*\d+\s*[集期话]|全\s*\d+\s*[集期话]).*$/g, '').trim();
                        if (cleaned) {
                            cnName = cleaned;
                            break;
                        }
                    }
                }
            }

            // 2. 提取英文剧名 + E\d+
            let rawName = title;
            const cutMatch = title.match(/^(.*?)(?:[\s.\-_]+(?:S\d{1,2}(?:E\d+)?|E\d+|(?:19|20)\d{2}|2160p|1080p|720p))(?:[\s.\-_]|$)/i);
            if (cutMatch && cutMatch[1].trim()) {
                rawName = cutMatch[1].trim();
            }
            rawName = rawName.replace(/[\.\-_]+/g, ' ').replace(/\s+/g, ' ').trim();
            let showCore = rawName + '.*E' + BS + 'd+';

            // 3. 提取所有命中的要素,并记录它们在原标题中的真实位置 pos
            const specs = [];
            const allDefs = [
                {label: '2160p', test: /(?:^|[\s.\-_])(2160p|4K)(?:$|[\s.\-_])/i, regex: '2160p', active: true, inName: false, syncTag: false},
                {label: '1080p', test: /(?:^|[\s.\-_])1080p(?:$|[\s.\-_])/i, regex: '1080p', active: true, inName: false, syncTag: false},
                {label: 'HFR', test: /(?:^|[\s.\-_])(60fps|HFR)(?:$|[\s.\-_])/i, regex: '(?:60fps|HFR)', active: true, inName: true, syncTag: false},
                {label: '50fps', test: /(?:^|[\s.\-_])50fps(?:$|[\s.\-_])/i, regex: '50fps', active: true, inName: false, syncTag: false},
                {label: '30fps', test: /(?:^|[\s.\-_])30fps(?:$|[\s.\-_])/i, regex: '30fps', active: true, inName: false, syncTag: false},
                {label: 'MAXPLUS', test: /(?:^|[\s.\-_])MAXPLUS(?:$|[\s.\-_])/i, regex: 'MAXPLUS', active: true, inName: false, syncTag: false},
                {label: 'HQ', test: /(?:^|[\s.\-_])HQ(?:$|[\s.\-_])/i, regex: 'HQ', active: true, inName: true, syncTag: true},
                {label: 'HDR', test: /(?:^|[\s.\-_])(HDR|HDRVivid|HDR10\+?)(?:$|[\s.\-_])/i, regex: '(?:HDR|HDRVivid)', active: true, inName: true, syncTag: true},
                {label: 'SDR', test: /(?:^|[\s.\-_])SDR(?:$|[\s.\-_])/i, regex: 'SDR', active: true, inName: true, syncTag: true},
                {label: 'DV', test: /(?:^|[\s.\-_])(DV|DoVi)(?:$|[\s.\-_])/i, regex: '(?:DV|DoVi)', active: true, inName: true, syncTag: true},
                {label: 'H265', test: /H\.?265|HEVC|x265/i, regex: '(?:265|HEVC)', active: false, inName: false, syncTag: false},
                {label: 'H264', test: /H\.?264|AVC|x264/i, regex: '(?:264|AVC)', active: false, inName: false, syncTag: false}
            ];

            allDefs.forEach(d => {
                const pos = title.search(d.test);
                if (pos !== -1) {
                    specs.push({label: d.label, regex: d.regex, active: d.active, inName: d.inName, syncTag: d.syncTag, pos: pos});
                }
            });

            // 关键:严格按在原标题中实际出现的先后位置排序,彻底杜绝顺序颠倒导致匹配失败!
            specs.sort((a, b) => a.pos - b.pos);

            // 制作组永远排在最后
            if (grp) {
                const safeGrp = grp.replace(/[^A-Za-z0-9_@]/g, '');
                if (safeGrp) specs.push({label: safeGrp, regex: safeGrp, active: true, inName: false, syncTag: false, pos: 9999});
            }

            rssBaseCnName = cnName || rawName;
            rssSpecState = specs;
            document.getElementById('rssShowCore').value = showCore;
            renderRssSpecPills();
            rebuildRssRegex();
        }

        function renderRssSpecPills() {
            const box = document.getElementById('rssSpecPills');
            box.innerHTML = rssSpecState.map((s, idx) => 
                `<div class="qbt-pill spec-pill ${s.active ? 'active' : ''}" onclick="toggleRssSpec(${idx})">${s.active ? '✓ ' : ''}${s.label}</div>`
            ).join('');
        }

        function toggleRssSpec(idx) {
            rssSpecState[idx].active = !rssSpecState[idx].active;
            renderRssSpecPills();
            rebuildRssRegex();
        }

        function rebuildRssRegex() {
            const core = document.getElementById('rssShowCore').value.trim();
            const activeSpecs = rssSpecState.filter(s => s.active);
            const activeLabels = activeSpecs.map(s => s.label);
            
            // 1. 生成正向匹配正则
            const parts = [core, ...activeSpecs.map(s => {
                if (s.regex.includes('|') && !s.regex.startsWith('(')) return `(?:${s.regex})`;
                return s.regex;
            })].filter(Boolean);
            document.getElementById('rssFinalRegex').value = parts.join('.*');

            // 2. 自动生成排他排除词 (mustNotContain):没选中的版本特性全部自动拉黑,彻底防止串版
            const baseExcludes = ['合集', 'Complete', 'Pack', '全集', '招募'];
            const exclusivePool = [
                {label: 'DV', exclude: 'DV|DoVi'},
                {label: 'HDR', exclude: 'HDR|HDRVivid'},
                {label: 'HQ', exclude: 'HQ'},
                {label: 'HFR', exclude: '60fps|HFR'},
                {label: 'MAXPLUS', exclude: 'MAXPLUS'}
            ];
            const autoExcludes = exclusivePool
                .filter(item => !activeLabels.includes(item.label))
                .map(item => item.exclude);
            document.getElementById('rssExcludeRegex').value = [...baseExcludes, ...autoExcludes].join('|');

            // 3. 规则名称:纯中文剧名 + 允许的版本要素 (DV/HDR/SDR/HQ/HFR)
            const nameLabels = activeSpecs.filter(s => s.inName).map(s => s.label);
            const nameParts = [rssBaseCnName, ...nameLabels].filter(Boolean);
            document.getElementById('rssRuleName').value = nameParts.join(' ');

            // 4. 仅在未手动修改时,按优先级只同步【唯一一个】版本标签到 qB
            if (!isTagsManuallyEdited) {
                const verPriority = ['DV', 'HDR', 'HQ', 'SDR'];
                const matchedVers = activeSpecs.filter(s => s.syncTag).map(s => s.label);
                const singleVer = verPriority.find(v => matchedVers.includes(v));

                const customTagInp = document.getElementById('qbtCustomTags');
                let baseTags = customTagInp.value.split(/[,,]/).map(s => s.trim()).filter(Boolean);
                baseTags = baseTags.filter(t => !verPriority.includes(t));
                if (baseTags.length === 0) baseTags = ['洗码'];
                if (singleVer) baseTags.push(singleVer);
                customTagInp.value = baseTags.join(',');
            }
        }

        function openQbtFromBtn(btn) {
            openQbtModal(
                btn.getAttribute('data-tid'),
                btn.getAttribute('data-title'),
                btn.getAttribute('data-sub'),
                btn.getAttribute('data-grp')
            );
        }

        function openQbtModal(tid, title, sub, grp) {
            currentPushTid = tid;
            document.getElementById('qbtSheetTitle').innerText = title || ('种子 #' + tid);
            document.getElementById('qbtDirectBtn').href = '/download/' + tid;
            document.getElementById('qbtCustomTags').value = '洗码';
            isTagsManuallyEdited = false;

            parseTitleForRss(title || '', sub || '', grp || '');
            switchModalMode('push');

            document.getElementById('qbtMask').classList.add('open');
            document.getElementById('qbtSheet').classList.add('open');
            selectQbtServer(currentQbtServer);
        }

        function closeQbtModal() {
            document.getElementById('qbtMask').classList.remove('open');
            document.getElementById('qbtSheet').classList.remove('open');
        }

        function selectQbtServer(srvId) {
            currentQbtServer = srvId;
            localStorage.setItem('longpt_qbt_srv', srvId);
            currentQbtCat = localStorage.getItem('longpt_qbt_cat_' + srvId) || '';

            document.querySelectorAll('#qbtServerPills .qbt-pill').forEach(el => {
                el.classList.toggle('active', el.getAttribute('data-srv') === srvId);
            });

            const statusEl = document.getElementById('qbtConnStatus');
            const catBox = document.getElementById('qbtCatPills');
            const tagBox = document.getElementById('qbtTagPills');
            const feedHint = document.getElementById('rssFeedHint');
            statusEl.innerText = '正在读取节点配置...';
            statusEl.style.color = '#888888';

            fetch('/api/qbt/meta?server=' + encodeURIComponent(srvId))
                .then(r => r.json())
                .then(d => {
                    if (!d.ok) {
                        statusEl.innerText = '⚠️ ' + d.msg;
                        statusEl.style.color = '#ef4444';
                        return;
                    }
                    statusEl.innerText = '🟢 在线 (' + d.version + ')';
                    statusEl.style.color = '#16a34a';
                    feedHint.innerText = d.rss_url ? d.rss_url : '未配置(将匹配全部源)';

                    let catHtml = `<div class="qbt-pill ${currentQbtCat === '' ? 'active' : ''}" data-cat="" onclick="selectQbtCat('', '')">不设分类(默认)</div>`;
                    let matchedPath = '';
                    (d.categories || []).forEach(c => {
                        const isAct = (c.name === currentQbtCat);
                        if (isAct) matchedPath = c.savePath || '';
                        catHtml += `<div class="qbt-pill ${isAct ? 'active' : ''}" data-cat="${c.name}" onclick="selectQbtCat('${c.name}', '${c.savePath || ''}')">📁 ${c.name}</div>`;
                    });
                    catBox.innerHTML = catHtml;
                    document.getElementById('qbtCatPath').innerText = matchedPath ? ('路径: ' + matchedPath) : '';

                    let tagHtml = '';
                    (d.tags || []).forEach(t => {
                        tagHtml += `<div class="qbt-pill" onclick="toggleInputTag('${t}')">🏷️ ${t}</div>`;
                    });
                    tagBox.innerHTML = tagHtml;
                })
                .catch(e => {
                    statusEl.innerText = '❌ 连接节点失败';
                    statusEl.style.color = '#ef4444';
                });
        }

        function selectQbtCat(catName, savePath) {
            currentQbtCat = catName;
            localStorage.setItem('longpt_qbt_cat_' + currentQbtServer, catName);
            document.querySelectorAll('#qbtCatPills .qbt-pill').forEach(el => {
                el.classList.toggle('active', el.getAttribute('data-cat') === catName);
            });
            document.getElementById('qbtCatPath').innerText = savePath ? ('路径: ' + savePath) : '';
        }

        function toggleInputTag(tag) {
            isTagsManuallyEdited = true;
            const inp = document.getElementById('qbtCustomTags');
            let arr = inp.value.split(/[,,]/).map(s => s.trim()).filter(Boolean);
            const singleVerGroup = ['DV', 'HDR', 'SDR', 'HQ', 'HFR', 'IQ', 'HDV', 'HHDR'];
            if (arr.includes(tag)) {
                arr = arr.filter(x => x !== tag);
            } else {
                if (singleVerGroup.includes(tag)) {
                    arr = arr.filter(x => !singleVerGroup.includes(x));
                }
                arr.push(tag);
            }
            inp.value = arr.join(',');
        }

        function handleModalSubmit() {
            if (currentModalMode === 'rss') {
                submitRssRule();
            } else {
                submitQbtPush();
            }
        }

        function submitRssRule() {
            const btn = document.getElementById('qbtSubmitBtn');
            const ruleName = document.getElementById('rssRuleName').value.trim();
            const mustContain = document.getElementById('rssFinalRegex').value.trim();
            const mustNotContain = document.getElementById('rssExcludeRegex').value.trim();
            const smartFilter = document.getElementById('rssSmartFilter').checked;
            const tags = document.getElementById('qbtCustomTags').value.split(/[,,]/).map(s => s.trim()).filter(Boolean).join(',');

            if (!ruleName || !mustContain) {
                alert('⚠️ 规则名称和匹配正则不能为空!');
                return;
            }

            btn.innerText = '正在下发规则并推送当前集...';
            btn.disabled = true;

            fetch('/api/qbt/rss/add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    server: currentQbtServer,
                    name: ruleName,
                    mustContain: mustContain,
                    mustNotContain: mustNotContain,
                    smartFilter: smartFilter,
                    category: currentQbtCat,
                    tags: tags
                })
            }).then(r => r.json()).then(d => {
                if (!d.ok) {
                    btn.disabled = false;
                    btn.innerText = '📡 保存并下发 RSS 追更规则';
                    alert('❌ ' + d.msg);
                    return;
                }
                if (currentPushTid) {
                    fetch('/api/qbt/push', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({
                            tid: currentPushTid,
                            server: currentQbtServer,
                            category: currentQbtCat,
                            tags: tags
                        })
                    }).then(r2 => r2.json()).then(d2 => {
                        btn.disabled = false;
                        btn.innerText = '📡 保存并下发 RSS 追更规则';
                        closeQbtModal();
                        alert('✅ ' + d.msg + '\\n' + (d2.ok ? '🚀 当前种子已同步推送到下载队列!' : '⚠️ 当前种子推送失败: ' + d2.msg));
                    }).catch(() => {
                        btn.disabled = false;
                        btn.innerText = '📡 保存并下发 RSS 追更规则';
                        closeQbtModal();
                        alert('✅ ' + d.msg + '\\n⚠️ 当前种子自动推送请求超时');
                    });
                } else {
                    btn.disabled = false;
                    btn.innerText = '📡 保存并下发 RSS 追更规则';
                    closeQbtModal();
                    alert('✅ ' + d.msg);
                }
            }).catch(e => {
                btn.disabled = false;
                btn.innerText = '📡 保存并下发 RSS 追更规则';
                alert('❌ 下发请求异常');
            });
        }

        function submitQbtPush() {
            if (!currentPushTid) return;
            const btn = document.getElementById('qbtSubmitBtn');
            const tags = document.getElementById('qbtCustomTags').value.split(/[,,]/).map(s => s.trim()).filter(Boolean).join(',');
            btn.innerText = '正在抓取种子并推送...';
            btn.disabled = true;

            fetch('/api/qbt/push', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    tid: currentPushTid,
                    server: currentQbtServer,
                    category: currentQbtCat,
                    tags: tags
                })
            }).then(r => r.json()).then(d => {
                btn.disabled = false;
                btn.innerText = '🚀 立即推送到 qB';
                if (d.ok) {
                    closeQbtModal();
                    alert('✅ ' + d.msg);
                } else {
                    alert('❌ ' + d.msg);
                }
            }).catch(e => {
                btn.disabled = false;
                btn.innerText = '🚀 立即推送到 qB';
                alert('❌ 请求异常');
            });
        }

        window.lazyObserver = null;
        document.addEventListener("DOMContentLoaded", function() {
            if ('IntersectionObserver' in window) {
                window.lazyObserver = new IntersectionObserver((entries, obs) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            const tid = img.getAttribute('data-tid');
                            if (tid) {
                                fetch('/api/extra/' + tid)
                                    .then(r => r.json())
                                    .then(data => {
                                        if (data.img) img.src = data.img;
                                        else img.src = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='140'><rect width='100%' height='100%' fill='%23f4f4f5'/><text x='50%' y='50%' fill='%23a1a1aa' font-size='12' font-family='sans-serif' text-anchor='middle' dominant-baseline='middle'>暂无海报</text></svg>";
                                        img.classList.remove('lazy-load');
                                        if (data.size && data.size !== '未知' && data.size !== '加载中...') {
                                            const sizeSpan = document.getElementById('size-' + tid);
                                            if (sizeSpan) sizeSpan.innerHTML = '📄 ' + data.size;
                                        }
                                    })
                                    .catch(e => {});
                                img.removeAttribute('data-tid');
                                obs.unobserve(img);
                            }
                        }
                    });
                }, { rootMargin: "300px" });

                document.querySelectorAll('.lazy-load').forEach(img => window.lazyObserver.observe(img));

                const sentinel = document.getElementById('load-more-sentinel');
                if (sentinel) {
                    let currentPage = 1; 
                    let isLoadingMore = false;
                    let hasMore = true;
                    const seenIds = new Set();
                    document.querySelectorAll('.list-item').forEach(el => seenIds.add(el.id.replace('item-', '')));

                    const loadMoreObserver = new IntersectionObserver((entries) => {
                        if (entries[0].isIntersecting && !isLoadingMore && hasMore) loadMore();
                    }, { rootMargin: "200px" });
                    loadMoreObserver.observe(sentinel);

                    function loadMore() {
                        isLoadingMore = true;
                        sentinel.innerText = "正在无痕加载下一页...";
                        const params = new URLSearchParams(window.location.search);
                        const tab = params.get('tab') || 'official';
                        const q = params.get('q') || '';
                        
                        fetch(`/api/load_more?tab=${tab}&q=${encodeURIComponent(q)}&page=${currentPage}`)
                            .then(r => r.json())
                            .then(data => {
                                currentPage++;
                                isLoadingMore = false;
                                if (data.error) { sentinel.innerText = "加载失败: " + data.error; return; }
                                if (data.torrents.length === 0) {
                                    if (currentPage < 10) loadMore();
                                    else { hasMore = false; sentinel.innerText = "缓存已探底,没有更多数据了"; }
                                    return;
                                }
                                let addedCount = 0;
                                data.torrents.forEach(item => {
                                    if (seenIds.has(item.id)) return;
                                    seenIds.add(item.id);
                                    addedCount++;
                                    
                                    let tagsTopHtml = '', tagsBotHtml = '', groupHtml = '';
                                    item.top_pri.forEach(t => tagsTopHtml += `<span class="badge-tech">${t}</span>`);
                                    item.top_sec.forEach(t => tagsTopHtml += `<span class="badge-tech secondary-tag">${t}</span>`);
                                    if (item.time_tag) tagsBotHtml += `<span class="badge-discount">${item.time_tag}</span>`;
                                    if (item.clock_tag) tagsBotHtml += `<span class="badge" style="background:#64748b;">${item.clock_tag}</span>`;
                                    item.bot_disc.forEach(t => tagsBotHtml += `<span class="badge-discount">${t}</span>`);
                                    item.bot_pri.forEach(t => tagsBotHtml += `<span class="badge">${t}</span>`);
                                    item.bot_sec.forEach(t => tagsBotHtml += `<span class="badge-lang secondary-tag">${t}</span>`);
                                    if (item.top_sec.length > 0 || item.bot_sec.length > 0) tagsBotHtml += `<span class="badge-toggle" onclick="toggleTags(this)">... ▾</span>`;
                                    if (item.group) groupHtml = item.group.toUpperCase() === 'LONGWEB' ? `<span class="badge-longweb">💎</span>` : `<span class="badge-group">${item.group}</span>`;
                                    let freeTagHtml = item.tags.join(' ').toUpperCase().includes('FREE') ? `<div class="tag-free">FREE</div>` : '';
                                    const imgPlaceholder = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='140'><rect width='100%' height='100%' fill='%23e6e6e6'/><text x='50%' y='50%' fill='%23999' font-size='12' font-family='sans-serif' text-anchor='middle' dominant-baseline='middle'>加载海报</text></svg>";
                                    const imgSrc = item.img ? item.img : imgPlaceholder;
                                    const needsLazy = !item.img || item.img.includes('data:image/svg+xml');
                                    const safeTitle = (item.title || '').replace(/"/g, '&quot;');
                                    const safeSub = (item.subtitle || '').replace(/"/g, '&quot;');

                                    const html = `
                                    <div class="list-item" id="item-${item.id}">
                                        <div class="poster-wrapper">
                                            <img class="poster ${needsLazy ? 'lazy-load' : ''}" src="${imgSrc}" ${needsLazy ? `data-tid="${item.id}"` : ''} referrerpolicy="no-referrer" alt="海报" onclick="window.open('${item.link}', '_blank')">
                                            ${freeTagHtml}
                                        </div>
                                        <div class="info">
                                            <div class="title" onclick="window.open('${item.link}', '_blank')">${item.title}</div>
                                            <div class="subtitle">${item.subtitle || ''}</div>
                                            <div class="stats-and-download">
                                                <div class="stats-row">
                                                    <span class="stat-item" id="size-${item.id}">📄 ${item.size}</span>
                                                    <span class="stat-item"><span class="seed-icon">▲</span> ${item.seeders}</span>
                                                    <span class="stat-item"><span class="leech-icon">▼</span> ${item.leechers}</span>
                                                    ${groupHtml}
                                                </div>
                                                <button type="button" class="download-btn" data-tid="${item.id}" data-title="${safeTitle}" data-sub="${safeSub}" data-grp="${item.group || ''}" onclick="openQbtFromBtn(this)">推送</button>
                                            </div>
                                            <div class="tags-wrapper">
                                                <div class="tags-top">${tagsTopHtml}</div>
                                                <div class="tags-bottom">${tagsBotHtml}</div>
                                            </div>
                                        </div>
                                    </div>`;
                                    sentinel.insertAdjacentHTML('beforebegin', html);
                                });
                                document.querySelectorAll('.lazy-load:not([data-observed])').forEach(img => { img.setAttribute('data-observed', '1'); window.lazyObserver.observe(img); });
                                if (addedCount === 0) loadMore();
                                else sentinel.innerText = "向下划动,无痕加载更多... ⚡";
                            });
                    }
                }
            }
        });
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    tab = request.args.get('tab', 'official')
    query = request.args.get('q', '')
    torrents = []
    user_info = {}
    seen_ids = set() 
    error_msg = None
    
    try:
        if tab == 'rss':
            pass
        elif tab == 'account':
            resp = HTTP_SESSION.get(INDEX_URL, headers=HEADERS, proxies=PROXIES)
            if "登录" in resp.text and "index.php" not in resp.url:
                error_msg = "⚠️ Cookie 已失效,请在代码中更新 Cookie!"
            else:
                soup = BeautifulSoup(resp.text, 'html.parser')
                for tag in soup.find_all(True):
                    title_attr = tag.get('title') or tag.get('alt') or tag.get('data-original-title')
                    if title_attr and isinstance(title_attr, str) and len(title_attr) < 20:
                        tag.append(f"{title_attr}")
                page_text = soup.get_text(separator='', strip=True)
                
                user_match = re.search(r'欢迎回来[\s,,]*([A-Za-z0-9_\-]+)', page_text)
                bonus_match = re.search(r'魔力值[^\d]*([\d\.,]+)', page_text)
                ratio_match = re.search(r'分享率[^\d]*([\d\.,]+|无限|Inf)', page_text, re.IGNORECASE)
                up_match = re.search(r'(?:上传量?|上传|上行)[^\d]*([\d\.,]+\s*[KMGTP]B)', page_text, re.IGNORECASE)
                down_match = re.search(r'(?:下载量?|下载|下行)[^\d]*([\d\.,]+\s*[KMGTP]B)', page_text, re.IGNORECASE)
                
                user_info = {
                    'username': user_match.group(1).strip() if user_match else "LongPT会员",
                    'bonus': bonus_match.group(1) if bonus_match else "0",
                    'ratio': ratio_match.group(1) if ratio_match else "0",
                    'upload': up_match.group(1) if up_match else "0 GB",
                    'download': down_match.group(1) if down_match else "0 GB"
                }

        elif tab in ['official', 'search']:
            if tab == 'search' and not query: pass
            else:
                if tab == 'search':
                    safe_query = urllib.parse.quote(query)
                    target_url = f"{BASE_URL}/torrents.php?incldead=1&spstate=0&inclbookmarked=0&search={safe_query}&search_area=0&search_mode=0"
                else: 
                    target_url = OFFICIAL_URL
                    
                fetched_torrents, err = parse_torrents_page(target_url, seen_ids, is_search=(tab == 'search'), skip_sticky=False)
                if fetched_torrents is not None:
                    history_dict = load_cache('official')
                    for item in fetched_torrents:
                        tid_str = str(item['id'])
                        if tid_str in history_dict:
                            cached = history_dict[tid_str]
                            if 'data:image' not in cached.get('img','') and 'data:image' in item.get('img',''):
                                item['img'] = cached['img']
                            if cached.get('size') not in ['未知', '加载中...'] and item.get('size') in ['未知', '-']:
                                item['size'] = cached['size']
                            if not item.get('group') and cached.get('group'):
                                item['group'] = cached['group']
                            item['tags'] = purify_tags(merge_tags_list(item.get('tags', []), cached.get('tags', [])))
                        
                        history_dict[tid_str] = item
                    if tab != 'search':
                        save_cache(history_dict, 'official')
                    torrents = fetched_torrents
                else:
                    if err: error_msg = err

        elif tab == 'recent':
            fetched_torrents, err_msg = parse_index_page(seen_ids)
            recent_dict = load_cache('recent')
            
            if fetched_torrents is not None:
                for item in fetched_torrents:
                    tid_str = str(item['id'])
                    if tid_str in recent_dict:
                        cached = recent_dict[tid_str]
                        if cached.get('img') and 'data:image/svg+xml' not in cached['img']: item['img'] = cached['img']
                        if cached.get('size') and cached.get('size') not in ['未知', '加载中...']: item['size'] = cached['size']
                        if cached.get('group') and not item.get('group'): item['group'] = cached['group']
                        item['tags'] = purify_tags(merge_tags_details(item.get('tags', []), cached.get('tags', [])))
                    recent_dict[tid_str] = item
                save_cache(recent_dict, 'recent')
                
                merged = list(recent_dict.values())
                merged.sort(key=lambda x: int(x['id']), reverse=True)
                torrents = merged[:50]
            else:
                history_data = list(recent_dict.values())
                history_data.sort(key=lambda x: int(x['id']), reverse=True)
                torrents = history_data[:50]
                if err_msg and not torrents: error_msg = err_msg

        if torrents:
            for item in torrents:
                tpri, tsec, bdisc, bpri, bsec = sort_tags(item.get('tags', []))
                item['top_pri'] = tpri
                item['top_sec'] = tsec
                item['bot_disc'] = bdisc
                item['bot_pri'] = bpri
                item['bot_sec'] = bsec
                item['time_tag'] = ""
                item['clock_tag'] = ""
                
                for arr in [item['top_pri'], item['top_sec'], item['bot_disc'], item['bot_pri'], item['bot_sec']]:
                    for t in list(arr):
                        if '剩余' in t.upper():
                            item['time_tag'] = t
                            arr.remove(t)
                        elif '🕒' in t:
                            item['clock_tag'] = t
                            arr.remove(t)

    except Exception as e:
        error_msg = f"服务器内部请求错误: {e}"
        torrents = torrents or []
        
    return render_template_string(HTML_TEMPLATE, tab=tab, query=query, torrents=torrents or [], user_info=user_info, error=error_msg, qbt_servers=QBT_SERVERS)

@app.route('/api/qbt/meta')
def api_qbt_meta():
    srv_id = request.args.get('server', '177')
    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})
    try:
        ver_r = sess.get(f"{base_url}/api/v2/app/version", timeout=4)
        cats_r = sess.get(f"{base_url}/api/v2/torrents/categories", timeout=4)
        tags_r = sess.get(f"{base_url}/api/v2/torrents/tags", timeout=4)

        cats_dict = cats_r.json() if cats_r.status_code == 200 else {}
        categories = [{"name": k, "savePath": v.get("savePath", "")} for k, v in cats_dict.items()]
        tags = tags_r.json() if tags_r.status_code == 200 else []
        rss_url = QBT_SERVERS.get(srv_id, {}).get('rss_url', '')
        return jsonify({
            "ok": True,
            "version": ver_r.text.strip(),
            "categories": categories,
            "tags": tags,
            "rss_url": rss_url
        })
    except Exception as e:
        return jsonify({"ok": False, "msg": f"读取节点元数据失败: {str(e)}"})

# ================= 📡 qBittorrent 原生 RSS 自动下载规则管理接口 =================
@app.route('/api/qbt/rss/rules')
def api_qbt_rss_rules():
    """读取指定 qB 节点上的所有 RSS 自动下载规则"""
    srv_id = request.args.get('server', '177')
    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})
    try:
        r = sess.get(f"{base_url}/api/v2/rss/rules", timeout=5)
        if r.status_code != 200:
            return jsonify({"ok": False, "msg": f"获取规则失败,状态码: {r.status_code}"})
        rules_dict = r.json()
        rules_list = []
        for name, defn in rules_dict.items():
            defn['name'] = name
            rules_list.append(defn)
        return jsonify({"ok": True, "rules": rules_list})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"读取 RSS 规则异常: {str(e)}"})

@app.route('/api/qbt/rss/add', methods=['POST'])
def api_qbt_rss_add():
    """在指定 qB 节点上创建/更新一条精准 RSS 自动下载规则,并自动开启 RSS 自动下载器"""
    data = request.get_json(force=True)
    srv_id = data.get('server', '177')
    rule_name = data.get('name', '').strip()
    must_contain = data.get('mustContain', '').strip()
    must_not_contain = data.get('mustNotContain', '').strip()
    smart_filter = bool(data.get('smartFilter', True))
    category = data.get('category', '').strip()
    tags_str = data.get('tags', '').strip()

    if not rule_name or not must_contain:
        return jsonify({"ok": False, "msg": "规则名称与匹配正则不能为空"})

    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})

    try:
        # 1. 确保该 qB 节点的 RSS 抓取和自动下载总开关处于开启状态
        sess.post(f"{base_url}/api/v2/app/setPreferences", data={
            "json": json.dumps({"rss_processing_enabled": True, "rss_auto_downloading_enabled": True})
        }, timeout=5)

        # 2. 绑定固定订阅源 URL(若 qB 中不存在该链接则自动添加,已存在则跳过)
        rss_url = QBT_SERVERS.get(srv_id, {}).get('rss_url', '').strip()
        affected_feeds = [rss_url] if rss_url else []

        if rss_url:
            items_r = sess.get(f"{base_url}/api/v2/rss/items", timeout=5)
            existing_urls = set()
            def collect_urls(obj):
                if isinstance(obj, dict):
                    if "url" in obj and isinstance(obj["url"], str):
                        existing_urls.add(obj["url"].strip())
                    for v in obj.values():
                        collect_urls(v)
            if items_r.status_code == 200:
                collect_urls(items_r.json())

            if rss_url not in existing_urls:
                sess.post(f"{base_url}/api/v2/rss/addFeed", data={
                    "url": rss_url,
                    "path": "LongPT"
                }, timeout=5)

        tags_list = [t.strip() for t in tags_str.split(',') if t.strip()]

        # 3. 构造 qBittorrent v2 标准 RSS 规则定义
        rule_def = {
            "enabled": True,
            "mustContain": must_contain,
            "mustNotContain": must_not_contain,
            "useRegex": True,
            "episodeFilter": "",
            "smartFilter": smart_filter,
            "previouslyMatchedEpisodes": [],
            "affectedFeeds": affected_feeds,
            "ignoreDays": 0,
            "lastMatch": "",
            "addPaused": False,
            "assignedCategory": category,
            "savePath": "",
            "torrentParams": {
                "category": category,
                "tags": tags_list,
                "paused": False
            }
        }

        res = sess.post(f"{base_url}/api/v2/rss/setRule", data={
            "ruleName": rule_name,
            "ruleDef": json.dumps(rule_def, ensure_ascii=False)
        }, timeout=6)

        if res.status_code == 200:
            srv_name = QBT_SERVERS[srv_id]['name']
            return jsonify({"ok": True, "msg": f"RSS 追剧规则【{rule_name}】已成功下发至 {srv_name}!"})
        return jsonify({"ok": False, "msg": f"qB 拒绝保存规则: {res.text}"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"下发 RSS 规则异常: {str(e)}"})

@app.route('/api/qbt/rss/toggle', methods=['POST'])
def api_qbt_rss_toggle():
    """启停指定的 RSS 规则"""
    data = request.get_json(force=True)
    srv_id = data.get('server', '177')
    rule_name = data.get('name', '')
    enabled = bool(data.get('enabled', True))

    sess, base_url, err = get_qbt_session(srv_id)
    if err: return jsonify({"ok": False, "msg": err})
    try:
        r = sess.get(f"{base_url}/api/v2/rss/rules", timeout=5)
        rules = r.json()
        if rule_name not in rules:
            return jsonify({"ok": False, "msg": "未找到该规则"})
        rules[rule_name]['enabled'] = enabled
        res = sess.post(f"{base_url}/api/v2/rss/setRule", data={
            "ruleName": rule_name,
            "ruleDef": json.dumps(rules[rule_name], ensure_ascii=False)
        }, timeout=5)
        return jsonify({"ok": res.status_code == 200, "msg": "状态已更新"})
    except Exception as e:
        return jsonify({"ok": False, "msg": str(e)})

@app.route('/api/qbt/rss/delete', methods=['POST'])
def api_qbt_rss_delete():
    """删除指定的 RSS 规则"""
    data = request.get_json(force=True)
    srv_id = data.get('server', '177')
    rule_name = data.get('name', '')

    sess, base_url, err = get_qbt_session(srv_id)
    if err: return jsonify({"ok": False, "msg": err})
    try:
        res = sess.post(f"{base_url}/api/v2/rss/removeRule", data={"ruleName": rule_name}, timeout=5)
        return jsonify({"ok": res.status_code == 200, "msg": "已删除"})
    except Exception as e:
        return jsonify({"ok": False, "msg": str(e)})
# ==============================================================================

@app.route('/api/qbt/push', methods=['POST'])
def api_qbt_push():
    data = request.get_json(force=True)
    tid = data.get('tid')
    srv_id = data.get('server', '177')
    category = data.get('category', '').strip()
    tags = data.get('tags', '').strip()

    if not tid:
        return jsonify({"ok": False, "msg": "缺少种子 ID"})

    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})

    try:
        dl_r = HTTP_SESSION.get(f"{BASE_URL}/download.php?id={tid}", headers=HEADERS, proxies=PROXIES)
        if dl_r.status_code != 200 or (b"announce" not in dl_r.content[:200] and b"info" not in dl_r.content[:200]):
            return jsonify({"ok": False, "msg": "从 LongPT 获取种子失败,请检查 Cookie 是否失效"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"从 LongPT 下载种子失败: {str(e)}"})

    try:
        form_data = {}
        if category: form_data['category'] = category
        if tags: form_data['tags'] = tags

        files = {'torrents': (f'LongPT_{tid}.torrent', dl_r.content, 'application/x-bittorrent')}
        push_r = sess.post(f"{base_url}/api/v2/torrents/add", data=form_data, files=files, timeout=10)
        res_txt = push_r.text.strip()
        if push_r.status_code == 200 and ("Ok." in res_txt or '"success_count":1' in res_txt.replace(" ", "") or "added_torrent_ids" in res_txt):
            srv_name = QBT_SERVERS[srv_id]['name']
            cat_info = f" [分类: {category}]" if category else ""
            return jsonify({"ok": True, "msg": f"已成功推送到 {srv_name}{cat_info}!"})
        return jsonify({"ok": False, "msg": f"qB 推送未成功: {res_txt}"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"推送到 qB 失败: {str(e)}"})

@app.route('/api/load_more')
def api_load_more():
    tab = request.args.get('tab', 'official')
    query = request.args.get('q', '')
    try: page = int(request.args.get('page', 1))
    except: page = 1
        
    seen_ids = set()
    err = None
    fetched = []
    
    if tab == 'search':
        safe_query = urllib.parse.quote(query)
        target_url = f"{BASE_URL}/torrents.php?incldead=1&spstate=0&inclbookmarked=0&search={safe_query}&search_area=0&search_mode=0&page={page}"
        fetched, err = parse_torrents_page(target_url, seen_ids, skip_sticky=False, start_page=page, max_pages=1)
    elif tab == 'official':
        target_url = f"{OFFICIAL_URL}?page={page}" if "?" not in OFFICIAL_URL else f"{OFFICIAL_URL}&page={page}"
        fetched, err = parse_torrents_page(target_url, seen_ids, skip_sticky=False, start_page=page, max_pages=1)
    else: 
        rec_dict = load_cache('recent')
        merged = list(rec_dict.values())
        merged.sort(key=lambda x: int(x['id']), reverse=True)
        start_idx = page * 50
        fetched = merged[start_idx : start_idx + 50]
        
    if fetched:
        for item in fetched:
            tpri, tsec, bdisc, bpri, bsec = sort_tags(item.get('tags', []))
            item['top_pri'] = tpri
            item['top_sec'] = tsec
            item['bot_disc'] = bdisc
            item['bot_pri'] = bpri
            item['bot_sec'] = bsec
            item['time_tag'] = ""
            item['clock_tag'] = ""
            
            for arr in [item['top_pri'], item['top_sec'], item['bot_disc'], item['bot_pri'], item['bot_sec']]:
                for t in list(arr):
                    if '剩余' in t.upper():
                        item['time_tag'] = t
                        arr.remove(t)
                    elif '🕒' in t:
                        item['clock_tag'] = t
                        arr.remove(t)
                        
    return jsonify({"torrents": fetched or [], "error": err})

@app.route('/api/extra/<int:tid>')
def api_extra(tid):
    img_src, size, extra_tags, release_group = fetch_details_info(tid)
    merged_tags = purify_tags(extra_tags)
    
    tid_str = str(tid)
    for c_type in ['recent', 'official']:
        history_dict = load_cache(c_type)
        if tid_str in history_dict:
            cached_item = history_dict[tid_str]
            final_tags = purify_tags(merge_tags_details(merged_tags, cached_item.get('tags', [])))
            cached_item['tags'] = final_tags
            merged_tags = final_tags
            
            if img_src: cached_item['img'] = img_src
            if size and size != "未知": cached_item['size'] = size
            if release_group and not cached_item.get('group'): cached_item['group'] = release_group
            
            history_dict[tid_str] = cached_item
            save_cache(history_dict, c_type)
        
    tpri, tsec, bdisc, bpri, bsec = sort_tags(merged_tags)
    time_tag = ""
    clock_tag = ""
    for arr in [tpri, tsec, bdisc, bpri, bsec]:
        for t in list(arr):
            if '剩余' in t.upper():
                time_tag = t
                arr.remove(t)
            elif '🕒' in t:
                clock_tag = t
                arr.remove(t)
    
    return jsonify({
        "img": img_src, "size": size, "tags": merged_tags,
        "top_pri": tpri, "top_sec": tsec, "bot_disc": bdisc,
        "bot_pri": bpri, "bot_sec": bsec, "time_tag": time_tag,
        "clock_tag": clock_tag, "group": release_group
    })

@app.route('/api/lottery')
def api_lottery():
    try:
        target_api = f"{BASE_URL}/pt-api/v1/lucky/pluginsPrizeReceiptRecord/join"
        r = HTTP_SESSION.get(target_api, headers=HEADERS, proxies=PROXIES, timeout=5)
        r.encoding = 'utf-8'
        if r.status_code == 200:
            try:
                data = r.json()
                msg_text = data.get('msg') or data.get('message') or str(data)
                clean_msg = re.sub(r'<[^>]+>', ' ', msg_text).replace('\n', '').strip()
                return jsonify({"msg": f"🎰 抽奖真实反馈:\n{clean_msg}"})
            except Exception:
                clean_txt = re.sub(r'<[^>]+>', ' ', r.text).replace('\n', '').strip()
                match = re.search(r'(恭喜.*?|获得.*?|已参与.*?|积分不足.*?|不够.*?|成功.*)', clean_txt)
                return jsonify({"msg": f"🎰 抽奖反馈:\n{match.group(1)[:100]}" if match else f"🎰 已发送,服务器返回:\n{clean_txt[:60]}..."})
        return jsonify({"msg": f"❌ 抽奖接口报错,状态码: {r.status_code}"})
    except Exception as e:
        return jsonify({"msg": f"❌ 抽奖请求异常: {str(e)}"})

@app.route('/api/signin')
def api_signin():
    try:
        r = HTTP_SESSION.get(SIGNIN_URL, headers=HEADERS, proxies=PROXIES)
        r.encoding = 'utf-8'
        if r.status_code == 200:
            if any(kw in r.text for kw in ["已经", "退下", "已签到", "请明天再来"]):
                return jsonify({"msg": "☕ 今天已经签到过了,明天再来吧。"})
            elif any(kw in r.text for kw in ["这是您的第", "签到成功", "魔力值"]):
                match = re.search(r'(这是您的第.*?魔力值|签到成功.*?魔力值)', BeautifulSoup(r.text, 'html.parser').get_text(separator=' ', strip=True))
                msg = match.group(1).replace('  ', ' ') if match else "签到成功!"
                return jsonify({"msg": f"🎉 {msg}"})
            elif "登录" in r.text:
                return jsonify({"msg": "⚠️ 签到失败:Cookie 已失效,请更新!"})
            return jsonify({"msg": "✅ 签到请求已发送,请留意积分变化。"})
        return jsonify({"msg": f"❌ 签到接口报错,状态码: {r.status_code}"})
    except Exception as e:
        return jsonify({"msg": f"❌ 网络请求出错: {str(e)}"})

@app.route('/download/<int:tid>')
def download_torrent(tid):
    try:
        r = HTTP_SESSION.get(f"{BASE_URL}/download.php?id={tid}", headers=HEADERS, proxies=PROXIES)
        if "application/x-bittorrent" in r.headers.get('Content-Type', '') or "octet-stream" in r.headers.get('Content-Type', ''):
            return Response(r.content, mimetype="application/x-bittorrent", headers={"Content-Disposition": f"attachment;filename=LongPT_{tid}.torrent"})
        return "下载失败,Cookie 可能失效或无权下载该种子。"
    except Exception as e:
        return f"请求下载出错: {str(e)}"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5051)

二、zmpt

from flask import Flask, render_template_string, Response, request, jsonify
import requests
from bs4 import BeautifulSoup
import urllib.parse
import re
import os
import json
import threading
import time
import datetime

app = Flask(__name__)

# ================= 必须配置的区域 =================
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Connection': 'close',
    # 【安全提醒】:请把你的 ZmPT (织梦) Cookie 填在下面
    'Cookie': 'cf_clearance=5ZBTxMjwbWjt0CdRG0MCruVac3dFptwGijOurXms3eM-1791902735-1.2.1.1-hswQ7D0XbIKhyq8Pkpwd4.i01CwuzGwxO9BGSMvIYp9D15bgjy8yQwpD_dK_c3C5YbF0Fun7XHoCxrdkRmH.b9Z7MwJ0gbx9H6bIa89Ns4zVXmGX_PohPE2a5etU3eEvuHFY9551hnEuJU0x7sC1.rGjWjuz9vodqJMkFYgWhKf2TW_tM9jjV.dStjka3EJ0iJpw40lyKyOf.e4HN.MUbquV5yEaQk6mN5wdooTneHscUignAhTsNSk4bqWf6_Lby6ahljaxbT6Z1I_dFesFlmIEFBQiJgJZfTfF1uhpx0bGkOzd_2fAvXm_uwADLvFYkZF93Up6ruQfuJRElE3eTaSJvlG644odsDRVsjmfQcdVTN_gkOb83m7jLPfJDWSx8sYv9HYkloeXsBTJAJfUFuTMDxgOpFZutH3XqkKffjpR8Nm5cdhc7y9lJkGhockX7I29vCJH41BhepoZVhh5Ddoupx_xxMQ.xsI.FrF5ZQZM9FAZJ09v.K2qkKonJl7ctshh3lAW_ipLIk.vcL2WKA; c_secure_pass=eyJ1c2VyX2lkIjoyNTQ4MSwiZXhwaXJlcyI6MTgyMzQzODc3MH0uNDY0YzZiOGJiZDEzODM2Nzc1NDhjOTgzMDdhOWFmNWFkMGJiMWM3ZTQwZTYwMTkyMGUzMWYyY2NmZWJmZWEwYg%3D%3D' 
}

PROXY_URL = ""
PROXIES = {"http": PROXY_URL, "https": PROXY_URL} if PROXY_URL else None
TIMEOUT = 10

BASE_URL = "https://zmpt.cc"

INDEX_URL = f"{BASE_URL}/index.php"
COMPREHENSIVE_URL = f"{BASE_URL}/torrents.php"
OFFICIAL_URL = f"{BASE_URL}/torrents.php?tag_id=3" 
SIGNIN_URL = f"{BASE_URL}/attendance.php"

OFFICIAL_HISTORY_FILE = "zmpt_official_history.json"
RECENT_HISTORY_FILE = "zmpt_recent_history.json"

# 🚀 三台 qBittorrent 节点配置(支持配置“电视剧”与“动漫”双固定 RSS 订阅源)
QBT_SERVERS = {
    "177": {
        "name": "177 节点 (192.168.2.177)",
        "url": "http://192.168.2.177:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_feeds": {
            "电视剧": "https://zmpt.cc/torrentrss.php?passkey=694936c97b9fc90a326a5b56e5281343&rows=50&cat402=1&med10=1&sta5=1&sta6=1&tea5=1&icat=1&ismalldescr=1&isize=1&iuplder=1&paid=0&linktype=dl",  # 👈 填入177节点里配置的 ZmPT 电视剧 RSS 订阅链接
            "动漫": "https://zmpt.cc/torrentrss.php?passkey=694936c97b9fc90a326a5b56e5281343&rows=50&cat417=1&tea5=1&ismalldescr=1&isize=1&paid=0&linktype=dl"     # 👈 填入177节点里配置的 ZmPT 动漫 RSS 订阅链接
        }
    },
    "188": {
        "name": "188 节点 (192.168.2.188)",
        "url": "http://192.168.2.188:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_feeds": {
            "电视剧": "https://zmpt.cc/torrentrss.php?passkey=694936c97b9fc90a326a5b56e5281343&rows=50&cat402=1&med10=1&sta5=1&sta6=1&tea5=1&icat=1&ismalldescr=1&isize=1&iuplder=1&paid=0&linktype=dl",  # 👈 填入188节点里配置的 ZmPT 电视剧 RSS 订阅链接
            "动漫": "https://zmpt.cc/torrentrss.php?passkey=694936c97b9fc90a326a5b56e5281343&rows=50&cat417=1&tea5=1&ismalldescr=1&isize=1&paid=0&linktype=dl"     # 👈 填入188节点里配置的 ZmPT 动漫 RSS 订阅链接
        }
    },
    "4": {
        "name": "4 节点 (192.168.2.4)",
        "url": "http://192.168.2.4:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_feeds": {
            "电视剧": "https://zmpt.cc/torrentrss.php?passkey=694936c97b9fc90a326a5b56e5281343&rows=50&cat402=1&med10=1&sta5=1&sta6=1&tea5=1&icat=1&ismalldescr=1&isize=1&iuplder=1&paid=0&linktype=dl",  # 👈 填入2.4节点里配置的 ZmPT 电视剧 RSS 订阅链接
            "动漫": "https://zmpt.cc/torrentrss.php?passkey=694936c97b9fc90a326a5b56e5281343&rows=50&cat417=1&tea5=1&ismalldescr=1&isize=1&paid=0&linktype=dl"     # 👈 填入2.4节点里配置的 ZmPT 动漫 RSS 订阅链接
        }
    }
}
# =================================================

class SafeRequester:
    """防半死连接包装器:强制短连接 + 偶发抖动自动重试"""
    @staticmethod
    def get(url, **kwargs):
        kwargs.setdefault('timeout', (5, 10))
        for i in range(2):
            try:
                with requests.Session() as s:
                    s.headers.update({'Connection': 'close'})
                    return s.get(url, **kwargs)
            except Exception as e:
                if i == 1: raise e

HTTP_SESSION = SafeRequester()
QBT_SESSIONS = {}
MEM_CACHE_OFFICIAL = {}
MEM_CACHE_RECENT = {}
CACHE_LOCK = threading.Lock()

def get_qbt_session(srv_id):
    cfg = QBT_SERVERS.get(srv_id)
    if not cfg:
        return None, None, "未找到该 qB 节点配置"
    base_url = cfg['url'].rstrip('/')
    sess = QBT_SESSIONS.get(srv_id)
    if not sess:
        sess = requests.Session()
        QBT_SESSIONS[srv_id] = sess

    try:
        test_r = sess.get(f"{base_url}/api/v2/app/version", timeout=3)
        if test_r.status_code == 200:
            return sess, base_url, None
    except Exception:
        pass

    # 会话失效或首次连接:彻底重建干净的 Session 并带上完整 Referer/Origin 重试登录
    for attempt in range(2):
        try:
            sess = requests.Session()
            QBT_SESSIONS[srv_id] = sess
            login_r = sess.post(
                f"{base_url}/api/v2/auth/login",
                data={"username": cfg.get("username", ""), "password": cfg.get("password", "")},
                headers={"Referer": base_url + "/", "Origin": base_url},
                timeout=5
            )
            if login_r.status_code == 200 and "Ok." in login_r.text:
                return sess, base_url, None
        except Exception as e:
            if attempt == 1:
                return None, None, f"无法连接 {base_url}: {str(e)}"
    return None, None, "qB 登录失败,请检查账号密码配置"

def load_cache(cache_type='official'):
    global MEM_CACHE_OFFICIAL, MEM_CACHE_RECENT
    filename = OFFICIAL_HISTORY_FILE if cache_type == 'official' else RECENT_HISTORY_FILE
    target_cache = MEM_CACHE_OFFICIAL if cache_type == 'official' else MEM_CACHE_RECENT
    
    with CACHE_LOCK:
        if not target_cache and os.path.exists(filename):
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    res = {str(item['id']): item for item in data}
                    if cache_type == 'official': MEM_CACHE_OFFICIAL = res
                    else: MEM_CACHE_RECENT = res
                    return res
            except Exception: pass
    return target_cache

def save_cache(cache_dict, cache_type='official'):
    global MEM_CACHE_OFFICIAL, MEM_CACHE_RECENT
    filename = OFFICIAL_HISTORY_FILE if cache_type == 'official' else RECENT_HISTORY_FILE
    with CACHE_LOCK:
        if cache_type == 'official': MEM_CACHE_OFFICIAL = cache_dict.copy()
        else: MEM_CACHE_RECENT = cache_dict.copy()
        
        merged = list(cache_dict.values())
        merged.sort(key=lambda x: int(x['id']), reverse=True)
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(merged[:50], f, ensure_ascii=False, indent=2)
        except Exception: pass

TECH_KEYWORDS = [
    'FREE', '50%', '30%', '2X', '热门', '官方', '中字', '英字', '国语', '粤语', '英语', 
    '简繁', '双语', '杜比', '高帧', '高码', '臻彩MAX', '高分', '完结', '4K', '2160P', '1440P', '1080P', '720P', 
    'WEB-DL', 'BLU-RAY', 'REMUX', 'HDR10+', 'HDR10', 'HDRVIVID', 
    'HDR', 'DOVI', 'DV', 'SDR', '60FPS', 'HFR', 'HQ', 'H.265', 'H.264', 'H265', 'H264', 
    'HEVC', 'AAC', 'DDP', 'ATMOS', '10BIT', '首发', '禁转', '应求', 'DIY', '字幕'
]

def purify_tags(tags):
    valid = []
    for t in tags:
        clean_t = t.upper()
        if '剩余' in clean_t or '🕒' in clean_t:
            valid.append(t)
        elif clean_t in [k.upper() for k in TECH_KEYWORDS] or re.match(r'^[\d]+%$', clean_t):
            valid.append(t)
            
    final_tags = []
    time_tags = [t for t in valid if '剩余' in t]
    best_time = max(time_tags, key=len) if time_tags else None
    
    clock_tags = [t for t in valid if '🕒' in t]
    best_clock = clock_tags[-1] if clock_tags else None
    
    if best_time and best_clock:
        pure_time = re.sub(r'^.*?(?:剩余时间|免费剩余)[::\s]*', '', best_time).strip()
        pure_clock = best_clock.replace('🕒', '').strip()
        if pure_time == pure_clock:
            best_clock = None
            
    for t in valid:
        if '剩余' in t:
            if t == best_time and best_time not in final_tags:
                if not re.match(r'^剩余时间[::\s]*\d+\s*分$', t):
                    final_tags.append(t)
        elif '🕒' in t:
            if t == best_clock and best_clock not in final_tags:
                final_tags.append(t)
        elif t not in final_tags:
            final_tags.append(t)
            
    return final_tags

def merge_smart_tags_from_list(list_tags, cached_tags):
    res = list(list_tags)
    for t in cached_tags:
        t_up = t.upper()
        is_dynamic = '%' in t_up or '2X' in t_up or t_up in ['FREE', '免费'] or '剩余' in t_up
        if not is_dynamic and t not in res:
            res.append(t)
    return res

def merge_smart_tags_from_details(details_tags, cached_tags):
    res = list(details_tags)
    has_discount = any('%' in x.upper() or '2X' in x.upper() for x in res)
    has_free = any(x.upper() in ['FREE', '免费'] for x in res)
    has_time = any('剩余' in x for x in res)
    has_clock = any('🕒' in x for x in res)
    
    for t in cached_tags:
        if t in res: continue
        t_up = t.upper()
        if '%' in t_up or '2X' in t_up:
            if not has_discount: res.append(t)
        elif t_up in ['FREE', '免费']:
            if not has_free: res.append(t)
        elif '剩余' in t_up:
            if not has_time: res.append(t)
        elif '🕒' in t_up:
            if not has_clock: res.append(t)
        else:
            res.append(t)
    return res

def auto_extract_tags(text, current_tags):
    en_matches = re.findall(r'(?i)\b(4K|2160P|1440P|1080P|720P|WEB-DL|BLU-RAY|REMUX|HDR10\+|HDR10|HDRVIVID|HDR|DOVI|DV|SDR|60FPS|HFR|HQ|H\.?265|H\.?264|HEVC|AAC|DDP|ATMOS|10BIT)\b', text)
    cn_matches = re.findall(r'(杜比|高帧|高码|臻彩MAX|高分|完结|国语|中字|英字|粤语|英语|简繁|双语|官方|首发)', text)
    disc_matches = re.findall(r'(50%|30%|2X)', text.upper())
    
    all_new = [m.upper() for m in en_matches] + cn_matches + disc_matches
    for tag in all_new:
        tag_up = tag.upper()
        if not any(tag_up in t.upper() or t.upper() in tag_up for t in current_tags):
            current_tags.append(tag)
    return current_tags

def sort_tags(tags):
    top_pri, top_sec, bot_disc, bot_pri, bot_sec = [], [], [], [], []
    remaining = list(tags)
    
    t_res = ['4K', '2160P', '1440P', '1080P', '720P']
    t_hdr = ['HDRVIVID', 'HDR10+', 'HDR10', 'HDR', 'DOVI', 'DV', 'SDR']
    t_fps = ['60FPS', 'HFR', '高帧', '臻彩MAX', 'BLU-RAY', 'REMUX']
    t_enc = ['WEB-DL', 'H.265', 'H.264', 'H265', 'H264', 'HEVC', 'AAC', 'DDP', 'ATMOS', '杜比', '10BIT', 'HQ', '高码']
    
    for t in list(remaining):
        t_upper = t.upper()
        if '%' in t_upper or '2X' in t_upper or t_upper in ['免费', 'FREE', '30%', '50%']:
            if t_upper not in ['FREE', '免费']:
                bot_disc.append(t)
            remaining.remove(t)
    
    t_status = ['热门', '完结', '首发', '高分', 'DIY']
    t_lang = ['国语', '中字', '英字', '粤语', '英语', '简繁', '双语', '官方', '字幕']
    
    for kw in t_res + t_hdr + t_fps:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                top_pri.append(t)
                remaining.remove(t)
                
    for kw in t_enc:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                top_sec.append(t)
                remaining.remove(t)
                
    for kw in t_status:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                bot_pri.append(t)
                remaining.remove(t)
                
    for kw in t_lang:
        for t in list(remaining):
            if kw in t.upper() and t in remaining:
                bot_sec.append(t)
                remaining.remove(t)
                
    for t in list(remaining):
        bot_pri.append(t)
        
    return top_pri, top_sec, bot_disc, bot_pri, bot_sec

def fetch_details_info(tid):
    try:
        r = HTTP_SESSION.get(f"{BASE_URL}/details.php?id={tid}", headers=HEADERS, proxies=PROXIES)
        raw_html = r.text
        soup = BeautifulSoup(raw_html, 'html.parser')
        extra_tags = []

        is_global_free = bool(re.search(r'(?:全站|全局).*?(?:Free|免费)', raw_html, re.IGNORECASE))
        if is_global_free: extra_tags.append('Free')

        time_match = re.search(r'(?:免费剩余时间|免费剩余|优惠剩余时间|剩余时间|还有|剩余)[^\d<]{0,30}(?:<[^>]+>)*\s*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', raw_html)
        if time_match:
            extra_tags.append(f"剩余时间: {time_match.group(1).strip()}")
        else:
            text_clean = soup.get_text(separator=' ')
            tm2 = re.search(r'(?:免费剩余时间|免费剩余|优惠剩余时间|剩余时间|还有|剩余)[::\s]+(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', text_clean)
            if tm2: extra_tags.append(f"剩余时间: {tm2.group(1).strip()}")

        img_src = ""
        descr_div = soup.find('div', id='kdescr')
        if descr_div:
            img = descr_div.find('img')
            if img: img_src = img.get('data-src') or img.get('src') or ""
        if not img_src:
            for img in soup.find_all('img'):
                src = img.get('data-src') or img.get('src') or ""
                if src and not any(x in src.lower() for x in ['category', 'smilies', 'icon', 'logo', 'avatar', 'rating', 'button', 'rule']):
                    img_src = src
                    break
        if img_src and not img_src.startswith('http'):
            img_src = f"{BASE_URL}/" + img_src

        size = "未知"
        size_match = re.search(r'大小.*?([\d\.]+\s*[KMGTP]B)', raw_html, re.IGNORECASE)
        if size_match: size = size_match.group(1)

        h1 = soup.find('h1')
        release_group = ""
        h1_text = ""
        if h1:
            h1_text = h1.get_text(strip=True)
            for kw in ['免费', 'FREE', '50%', '30%', '2X']:
                if kw in h1_text.upper():
                    if kw in ['免费', 'FREE']:
                        if 'Free' not in extra_tags: extra_tags.append('Free')
                    else:
                        if kw not in extra_tags: extra_tags.append(kw)
            
            for span in h1.find_all('span', class_=re.compile(r'tag|label|badge', re.I)):
                text = span.get_text(strip=True).replace('[', '').replace(']', '').strip()
                if text.upper() in ['FREE', '免费']:
                    if 'Free' not in extra_tags: extra_tags.append('Free')
                elif text and text not in extra_tags and len(text) <= 15:
                    extra_tags.append(text)
                    
            group_match = re.search(r'-([A-Za-z0-9@_]+)$', h1_text)
            if group_match:
                release_group = group_match.group(1).upper()

        sub_td = soup.find('td', class_='rowhead', string=re.compile('副标题|副標題'))
        sub_text = ""
        if sub_td:
            sub_text = sub_td.find_next_sibling('td').get_text(strip=True)
            
        extra_tags = auto_extract_tags(h1_text + " " + sub_text, extra_tags)
        
        page_clean_text = soup.get_text(separator=' ')
        pub_exact = re.search(r'(?:发布时间|添加时间|上传时间|创建时间)[^\d]*(\d{4}-\d{2}-\d{2}\s*\d{2}:\d{2}(?::\d{2})?)', page_clean_text)
        if pub_exact:
            extra_tags.append(f"🕒 {pub_exact.group(1)}")
        else:
            pub_rel = re.search(r'发布于\s*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)\s*前', page_clean_text)
            if pub_rel:
                extra_tags.append(f"🕒 {re.sub(r'\s+', '', pub_rel.group(1))}前")
        
        return img_src, size, purify_tags(extra_tags), release_group
    except Exception:
        return "", "未知", [], ""

def is_real_sticky(row):
    for img in row.find_all('img'):
        src = img.get('src', '').lower()
        alt = img.get('alt', '').lower()
        title = img.get('title', '').lower()
        cls = ' '.join(img.get('class', [])).lower()
        if 'sticky' in cls: return True
        if alt in ['sticky', '置顶'] or title in ['sticky', '置顶']: return True
        if any(x in src for x in ['sticky.gif', 'pin.gif', 'pro_sticky.gif']): return True
        
    for tag in row.find_all(['span', 'font', 'b']):
        t = tag.get_text(strip=True).upper()
        if t in ['[置顶]', '置顶', '[STICKY]', 'STICKY']: return True
        if 'sticky' in ' '.join(tag.get('class', [])).lower(): return True
            
    tr_cls = ' '.join(row.get('class', [])).lower()
    if any(x in tr_cls for x in ['sticky_bg', 'sticky_blank', 'pro_sticky']): return True
    return False

def parse_torrents_page(target_url_base, seen_ids, is_search=False, skip_sticky=False, start_page=0, max_pages=1):
    torrents = []
    try:
        for page in range(start_page, start_page + max_pages):
            url = f"{target_url_base}&page={page}" if "?" in target_url_base else f"{target_url_base}?page={page}"
            resp = HTTP_SESSION.get(url, headers=HEADERS, proxies=PROXIES)
            
            if "登录" in resp.text and "torrents.php" not in resp.url: return None, "⚠️ Cookie 已失效!请更新。"
            if resp.status_code != 200: break

            is_global_free = bool(re.search(r'(?:全站|全局).*?(?:Free|免费)', resp.text, re.IGNORECASE))
            soup = BeautifulSoup(resp.text, 'html.parser')
            
            for row in soup.find_all('tr'):
                if skip_sticky and is_real_sticky(row): continue

                tds = row.find_all('td')
                if len(tds) < 6: continue
                title_a = row.find('a', href=lambda h: h and h.startswith('details.php?id='))
                if not title_a: continue
                
                tid = re.search(r'id=(\d+)', title_a['href']).group(1)
                title = title_a.get('title') or title_a.get_text(strip=True)
                if not title and title_a.find('b'): title = title_a.find('b').get_text(strip=True)
                if not title or tid in seen_ids: continue
                seen_ids.add(tid)
                link = f"{BASE_URL}/" + title_a['href']
                
                release_group = ""
                group_match = re.search(r'-([A-Za-z0-9@_]+)$', title.strip())
                if group_match: release_group = group_match.group(1)
                
                try: 
                    size = tds[-5].get_text(strip=True)
                    seeders = tds[-4].get_text(strip=True)
                    leechers = tds[-3].get_text(strip=True)
                    time_col_td = tds[-6]
                except: 
                    size, seeders, leechers, time_col_td = "未知", "-", "-", None

                img_src = ""
                td = title_a.find_parent('td')
                tags = []
                
                if is_global_free: tags.append('Free')
                
                if time_col_td:
                    time_span = time_col_td.find('span', title=re.compile(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'))
                    t_text = time_span.get_text(separator='', strip=True) if time_span else time_col_td.get_text(separator='', strip=True)
                    if t_text and any(x in t_text for x in ['年', '月', '周', '天', '时', '分', '秒']):
                        clean_t = re.sub(r'\s+', '', t_text)
                        if not clean_t.endswith('前') and not re.search(r'\d{4}-\d{2}-\d{2}', clean_t):
                            clean_t += '前'
                        tags.append(f"🕒 {clean_t}")
                    elif re.search(r'\d{4}-\d{2}-\d{2}', t_text):
                        tags.append(f"🕒 {t_text.strip()}")
                
                subtitle = ""
                if td:
                    raw_html = str(td)
                    
                    if not any('🕒' in t for t in tags):
                        t_match = re.search(r'\b(20\d{2}-\d{2}-\d{2}\s+\d{2}:\d{2}(?::\d{2})?)\b', raw_html)
                        if t_match: tags.append(f"🕒 {t_match.group(1)}")

                    time_matches = re.finditer(r'(?:免费剩余时间|免费剩余|剩余时间|剩余)[::\s]*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', raw_html)
                    for tm in time_matches:
                        t_str = f"剩余时间: {tm.group(1).strip()}"
                        if t_str not in tags: tags.append(t_str)

                    for icon in td.find_all('img'):
                        alt = str(icon.get('alt') or '')
                        title_attr = str(icon.get('title') or '')
                        combined_text = alt + " " + title_attr
                        if '免费' in combined_text or 'Free' in combined_text:
                            if 'Free' not in tags: tags.append('Free')
                        if icon.get('src', '') != img_src: 
                            icon.replace_with(soup.new_tag("span", string=f" [{alt}] "))
                    
                    for span in td.find_all('span'):
                        text = span.get_text(strip=True)
                        title_attr = str(span.get('title') or '')
                        combined = (text + " " + title_attr).upper()
                        if 'FREE' in combined or '免费' in combined:
                            if 'Free' not in tags: tags.append('Free')
                        for disc in ['50%', '30%', '2X']:
                            if disc in combined and disc not in tags: tags.append(disc)
                                
                        text_clean = text.replace('[', '').replace(']', '').strip()
                        if not text_clean: continue
                        
                        span_class = ' '.join(span.get('class', [])).lower()
                        is_valid_class = bool(re.search(r'tag|label|badge', span_class))
                        is_known_kw = bool(text_clean.upper() in [k.upper() for k in TECH_KEYWORDS])
                        if (is_valid_class or is_known_kw) and text_clean.upper() in [k.upper() for k in TECH_KEYWORDS] or re.match(r'^[\d]+%$', text_clean):
                            if text_clean not in tags: tags.append(text_clean)
                            span.replace_with(soup.new_tag("span", string=f" [{text_clean}] "))
                    
                    subtitle = td.get_text(separator=' | ', strip=True).replace(title, '').strip(' | ')
                    subtitle = re.sub(r'(?i)\[?(?:Sticky|置顶|poster)\]?[\s\|]*', '', subtitle)
                    
                    inline_time = re.search(r'\[?(?:剩余时间)[::\s]*\]?[\s\|]*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', subtitle)
                    if inline_time:
                        t_str = f"剩余时间: {inline_time.group(1).strip()}"
                        if t_str not in tags: tags.append(t_str)
                        subtitle = subtitle.replace(inline_time.group(0), '')
                    
                    clean_sub = subtitle
                    for m in re.finditer(r'\[(.*?)\]', subtitle):
                        tag = m.group(1).strip(' |[]')
                        if tag.upper() in [k.upper() for k in TECH_KEYWORDS] or re.match(r'^[\d]+%$', tag) or tag.upper() in ['热门']:
                            if tag not in tags: tags.append(tag)
                            clean_sub = clean_sub.replace(m.group(0), '')
                        else:
                            clean_sub = clean_sub.replace(m.group(0), tag)
                    
                    clean_sub = re.sub(r'热门|免费', '', clean_sub)
                    parts = [p.strip() for p in clean_sub.split('|') if p.strip()]
                    kept_sub = []
                    for p in parts:
                        clean_p = re.sub(r'^[()\[\]\-|\s]+|[()\[\]\-|\s]+$', '', p)
                        if not clean_p: continue
                        if clean_p.upper() in [k.upper() for k in TECH_KEYWORDS]:
                            if clean_p not in tags: tags.append(clean_p)
                        else:
                            kept_sub.append(p)
                    subtitle = ' | '.join(kept_sub)
                
                tags = auto_extract_tags(title + " " + subtitle, tags)
                tags = purify_tags(tags)

                torrents.append({
                    'id': tid, 'title': title, 'link': link, 'subtitle': subtitle, 'img': img_src,
                    'seeders': seeders, 'leechers': leechers, 'size': size, 'tags': tags, 'group': release_group
                })
                
                if len(torrents) >= 50 and max_pages > 1: break
            if len(torrents) >= 50 and max_pages > 1: break
            
        return torrents, None
    except Exception as e:
        return None, f"网络请求异常: {str(e)}"

def background_monitor():
    last_sign_date = None
    while True:
        try:
            current_date = datetime.datetime.now().strftime("%Y-%m-%d")
            if last_sign_date != current_date:
                r = HTTP_SESSION.get(SIGNIN_URL, headers=HEADERS, proxies=PROXIES)
                r.encoding = 'utf-8'
                res_text = r.text
                if any(kw in res_text for kw in ["已经签到", "请明天再来", "签到成功", "魔力值", "电力值", "次签到", "退下", "已经"]):
                    last_sign_date = current_date
        except Exception: pass

        try:
            current_off, err = parse_torrents_page(OFFICIAL_URL, set(), skip_sticky=False, max_pages=2)
            if current_off:
                off_dict = load_cache('official')
                for item in current_off[:5]:
                    tid_str = str(item['id'])
                    if tid_str not in off_dict or not off_dict[tid_str].get('img') or 'data:image/svg+xml' in off_dict[tid_str]['img'] or off_dict[tid_str].get('size') in ['未知', '加载中...']:
                        det_img, det_size, det_tags, det_group = fetch_details_info(item['id'])
                        if det_img: item['img'] = det_img
                        if det_size and det_size != "未知": item['size'] = det_size
                        if det_group and not item.get('group'): item['group'] = det_group
                        if det_tags:
                            item['tags'] = purify_tags(merge_smart_tags_from_details(det_tags, item.get('tags', [])))

                    if tid_str in off_dict:
                        cached = off_dict[tid_str]
                        if cached.get('img') and 'data:image/svg+xml' not in cached['img']: item['img'] = cached['img']
                        if cached.get('size') not in ['未知', '加载中...']: item['size'] = cached['size']
                        if not item.get('group') and cached.get('group'): item['group'] = cached['group']
                        item['tags'] = purify_tags(merge_smart_tags_from_list(item.get('tags', []), cached.get('tags', [])))
                        
                    off_dict[tid_str] = item
                save_cache(off_dict, 'official')
        except Exception: pass

        try:
            current_rec, err = parse_torrents_page(COMPREHENSIVE_URL, set(), skip_sticky=True, max_pages=4)
            if current_rec:
                rec_dict = load_cache('recent')
                for item in current_rec[:5]:
                    tid_str = str(item['id'])
                    if tid_str not in rec_dict or not rec_dict[tid_str].get('img') or 'data:image/svg+xml' in rec_dict[tid_str]['img'] or rec_dict[tid_str].get('size') in ['未知', '加载中...']:
                        det_img, det_size, det_tags, det_group = fetch_details_info(item['id'])
                        if det_img: item['img'] = det_img
                        if det_size and det_size != "未知": item['size'] = det_size
                        if det_group and not item.get('group'): item['group'] = det_group
                        if det_tags:
                            item['tags'] = purify_tags(merge_smart_tags_from_details(det_tags, item.get('tags', [])))

                    if tid_str in rec_dict:
                        cached = rec_dict[tid_str]
                        if cached.get('img') and 'data:image/svg+xml' not in cached['img']: item['img'] = cached['img']
                        if cached.get('size') not in ['未知', '加载中...']: item['size'] = cached['size']
                        if not item.get('group') and cached.get('group'): item['group'] = cached['group']
                        item['tags'] = purify_tags(merge_smart_tags_from_list(item.get('tags', []), cached.get('tags', [])))
                        
                    rec_dict[tid_str] = item
                save_cache(rec_dict, 'recent')
        except Exception: pass

        time.sleep(900)

threading.Thread(target=background_monitor, daemon=True).start()

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>织梦PT 手机端</title>
    <style>
        :root { --bg-color: #f7f7f7; --card-bg: #ffffff; --text-main: #333333; --text-sub: #888888; --border-color: #eeeeee; --topbar-bg: #ffffff; --icon-bg: #fef3c7; --primary-color: #f59e0b; }
        [data-theme="dark"] { --bg-color: #121212; --card-bg: #1e1e1e; --text-main: #eeeeee; --text-sub: #aaaaaa; --border-color: #333333; --topbar-bg: #1e1e1e; --icon-bg: #452e05; --primary-color: #fbbf24; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background-color: var(--bg-color); color: var(--text-main); margin: 0; padding: 0; padding-top: 55px; transition: background-color 0.3s; }
        
        .top-bar { position: fixed; top: 0; left: 0; right: 0; height: 50px; background: var(--topbar-bg); display: flex; align-items: center; justify-content: space-between; padding: 0 15px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); z-index: 100; transition: background 0.3s; }
        .menu-btn { width: 22px; height: 16px; position: relative; cursor: pointer; display: flex; flex-direction: column; justify-content: space-between; padding: 0; }
        .menu-btn span { display: block; height: 2px; width: 100%; background: var(--text-main); border-radius: 2px; transition: all 0.3s ease; }
        .menu-btn.open span:nth-child(1) { transform: translateY(7px) rotate(45deg); }
        .menu-btn.open span:nth-child(2) { opacity: 0; }
        .menu-btn.open span:nth-child(3) { transform: translateY(-7px) rotate(-45deg); }

        .logo { font-weight: 800; font-size: 20px; color: var(--primary-color); letter-spacing: 1px; display: flex; align-items: center; gap: 4px;}
        .logo-icon { font-size: 22px; }
        
        .theme-half-circle { width: 24px; height: 24px; cursor: pointer; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: transform 0.35s ease; color: var(--text-main); user-select: none; }
        [data-theme="dark"] .theme-half-circle { transform: rotate(180deg); }

        .sidebar { position: fixed; top: 0; left: -260px; bottom: 0; width: 260px; background: var(--card-bg); z-index: 1001; transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 2px 0 10px rgba(0,0,0,0.1); padding-top: 60px; display: flex; flex-direction: column; }
        .sidebar.open { left: 0; }
        .menu-item { padding: 16px 24px; font-size: 16px; font-weight: 500; color: var(--text-main); text-decoration: none; display: block; border-bottom: 1px solid var(--border-color); }
        .menu-item.active { color: var(--primary-color); border-left: 4px solid var(--primary-color); padding-left: 20px; background: rgba(245,158,11,0.1); }
        .overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1000; opacity: 0; pointer-events: none; transition: opacity 0.3s; }
        .overlay.open { opacity: 1; pointer-events: auto; }

        .container { padding: 5px 10px 10px 10px; }
        .global-search-container { display: flex; gap: 8px; margin: 5px 5px 15px 5px; align-items: center; background: var(--card-bg); padding: 5px; border-radius: 20px; border: 1px solid var(--border-color); }
        .search-input { flex: 1; padding: 8px 15px; border: none; outline: none; font-size: 14px; background: transparent; color: var(--text-main); }
        .search-btn { background: rgba(245,158,11,0.1); color: var(--primary-color); border: none; width: 36px; height: 36px; border-radius: 18px; font-weight: bold; font-size: 16px; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        
        .list-item { display: flex; gap: 12px; padding: 15px 5px; border-bottom: 1px solid var(--border-color); }
        .poster-wrapper { position: relative; flex-shrink: 0; width: 100px; height: 140px; }
        .poster { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; background-color: #e0e0e0; }
        .tag-free { position: absolute; top: 0; left: 0; background: #22c55e; color: #fff; font-size: 10px; font-weight: bold; padding: 2px 6px; border-radius: 8px 0 8px 0; z-index: 10; }
        
        .info { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; justify-content: space-between; padding-bottom: 2px; }
        .title { font-size: 15px; font-weight: bold; margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height: 1.3; cursor: pointer; }
        .subtitle { font-size: 12px; color: var(--text-sub); line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; margin-bottom: 4px; }
        .subtitle:empty { display: none; margin: 0; }
        
        .stats-and-download { display: flex; justify-content: space-between; align-items: center; gap: 8px; width: 100%; margin-bottom: 4px; }
        .stats-row { font-size: 12px; color: var(--text-sub); display: flex; align-items: center; gap: 6px; overflow-x: auto; white-space: nowrap; scrollbar-width: none; flex: 1; min-width: 0; }
        .stats-row::-webkit-scrollbar { display: none; }
        .stat-item { display: flex; align-items: center; gap: 2px; flex-shrink: 0; }
        .seed-icon { color: #22c55e; font-size: 10px; }
        .leech-icon { color: #ef4444; font-size: 10px; }
        
        .tags-wrapper { display: flex; flex-direction: column; gap: 6px; margin-top: auto; width: 100%; overflow: hidden; padding-top: 2px; }
        .tags-top, .tags-bottom { display: flex; gap: 6px; overflow-x: auto; white-space: nowrap; scrollbar-width: none; align-items: center; }
        .tags-top:empty, .tags-bottom:empty { display: none; }
        .secondary-tag { display: none !important; }
        .show-extra .secondary-tag { display: inline-flex !important; }
        .badge-toggle { background: #e5e7eb; color: #6b7280; font-size: 10px; padding: 2px 8px; border-radius: 4px; flex-shrink: 0; cursor: pointer; font-weight: bold; }
        [data-theme="dark"] .badge-toggle { background: #374151; color: #9ca3af; }
        
        .badge { background: #8b5cf6; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-discount { background: #ef4444; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-tech { background: #0ea5e9; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-lang { background: #10b981; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-group { background: #ec4899; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; font-weight: bold; } 
        .badge-zmpt { background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%); color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; font-weight: bold; }

        .download-btn { background: var(--primary-color); color: #fff; font-size: 11px; padding: 3px 9px; border-radius: 4px; font-weight: bold; border: none; cursor: pointer; flex-shrink: 0; }

        /* 底部滑出式多功能面板(单集直推 + 双RSS源精准建规则) */
        .qbt-modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.55); z-index: 2000; opacity: 0; pointer-events: none; transition: opacity 0.25s; }
        .qbt-modal-mask.open { opacity: 1; pointer-events: auto; }
        .qbt-sheet { position: fixed; left: 0; right: 0; bottom: -100%; background: var(--card-bg); border-radius: 16px 16px 0 0; padding: 16px 16px 24px 16px; z-index: 2001; transition: bottom 0.28s cubic-bezier(0.2, 0.8, 0.2, 1); max-height: 86vh; overflow-y: auto; box-shadow: 0 -4px 20px rgba(0,0,0,0.18); }
        .qbt-sheet.open { bottom: 0; }
        .qbt-sheet-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .qbt-sheet-title { font-size: 14px; font-weight: bold; color: var(--text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 88%; }
        .qbt-close { font-size: 20px; color: var(--text-sub); cursor: pointer; padding: 0 4px; }
        
        .mode-tabs { display: flex; background: var(--bg-color); padding: 4px; border-radius: 10px; border: 1px solid var(--border-color); margin-bottom: 10px; }
        .mode-tab { flex: 1; text-align: center; padding: 7px 0; font-size: 13px; font-weight: bold; border-radius: 7px; cursor: pointer; color: var(--text-sub); transition: all 0.2s; }
        .mode-tab.active { background: var(--primary-color); color: #fff; box-shadow: 0 2px 6px rgba(245,158,11,0.25); }

        .qbt-sec-lbl { font-size: 12px; font-weight: bold; color: var(--text-sub); margin: 11px 0 5px 0; display: flex; justify-content: space-between; align-items: center; }
        .qbt-pills { display: flex; flex-wrap: wrap; gap: 7px; }
        .qbt-pill { font-size: 12px; padding: 5px 11px; border-radius: 15px; background: var(--bg-color); color: var(--text-main); border: 1px solid var(--border-color); cursor: pointer; user-select: none; }
        .qbt-pill.active { background: var(--primary-color); color: #fff; border-color: var(--primary-color); font-weight: bold; }
        .qbt-pill.spec-pill.active { background: #0ea5e9; border-color: #0ea5e9; }
        .qbt-pill.feed-pill.active { background: #10b981; border-color: #10b981; }
        .qbt-input { width: 100%; box-sizing: border-box; padding: 8px 11px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-color); color: var(--text-main); font-size: 12px; margin-top: 4px; outline: none; font-family: monospace; }
        .qbt-check-row { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; font-size: 12px; color: var(--text-main); background: var(--bg-color); padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); }
        .qbt-actions { display: flex; gap: 10px; margin-top: 16px; }
        .qbt-submit-btn { flex: 1; background: var(--primary-color); color: #fff; border: none; padding: 11px; border-radius: 8px; font-size: 14px; font-weight: bold; cursor: pointer; }
        .qbt-direct-link { padding: 11px 14px; border-radius: 8px; background: var(--bg-color); color: var(--text-sub); font-size: 13px; text-decoration: none; border: 1px solid var(--border-color); text-align: center; font-weight: 500; }

        /* RSS 规则列表卡片样式 */
        .rss-card { background: var(--card-bg); border-radius: 10px; padding: 14px; margin-bottom: 10px; border: 1px solid var(--border-color); }
        .rss-card-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
        .rss-rule-name { font-size: 15px; font-weight: bold; color: var(--text-main); }
        .rss-meta { font-size: 12px; color: var(--text-sub); line-height: 1.6; word-break: break-all; }
        .rss-regex-box { background: var(--bg-color); padding: 6px 8px; border-radius: 6px; font-family: monospace; font-size: 11px; color: var(--primary-color); margin: 6px 0; border: 1px solid var(--border-color); word-break: break-all; }
        .rss-del-btn { background: #fee2e2; color: #dc2626; border: none; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: bold; cursor: pointer; }
        .rss-toggle-btn { background: #dcfce7; color: #15803d; border: none; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: bold; cursor: pointer; margin-right: 6px; }
        .rss-toggle-btn.off { background: #f4f4f5; color: #71717a; }

        .account-box { background: var(--card-bg); border-radius: 12px; padding: 20px; text-align: center; border: 1px solid var(--border-color); }
        .avatar { width: 70px; height: 70px; background: var(--primary-color); color: #fff; border-radius: 35px; line-height: 70px; font-size: 24px; margin: 0 auto 10px; }
        .account-name { font-size: 18px; font-weight: bold; }
        .stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 20px; }
        .stat-val { font-size: 18px; font-weight: bold; color: var(--primary-color); margin-bottom: 4px; }
        .stat-lbl { font-size: 12px; color: var(--text-sub); }
        .btn-signin { background: #22c55e; color: #fff; width: 100%; padding: 12px; font-size: 16px; border-radius: 8px; font-weight: bold; margin-top: 25px; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <script>
        function setTheme(theme) {
            const html = document.documentElement;
            if (theme === 'dark') { html.setAttribute('data-theme', 'dark'); }
            else if (theme === 'light') { html.removeAttribute('data-theme'); }
            else { 
                if (window.matchMedia('(prefers-color-scheme: dark)').matches) html.setAttribute('data-theme', 'dark');
                else html.removeAttribute('data-theme');
            }
        }
        let currentTheme = localStorage.getItem('zmpt_theme') || 'auto';
        setTheme(currentTheme);
        
        window.toggleTags = function(btn) {
            const wrapper = btn.closest('.tags-wrapper');
            wrapper.classList.toggle('show-extra');
            btn.innerText = wrapper.classList.contains('show-extra') ? '收起 ▴' : '... ▾';
        };
    </script>

    <div class="top-bar">
        <div class="menu-btn" id="menuBtn" onclick="toggleMenu()">
            <span></span><span></span><span></span>
        </div>
        <div class="logo"><span class="logo-icon">🌟</span> ZM</div>
        <div class="theme-half-circle" onclick="cycleTheme()" title="切换深浅模式">
            <svg viewBox="0 0 24 24" width="20" height="20">
                <circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/>
                <path d="M 12 3 A 9 9 0 0 0 12 21 Z" fill="currentColor"/>
            </svg>
        </div>
    </div>

    <div class="overlay" id="overlay" onclick="toggleMenu()"></div>
    <div class="sidebar" id="sidebar">
        <a href="/?tab=recent" class="menu-item {% if tab == 'recent' %}active{% endif %}">最近发布</a>
        <a href="/?tab=official" class="menu-item {% if tab == 'official' %}active{% endif %}">官种发布</a>
        <a href="/?tab=rss" class="menu-item {% if tab == 'rss' %}active{% endif %}">📡 RSS 订阅规则</a>
        <a href="/?tab=account" class="menu-item {% if tab == 'account' %}active{% endif %}">我的帐号</a>
    </div>

    <!-- 🚀 底部多功能面板:单集直推 + 电视剧/动漫双RSS源精准建规则 -->
    <div class="qbt-modal-mask" id="qbtMask" onclick="closeQbtModal()"></div>
    <div class="qbt-sheet" id="qbtSheet">
        <div class="qbt-sheet-header">
            <div class="qbt-sheet-title" id="qbtSheetTitle">操作面板</div>
            <div class="qbt-close" onclick="closeQbtModal()">✕</div>
        </div>

        <div class="mode-tabs">
            <div class="mode-tab active" id="modeTabPush" onclick="switchModalMode('push')">🚀 单集立即推送</div>
            <div class="mode-tab" id="modeTabRss" onclick="switchModalMode('rss')">📡 精准 RSS 追更</div>
        </div>

        <div class="qbt-sec-lbl">
            <span>1. 选择目标 qBittorrent 节点</span>
            <span id="qbtConnStatus" style="font-weight:normal; font-size:11px;"></span>
        </div>
        <div class="qbt-pills" id="qbtServerPills">
            {% for sid, scfg in qbt_servers.items() %}
            <div class="qbt-pill" data-srv="{{ sid }}" onclick="selectQbtServer('{{ sid }}')">{{ scfg.name }}</div>
            {% endfor %}
        </div>

        <div class="qbt-sec-lbl">
            <span>2. 选择分类 (自动同步所选节点)</span>
            <span id="qbtCatPath" style="font-weight:normal; font-size:11px; max-width:52%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"></span>
        </div>
        <div class="qbt-pills" id="qbtCatPills">
            <div class="qbt-pill active" data-cat="" onclick="selectQbtCat('', '')">不设分类(默认路径)</div>
        </div>

        <div class="qbt-sec-lbl"><span>3. 附加标签 (默认洗码,自动附加版本标签)</span></div>
        <div class="qbt-pills" id="qbtTagPills"></div>
        <input type="text" id="qbtCustomTags" class="qbt-input" value="洗码" oninput="isTagsManuallyEdited = true">

        <!-- 📡 RSS 专属精准过滤配置区 -->
        <div id="rssConfigZone" style="display:none;">
            <div class="qbt-sec-lbl">
                <span>4. 选择绑定的固定订阅源 (电视剧 / 动漫防漏源)</span>
            </div>
            <div class="qbt-pills" id="rssFeedPills"></div>

            <div class="qbt-sec-lbl"><span>5. 规则名称 & 剧名/集数核心</span></div>
            <input type="text" id="rssRuleName" class="qbt-input" placeholder="纯中文剧名 (或剧名+版本)">
            <input type="text" id="rssShowCore" class="qbt-input" placeholder="英文剧名.*E\d+" oninput="rebuildRssRegex()">

            <div class="qbt-sec-lbl"><span>6. 精准分辨率 / 色彩版本 / 制作组锁定</span></div>
            <div class="qbt-pills" id="rssSpecPills"></div>

            <div class="qbt-sec-lbl"><span>7. 最终正则预览 (mustContain,支持手动微调)</span></div>
            <input type="text" id="rssFinalRegex" class="qbt-input" placeholder="自动生成的精准正则">

            <div class="qbt-sec-lbl"><span>8. 排除关键词 (mustNotContain,防洗版/防合集包)</span></div>
            <input type="text" id="rssExcludeRegex" class="qbt-input" value="合集|Complete|Pack|全集|招募">

            <div class="qbt-check-row">
                <span>启用智能集数过滤 (Smart Filter 防同集重下)</span>
                <input type="checkbox" id="rssSmartFilter" style="width:18px; height:18px;">
            </div>
        </div>

        <div class="qbt-actions">
            <button class="qbt-submit-btn" id="qbtSubmitBtn" onclick="handleModalSubmit()">🚀 立即推送到 qB</button>
            <a id="qbtDirectBtn" href="#" class="qbt-direct-link">原文件</a>
        </div>
    </div>

    <div class="container" id="list-container">
        {% if tab in ['official', 'recent', 'search'] %}
        <form class="global-search-container" action="/" method="GET">
            <input type="hidden" name="tab" value="search">
            <input type="text" name="q" class="search-input" placeholder="输入关键词搜全站..." value="{{ query }}">
            <button type="submit" class="search-btn">🔍</button>
        </form>
        {% endif %}

        {% if error %}<div style="text-align:center; color:#ef4444; margin-top:30px; font-weight:bold;">{{ error }}</div>{% endif %}

        {% if tab == 'rss' %}
            <div style="margin: 8px 4px 12px 4px;">
                <div style="font-size:13px; font-weight:bold; color:var(--text-sub); margin-bottom:8px;">选择要查看的 qBittorrent 节点:</div>
                <div class="qbt-pills" id="rssManageNodes">
                    {% for sid, scfg in qbt_servers.items() %}
                    <div class="qbt-pill {% if loop.first %}active{% endif %}" data-srv="{{ sid }}" onclick="loadNodeRssRules('{{ sid }}')">{{ scfg.name }}</div>
                    {% endfor %}
                </div>
            </div>
            <div id="rssRulesContainer" style="margin-top:10px;">
                <div style="text-align:center; padding:30px; color:var(--text-sub);">正在加载节点订阅规则...</div>
            </div>
            <script>
                document.addEventListener("DOMContentLoaded", function() {
                    const savedSrv = localStorage.getItem('zmpt_qbt_srv') || '177';
                    loadNodeRssRules(savedSrv);
                });
                function loadNodeRssRules(srvId) {
                    localStorage.setItem('zmpt_qbt_srv', srvId);
                    document.querySelectorAll('#rssManageNodes .qbt-pill').forEach(el => {
                        el.classList.toggle('active', el.getAttribute('data-srv') === srvId);
                    });
                    const box = document.getElementById('rssRulesContainer');
                    box.innerHTML = '<div style="text-align:center; padding:30px; color:var(--text-sub);">正在读取 qB RSS 规则...</div>';
                    fetch('/api/qbt/rss/rules?server=' + encodeURIComponent(srvId))
                        .then(r => r.json())
                        .then(d => {
                            if (!d.ok) {
                                box.innerHTML = `<div style="text-align:center; color:#ef4444; padding:20px;">⚠️ ${d.msg}</div>`;
                                return;
                            }
                            const rules = d.rules || [];
                            if (rules.length === 0) {
                                box.innerHTML = `<div style="text-align:center; color:var(--text-sub); padding:30px;">该节点暂无 RSS 自动下载规则<br><span style="font-size:12px;">去种子列表点击“推送” -> 切换到“RSS 追更”即可一键创建</span></div>`;
                                return;
                            }
                            let html = '';
                            rules.forEach(r => {
                                const safeName = r.name.replace(/'/g, "\\'");
                                const feedLabel = r.feedLabel || '全部/已绑定源';
                                html += `
                                <div class="rss-card">
                                    <div class="rss-card-top">
                                        <div class="rss-rule-name">${r.enabled ? '🟢' : '⏸️'} ${r.name}</div>
                                        <div>
                                            <button class="rss-toggle-btn ${r.enabled ? '' : 'off'}" onclick="toggleRssRule('${srvId}', '${safeName}', ${!r.enabled})">${r.enabled ? '运行中' : '已暂停'}</button>
                                            <button class="rss-del-btn" onclick="deleteRssRule('${srvId}', '${safeName}')">删除</button>
                                        </div>
                                    </div>
                                    <div class="rss-meta">
                                        📡 订阅源: <b>${feedLabel}</b> &nbsp;|&nbsp; 📁 分类: <b>${r.assignedCategory || '未设'}</b> &nbsp;|&nbsp; 🏷️ 标签: <b>${(r.torrentParams && r.torrentParams.tags ? r.torrentParams.tags.join(',') : '') || '无'}</b>
                                    </div>
                                    <div class="rss-regex-box">匹配: ${r.mustContain || '(空)'}</div>
                                    ${r.mustNotContain ? `<div class="rss-meta" style="font-size:11px;">🚫 排除: ${r.mustNotContain}</div>` : ''}
                                    <div class="rss-meta" style="font-size:11px; margin-top:4px;">
                                        📌 智能集数过滤: ${r.smartFilter ? '开启' : '关闭'} &nbsp;|&nbsp; 历史命中: ${(r.previouslyMatchedEpisodes || []).length} 集
                                    </div>
                                </div>`;
                            });
                            box.innerHTML = html;
                        });
                }
                function toggleRssRule(srvId, ruleName, targetState) {
                    fetch('/api/qbt/rss/toggle', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({server: srvId, name: ruleName, enabled: targetState})
                    }).then(r => r.json()).then(d => {
                        if (d.ok) loadNodeRssRules(srvId);
                        else alert('❌ ' + d.msg);
                    });
                }
                function deleteRssRule(srvId, ruleName) {
                    if (!confirm('确定要删除追剧规则【' + ruleName + '】吗?')) return;
                    fetch('/api/qbt/rss/delete', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({server: srvId, name: ruleName})
                    }).then(r => r.json()).then(d => {
                        if (d.ok) loadNodeRssRules(srvId);
                        else alert('❌ ' + d.msg);
                    });
                }
            </script>

        {% elif tab == 'account' and user_info %}
        <div class="account-box">
            <div class="avatar">{{ user_info.username[:1] | upper }}</div>
            <div class="account-name">{{ user_info.username }}</div>
            <div class="stat-grid">
                <div><div class="stat-val">{{ user_info.bonus }}</div><div class="stat-lbl">电力值</div></div>
                <div><div class="stat-val">{{ user_info.ratio }}</div><div class="stat-lbl">分享率</div></div>
                <div><div class="stat-val">{{ user_info.upload }}</div><div class="stat-lbl">总上传</div></div>
                <div><div class="stat-val">{{ user_info.download }}</div><div class="stat-lbl">总下载</div></div>
            </div>
            <button id="signinBtn" class="btn-signin" onclick="doSignIn()">✅ 手动签到</button>
        </div>
        <script>
            function doSignIn() {
                const btn = document.getElementById('signinBtn');
                btn.innerText = '签到中...'; btn.disabled = true;
                fetch('/api/signin').then(r => r.json()).then(data => {
                    alert(data.msg); btn.innerText = '✅ 手动签到'; btn.disabled = false;
                }).catch(e => { alert('请求失败'); btn.innerText = '✅ 手动签到'; btn.disabled = false; });
            }
        </script>
        
        {% elif tab not in ['account', 'rss'] %}
            {% for item in torrents %}
            <div class="list-item" id="item-{{ item.id }}">
                <div class="poster-wrapper">
                    {% set needs_lazy = not item.img or ('data:image/svg+xml' in item.img) %}
                    <img class="poster {% if needs_lazy %}lazy-load{% endif %}" 
                         src="{{ item.img if item.img else 'data:image/svg+xml;utf8,<svg xmlns=\\'http://www.w3.org/2000/svg\\' width=\\'100\\' height=\\'140\\'><rect width=\\'100%\\' height=\\'100%\\' fill=\\'%23e6e6e6\\'/><text x=\\'50%\\' y=\\'50%\\' fill=\\'%23999\\' font-size=\\'12\\' font-family=\\'sans-serif\\' text-anchor=\\'middle\\' dominant-baseline=\\'middle\\'>加载海报</text></svg>' }}" 
                         {% if needs_lazy %}data-tid="{{ item.id }}"{% endif %}
                         referrerpolicy="no-referrer" alt="海报" onclick="window.open('{{ item.link }}', '_blank')">
                    {% if 'FREE' in item.tags|join(' ')|upper %}
                        <div class="tag-free">FREE</div>
                    {% endif %}
                </div>
                <div class="info">
                    <div class="title" onclick="window.open('{{ item.link }}', '_blank')">{{ item.title }}</div>
                    <div class="subtitle">{{ item.subtitle }}</div>
                    
                    <div class="stats-and-download">
                        <div class="stats-row">
                            <span class="stat-item" id="size-{{ item.id }}">📄 {{ item.size }}</span>
                            <span class="stat-item"><span class="seed-icon">▲</span> {{ item.seeders }}</span>
                            <span class="stat-item"><span class="leech-icon">▼</span> {{ item.leechers }}</span>
                            {% if item.group %}
                                {% if item.group|upper == 'ZMPT' %}
                                    <span class="badge-zmpt">💎 ZmPT</span>
                                {% else %}
                                    <span class="badge-group">{{ item.group }}</span>
                                {% endif %}
                            {% endif %}
                        </div>
                        <button type="button" class="download-btn" data-tid="{{ item.id }}" data-title="{{ item.title|e }}" data-sub="{{ item.subtitle|e }}" data-grp="{{ item.group|e }}" onclick="openQbtFromBtn(this)">推送</button>
                    </div>

                    <div class="tags-wrapper">
                        <div class="tags-top">
                            {% for tag in item.top_pri %}<span class="badge-tech">{{ tag }}</span>{% endfor %}
                            {% for tag in item.top_sec %}<span class="badge-tech secondary-tag">{{ tag }}</span>{% endfor %}
                        </div>
                        <div class="tags-bottom">
                            {% if item.time_tag %}<span class="badge-discount">{{ item.time_tag }}</span>{% endif %}
                            {% if item.clock_tag %}<span class="badge" style="background:#64748b;">{{ item.clock_tag }}</span>{% endif %}
                            {% for tag in item.bot_disc %}<span class="badge-discount">{{ tag }}</span>{% endfor %}
                            {% for tag in item.bot_pri %}<span class="badge">{{ tag }}</span>{% endfor %}
                            {% for tag in item.bot_sec %}<span class="badge-lang secondary-tag">{{ tag }}</span>{% endfor %}
                            {% if item.top_sec|length > 0 or item.bot_sec|length > 0 %}
                                <span class="badge-toggle" onclick="toggleTags(this)">... ▾</span>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
            
            {% if tab == 'search' and not torrents and query %}
                <div style="text-align:center; color:var(--text-sub); margin-top:30px;">找到 0 个结果</div>
            {% elif tab == 'search' and torrents %}
                <div style="text-align:center; color:var(--text-sub); margin: 20px 0; font-size:12px;">已展示当前页全部结果</div>
            {% elif tab in ['recent', 'official'] and not error %}
                <div id="load-more-sentinel" style="text-align:center; padding: 20px; color:var(--text-sub); font-size:12px; clear:both;">
                    向下划动,无痕加载更多... ⚡
                </div>
            {% endif %}
        {% endif %}
    </div>

    <script>
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        const menuBtn = document.getElementById('menuBtn');

        function toggleMenu() { 
            sidebar.classList.toggle('open'); 
            overlay.classList.toggle('open'); 
            menuBtn.classList.toggle('open');
        }

        function cycleTheme() {
            if (currentTheme === 'dark') currentTheme = 'light';
            else currentTheme = 'dark';
            localStorage.setItem('zmpt_theme', currentTheme);
            setTheme(currentTheme);
        }

        // 🚀 底部面板状态控制(支持单集推送 & 双订阅源精准RSS建规则)
        let currentModalMode = 'push';
        let currentPushTid = null;
        let currentQbtServer = localStorage.getItem('zmpt_qbt_srv') || '177';
        let currentQbtCat = localStorage.getItem('zmpt_qbt_cat_' + currentQbtServer) || '';
        let currentFeedKey = localStorage.getItem('zmpt_qbt_feed_' + currentQbtServer) || '电视剧';
        let nodeRssFeeds = {}; // { "电视剧": "url1", "动漫": "url2" }
        let rssSpecState = [];
        let rssBaseCnName = '';
        let isTagsManuallyEdited = false;

        function switchModalMode(mode) {
            currentModalMode = mode;
            document.getElementById('modeTabPush').classList.toggle('active', mode === 'push');
            document.getElementById('modeTabRss').classList.toggle('active', mode === 'rss');
            document.getElementById('rssConfigZone').style.display = (mode === 'rss') ? 'block' : 'none';
            document.getElementById('qbtSubmitBtn').innerText = (mode === 'rss') ? '📡 保存并下发 RSS 追更规则' : '🚀 立即推送到 qB';
        }

        function parseTitleForRss(title, sub, grp) {
            const BS = String.fromCharCode(92);

            // 1. 提取纯中文剧名
            let cnName = '';
            if (sub) {
                const skipWords = /^(分集|完结|官种|官方|国语|中字|粤语|英语|双语|简繁|热门|首发|禁转|DIY|4K|HDR|DV|HQ|SDR|杜比|高帧|高码)$/i;
                const parts = sub.split('|').map(s => s.trim()).filter(Boolean);
                for (let p of parts) {
                    if (!skipWords.test(p) && /[\u4e00-\u9fa5]/.test(p)) {
                        let cleaned = p.replace(/^.*?[::]/, '').split('/')[0].trim();
                        cleaned = cleaned.replace(/\s*(?:第\s*[一二三四五六七八九十百\d]+(?:\s*-\s*\d+)?\s*[集期话季]|更新至\s*\d+\s*[集期话]|全\s*\d+\s*[集期话]).*$/g, '').trim();
                        if (cleaned) {
                            cnName = cleaned;
                            break;
                        }
                    }
                }
            }

            // 2. 提取英文剧名 + E\d+
            let rawName = title;
            const cutMatch = title.match(/^(.*?)(?:[\s.\-_]+(?:S\d{1,2}(?:E\d+)?|E\d+|(?:19|20)\d{2}|2160p|1080p|720p))(?:[\s.\-_]|$)/i);
            if (cutMatch && cutMatch[1].trim()) {
                rawName = cutMatch[1].trim();
            }
            rawName = rawName.replace(/[\.\-_]+/g, ' ').replace(/\s+/g, ' ').trim();
            let showCore = rawName + '.*E' + BS + 'd+';

            // 3. 提取所有命中的要素,并记录它们在原标题中的真实位置 pos
            const specs = [];
            const allDefs = [
                {label: '2160p', test: /(?:^|[\s.\-_])(2160p|4K)(?:$|[\s.\-_])/i, regex: '2160p', active: true, inName: false, syncTag: false},
                {label: '1080p', test: /(?:^|[\s.\-_])1080p(?:$|[\s.\-_])/i, regex: '1080p', active: true, inName: false, syncTag: false},
                {label: 'HFR', test: /(?:^|[\s.\-_])(60fps|HFR)(?:$|[\s.\-_])/i, regex: '(?:60fps|HFR)', active: true, inName: true, syncTag: false},
                {label: '50fps', test: /(?:^|[\s.\-_])50fps(?:$|[\s.\-_])/i, regex: '50fps', active: true, inName: false, syncTag: false},
                {label: '30fps', test: /(?:^|[\s.\-_])30fps(?:$|[\s.\-_])/i, regex: '30fps', active: true, inName: false, syncTag: false},
                {label: 'MAXPLUS', test: /(?:^|[\s.\-_])MAXPLUS(?:$|[\s.\-_])/i, regex: 'MAXPLUS', active: true, inName: false, syncTag: false},
                {label: 'HQ', test: /(?:^|[\s.\-_])HQ(?:$|[\s.\-_])/i, regex: 'HQ', active: true, inName: true, syncTag: true},
                {label: 'HDR', test: /(?:^|[\s.\-_])(HDR|HDRVivid|HDR10\+?)(?:$|[\s.\-_])/i, regex: '(?:HDR|HDRVivid)', active: true, inName: true, syncTag: true},
                {label: 'SDR', test: /(?:^|[\s.\-_])SDR(?:$|[\s.\-_])/i, regex: 'SDR', active: true, inName: true, syncTag: true},
                {label: 'DV', test: /(?:^|[\s.\-_])(DV|DoVi)(?:$|[\s.\-_])/i, regex: '(?:DV|DoVi)', active: true, inName: true, syncTag: true},
                {label: 'H265', test: /H\.?265|HEVC|x265/i, regex: '(?:265|HEVC)', active: false, inName: false, syncTag: false},
                {label: 'H264', test: /H\.?264|AVC|x264/i, regex: '(?:264|AVC)', active: false, inName: false, syncTag: false}
            ];

            allDefs.forEach(d => {
                const pos = title.search(d.test);
                if (pos !== -1) {
                    specs.push({label: d.label, regex: d.regex, active: d.active, inName: d.inName, syncTag: d.syncTag, pos: pos});
                }
            });

            // 关键:严格按在原标题中实际出现的先后位置排序,彻底杜绝顺序颠倒导致匹配失败!
            specs.sort((a, b) => a.pos - b.pos);

            // 制作组永远排在最后
            if (grp) {
                const safeGrp = grp.replace(/[^A-Za-z0-9_@]/g, '');
                if (safeGrp) specs.push({label: safeGrp, regex: safeGrp, active: true, inName: false, syncTag: false, pos: 9999});
            }

            rssBaseCnName = cnName || rawName;
            rssSpecState = specs;
            document.getElementById('rssShowCore').value = showCore;
            renderRssSpecPills();
            rebuildRssRegex();
        }

        function renderRssSpecPills() {
            const box = document.getElementById('rssSpecPills');
            box.innerHTML = rssSpecState.map((s, idx) => 
                `<div class="qbt-pill spec-pill ${s.active ? 'active' : ''}" onclick="toggleRssSpec(${idx})">${s.active ? '✓ ' : ''}${s.label}</div>`
            ).join('');
        }

        function toggleRssSpec(idx) {
            rssSpecState[idx].active = !rssSpecState[idx].active;
            renderRssSpecPills();
            rebuildRssRegex();
        }

        function rebuildRssRegex() {
            const core = document.getElementById('rssShowCore').value.trim();
            const activeSpecs = rssSpecState.filter(s => s.active);
            const activeLabels = activeSpecs.map(s => s.label);
            
            // 1. 生成正向匹配正则
            const parts = [core, ...activeSpecs.map(s => {
                if (s.regex.includes('|') && !s.regex.startsWith('(')) return `(?:${s.regex})`;
                return s.regex;
            })].filter(Boolean);
            document.getElementById('rssFinalRegex').value = parts.join('.*');

            // 2. 自动生成排他排除词 (mustNotContain):没选中的版本特性全部自动拉黑,彻底防止串版
            const baseExcludes = ['合集', 'Complete', 'Pack', '全集', '招募'];
            const exclusivePool = [
                {label: 'DV', exclude: 'DV|DoVi'},
                {label: 'HDR', exclude: 'HDR|HDRVivid'},
                {label: 'HQ', exclude: 'HQ'},
                {label: 'HFR', exclude: '60fps|HFR'},
                {label: 'MAXPLUS', exclude: 'MAXPLUS'}
            ];
            const autoExcludes = exclusivePool
                .filter(item => !activeLabels.includes(item.label))
                .map(item => item.exclude);
            document.getElementById('rssExcludeRegex').value = [...baseExcludes, ...autoExcludes].join('|');

            // 3. 规则名称:纯中文剧名 + 允许的版本要素 (DV/HDR/SDR/HQ/HFR)
            const nameLabels = activeSpecs.filter(s => s.inName).map(s => s.label);
            const nameParts = [rssBaseCnName, ...nameLabels].filter(Boolean);
            document.getElementById('rssRuleName').value = nameParts.join(' ');

            // 4. 仅在未手动修改时,按优先级只同步【唯一一个】版本标签到 qB
            if (!isTagsManuallyEdited) {
                const verPriority = ['DV', 'HDR', 'HQ', 'SDR'];
                const matchedVers = activeSpecs.filter(s => s.syncTag).map(s => s.label);
                const singleVer = verPriority.find(v => matchedVers.includes(v));

                const customTagInp = document.getElementById('qbtCustomTags');
                let baseTags = customTagInp.value.split(/[,,]/).map(s => s.trim()).filter(Boolean);
                baseTags = baseTags.filter(t => !verPriority.includes(t));
                if (baseTags.length === 0) baseTags = ['洗码'];
                if (singleVer) baseTags.push(singleVer);
                customTagInp.value = baseTags.join(',');
            }
        }

        function openQbtFromBtn(btn) {
            openQbtModal(
                btn.getAttribute('data-tid'),
                btn.getAttribute('data-title'),
                btn.getAttribute('data-sub'),
                btn.getAttribute('data-grp')
            );
        }

        function openQbtModal(tid, title, sub, grp) {
            currentPushTid = tid;
            document.getElementById('qbtSheetTitle').innerText = title || ('种子 #' + tid);
            document.getElementById('qbtDirectBtn').href = '/download/' + tid;
            document.getElementById('qbtCustomTags').value = '洗码';
            isTagsManuallyEdited = false;

            parseTitleForRss(title || '', sub || '', grp || '');
            switchModalMode('push');

            document.getElementById('qbtMask').classList.add('open');
            document.getElementById('qbtSheet').classList.add('open');
            selectQbtServer(currentQbtServer);
        }

        function closeQbtModal() {
            document.getElementById('qbtMask').classList.remove('open');
            document.getElementById('qbtSheet').classList.remove('open');
        }

        function renderFeedPills() {
            const box = document.getElementById('rssFeedPills');
            const keys = Object.keys(nodeRssFeeds);
            if (keys.length === 0) {
                box.innerHTML = `<div class="qbt-pill feed-pill active">未配置固定源(将匹配全部)</div>`;
                return;
            }
            if (!keys.includes(currentFeedKey) && currentFeedKey !== 'ALL') {
                currentFeedKey = keys[0];
            }
            let html = keys.map(k => {
                const icon = k.includes('动漫') ? '🌸 ' : '📺 ';
                const isAct = (currentFeedKey === k);
                return `<div class="qbt-pill feed-pill ${isAct ? 'active' : ''}" onclick="selectRssFeed('${k}')">${icon}${k}</div>`;
            }).join('');
            if (keys.length > 1) {
                html += `<div class="qbt-pill feed-pill ${currentFeedKey === 'ALL' ? 'active' : ''}" onclick="selectRssFeed('ALL')">🔗 同时绑定全部(${keys.length}个)</div>`;
            }
            box.innerHTML = html;
        }

        function selectRssFeed(feedKey) {
            currentFeedKey = feedKey;
            localStorage.setItem('zmpt_qbt_feed_' + currentQbtServer, feedKey);
            renderFeedPills();
        }

        function selectQbtServer(srvId) {
            currentQbtServer = srvId;
            localStorage.setItem('zmpt_qbt_srv', srvId);
            currentQbtCat = localStorage.getItem('zmpt_qbt_cat_' + srvId) || '';
            currentFeedKey = localStorage.getItem('zmpt_qbt_feed_' + srvId) || '电视剧';

            document.querySelectorAll('#qbtServerPills .qbt-pill').forEach(el => {
                el.classList.toggle('active', el.getAttribute('data-srv') === srvId);
            });

            const statusEl = document.getElementById('qbtConnStatus');
            const catBox = document.getElementById('qbtCatPills');
            const tagBox = document.getElementById('qbtTagPills');
            statusEl.innerText = '正在读取节点配置...';
            statusEl.style.color = '#888888';

            fetch('/api/qbt/meta?server=' + encodeURIComponent(srvId))
                .then(r => r.json())
                .then(d => {
                    if (!d.ok) {
                        statusEl.innerText = '⚠️ ' + d.msg;
                        statusEl.style.color = '#ef4444';
                        return;
                    }
                    statusEl.innerText = '🟢 在线 (' + d.version + ')';
                    statusEl.style.color = '#16a34a';

                    nodeRssFeeds = d.rss_feeds || {};
                    renderFeedPills();

                    let catHtml = `<div class="qbt-pill ${currentQbtCat === '' ? 'active' : ''}" data-cat="" onclick="selectQbtCat('', '')">不设分类(默认)</div>`;
                    let matchedPath = '';
                    (d.categories || []).forEach(c => {
                        const isAct = (c.name === currentQbtCat);
                        if (isAct) matchedPath = c.savePath || '';
                        catHtml += `<div class="qbt-pill ${isAct ? 'active' : ''}" data-cat="${c.name}" onclick="selectQbtCat('${c.name}', '${c.savePath || ''}')">📁 ${c.name}</div>`;
                    });
                    catBox.innerHTML = catHtml;
                    document.getElementById('qbtCatPath').innerText = matchedPath ? ('路径: ' + matchedPath) : '';

                    let tagHtml = '';
                    (d.tags || []).forEach(t => {
                        tagHtml += `<div class="qbt-pill" onclick="toggleInputTag('${t}')">🏷️ ${t}</div>`;
                    });
                    tagBox.innerHTML = tagHtml;
                })
                .catch(e => {
                    statusEl.innerText = '❌ 连接节点失败';
                    statusEl.style.color = '#ef4444';
                });
        }

        function selectQbtCat(catName, savePath) {
            currentQbtCat = catName;
            localStorage.setItem('zmpt_qbt_cat_' + currentQbtServer, catName);
            document.querySelectorAll('#qbtCatPills .qbt-pill').forEach(el => {
                el.classList.toggle('active', el.getAttribute('data-cat') === catName);
            });
            document.getElementById('qbtCatPath').innerText = savePath ? ('路径: ' + savePath) : '';

            // 智能联动:如果分类包含“动漫”或“国漫”,自动切换到动漫订阅源;包含“剧”则切换到电视剧订阅源
            if (catName.includes('动漫') || catName.includes('国漫')) {
                if (nodeRssFeeds['动漫']) selectRssFeed('动漫');
            } else if (catName.includes('剧')) {
                if (nodeRssFeeds['电视剧']) selectRssFeed('电视剧');
            }
        }

        function toggleInputTag(tag) {
            isTagsManuallyEdited = true;
            const inp = document.getElementById('qbtCustomTags');
            let arr = inp.value.split(/[,,]/).map(s => s.trim()).filter(Boolean);
            const singleVerGroup = ['DV', 'HDR', 'SDR', 'HQ', 'HFR', 'IQ', 'HDV', 'HHDR'];
            if (arr.includes(tag)) {
                arr = arr.filter(x => x !== tag);
            } else {
                if (singleVerGroup.includes(tag)) {
                    arr = arr.filter(x => !singleVerGroup.includes(x));
                }
                arr.push(tag);
            }
            inp.value = arr.join(',');
        }

        function handleModalSubmit() {
            if (currentModalMode === 'rss') submitRssRule();
            else submitQbtPush();
        }

        function submitRssRule() {
            const btn = document.getElementById('qbtSubmitBtn');
            const ruleName = document.getElementById('rssRuleName').value.trim();
            const mustContain = document.getElementById('rssFinalRegex').value.trim();
            const mustNotContain = document.getElementById('rssExcludeRegex').value.trim();
            const smartFilter = document.getElementById('rssSmartFilter').checked;
            const tags = document.getElementById('qbtCustomTags').value.split(/[,,]/).map(s => s.trim()).filter(Boolean).join(',');

            if (!ruleName || !mustContain) {
                alert('⚠️ 规则名称和匹配正则不能为空!');
                return;
            }

            let selectedFeeds = [];
            if (currentFeedKey === 'ALL') {
                selectedFeeds = Object.values(nodeRssFeeds).filter(Boolean);
            } else if (nodeRssFeeds[currentFeedKey]) {
                selectedFeeds = [nodeRssFeeds[currentFeedKey]];
            }

            btn.innerText = '正在下发规则并推送当前集...';
            btn.disabled = true;

            fetch('/api/qbt/rss/add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    server: currentQbtServer,
                    name: ruleName,
                    mustContain: mustContain,
                    mustNotContain: mustNotContain,
                    smartFilter: smartFilter,
                    category: currentQbtCat,
                    tags: tags,
                    affectedFeeds: selectedFeeds
                })
            }).then(r => r.json()).then(d => {
                if (!d.ok) {
                    btn.disabled = false;
                    btn.innerText = '📡 保存并下发 RSS 追更规则';
                    alert('❌ ' + d.msg);
                    return;
                }
                // 规则下发成功后,如果当前有选中种子,立刻把当前这一集推进 qB 下载
                if (currentPushTid) {
                    fetch('/api/qbt/push', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({
                            tid: currentPushTid,
                            server: currentQbtServer,
                            category: currentQbtCat,
                            tags: tags
                        })
                    }).then(r2 => r2.json()).then(d2 => {
                        btn.disabled = false;
                        btn.innerText = '📡 保存并下发 RSS 追更规则';
                        closeQbtModal();
                        alert('✅ ' + d.msg + '\\n' + (d2.ok ? '🚀 当前种子已同步推送到下载队列!' : '⚠️ 当前种子推送失败: ' + d2.msg));
                    }).catch(() => {
                        btn.disabled = false;
                        btn.innerText = '📡 保存并下发 RSS 追更规则';
                        closeQbtModal();
                        alert('✅ ' + d.msg + '\\n⚠️ 当前种子自动推送请求超时');
                    });
                } else {
                    btn.disabled = false;
                    btn.innerText = '📡 保存并下发 RSS 追更规则';
                    closeQbtModal();
                    alert('✅ ' + d.msg);
                }
            }).catch(e => {
                btn.disabled = false;
                btn.innerText = '📡 保存并下发 RSS 追更规则';
                alert('❌ 下发请求异常');
            });
        }

        function submitQbtPush() {
            if (!currentPushTid) return;
            const btn = document.getElementById('qbtSubmitBtn');
            const tags = document.getElementById('qbtCustomTags').value.split(/[,,]/).map(s => s.trim()).filter(Boolean).join(',');
            btn.innerText = '正在抓取种子并推送...';
            btn.disabled = true;

            fetch('/api/qbt/push', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    tid: currentPushTid,
                    server: currentQbtServer,
                    category: currentQbtCat,
                    tags: tags
                })
            }).then(r => r.json()).then(d => {
                btn.disabled = false;
                btn.innerText = '🚀 立即推送到 qB';
                if (d.ok) {
                    closeQbtModal();
                    alert('✅ ' + d.msg);
                } else {
                    alert('❌ ' + d.msg);
                }
            }).catch(e => {
                btn.disabled = false;
                btn.innerText = '🚀 立即推送到 qB';
                alert('❌ 请求异常');
            });
        }

        window.lazyObserver = null;
        document.addEventListener("DOMContentLoaded", function() {
            if ('IntersectionObserver' in window) {
                window.lazyObserver = new IntersectionObserver((entries, obs) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            const tid = img.getAttribute('data-tid');
                            if (tid) {
                                fetch('/api/extra/' + tid)
                                    .then(r => r.json())
                                    .then(data => {
                                        if (data.img) {
                                            img.src = data.img;
                                            img.classList.remove('lazy-load');
                                        }
                                        if (data.size && data.size !== '未知' && data.size !== '加载中...') {
                                            const sizeSpan = document.getElementById('size-' + tid);
                                            if (sizeSpan) sizeSpan.innerHTML = '📄 ' + data.size;
                                        }
                                    })
                                    .catch(e => {});
                                img.removeAttribute('data-tid');
                                obs.unobserve(img);
                            }
                        }
                    });
                }, { rootMargin: "300px" });

                document.querySelectorAll('.lazy-load').forEach(img => window.lazyObserver.observe(img));

                const sentinel = document.getElementById('load-more-sentinel');
                if (sentinel) {
                    let currentPage = 1; 
                    let isLoadingMore = false;
                    let hasMore = true;
                    const seenIds = new Set();
                    document.querySelectorAll('.list-item').forEach(el => seenIds.add(el.id.replace('item-', '')));

                    const loadMoreObserver = new IntersectionObserver((entries) => {
                        if (entries[0].isIntersecting && !isLoadingMore && hasMore) loadMore();
                    }, { rootMargin: "200px" });
                    loadMoreObserver.observe(sentinel);

                    function loadMore() {
                        isLoadingMore = true;
                        sentinel.innerText = "正在无痕加载下一页...";
                        const params = new URLSearchParams(window.location.search);
                        const tab = params.get('tab') || 'recent';
                        const q = params.get('q') || '';
                        
                        fetch(`/api/load_more?tab=${tab}&q=${encodeURIComponent(q)}&page=${currentPage}`)
                            .then(r => r.json())
                            .then(data => {
                                currentPage++;
                                isLoadingMore = false;
                                if (data.error) { sentinel.innerText = "加载失败: " + data.error; return; }
                                if (data.torrents.length === 0) {
                                    if (currentPage < 10) loadMore();
                                    else { hasMore = false; sentinel.innerText = "没有更多数据了"; }
                                    return;
                                }
                                let addedCount = 0;
                                data.torrents.forEach(item => {
                                    if (seenIds.has(item.id)) return;
                                    seenIds.add(item.id);
                                    addedCount++;
                                    
                                    let tagsTopHtml = '', tagsBotHtml = '', groupHtml = '';
                                    item.top_pri.forEach(t => tagsTopHtml += `<span class="badge-tech">${t}</span>`);
                                    item.top_sec.forEach(t => tagsTopHtml += `<span class="badge-tech secondary-tag">${t}</span>`);
                                    if (item.time_tag) tagsBotHtml += `<span class="badge-discount">${item.time_tag}</span>`;
                                    if (item.clock_tag) tagsBotHtml += `<span class="badge" style="background:#64748b;">${item.clock_tag}</span>`;
                                    item.bot_disc.forEach(t => tagsBotHtml += `<span class="badge-discount">${t}</span>`);
                                    item.bot_pri.forEach(t => tagsBotHtml += `<span class="badge">${t}</span>`);
                                    item.bot_sec.forEach(t => tagsBotHtml += `<span class="badge-lang secondary-tag">${t}</span>`);
                                    if (item.top_sec.length > 0 || item.bot_sec.length > 0) tagsBotHtml += `<span class="badge-toggle" onclick="toggleTags(this)">... ▾</span>`;
                                    if (item.group) groupHtml = item.group.toUpperCase() === 'ZMPT' ? `<span class="badge-zmpt">💎 ZmPT</span>` : `<span class="badge-group">${item.group}</span>`;
                                    let freeTagHtml = item.tags.join(' ').toUpperCase().includes('FREE') ? `<div class="tag-free">FREE</div>` : '';
                                    const imgPlaceholder = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='140'><rect width='100%' height='100%' fill='%23e6e6e6'/><text x='50%' y='50%' fill='%23999' font-size='12' font-family='sans-serif' text-anchor='middle' dominant-baseline='middle'>加载海报</text></svg>";
                                    const imgSrc = item.img ? item.img : imgPlaceholder;
                                    const needsLazy = !item.img || item.img.includes('data:image/svg+xml');
                                    const safeTitle = (item.title || '').replace(/"/g, '&quot;');
                                    const safeSub = (item.subtitle || '').replace(/"/g, '&quot;');

                                    const html = `
                                    <div class="list-item" id="item-${item.id}">
                                        <div class="poster-wrapper">
                                            <img class="poster ${needsLazy ? 'lazy-load' : ''}" src="${imgSrc}" ${needsLazy ? `data-tid="${item.id}"` : ''} referrerpolicy="no-referrer" alt="海报" onclick="window.open('${item.link}', '_blank')">
                                            ${freeTagHtml}
                                        </div>
                                        <div class="info">
                                            <div class="title" onclick="window.open('${item.link}', '_blank')">${item.title}</div>
                                            <div class="subtitle">${item.subtitle || ''}</div>
                                            <div class="stats-and-download">
                                                <div class="stats-row">
                                                    <span class="stat-item" id="size-${item.id}">📄 ${item.size}</span>
                                                    <span class="stat-item"><span class="seed-icon">▲</span> ${item.seeders}</span>
                                                    <span class="stat-item"><span class="leech-icon">▼</span> ${item.leechers}</span>
                                                    ${groupHtml}
                                                </div>
                                                <button type="button" class="download-btn" data-tid="${item.id}" data-title="${safeTitle}" data-sub="${safeSub}" data-grp="${item.group || ''}" onclick="openQbtFromBtn(this)">推送</button>
                                            </div>
                                            <div class="tags-wrapper">
                                                <div class="tags-top">${tagsTopHtml}</div>
                                                <div class="tags-bottom">${tagsBotHtml}</div>
                                            </div>
                                        </div>
                                    </div>`;
                                    sentinel.insertAdjacentHTML('beforebegin', html);
                                });
                                document.querySelectorAll('.lazy-load:not([data-observed])').forEach(img => { img.setAttribute('data-observed', '1'); window.lazyObserver.observe(img); });
                                if (addedCount === 0) loadMore();
                                else sentinel.innerText = "向下划动,无痕加载更多... ⚡";
                            });
                    }
                }
            }
        });
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    tab = request.args.get('tab', 'recent')
    query = request.args.get('q', '')
    torrents = []
    user_info = {}
    seen_ids = set() 
    error_msg = None
    
    try:
        if tab == 'rss':
            pass
        elif tab == 'account':
            resp = HTTP_SESSION.get(INDEX_URL, headers=HEADERS, proxies=PROXIES)
            if "登录" in resp.text and "index.php" not in resp.url:
                error_msg = "⚠️ Cookie 已失效,请在代码中更新 Cookie!"
            else:
                soup = BeautifulSoup(resp.text, 'html.parser')
                for tag in soup.find_all(True):
                    title_attr = tag.get('title') or tag.get('alt') or tag.get('data-original-title')
                    if title_attr and isinstance(title_attr, str) and len(title_attr) < 20:
                        tag.append(f"{title_attr}")
                page_text = soup.get_text(separator='', strip=True)
                
                user_match = re.search(r'([A-Za-z0-9_]+)\s*\[.*?签到|欢迎回来[\s,,]*([A-Za-z0-9_]+)', page_text)
                username = user_match.group(1) or user_match.group(2) if user_match else "织梦会员"
                
                bonus_match = re.search(r'(?:魔力值|电力值)[::\s]*([\d\.,]+)', page_text)
                ratio_match = re.search(r'分享率[::\s]*([无限Inf]+|[\d\.,]+)', page_text, re.IGNORECASE)
                up_match = re.search(r'(?:上传量?|上传|上行)[::\s]*([\d\.,]+\s*[KMGTP]B)', page_text, re.IGNORECASE)
                down_match = re.search(r'(?:下载量?|下载|下行)[::\s]*([\d\.,]+\s*[KMGTP]B)', page_text, re.IGNORECASE)
                
                user_info = {
                    'username': username,
                    'bonus': bonus_match.group(1) if bonus_match else "0",
                    'ratio': ratio_match.group(1) if ratio_match else "0",
                    'upload': up_match.group(1) if up_match else "0 GB",
                    'download': down_match.group(1) if down_match else "0 GB"
                }

        elif tab in ['official', 'search']:
            if tab == 'search' and not query: pass
            else:
                if tab == 'search':
                    safe_query = urllib.parse.quote(query)
                    target_url = f"{BASE_URL}/torrents.php?incldead=1&spstate=0&inclbookmarked=0&search={safe_query}&search_area=0&search_mode=0"
                else: 
                    target_url = OFFICIAL_URL
                    
                fetched_torrents, err = parse_torrents_page(target_url, seen_ids, is_search=(tab == 'search'), skip_sticky=False, start_page=0, max_pages=2)
                if fetched_torrents is not None:
                    history_dict = load_cache('official')
                    for item in fetched_torrents:
                        tid_str = str(item['id'])
                        if tid_str in history_dict:
                            cached = history_dict[tid_str]
                            if 'data:image' not in cached.get('img','') and 'data:image' in item.get('img',''):
                                item['img'] = cached['img']
                            if cached.get('size') not in ['未知', '加载中...'] and item.get('size') in ['未知', '-']:
                                item['size'] = cached['size']
                            if not item.get('group') and cached.get('group'):
                                item['group'] = cached['group']
                            item['tags'] = purify_tags(merge_smart_tags_from_list(item.get('tags', []), cached.get('tags', [])))
                        
                        history_dict[tid_str] = item
                    if tab != 'search':
                        save_cache(history_dict, 'official')
                    torrents = fetched_torrents
                else:
                    if err: error_msg = err

        elif tab == 'recent':
            fetched_torrents, err_msg = parse_torrents_page(COMPREHENSIVE_URL, seen_ids, is_search=False, skip_sticky=True, start_page=0, max_pages=4)
            if fetched_torrents is not None:
                history_dict = load_cache('recent')
                for item in fetched_torrents:
                    tid_str = str(item['id'])
                    if tid_str in history_dict:
                        cached = history_dict[tid_str]
                        if cached.get('img') and 'data:image/svg+xml' not in cached['img']: item['img'] = cached['img']
                        if cached.get('size') and cached.get('size') not in ['未知', '加载中...']: item['size'] = cached['size']
                        if cached.get('group') and not item.get('group'): item['group'] = cached['group']
                        item['tags'] = purify_tags(merge_smart_tags_from_list(item.get('tags', []), cached.get('tags', [])))
                    history_dict[tid_str] = item
                    
                save_cache(history_dict, 'recent')
                merged = list(history_dict.values())
                merged.sort(key=lambda x: int(x['id']), reverse=True)
                torrents = merged[:50]
            else:
                history_data = list(load_cache('recent').values())
                history_data.sort(key=lambda x: int(x['id']), reverse=True)
                torrents = history_data[:50]
                if err_msg and not torrents: error_msg = err_msg

        if torrents:
            for item in torrents:
                tpri, tsec, bdisc, bpri, bsec = sort_tags(item.get('tags', []))
                item['top_pri'] = tpri
                item['top_sec'] = tsec
                item['bot_disc'] = bdisc
                item['bot_pri'] = bpri
                item['bot_sec'] = bsec
                item['time_tag'] = ""
                item['clock_tag'] = ""
                
                for arr in [item['top_pri'], item['top_sec'], item['bot_disc'], item['bot_pri'], item['bot_sec']]:
                    for t in list(arr):
                        if '剩余' in t.upper():
                            item['time_tag'] = t
                            arr.remove(t)
                        elif '🕒' in t:
                            item['clock_tag'] = t
                            arr.remove(t)

    except Exception as e:
        error_msg = f"服务器内部请求错误: {e}"
        torrents = torrents or []
        
    return render_template_string(HTML_TEMPLATE, tab=tab, query=query, torrents=torrents or [], user_info=user_info, error=error_msg, qbt_servers=QBT_SERVERS)

@app.route('/api/qbt/meta')
def api_qbt_meta():
    srv_id = request.args.get('server', '177')
    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})
    try:
        ver_r = sess.get(f"{base_url}/api/v2/app/version", timeout=4)
        cats_r = sess.get(f"{base_url}/api/v2/torrents/categories", timeout=4)
        tags_r = sess.get(f"{base_url}/api/v2/torrents/tags", timeout=4)

        cats_dict = cats_r.json() if cats_r.status_code == 200 else {}
        categories = [{"name": k, "savePath": v.get("savePath", "")} for k, v in cats_dict.items()]
        tags = tags_r.json() if tags_r.status_code == 200 else []
        rss_feeds = QBT_SERVERS.get(srv_id, {}).get('rss_feeds', {})
        return jsonify({
            "ok": True,
            "version": ver_r.text.strip(),
            "categories": categories,
            "tags": tags,
            "rss_feeds": rss_feeds
        })
    except Exception as e:
        return jsonify({"ok": False, "msg": f"读取节点元数据失败: {str(e)}"})

# ================= 📡 qBittorrent 原生 RSS 自动下载规则管理接口 =================
@app.route('/api/qbt/rss/rules')
def api_qbt_rss_rules():
    srv_id = request.args.get('server', '177')
    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})
    try:
        r = sess.get(f"{base_url}/api/v2/rss/rules", timeout=5)
        if r.status_code != 200:
            return jsonify({"ok": False, "msg": f"获取规则失败,状态码: {r.status_code}"})
        rules_dict = r.json()
        feeds_cfg = QBT_SERVERS.get(srv_id, {}).get('rss_feeds', {})
        url_to_label = {v: k for k, v in feeds_cfg.items() if v}

        rules_list = []
        for name, defn in rules_dict.items():
            defn['name'] = name
            aff = defn.get('affectedFeeds', [])
            labels = [url_to_label.get(u, u[:25] + '...') for u in aff]
            defn['feedLabel'] = ' + '.join(labels) if labels else '全部源'
            rules_list.append(defn)
        return jsonify({"ok": True, "rules": rules_list})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"读取 RSS 规则异常: {str(e)}"})

@app.route('/api/qbt/rss/add', methods=['POST'])
def api_qbt_rss_add():
    data = request.get_json(force=True)
    srv_id = data.get('server', '177')
    rule_name = data.get('name', '').strip()
    must_contain = data.get('mustContain', '').strip()
    must_not_contain = data.get('mustNotContain', '').strip()
    smart_filter = bool(data.get('smartFilter', False))
    category = data.get('category', '').strip()
    tags_str = data.get('tags', '').strip()
    affected_feeds = [u.strip() for u in data.get('affectedFeeds', []) if u and u.strip()]

    if not rule_name or not must_contain:
        return jsonify({"ok": False, "msg": "规则名称与匹配正则不能为空"})

    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})

    try:
        sess.post(f"{base_url}/api/v2/app/setPreferences", data={
            "json": json.dumps({"rss_processing_enabled": True, "rss_auto_downloading_enabled": True})
        }, timeout=5)

        # 自动检测:qB 里不存在该 RSS 源时才自动添加,已存在则跳过,绝不重复
        if affected_feeds:
            items_r = sess.get(f"{base_url}/api/v2/rss/items", timeout=5)
            existing_urls = set()
            def collect_urls(obj):
                if isinstance(obj, dict):
                    if "url" in obj and isinstance(obj["url"], str):
                        existing_urls.add(obj["url"].strip())
                    for v in obj.values():
                        collect_urls(v)
            if items_r.status_code == 200:
                collect_urls(items_r.json())

            feeds_cfg = QBT_SERVERS.get(srv_id, {}).get('rss_feeds', {})
            url_to_label = {v.strip(): k for k, v in feeds_cfg.items() if v}

            for feed_url in affected_feeds:
                if feed_url not in existing_urls:
                    label = url_to_label.get(feed_url, "")
                    # 财神用 CSPT,织梦改成 ZmPT,龙站改成 LongPT
                    feed_path = f"ZMPT-{label}" if label else "ZMPT"
                    sess.post(f"{base_url}/api/v2/rss/addFeed", data={
                        "url": feed_url,
                        "path": feed_path
                    }, timeout=5)

        tags_list = [t.strip() for t in tags_str.split(',') if t.strip()]

        rule_def = {
            "enabled": True,
            "mustContain": must_contain,
            "mustNotContain": must_not_contain,
            "useRegex": True,
            "episodeFilter": "",
            "smartFilter": smart_filter,
            "previouslyMatchedEpisodes": [],
            "affectedFeeds": affected_feeds,
            "ignoreDays": 0,
            "lastMatch": "",
            "addPaused": False,
            "assignedCategory": category,
            "savePath": "",
            "torrentParams": {
                "category": category,
                "tags": tags_list,
                "paused": False
            }
        }

        res = sess.post(f"{base_url}/api/v2/rss/setRule", data={
            "ruleName": rule_name,
            "ruleDef": json.dumps(rule_def, ensure_ascii=False)
        }, timeout=6)

        if res.status_code == 200:
            srv_name = QBT_SERVERS[srv_id]['name']
            return jsonify({"ok": True, "msg": f"RSS 追剧规则【{rule_name}】已成功下发至 {srv_name}!"})
        return jsonify({"ok": False, "msg": f"qB 拒绝保存规则: {res.text}"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"下发 RSS 规则异常: {str(e)}"})

@app.route('/api/qbt/rss/toggle', methods=['POST'])
def api_qbt_rss_toggle():
    data = request.get_json(force=True)
    srv_id = data.get('server', '177')
    rule_name = data.get('name', '')
    enabled = bool(data.get('enabled', True))

    sess, base_url, err = get_qbt_session(srv_id)
    if err: return jsonify({"ok": False, "msg": err})
    try:
        r = sess.get(f"{base_url}/api/v2/rss/rules", timeout=5)
        rules = r.json()
        if rule_name not in rules:
            return jsonify({"ok": False, "msg": "未找到该规则"})
        rules[rule_name]['enabled'] = enabled
        res = sess.post(f"{base_url}/api/v2/rss/setRule", data={
            "ruleName": rule_name,
            "ruleDef": json.dumps(rules[rule_name], ensure_ascii=False)
        }, timeout=5)
        return jsonify({"ok": res.status_code == 200, "msg": "状态已更新"})
    except Exception as e:
        return jsonify({"ok": False, "msg": str(e)})

@app.route('/api/qbt/rss/delete', methods=['POST'])
def api_qbt_rss_delete():
    data = request.get_json(force=True)
    srv_id = data.get('server', '177')
    rule_name = data.get('name', '')

    sess, base_url, err = get_qbt_session(srv_id)
    if err: return jsonify({"ok": False, "msg": err})
    try:
        res = sess.post(f"{base_url}/api/v2/rss/removeRule", data={"ruleName": rule_name}, timeout=5)
        return jsonify({"ok": res.status_code == 200, "msg": "已删除"})
    except Exception as e:
        return jsonify({"ok": False, "msg": str(e)})
# ==============================================================================

@app.route('/api/qbt/push', methods=['POST'])
def api_qbt_push():
    data = request.get_json(force=True)
    tid = data.get('tid')
    srv_id = data.get('server', '177')
    category = data.get('category', '').strip()
    tags = data.get('tags', '').strip()

    if not tid:
        return jsonify({"ok": False, "msg": "缺少种子 ID"})

    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})

    try:
        dl_r = HTTP_SESSION.get(f"{BASE_URL}/download.php?id={tid}", headers=HEADERS, proxies=PROXIES)
        if dl_r.status_code != 200 or (b"announce" not in dl_r.content[:200] and b"info" not in dl_r.content[:200]):
            return jsonify({"ok": False, "msg": "从 ZmPT 获取种子失败,请检查 Cookie 是否失效"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"从 ZmPT 下载种子失败: {str(e)}"})

    try:
        form_data = {}
        if category: form_data['category'] = category
        if tags: form_data['tags'] = tags

        files = {'torrents': (f'ZmPT_{tid}.torrent', dl_r.content, 'application/x-bittorrent')}
        push_r = sess.post(f"{base_url}/api/v2/torrents/add", data=form_data, files=files, timeout=10)
        res_txt = push_r.text.strip()
        if push_r.status_code == 200 and ("Ok." in res_txt or '"success_count":1' in res_txt.replace(" ", "") or "added_torrent_ids" in res_txt):
            srv_name = QBT_SERVERS[srv_id]['name']
            cat_info = f" [分类: {category}]" if category else ""
            return jsonify({"ok": True, "msg": f"已成功推送到 {srv_name}{cat_info}!"})
        return jsonify({"ok": False, "msg": f"qB 推送未成功: {res_txt}"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"推送到 qB 失败: {str(e)}"})

@app.route('/api/load_more')
def api_load_more():
    tab = request.args.get('tab', 'recent')
    query = request.args.get('q', '')
    try: page = int(request.args.get('page', 1))
    except: page = 1
        
    seen_ids = set()
    if tab == 'search':
        safe_query = urllib.parse.quote(query)
        target_url = f"{BASE_URL}/torrents.php?incldead=1&spstate=0&inclbookmarked=0&search={safe_query}&search_area=0&search_mode=0"
        fetched, err = parse_torrents_page(target_url, seen_ids, skip_sticky=False, start_page=page, max_pages=1)
    elif tab == 'official':
        fetched, err = parse_torrents_page(OFFICIAL_URL, seen_ids, skip_sticky=False, start_page=page, max_pages=1)
    else: 
        fetched, err = parse_torrents_page(COMPREHENSIVE_URL, seen_ids, skip_sticky=True, start_page=page, max_pages=1)
        
    if fetched:
        for item in fetched:
            tpri, tsec, bdisc, bpri, bsec = sort_tags(item.get('tags', []))
            item['top_pri'] = tpri
            item['top_sec'] = tsec
            item['bot_disc'] = bdisc
            item['bot_pri'] = bpri
            item['bot_sec'] = bsec
            item['time_tag'] = ""
            item['clock_tag'] = ""
            
            for arr in [item['top_pri'], item['top_sec'], item['bot_disc'], item['bot_pri'], item['bot_sec']]:
                for t in list(arr):
                    if '剩余' in t.upper():
                        item['time_tag'] = t
                        arr.remove(t)
                    elif '🕒' in t:
                        item['clock_tag'] = t
                        arr.remove(t)
                        
    return jsonify({"torrents": fetched or [], "error": err})

@app.route('/api/extra/<int:tid>')
def api_extra(tid):
    img_src, size, extra_tags, release_group = fetch_details_info(tid)
    merged_tags = purify_tags(extra_tags)
    
    tid_str = str(tid)
    for c_type in ['recent', 'official']:
        history_dict = load_cache(c_type)
        if tid_str in history_dict:
            cached_item = history_dict[tid_str]
            final_tags = purify_tags(merge_smart_tags_from_details(merged_tags, cached_item.get('tags', [])))
            cached_item['tags'] = final_tags
            merged_tags = final_tags
            
            if img_src: cached_item['img'] = img_src
            if size and size != "未知": cached_item['size'] = size
            if release_group and not cached_item.get('group'): cached_item['group'] = release_group
            
            history_dict[tid_str] = cached_item
            save_cache(history_dict, c_type)
        
    tpri, tsec, bdisc, bpri, bsec = sort_tags(merged_tags)
    time_tag = ""
    clock_tag = ""
    for arr in [tpri, tsec, bdisc, bpri, bsec]:
        for t in list(arr):
            if '剩余' in t.upper():
                time_tag = t
                arr.remove(t)
            elif '🕒' in t:
                clock_tag = t
                arr.remove(t)
    
    return jsonify({
        "img": img_src, "size": size, "tags": merged_tags,
        "top_pri": tpri, "top_sec": tsec, "bot_disc": bdisc,
        "bot_pri": bpri, "bot_sec": bsec, "time_tag": time_tag,
        "clock_tag": clock_tag, "group": release_group
    })

@app.route('/api/signin')
def api_signin():
    try:
        r = HTTP_SESSION.get(SIGNIN_URL, headers=HEADERS, proxies=PROXIES)
        r.encoding = 'utf-8'
        res_text = r.text
        if r.status_code == 200:
            if any(kw in res_text for kw in ["已经", "退下", "已签到", "请明天再来"]):
                return jsonify({"msg": "☕ 今天已经签到过了,明天再来吧。"})
            elif any(kw in res_text for kw in ["这是您的第", "签到成功", "魔力值", "电力值"]):
                match = re.search(r'(这是您的第.*?(?:魔力值|电力值)|签到成功.*?(?:魔力值|电力值))', BeautifulSoup(res_text, 'html.parser').get_text(separator=' ', strip=True))
                msg = match.group(1).replace('  ', ' ') if match else "签到成功!"
                return jsonify({"msg": f"🎉 {msg}"})
            elif "登录" in res_text:
                return jsonify({"msg": "⚠️ 签到失败:Cookie 已失效,请更新!"})
            return jsonify({"msg": "✅ 签到请求已发送,请留意积分变化。"})
        return jsonify({"msg": f"❌ 签到接口报错,状态码: {r.status_code}"})
    except Exception as e:
        return jsonify({"msg": f"❌ 网络请求出错: {str(e)}"})

@app.route('/download/<int:tid>')
def download_torrent(tid):
    try:
        r = HTTP_SESSION.get(f"{BASE_URL}/download.php?id={tid}", headers=HEADERS, proxies=PROXIES)
        if "application/x-bittorrent" in r.headers.get('Content-Type', '') or "octet-stream" in r.headers.get('Content-Type', ''):
            return Response(r.content, mimetype="application/x-bittorrent", headers={"Content-Disposition": f"attachment;filename=ZmPT_{tid}.torrent"})
        return "下载失败,Cookie 可能失效或无权下载该种子。"
    except Exception as e:
        return f"请求下载出错: {str(e)}"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5054)

三、cspt

from flask import Flask, render_template_string, Response, request, jsonify
import requests
from bs4 import BeautifulSoup
import urllib.parse
import re
import os
import json
import datetime
import threading
import time
import random

app = Flask(__name__)

# ================= 必须配置的区域 =================
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Referer': 'https://cspt.top/torrents.php',
    'Cookie': 'c_secure_uid=MTAwMTE1MjA%3D; c_secure_pass=d0b0049a7d4035b6e0306e9ae81392bf; c_secure_ssl=eWVhaA%3D%3D; c_secure_tracker_ssl=eWVhaA%3D%3D; c_secure_login=bm9wZQ%3D%3D' 
}
PROXY_URL = ""
PROXIES = {"http": PROXY_URL, "https": PROXY_URL} if PROXY_URL else None
TIMEOUT = 15

BASE_URL = "https://cspt.top"
OFFICIAL_URL = f"{BASE_URL}/torrents.php"
USERCP_URL = f"{BASE_URL}/usercp.php"
SIGNIN_URL = f"{BASE_URL}/attendance.php"

# 🚀 多台 qBittorrent 服务器配置(支持配置“电视剧”与“动漫”双固定 RSS 订阅源)
QBT_SERVERS = {
    "188": {
        "name": "188 节点 (192.168.2.188)",
        "url": "http://192.168.2.188:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_feeds": {
            "电视剧": "https://cspt.top/torrentrss.php?passkey=682a49c58e7f24998d131f968f74ad64&rows=50&cat418=1&cat404=1&cat403=1&cat402=1&icat=1&ismalldescr=1&isize=1&iuplder=1&torrentstatus=0&linktype=dl",  # 👈 填入188节点里配置的 CSPT 电视剧 RSS 订阅链接
            "动漫": "https://cspt.top/torrentrss.php?passkey=682a49c58e7f24998d131f968f74ad64&rows=50&cat405=1&icat=1&ismalldescr=1&isize=1&iuplder=1&torrentstatus=0&linktype=dl"     # 👈 填入188节点里配置的 CSPT 动漫 RSS 订阅链接
        }
    },
    "177": {
        "name": "166 节点 (192.168.2.177)",
        "url": "http://192.168.2.177:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_feeds": {
            "电视剧": "https://cspt.top/torrentrss.php?passkey=682a49c58e7f24998d131f968f74ad64&rows=50&cat418=1&cat404=1&cat403=1&cat402=1&icat=1&ismalldescr=1&isize=1&iuplder=1&torrentstatus=0&linktype=dl",  # 👈 填入166节点里配置的 CSPT 电视剧 RSS 订阅链接
            "动漫": "https://cspt.top/torrentrss.php?passkey=682a49c58e7f24998d131f968f74ad64&rows=50&cat405=1&icat=1&ismalldescr=1&isize=1&iuplder=1&torrentstatus=0&linktype=dl"     # 👈 填入166节点里配置的 CSPT 动漫 RSS 订阅链接
        }
    },
    "004": {
        "name": "004 节点 (192.168.2.4)",
        "url": "http://192.168.2.4:8080",
        "username": "admin",
        "password": "xxsky1127",
        "rss_feeds": {
            "电视剧": "https://cspt.top/torrentrss.php?passkey=682a49c58e7f24998d131f968f74ad64&rows=50&cat418=1&cat404=1&cat403=1&cat402=1&icat=1&ismalldescr=1&isize=1&iuplder=1&torrentstatus=0&linktype=dl",  # 👈 填入2.4节点里配置的 CSPT 电视剧 RSS 订阅链接
            "动漫": "https://cspt.top/torrentrss.php?passkey=682a49c58e7f24998d131f968f74ad64&rows=50&cat405=1&icat=1&ismalldescr=1&isize=1&iuplder=1&torrentstatus=0&linktype=dl"     # 👈 填入2.4节点里配置的 CSPT 动漫 RSS 订阅链接
        }
    }
}
# =================================================

POSTER_CACHE = {}
DETAIL_CACHE = {}
QBT_SESSIONS = {}        # 缓存各台 qB 的登录 Session
AUTO_SIGN_DATE = ""      # 记录最后成功签到的日期 (YYYY-MM-DD)
AUTO_SIGN_MSG = "待签到"  # 签到状态文字
NEXT_SIGN_TIME = ""      # 下次计划随机签到时间

TECH_KEYWORDS = [
    'FREE', '50%', '30%', '2X', '热门', '官方', '中字', '英字', '国语', '粤语', '英语', 
    '简繁', '双语', '杜比', '高帧', '高码', '臻彩MAX', '高分', '完结', '4K', '1080P', 
    '2160P', '720P', 'WEB-DL', 'BLU-RAY', 'REMUX', 'HDR10+', 'HDR10', 'HDRVIVID', 
    'HDR', 'DOVI', 'DV', 'SDR', '60FPS', 'HFR', 'HQ', 'H.265', 'H.264', 'H265', 'H264', 
    'HEVC', 'AAC', 'DDP', 'ATMOS', '10BIT', '首发', '禁转', '应求', 'DIY', '字幕'
]

def get_qbt_session(srv_id):
    """获取并维护指定 qBittorrent 节点的登录会话(自动重建防首次登录失败)"""
    cfg = QBT_SERVERS.get(srv_id)
    if not cfg:
        return None, None, "未找到该 qB 节点配置"
    base_url = cfg['url'].rstrip('/')
    sess = QBT_SESSIONS.get(srv_id)
    if not sess:
        sess = requests.Session()
        QBT_SESSIONS[srv_id] = sess

    try:
        test_r = sess.get(f"{base_url}/api/v2/app/version", timeout=3)
        if test_r.status_code == 200:
            return sess, base_url, None
    except Exception:
        pass

    for attempt in range(2):
        try:
            sess = requests.Session()
            QBT_SESSIONS[srv_id] = sess
            login_r = sess.post(
                f"{base_url}/api/v2/auth/login",
                data={"username": cfg.get("username", ""), "password": cfg.get("password", "")},
                headers={"Referer": base_url + "/", "Origin": base_url},
                timeout=5
            )
            if login_r.status_code == 200 and "Ok." in login_r.text:
                return sess, base_url, None
        except Exception as e:
            if attempt == 1:
                return None, None, f"无法连接 {base_url}: {str(e)}"
    return None, None, "qB 登录失败,请检查账号密码配置"

def clean_group_name(grp):
    """卡片徽章显示用:去掉末尾的 WEB 字样"""
    if not grp:
        return ""
    g = grp.strip().upper()
    if g.endswith('WEB') and len(g) > 3:
        g = g[:-3].rstrip('-_')
    return g

def do_attendance():
    """执行签到并更新全局状态"""
    global AUTO_SIGN_DATE, AUTO_SIGN_MSG
    today = datetime.date.today().isoformat()
    try:
        r = requests.get(SIGNIN_URL, headers=HEADERS, proxies=PROXIES, timeout=10)
        r.encoding = 'utf-8'
        txt = BeautifulSoup(r.text, 'html.parser').get_text(" ", strip=True)
        if "登录" in txt and "attendance" not in r.url:
            AUTO_SIGN_MSG = "Cookie失效"
            return False, "⚠️ 签到失败:Cookie 已失效!"
        if any(k in txt for k in ["已经签到", "已签到", "请明天再来", "今日已", "已经打卡", "今日签到过了"]):
            AUTO_SIGN_DATE = today
            AUTO_SIGN_MSG = "今日已签到"
            return True, "☕ 今天已经向财神爷求过签了(已签到)!"
        if any(k in txt for k in ["签到成功", "获得", "魔力值", "元宝", "连续签到", "第"]):
            AUTO_SIGN_DATE = today
            AUTO_SIGN_MSG = "今日已签到"
            m = re.search(r'(签到成功[^\s。!]{0,30}|这是您的第[^\s。!]{0,35}|获得[^\s。!]{0,25})', txt)
            return True, (f"🎉 {m.group(1)}" if m else "🎉 自动签到成功,元宝已到账!")
        AUTO_SIGN_DATE = today
        AUTO_SIGN_MSG = "今日已签到"
        return True, f"✅ 已完成签到请求:{txt[:40]}"
    except Exception as e:
        return False, f"❌ 签到网络请求出错: {str(e)}"

def auto_signin_scheduler():
    """后台守护线程:每天随机时间自动签到,无需打开网页"""
    global NEXT_SIGN_TIME
    time.sleep(5)
    today_str = datetime.date.today().isoformat()
    if AUTO_SIGN_DATE != today_str:
        do_attendance()

    target_date = None
    target_dt = None

    while True:
        try:
            now = datetime.datetime.now()
            today = now.date()

            if AUTO_SIGN_DATE == today.isoformat():
                tomorrow = today + datetime.timedelta(days=1)
                if target_date != tomorrow:
                     target_date = tomorrow
                     rand_hour = random.randint(8, 11)
                     rand_min = random.randint(0, 59) if rand_hour < 11 else random.randint(0, 30)
                     rand_sec = random.randint(0, 59)
                     target_dt = datetime.datetime.combine(tomorrow, datetime.time(rand_hour, rand_min, rand_sec))
                     NEXT_SIGN_TIME = target_dt.strftime("%m-%d %H:%M")
            else:
                if target_dt is None or now >= target_dt:
                    ok, _ = do_attendance()
                    if not ok:
                        target_dt = now + datetime.timedelta(minutes=random.randint(15, 30))
                        NEXT_SIGN_TIME = target_dt.strftime("%H:%M 重试")
        except Exception:
            pass
        time.sleep(60)

if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
    threading.Thread(target=auto_signin_scheduler, daemon=True).start()

def purify_tags(tags):
    valid = []
    for t in tags:
        clean_t = str(t).upper()
        if '剩余' in clean_t or '🕒' in clean_t:
            valid.append(t)
        elif clean_t in [k.upper() for k in TECH_KEYWORDS] or re.match(r'^[\d]+%$', clean_t):
            valid.append(t)
            
    final_tags = []
    time_tags = [t for t in valid if '剩余' in t]
    best_time = max(time_tags, key=len) if time_tags else None
    clock_tags = [t for t in valid if '🕒' in t]
    best_clock = clock_tags[-1] if clock_tags else None
    
    for t in valid:
        if '剩余' in t:
            if t == best_time and best_time not in final_tags: final_tags.append(t)
        elif '🕒' in t:
            if t == best_clock and best_clock not in final_tags: final_tags.append(t)
        elif t not in final_tags: final_tags.append(t)
    return final_tags

def auto_extract_tags(text, current_tags):
    if not text: return current_tags
    en_matches = re.findall(r'(?i)\b(4K|1080P|2160P|720P|WEB-DL|BLU-RAY|REMUX|HDR10\+|HDR10|HDRVIVID|HDR|DOVI|DV|SDR|60FPS|HFR|HQ|H\.?265|H\.?264|HEVC|AAC|DDP|ATMOS|10BIT)\b', text)
    cn_matches = re.findall(r'(杜比|高帧|高码|臻彩MAX|高分|完结|国语|中字|英字|粤语|英语|简繁|双语|官方|首发)', text)
    disc_matches = re.findall(r'(50%|30%|2X)', text.upper())
    for tag in [m.upper() for m in en_matches] + cn_matches + disc_matches:
        if not any(tag.upper() in str(t).upper() or str(t).upper() in tag.upper() for t in current_tags):
            current_tags.append(tag)
    return current_tags

def sort_tags(tags):
    top_pri, top_sec, bot_disc, bot_pri, bot_sec = [], [], [], [], []
    remaining = list(tags)
    
    t_res = ['4K', '2160P', '1080P', '720P']
    t_hdr = ['HDRVIVID', 'HDR10+', 'HDR10', 'HDR', 'DOVI', 'DV', 'SDR']
    t_fps = ['60FPS', 'HFR', '高帧', '臻彩MAX', 'BLU-RAY', 'REMUX']
    t_enc = ['WEB-DL', 'H.265', 'H.264', 'H265', 'H264', 'HEVC', 'AAC', 'DDP', 'ATMOS', '杜比', '10BIT', 'HQ', '高码']
    
    for t in list(remaining):
        t_upper = str(t).upper()
        if '%' in t_upper or '2X' in t_upper or t_upper in ['免费', 'FREE', '30%', '50%']:
            if t_upper not in ['FREE', '免费']: bot_disc.append(t)
            remaining.remove(t)
            
    for kw in t_res + t_hdr + t_fps:
        for t in list(remaining):
            if kw in str(t).upper() and t in remaining: top_pri.append(t); remaining.remove(t)
    for kw in t_enc:
        for t in list(remaining):
            if kw in str(t).upper() and t in remaining: top_sec.append(t); remaining.remove(t)
    for kw in ['热门', '完结', '首发', '高分', 'DIY']:
        for t in list(remaining):
            if kw in str(t).upper() and t in remaining: bot_pri.append(t); remaining.remove(t)
    for kw in ['国语', '中字', '英字', '粤语', '英语', '简繁', '双语', '官方', '字幕']:
        for t in list(remaining):
            if kw in str(t).upper() and t in remaining: bot_sec.append(t); remaining.remove(t)
                
    for t in list(remaining): bot_pri.append(t)
    return top_pri, top_sec, bot_disc, bot_pri, bot_sec

def fetch_details_info(tid):
    tid_str = str(tid)
    if tid_str in DETAIL_CACHE: return DETAIL_CACHE[tid_str]
    try:
        r = requests.get(f"{BASE_URL}/details.php?id={tid}", headers=HEADERS, proxies=PROXIES, timeout=TIMEOUT)
        raw_html = r.text
        soup = BeautifulSoup(raw_html, 'html.parser')
        extra_tags = []

        text_clean = soup.get_text(separator=' ')
        tm2 = re.search(r'(?:免费剩余时间|免费剩余|优惠剩余时间|剩余时间|还有|剩余)[::\s]+(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', text_clean)
        if tm2: extra_tags.append(f"剩余时间: {tm2.group(1).strip()}")

        pub_time = ""
        pub_m = re.search(r'发布于\s*(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2})', text_clean)
        if pub_m:
            try:
                dt = datetime.datetime.strptime(pub_m.group(1), "%Y-%m-%d %H:%M")
                diff = datetime.datetime.now() - dt
                if diff.days > 0:
                    pub_time = f"{diff.days}天{diff.seconds // 3600}时"
                elif diff.seconds >= 3600:
                    pub_time = f"{diff.seconds // 3600}时{(diff.seconds % 3600) // 60}分"
                else:
                    pub_time = f"{max(1, diff.seconds // 60)}分钟"
            except:
                pub_time = pub_m.group(1)[5:]

        seeders, leechers = "", ""
        peer_m = re.search(r'(\d+)\s*个?做种者?\s*[,,\s]*(\d+)\s*个?下载者?', text_clean)
        if peer_m:
            seeders, leechers = peer_m.group(1), peer_m.group(2)

        img_src = ""
        descr_div = soup.find('div', id='kdescr')
        if descr_div and descr_div.find('img'): 
            img_src = descr_div.find('img').get('data-src') or descr_div.find('img').get('src') or ""
        if not img_src:
            for img in soup.find_all('img'):
                src = img.get('data-src') or img.get('src') or ""
                if src and not any(x in src.lower() for x in ['category', 'smilies', 'icon', 'logo', 'avatar', 'rating', 'button', 'rule']):
                    img_src = src; break
        if img_src and not img_src.startswith('http'): img_src = f"{BASE_URL}/" + img_src
        if img_src: POSTER_CACHE[tid_str] = img_src

        size = "未知"
        size_match = re.search(r'大小.*?([\d\.]+\s*[KMGTP]B)', raw_html, re.IGNORECASE)
        if size_match: size = size_match.group(1).upper()

        h1 = soup.find('h1')
        release_group = ""
        if h1:
            h1_text = h1.get_text(strip=True)
            for kw in ['免费', 'FREE', '50%', '30%', '2X']:
                if kw in h1_text.upper():
                    if kw in ['免费', 'FREE'] and 'Free' not in extra_tags: extra_tags.append('Free')
                    elif kw not in extra_tags: extra_tags.append(kw)
            group_match = re.search(r'-([A-Za-z0-9@_]+)$', h1_text)
            if group_match: release_group = clean_group_name(group_match.group(1))

        sub_text = ""
        sub_td = soup.find('td', class_='rowhead', string=re.compile('副标题|副標題'))
        if sub_td and sub_td.find_next_sibling('td'):
            sub_text = sub_td.find_next_sibling('td').get_text(strip=True)
        
        if pub_time:
            extra_tags.append(f"🕒 {pub_time}")
        extra_tags = auto_extract_tags((h1.get_text(strip=True) if h1 else "") + " " + sub_text, extra_tags)
        res = (img_src, size, purify_tags(extra_tags), release_group, sub_text, seeders, leechers, pub_time)
        DETAIL_CACHE[tid_str] = res
        return res
    except Exception:
        return "", "未知", [], "", "", "", "", ""

def parse_user_account():
    """精准解析 usercp.php 中的用户名、金元宝、上传量、下载量和真实分享率"""
    resp = requests.get(USERCP_URL, headers=HEADERS, proxies=PROXIES, timeout=TIMEOUT)
    soup = BeautifulSoup(resp.text, 'html.parser')
    plain_text = soup.get_text(" ", strip=True)

    username = "财神信徒"
    u_m = re.search(r'([A-Za-z0-9_\-\u4e00-\u9fa5]+)\s+UID\s*[::]\s*\d+', plain_text)
    if u_m:
        username = u_m.group(1).strip()
    else:
        u_link = soup.find('a', href=re.compile(r'userdetails\.php\?id=\d+', re.I))
        if u_link and u_link.get_text(strip=True):
            username = u_link.get_text(strip=True)

    bonus = "0"
    b_m = re.search(r'(?:金元宝|元宝|魔力值)\s*[::]?\s*([\d\.,]+)', plain_text)
    if b_m:
        bonus = b_m.group(1).strip()

    upload = "0.00 KB"
    download = "0.00 KB"
    up_m = re.search(r'(?:上传量?|上行|↑)\s*[::]?\s*([\d\.,]+\s*[KMGTP]B)', plain_text, re.I)
    if up_m:
        upload = up_m.group(1).strip()
    down_m = re.search(r'(?:下载量?|下行|↓)\s*[::]?\s*([\d\.,]+\s*[KMGTP]B)', plain_text, re.I)
    if down_m:
        download = down_m.group(1).strip()

    down_num_m = re.search(r'^([\d\.]+)', download)
    down_val = float(down_num_m.group(1)) if down_num_m else 0.0
    if down_val == 0.0 or re.search(r'分享率\s*[::]?\s*(?:无限|Inf|∞)', plain_text, re.I):
        ratio = "无限"
    else:
        r_m = re.search(r'分享率\s*[::]?\s*([\d\.,]+)', plain_text)
        ratio = r_m.group(1) if r_m else "无限"

    return {
        'username': username,
        'bonus': bonus,
        'ratio': ratio,
        'upload': upload,
        'download': download
    }

def parse_torrents_page(seen_ids, cat='all', is_search=False, skip_sticky=False, page=0, query=""):
    torrents = []
    try:
        url = f"{BASE_URL}/torrents.php"
        params = []
        if is_search and query:
            url += f"?incldead=1&spstate=0&inclbookmarked=0&search={urllib.parse.quote(query)}&search_area=0&search_mode=0"
            if cat != 'all': url += f"&cat={cat}"
            if page > 0: url += f"&page={page}"
        else:
            if cat != 'all': params.append(f"cat={cat}")
            if page > 0: params.append(f"page={page}")
            if params: url += ("&" if "?" in url else "?") + "&".join(params)
            
        resp = requests.get(url, headers=HEADERS, proxies=PROXIES, timeout=TIMEOUT)
        if resp.status_code != 200: return None, f"获取数据失败,状态码: {resp.status_code}", 0
        raw_html = resp.text
        if "登录" in raw_html and "torrents.php" not in resp.url: return None, "⚠️ Cookie 已失效!请重新获取", 0

        table_start = re.search(r'<table[^>]*class=["\']?[^"\']*torrents[^"\']*["\']?', raw_html, re.I)
        list_html = raw_html[table_start.start():] if table_start else raw_html

        link_pattern = re.compile(r'<a\s+[^>]*href=["\']([^"\']*details\.php\?id=(\d+)[^"\']*)["\'][^>]*>(.*?)</a>', re.I | re.S)
        valid_matches = []
        seen_in_page = set()

        for m in link_pattern.finditer(list_html):
            href, tid, inner_html = m.group(1), m.group(2), m.group(3)
            if tid == "10011520" or tid in seen_in_page: continue
            if any(b in href.lower() for b in ['userdetails', 'comments', 'download', 'bookmark', 'peerlist', 'snatches']):
                continue
            
            full_a_tag = m.group(0)
            a_soup = BeautifulSoup(full_a_tag, 'html.parser').find('a')
            t_txt = (a_soup.get('title') or a_soup.get_text(strip=True)) if a_soup else ""
            if not t_txt or len(t_txt) < 4:
                continue
                
            seen_in_page.add(tid)
            valid_matches.append((m.start(), m.end(), tid, t_txt, href))

        raw_count = len(valid_matches)
        if raw_count == 0 and page == 0: return None, "当前分类未找到种子数据", 0

        for idx, (start_pos, end_pos, tid, title, href) in enumerate(valid_matches):
            if tid in seen_ids: continue
            seen_ids.add(tid)

            next_start = valid_matches[idx + 1][0] if idx + 1 < len(valid_matches) else len(list_html)
            chunk_html = list_html[max(0, start_pos - 350):min(len(list_html), next_start)]
            after_title_html = list_html[end_pos:min(len(list_html), next_start)]
            chunk_soup = BeautifulSoup(chunk_html, 'html.parser')

            if skip_sticky:
                is_sticky = False
                for img in chunk_soup.find_all('img'):
                    src = img.get('src', '').lower()
                    alt = (img.get('alt', '') + img.get('title', '')).lower()
                    if 'sticky' in src or 'pin.gif' in src or 'sticky' in alt or '置顶' in alt:
                        is_sticky = True; break
                if is_sticky: continue

            link = f"{BASE_URL}/{href.lstrip('/')}"
            release_group = ""
            raw_group = ""
            group_match = re.search(r'-([A-Za-z0-9@_]+)$', title.strip())
            if group_match:
                raw_group = group_match.group(1)
                release_group = clean_group_name(raw_group)

            size, seeders, leechers, time_col_text = "未知", "0", "0", ""
            after_soup = BeautifulSoup(after_title_html, 'html.parser')
            
            cell_texts = []
            for td in after_soup.find_all('td'):
                if not td.find('td'):
                    txt = td.get_text(" ", strip=True)
                    if txt != "":
                        cell_texts.append(txt)

            for i, txt in enumerate(cell_texts):
                sz_m = re.search(r'^(\d+(?:\.\d+)?)\s*([KMGTP]B)$', txt, re.I)
                if sz_m:
                    size = f"{sz_m.group(1)} {sz_m.group(2).upper()}"
                    if i - 1 >= 0:
                        prev_t = re.sub(r'\s+', '', cell_texts[i - 1])
                        if any(u in prev_t for u in ['年', '月', '周', '天', '时', '分', '秒']) or re.match(r'^\d{2,4}-\d{1,2}-\d{1,2}', prev_t):
                            time_col_text = prev_t
                    if i + 1 < len(cell_texts):
                        s_m = re.search(r'(\d+)', cell_texts[i + 1].replace(',', ''))
                        if s_m: seeders = s_m.group(1)
                    if i + 2 < len(cell_texts):
                        l_m = re.search(r'(\d+)', cell_texts[i + 2].replace(',', ''))
                        if l_m: leechers = l_m.group(1)
                    break

            if size == "未知" or (seeders == "0" and leechers == "0" and not time_col_text):
                plain_after = re.sub(r'<[^>]+>', ' ', after_title_html)
                plain_after = re.sub(r'\s+', ' ', plain_after)
                combo_m = re.search(
                    r'(\d+\s*[年月周天时分秒][^\s]{0,6}|\d{4}-\d{2}-\d{2})?\s*(\d+(?:\.\d+)?)\s*([KMGTP]B)\s+(\d+)\s+(\d+)',
                    plain_after, re.I
                )
                if combo_m:
                    if combo_m.group(1) and not time_col_text:
                        time_col_text = re.sub(r'\s+', '', combo_m.group(1))
                    size = f"{combo_m.group(2)} {combo_m.group(3).upper()}"
                    seeders = combo_m.group(4)
                    leechers = combo_m.group(5)

            tags = []
            if time_col_text: tags.append(f"🕒 {time_col_text}")

            chunk_text = chunk_soup.get_text(" ", strip=True)
            if re.search(r'(?i)\b(free|2xfree)\b|免费', chunk_text) or re.search(r'(?i)pro_free|free\.gif|2up', chunk_html):
                tags.append('Free')
            if re.search(r'(?i)\b2x\b|2up', chunk_text + chunk_html):
                tags.append('2X')

            tm = re.search(r'(?:免费剩余时间|免费剩余|剩余时间|剩余)[::\s]*(\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)', chunk_text)
            if tm: tags.append(f"剩余时间: {tm.group(1).strip()}")

            subtitle = ""
            sub_zone_html = after_title_html
            sz_idx = sub_zone_html.find(size.split()[0]) if size != "未知" else -1
            if sz_idx != -1: sub_zone_html = sub_zone_html[:sz_idx]
            
            sub_soup = BeautifulSoup(sub_zone_html, 'html.parser')
            for br in sub_soup.find_all('br'): br.replace_with('\n')
            for sp in sub_soup.find_all(['span', 'img', 'a']):
                sp_t = sp.get_text(strip=True)
                if sp_t.upper() in [k.upper() for k in TECH_KEYWORDS]:
                    if sp_t not in tags: tags.append(sp_t)
                sp.decompose()
                
            for line in sub_soup.get_text(" ", strip=True).split('\n'):
                line = line.strip()
                if not line: continue
                line = re.sub(r'(?:免费剩余时间|免费剩余|优惠剩余时间|剩余时间|剩余)[::\s]*(?:\d+\s*[年月周天小时分秒钟]+(?:\s*\d+\s*[年月周天小时分秒钟]+)*)?', '', line).strip()
                line = re.sub(r'(?i)\b(2X|Free|N/A)\b|免费|置顶|匿名|\b\d+\.\d+\b', '', line).strip()
                if len(line) > 2 and re.search(r'[\u4e00-\u9fa5]', line):
                    parts = [p.strip() for p in re.split(r'[\|/]+', line) if p.strip() and p.strip().upper() not in [k.upper() for k in TECH_KEYWORDS]]
                    if parts:
                        subtitle = ' | '.join(parts)
                        break

            cached = DETAIL_CACHE.get(tid)
            img_src = ""
            if cached:
                img_src = cached[0]
                if size == "未知" and cached[1] != "未知": size = cached[1]
                if not subtitle and cached[4]: subtitle = cached[4]
                if seeders == "0" and cached[5]: seeders = cached[5]
                if leechers == "0" and cached[6]: leechers = cached[6]
                if not time_col_text and cached[7]: tags.append(f"🕒 {cached[7]}")

            tags = purify_tags(auto_extract_tags(title + " " + subtitle, tags))
            torrents.append({
                'id': tid, 'title': title, 'link': link, 'subtitle': subtitle,
                'img': img_src, 'seeders': seeders, 'leechers': leechers, 'size': size,
                'tags': tags, 'group': release_group, 'raw_group': raw_group
            })

        return torrents, None, raw_count
    except Exception as e:
        return None, f"解析异常: {str(e)}", 0

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>财神 CSPT 满血版</title>
    <style>
        :root { --bg-color: #fafafa; --card-bg: #ffffff; --text-main: #27272a; --text-sub: #71717a; --border-color: #f4f4f5; --topbar-bg: #ffffff; --icon-bg: #ffe4e6; --primary-color: #e11d48; }
        [data-theme="dark"] { --bg-color: #18181b; --card-bg: #27272a; --text-main: #f4f4f5; --text-sub: #a1a1aa; --border-color: #3f3f46; --topbar-bg: #27272a; --icon-bg: #3f3f46; --primary-color: #f43f5e; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background-color: var(--bg-color); color: var(--text-main); margin: 0; padding: 0; padding-top: {% if tab in ['official', 'recent', 'search'] %}95px{% else %}55px{% endif %}; }
        .top-bar { position: fixed; top: 0; left: 0; right: 0; height: 50px; background: var(--topbar-bg); display: flex; align-items: center; justify-content: space-between; padding: 0 15px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); z-index: 100; }
        .menu-btn { width: 22px; height: 16px; cursor: pointer; display: flex; flex-direction: column; justify-content: space-between; }
        .menu-btn span { display: block; height: 2px; width: 100%; background: var(--text-main); border-radius: 2px; }
        .logo { font-weight: 800; font-size: 19px; color: var(--primary-color); display: flex; align-items: center; gap: 4px;}
        .top-right { display: flex; align-items: center; gap: 10px; }
        
        .theme-half-circle { width: 22px; height: 22px; cursor: pointer; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: transform 0.35s ease; color: var(--text-main); }
        [data-theme="dark"] .theme-half-circle { transform: rotate(180deg); }

        .category-bar { position: fixed; top: 50px; left: 0; right: 0; height: 45px; background: var(--topbar-bg); display: flex; align-items: center; padding: 0 15px; gap: 12px; overflow-x: auto; white-space: nowrap; scrollbar-width: none; z-index: 99; border-bottom: 1px solid var(--border-color); }
        .category-bar::-webkit-scrollbar { display: none; }
        .cat-item { font-size: 13px; color: var(--text-main); text-decoration: none; padding: 6px 14px; border-radius: 20px; background: var(--icon-bg); font-weight: 500; }
        .cat-item.active { background: var(--primary-color); color: #fff; }
        .sidebar { position: fixed; top: 0; left: -260px; bottom: 0; width: 260px; background: var(--card-bg); z-index: 1001; transition: left 0.3s; box-shadow: 2px 0 10px rgba(0,0,0,0.1); padding-top: 60px; display: flex; flex-direction: column; }
        .sidebar.open { left: 0; }
        .menu-item { padding: 16px 24px; font-size: 16px; font-weight: 500; color: var(--text-main); text-decoration: none; display: block; border-bottom: 1px solid var(--border-color); }
        .menu-item.active { color: var(--primary-color); border-left: 4px solid var(--primary-color); background: rgba(225,29,72,0.05); }
        .overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1000; opacity: 0; pointer-events: none; transition: opacity 0.3s; }
        .overlay.open { opacity: 1; pointer-events: auto; }
        .container { padding: 5px 10px 10px 10px; }
        .global-search-container { display: flex; gap: 8px; margin: 5px 5px 15px 5px; align-items: center; background: var(--card-bg); padding: 5px; border-radius: 20px; border: 1px solid var(--border-color); }
        .search-input { flex: 1; padding: 8px 15px; border: none; outline: none; font-size: 14px; background: transparent; color: var(--text-main); }
        .search-btn { background: rgba(225,29,72,0.1); color: var(--primary-color); border: none; width: 36px; height: 36px; border-radius: 18px; cursor: pointer; }
        .list-item { display: flex; gap: 12px; padding: 15px 5px; border-bottom: 1px solid var(--border-color); background: var(--card-bg); border-radius: 8px; margin-bottom: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
        .poster-wrapper { position: relative; flex-shrink: 0; width: 100px; height: 140px; }
        .poster { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; background-color: #e0e0e0; }
        .tag-free { position: absolute; top: 0; left: 0; background: #22c55e; color: #fff; font-size: 10px; font-weight: bold; padding: 2px 6px; border-radius: 8px 0 8px 0; z-index: 10; }
        .info { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; justify-content: space-between; padding-bottom: 2px; }
        .title { font-size: 15px; font-weight: bold; margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height: 1.3; color: var(--text-main); text-decoration: none;}
        .subtitle { font-size: 12px; color: var(--text-sub); line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; margin-bottom: 4px; }
        .subtitle:empty { display: none; margin: 0; }
        
        .stats-and-download { display: flex; justify-content: space-between; align-items: center; gap: 6px; width: 100%; margin-bottom: 4px; }
        .stats-row { font-size: 12px; color: var(--text-sub); display: flex; align-items: center; gap: 6px; overflow-x: auto; white-space: nowrap; scrollbar-width: none; flex: 1; min-width: 0; }
        .stats-row::-webkit-scrollbar { display: none; }
        .stat-item { display: inline-flex; align-items: center; gap: 2px; flex-shrink: 0; }
        .seed-icon { color: #22c55e; font-size: 10px; }
        .leech-icon { color: #ef4444; font-size: 10px; }
        
        .tags-wrapper { display: flex; flex-direction: column; gap: 6px; margin-top: auto; width: 100%; overflow: hidden; padding-top: 2px; }
        .tags-top, .tags-bottom { display: flex; gap: 6px; overflow-x: auto; white-space: nowrap; align-items: center; scrollbar-width: none; }
        .tags-top:empty, .tags-bottom:empty { display: none; }
        .secondary-tag { display: none !important; }
        .show-extra .secondary-tag { display: inline-flex !important; }
        .badge-toggle { background: #e5e7eb; color: #6b7280; font-size: 10px; padding: 2px 8px; border-radius: 4px; cursor: pointer; font-weight: bold; }
        .badge { background: #8b5cf6; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-discount { background: #ef4444; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-tech { background: #0ea5e9; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-lang { background: #10b981; color: #fff; font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; }
        .badge-group { background: #ec4899; color: #fff; font-size: 10px; padding: 2px 5px; border-radius: 4px; font-weight: bold; flex-shrink: 0; } 
        .badge-csweb { background: linear-gradient(135deg, #2563eb 0%, #3b82f6 100%); color: #fff; font-size: 10px; padding: 2px 5px; border-radius: 4px; font-weight: bold; flex-shrink: 0; }
        .badge-ubweb { background: linear-gradient(135deg, #e11d48 0%, #f43f5e 100%); color: #fff; font-size: 10px; padding: 2px 5px; border-radius: 4px; font-weight: bold; flex-shrink: 0; }
        .download-btn { background: var(--primary-color); color: #fff; font-size: 11px; padding: 3px 9px; border-radius: 4px; font-weight: bold; border: none; cursor: pointer; flex-shrink: 0; }
        
        /* 底部滑出式多功能面板(单集直推 + 双RSS源精准建规则) */
        .qbt-modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.55); z-index: 2000; opacity: 0; pointer-events: none; transition: opacity 0.25s; }
        .qbt-modal-mask.open { opacity: 1; pointer-events: auto; }
        .qbt-sheet { position: fixed; left: 0; right: 0; bottom: -100%; background: var(--card-bg); border-radius: 16px 16px 0 0; padding: 16px 16px 24px 16px; z-index: 2001; transition: bottom 0.28s cubic-bezier(0.2, 0.8, 0.2, 1); max-height: 86vh; overflow-y: auto; box-shadow: 0 -4px 20px rgba(0,0,0,0.18); }
        .qbt-sheet.open { bottom: 0; }
        .qbt-sheet-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .qbt-sheet-title { font-size: 14px; font-weight: bold; color: var(--text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 88%; }
        .qbt-close { font-size: 20px; color: var(--text-sub); cursor: pointer; padding: 0 4px; }
        
        .mode-tabs { display: flex; background: var(--bg-color); padding: 4px; border-radius: 10px; border: 1px solid var(--border-color); margin-bottom: 10px; }
        .mode-tab { flex: 1; text-align: center; padding: 7px 0; font-size: 13px; font-weight: bold; border-radius: 7px; cursor: pointer; color: var(--text-sub); transition: all 0.2s; }
        .mode-tab.active { background: var(--primary-color); color: #fff; box-shadow: 0 2px 6px rgba(225,29,72,0.25); }

        .qbt-sec-lbl { font-size: 12px; font-weight: bold; color: var(--text-sub); margin: 11px 0 5px 0; display: flex; justify-content: space-between; align-items: center; }
        .qbt-pills { display: flex; flex-wrap: wrap; gap: 7px; }
        .qbt-pill { font-size: 12px; padding: 5px 11px; border-radius: 15px; background: var(--bg-color); color: var(--text-main); border: 1px solid var(--border-color); cursor: pointer; user-select: none; }
        .qbt-pill.active { background: var(--primary-color); color: #fff; border-color: var(--primary-color); font-weight: bold; }
        .qbt-pill.spec-pill.active { background: #0ea5e9; border-color: #0ea5e9; }
        .qbt-pill.feed-pill.active { background: #10b981; border-color: #10b981; }
        .qbt-input { width: 100%; box-sizing: border-box; padding: 8px 11px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-color); color: var(--text-main); font-size: 12px; margin-top: 4px; outline: none; font-family: monospace; }
        .qbt-check-row { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; font-size: 12px; color: var(--text-main); background: var(--bg-color); padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); }
        .qbt-actions { display: flex; gap: 10px; margin-top: 16px; }
        .qbt-submit-btn { flex: 1; background: var(--primary-color); color: #fff; border: none; padding: 11px; border-radius: 8px; font-size: 14px; font-weight: bold; cursor: pointer; }
        .qbt-direct-link { padding: 11px 14px; border-radius: 8px; background: var(--bg-color); color: var(--text-sub); font-size: 13px; text-decoration: none; border: 1px solid var(--border-color); text-align: center; font-weight: 500; }

        /* RSS 规则列表卡片样式 */
        .rss-card { background: var(--card-bg); border-radius: 10px; padding: 14px; margin-bottom: 10px; border: 1px solid var(--border-color); }
        .rss-card-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
        .rss-rule-name { font-size: 15px; font-weight: bold; color: var(--text-main); }
        .rss-meta { font-size: 12px; color: var(--text-sub); line-height: 1.6; word-break: break-all; }
        .rss-regex-box { background: var(--bg-color); padding: 6px 8px; border-radius: 6px; font-family: monospace; font-size: 11px; color: var(--primary-color); margin: 6px 0; border: 1px solid var(--border-color); word-break: break-all; }
        .rss-del-btn { background: #fee2e2; color: #dc2626; border: none; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: bold; cursor: pointer; }
        .rss-toggle-btn { background: #dcfce7; color: #15803d; border: none; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: bold; cursor: pointer; margin-right: 6px; }
        .rss-toggle-btn.off { background: #f4f4f5; color: #71717a; }

        .account-box { background: var(--card-bg); border-radius: 12px; padding: 24px 20px; text-align: center; border: 1px solid var(--border-color); margin-top: 20px; position: relative; }
        .sign-status-pill { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; padding: 4px 12px; border-radius: 16px; background: #ffe4e6; color: #e11d48; font-weight: bold; margin-top: 10px; }
        .sign-status-pill.done { background: #dcfce7; color: #15803d; }
        .avatar { width: 70px; height: 70px; background: var(--primary-color); color: #fff; border-radius: 35px; line-height: 70px; font-size: 26px; font-weight: bold; margin: 0 auto 10px; }
        .stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 20px; }
        .stat-val { font-size: 18px; font-weight: bold; color: var(--primary-color); margin-bottom: 4px; }
        .stat-lbl { font-size: 12px; color: var(--text-sub); }
        .btn-signin { background: #e11d48; color: #fff; width: 100%; padding: 12px; font-size: 16px; border-radius: 8px; font-weight: bold; margin-top: 20px; border: none; cursor: pointer; }
        .alert-error { background: #fee2e2; color: #b91c1c; padding: 15px; border-radius: 8px; font-weight: bold; margin: 10px 5px; text-align: center; }
        .load-more { text-align: center; padding: 15px; margin: 20px 5px; background: var(--card-bg); border-radius: 8px; border: 1px solid var(--border-color); cursor: pointer; color: var(--primary-color); font-weight: bold; }
    </style>
</head>
<body>
    <script>
        function setTheme(theme) {
            if (theme === 'dark') document.documentElement.setAttribute('data-theme', 'dark');
            else document.documentElement.removeAttribute('data-theme');
        }
        setTheme(localStorage.getItem('cspt_theme') || 'light');
        window.toggleTags = function(btn) {
            const wrapper = btn.closest('.tags-wrapper');
            wrapper.classList.toggle('show-extra');
            btn.innerText = wrapper.classList.contains('show-extra') ? '收起 ▴' : '... ▾';
        };
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('open'); 
            document.getElementById('overlay').classList.toggle('open'); 
        }
        function cycleTheme() {
            let t = localStorage.getItem('cspt_theme') === 'dark' ? 'light' : 'dark';
            localStorage.setItem('cspt_theme', t);
            setTheme(t);
        }
        function manualSign() {
            const btn = document.getElementById('signinBtn');
            const pill = document.getElementById('accountSignPill');
            if (btn) { btn.innerText = '正在求签...'; btn.disabled = true; }
            fetch('/api/signin').then(r => r.json()).then(d => {
                if (btn) { btn.innerText = '🧧 立即手动签到'; btn.disabled = false; }
                if (pill && d.status) {
                    pill.innerText = d.status;
                    if (d.ok) pill.classList.add('done');
                }
                alert(d.msg + (d.next_time ? '\\n下次随机自动签到: ' + d.next_time : ''));
            }).catch(e => {
                if (btn) { btn.innerText = '🧧 立即手动签到'; btn.disabled = false; }
                alert('请求失败,请检查网络');
            });
        }
    </script>
    <div class="top-bar">
        <div class="menu-btn" onclick="toggleMenu()"><span></span><span></span><span></span></div>
        <div class="logo">🧧 财神 CSPT</div>
        <div class="top-right">
            <div class="theme-half-circle" onclick="cycleTheme()" title="切换深浅模式">
                <svg viewBox="0 0 24 24" width="20" height="20">
                    <circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/>
                    <path d="M 12 3 A 9 9 0 0 0 12 21 Z" fill="currentColor"/>
                </svg>
            </div>
        </div>
    </div>
    {% if tab in ['official', 'recent', 'search'] %}
    <div class="category-bar">
        <a href="/?tab={{ tab }}&cat=all" class="cat-item {% if cat == 'all' %}active{% endif %}">综合</a>
        <a href="/?tab={{ tab }}&cat=401" class="cat-item {% if cat == '401' %}active{% endif %}">电影(401)</a>
        <a href="/?tab={{ tab }}&cat=402" class="cat-item {% if cat == '402' %}active{% endif %}">电视(402)</a>
        <a href="/?tab={{ tab }}&cat=405" class="cat-item {% if cat == '405' %}active{% endif %}">动漫(405)</a>
        <a href="/?tab={{ tab }}&cat=403" class="cat-item {% if cat == '403' %}active{% endif %}">综艺(403)</a>
        <a href="/?tab={{ tab }}&cat=418" class="cat-item {% if cat == '418' %}active{% endif %}">短剧(418)</a>
        <a href="/?tab={{ tab }}&cat=404" class="cat-item {% if cat == '404' %}active{% endif %}">纪录(404)</a>
    </div>
    {% endif %}
    <div class="overlay" id="overlay" onclick="toggleMenu()"></div>
    <div class="sidebar" id="sidebar">
        <a href="/?tab=official&cat={{ cat }}" class="menu-item {% if tab == 'official' %}active{% endif %}">全部发布(全量)</a>
        <a href="/?tab=recent&cat={{ cat }}" class="menu-item {% if tab == 'recent' %}active{% endif %}">最近发布(无置顶)</a>
        <a href="/?tab=rss" class="menu-item {% if tab == 'rss' %}active{% endif %}">📡 RSS 订阅规则</a>
        <a href="/?tab=account&cat={{ cat }}" class="menu-item {% if tab == 'account' %}active{% endif %}">我的帐号</a>
    </div>

    <!-- 🚀 底部多功能面板:单集直推 + 电视剧/动漫双RSS源精准建规则 -->
    <div class="qbt-modal-mask" id="qbtMask" onclick="closeQbtModal()"></div>
    <div class="qbt-sheet" id="qbtSheet">
        <div class="qbt-sheet-header">
            <div class="qbt-sheet-title" id="qbtSheetTitle">操作面板</div>
            <div class="qbt-close" onclick="closeQbtModal()">✕</div>
        </div>

        <div class="mode-tabs">
            <div class="mode-tab active" id="modeTabPush" onclick="switchModalMode('push')">🚀 单集立即推送</div>
            <div class="mode-tab" id="modeTabRss" onclick="switchModalMode('rss')">📡 精准 RSS 追更</div>
        </div>

        <div class="qbt-sec-lbl">
            <span>1. 选择目标 qBittorrent 节点</span>
            <span id="qbtConnStatus" style="font-weight:normal; font-size:11px;"></span>
        </div>
        <div class="qbt-pills" id="qbtServerPills">
            {% for sid, scfg in qbt_servers.items() %}
            <div class="qbt-pill" data-srv="{{ sid }}" onclick="selectQbtServer('{{ sid }}')">{{ scfg.name }}</div>
            {% endfor %}
        </div>

        <div class="qbt-sec-lbl">
            <span>2. 选择分类 (自动同步所选节点)</span>
            <span id="qbtCatPath" style="font-weight:normal; font-size:11px; max-width:52%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"></span>
        </div>
        <div class="qbt-pills" id="qbtCatPills">
            <div class="qbt-pill active" data-cat="" onclick="selectQbtCat('', '')">不设分类(默认路径)</div>
        </div>

        <div class="qbt-sec-lbl"><span>3. 附加标签 (单版本互斥,支持手动修改)</span></div>
        <div class="qbt-pills" id="qbtTagPills"></div>
        <input type="text" id="qbtCustomTags" class="qbt-input" value="洗码" oninput="isTagsManuallyEdited = true">

        <!-- 📡 RSS 专属精准过滤配置区 -->
        <div id="rssConfigZone" style="display:none;">
            <div class="qbt-sec-lbl">
                <span>4. 选择绑定的固定订阅源 (电视剧 / 动漫防漏源)</span>
            </div>
            <div class="qbt-pills" id="rssFeedPills"></div>

            <div class="qbt-sec-lbl"><span>5. 规则名称 & 剧名/集数核心</span></div>
            <input type="text" id="rssRuleName" class="qbt-input" placeholder="纯中文剧名 (或剧名+版本)">
            <input type="text" id="rssShowCore" class="qbt-input" placeholder="英文剧名.*E\\d+" oninput="rebuildRssRegex()">

            <div class="qbt-sec-lbl"><span>6. 精准分辨率 / 色彩版本 / 制作组锁定 (支持多选)</span></div>
            <div class="qbt-pills" id="rssSpecPills"></div>

            <div class="qbt-sec-lbl"><span>7. 最终正则预览 (mustContain,支持手动微调)</span></div>
            <input type="text" id="rssFinalRegex" class="qbt-input" placeholder="自动生成的精准正则">

            <div class="qbt-sec-lbl"><span>8. 排除关键词 (mustNotContain,未选中版本自动拉黑)</span></div>
            <input type="text" id="rssExcludeRegex" class="qbt-input" value="合集|Complete|Pack|全集|招募">

            <div class="qbt-check-row">
                <span>启用智能集数过滤 (Smart Filter 防同集重下)</span>
                <input type="checkbox" id="rssSmartFilter" style="width:18px; height:18px;">
            </div>
        </div>

        <div class="qbt-actions">
            <button class="qbt-submit-btn" id="qbtSubmitBtn" onclick="handleModalSubmit()">🚀 立即推送到 qB</button>
            <a id="qbtDirectBtn" href="#" class="qbt-direct-link">原文件</a>
        </div>
    </div>

    <div class="container">
        {% if tab in ['official', 'recent', 'search'] %}
        <form class="global-search-container" action="/" method="GET">
            <input type="hidden" name="tab" value="search"><input type="hidden" name="cat" value="{{ cat }}">
            <input type="text" name="q" class="search-input" placeholder="输入关键词搜全站..." value="{{ query }}">
            <button type="submit" class="search-btn">🔍</button>
        </form>
        {% endif %}
        {% if error %}<div class="alert-error">{{ error }}</div>{% endif %}

        {% if tab == 'rss' %}
            <div style="margin: 8px 4px 12px 4px;">
                <div style="font-size:13px; font-weight:bold; color:var(--text-sub); margin-bottom:8px;">选择要查看的 qBittorrent 节点:</div>
                <div class="qbt-pills" id="rssManageNodes">
                    {% for sid, scfg in qbt_servers.items() %}
                    <div class="qbt-pill {% if loop.first %}active{% endif %}" data-srv="{{ sid }}" onclick="loadNodeRssRules('{{ sid }}')">{{ scfg.name }}</div>
                    {% endfor %}
                </div>
            </div>
            <div id="rssRulesContainer" style="margin-top:10px;">
                <div style="text-align:center; padding:30px; color:var(--text-sub);">正在加载节点订阅规则...</div>
            </div>
            <script>
                document.addEventListener("DOMContentLoaded", function() {
                    const savedSrv = localStorage.getItem('cspt_qbt_srv') || '188';
                    loadNodeRssRules(savedSrv);
                });
                function loadNodeRssRules(srvId) {
                    localStorage.setItem('cspt_qbt_srv', srvId);
                    document.querySelectorAll('#rssManageNodes .qbt-pill').forEach(el => {
                        el.classList.toggle('active', el.getAttribute('data-srv') === srvId);
                    });
                    const box = document.getElementById('rssRulesContainer');
                    box.innerHTML = '<div style="text-align:center; padding:30px; color:var(--text-sub);">正在读取 qB RSS 规则...</div>';
                    fetch('/api/qbt/rss/rules?server=' + encodeURIComponent(srvId))
                        .then(r => r.json())
                        .then(d => {
                            if (!d.ok) {
                                box.innerHTML = `<div style="text-align:center; color:#ef4444; padding:20px;">⚠️ ${d.msg}</div>`;
                                return;
                            }
                            const rules = d.rules || [];
                            if (rules.length === 0) {
                                box.innerHTML = `<div style="text-align:center; color:var(--text-sub); padding:30px;">该节点暂无 RSS 自动下载规则<br><span style="font-size:12px;">去种子列表点击“推送” -> 切换到“RSS 追更”即可一键创建</span></div>`;
                                return;
                            }
                            let html = '';
                            rules.forEach(r => {
                                const safeName = r.name.replace(/'/g, "\\\\'");
                                const feedLabel = r.feedLabel || '全部/已绑定源';
                                html += `
                                <div class="rss-card">
                                    <div class="rss-card-top">
                                        <div class="rss-rule-name">${r.enabled ? '🟢' : '⏸️'} ${r.name}</div>
                                        <div>
                                            <button class="rss-toggle-btn ${r.enabled ? '' : 'off'}" onclick="toggleRssRule('${srvId}', '${safeName}', ${!r.enabled})">${r.enabled ? '运行中' : '已暂停'}</button>
                                            <button class="rss-del-btn" onclick="deleteRssRule('${srvId}', '${safeName}')">删除</button>
                                        </div>
                                    </div>
                                    <div class="rss-meta">
                                        📡 订阅源: <b>${feedLabel}</b> &nbsp;|&nbsp; 📁 分类: <b>${r.assignedCategory || '未设'}</b> &nbsp;|&nbsp; 🏷️ 标签: <b>${(r.torrentParams && r.torrentParams.tags ? r.torrentParams.tags.join(',') : '') || '无'}</b>
                                    </div>
                                    <div class="rss-regex-box">匹配: ${r.mustContain || '(空)'}</div>
                                    ${r.mustNotContain ? `<div class="rss-meta" style="font-size:11px;">🚫 排除: ${r.mustNotContain}</div>` : ''}
                                    <div class="rss-meta" style="font-size:11px; margin-top:4px;">
                                        📌 智能集数过滤: ${r.smartFilter ? '开启' : '关闭'} &nbsp;|&nbsp; 历史命中: ${(r.previouslyMatchedEpisodes || []).length} 集
                                    </div>
                                </div>`;
                            });
                            box.innerHTML = html;
                        });
                }
                function toggleRssRule(srvId, ruleName, targetState) {
                    fetch('/api/qbt/rss/toggle', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({server: srvId, name: ruleName, enabled: targetState})
                    }).then(r => r.json()).then(d => {
                        if (d.ok) loadNodeRssRules(srvId);
                        else alert('❌ ' + d.msg);
                    });
                }
                function deleteRssRule(srvId, ruleName) {
                    if (!confirm('确定要删除追剧规则【' + ruleName + '】吗?')) return;
                    fetch('/api/qbt/rss/delete', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({server: srvId, name: ruleName})
                    }).then(r => r.json()).then(d => {
                        if (d.ok) loadNodeRssRules(srvId);
                        else alert('❌ ' + d.msg);
                    });
                }
            </script>

        {% elif tab == 'account' and user_info %}
        <div class="account-box">
            <div class="avatar">{{ user_info.username[:1] | upper }}</div>
            <div style="font-size: 19px; font-weight: bold;">{{ user_info.username }}</div>
            <div>
                <span id="accountSignPill" class="sign-status-pill {% if sign_done %}done{% endif %}">
                    {{ sign_msg }}
                </span>
            </div>
            <div class="stat-grid">
                <div><div class="stat-val">{{ user_info.bonus }}</div><div class="stat-lbl">元宝</div></div>
                <div><div class="stat-val">{{ user_info.ratio }}</div><div class="stat-lbl">分享率</div></div>
                <div><div class="stat-val">{{ user_info.upload }}</div><div class="stat-lbl">总上传</div></div>
                <div><div class="stat-val">{{ user_info.download }}</div><div class="stat-lbl">总下载</div></div>
            </div>
            <div style="margin-top: 18px; font-size: 12px; color: var(--text-sub);">
                🕒 后台随机自动签到已启用 {% if next_sign %}(下次计划: {{ next_sign }}){% endif %}
            </div>
            <button id="signinBtn" class="btn-signin" onclick="manualSign()">🧧 立即手动签到</button>
        </div>

        {% elif tab not in ['account', 'rss'] %}
            <div id="torrent-list">
            {% for item in torrents %}
            <div class="list-item" id="item-{{ item.id }}">
                <div class="poster-wrapper" id="pw-{{ item.id }}">
                    {% set needs_lazy = not item.img %}
                    <img class="poster {% if needs_lazy %}lazy-load{% endif %}" 
                         src="{{ item.img if item.img else 'data:image/svg+xml;utf8,<svg xmlns=\\'http://www.w3.org/2000/svg\\' width=\\'100\\' height=\\'140\\'><rect width=\\'100%\\' height=\\'100%\\' fill=\\'%23e6e6e6\\'/><text x=\\'50%\\' y=\\'50%\\' fill=\\'%23999\\' font-size=\\'12\\' text-anchor=\\'middle\\' dominant-baseline=\\'middle\\'>加载海报</text></svg>' }}" 
                         {% if needs_lazy %}data-tid="{{ item.id }}"{% endif %} referrerpolicy="no-referrer" alt="海报" onclick="window.open('{{ item.link }}', '_blank')">
                    {% if 'FREE' in item.tags|join(' ')|upper %}<div class="tag-free">FREE</div>{% endif %}
                </div>
                <div class="info">
                    <a class="title" href="{{ item.link }}" target="_blank">{{ item.title }}</a>
                    <div class="subtitle" id="sub-{{ item.id }}">{{ item.subtitle }}</div>
                    <div class="stats-and-download">
                        <div class="stats-row">
                            <span class="stat-item" id="size-{{ item.id }}">📄 {{ item.size }}</span>
                            <span class="stat-item"><span class="seed-icon">▲</span> <span id="seed-{{ item.id }}">{{ item.seeders }}</span></span>
                            <span class="stat-item"><span class="leech-icon">▼</span> <span id="leech-{{ item.id }}">{{ item.leechers }}</span></span>
                            <span id="group-{{ item.id }}" style="display:inline-flex;">
                            {% if item.group %}
                                {% if item.group|upper == 'CS' %}<span class="badge-csweb">💎 CS</span>
                                {% elif item.group|upper in ['UB', 'US'] %}<span class="badge-ubweb">🔥 {{ item.group|upper }}</span>
                                {% else %}<span class="badge-group">{{ item.group }}</span>{% endif %}
                            {% endif %}
                            </span>
                        </div>
                        <button type="button" class="download-btn" data-tid="{{ item.id }}" data-title="{{ item.title|e }}" data-sub="{{ item.subtitle|e }}" data-grp="{{ item.raw_group|e }}" onclick="openQbtFromBtn(this)">推送</button>
                    </div>
                    <div class="tags-wrapper" id="tags-{{ item.id }}">
                        <div class="tags-top">
                            {% for tag in item.top_pri %}<span class="badge-tech">{{ tag }}</span>{% endfor %}
                            {% for tag in item.top_sec %}<span class="badge-tech secondary-tag">{{ tag }}</span>{% endfor %}
                        </div>
                        <div class="tags-bottom">
                            {% if item.time_tag %}<span class="badge-discount" id="timetag-{{ item.id }}">{{ item.time_tag }}</span>{% endif %}
                            {% if item.clock_tag %}<span class="badge" id="clock-{{ item.id }}" style="background:#64748b;">{{ item.clock_tag }}</span>{% endif %}
                            {% for tag in item.bot_disc %}<span class="badge-discount">{{ tag }}</span>{% endfor %}
                            {% for tag in item.bot_pri %}<span class="badge">{{ tag }}</span>{% endfor %}
                            {% for tag in item.bot_sec %}<span class="badge-lang secondary-tag">{{ tag }}</span>{% endfor %}
                            {% if item.top_sec|length > 0 or item.bot_sec|length > 0 %}<span class="badge-toggle" onclick="toggleTags(this)">... ▾</span>{% endif %}
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
            </div>
            {% if not error %}
                <div id="load-btn" class="load-more" onclick="loadNext()">👇 点击加载第 {{ next_page }} 页 👇</div>
            {% endif %}
        {% endif %}
    </div>
    <script>
        let currentModalMode = 'push';
        let currentPushTid = null;
        let currentQbtServer = localStorage.getItem('cspt_qbt_srv') || '188';
        let currentQbtCat = localStorage.getItem('cspt_qbt_cat_' + currentQbtServer) || '';
        let currentFeedKey = localStorage.getItem('cspt_qbt_feed_' + currentQbtServer) || '电视剧';
        let nodeRssFeeds = {};
        let rssSpecState = [];
        let rssBaseCnName = '';
        let isTagsManuallyEdited = false;

        function switchModalMode(mode) {
            currentModalMode = mode;
            document.getElementById('modeTabPush').classList.toggle('active', mode === 'push');
            document.getElementById('modeTabRss').classList.toggle('active', mode === 'rss');
            document.getElementById('rssConfigZone').style.display = (mode === 'rss') ? 'block' : 'none';
            document.getElementById('qbtSubmitBtn').innerText = (mode === 'rss') ? '📡 保存并下发 RSS 追更规则' : '🚀 立即推送到 qB';
        }

        function parseTitleForRss(title, sub, grp) {
            const BS = String.fromCharCode(92);

            // 1. 提取纯中文剧名(剥离中文/阿拉伯数字季数与集数)
            let cnName = '';
            if (sub) {
                const skipWords = /^(分集|完结|官种|官方|国语|中字|粤语|英语|双语|简繁|热门|首发|禁转|DIY|4K|HDR|DV|HQ|SDR|杜比|高帧|高码)$/i;
                const parts = sub.split('|').map(s => s.trim()).filter(Boolean);
                for (let p of parts) {
                    if (!skipWords.test(p) && /[\u4e00-\u9fa5]/.test(p)) {
                        let cleaned = p.replace(/^.*?[::]/, '').split('/')[0].trim();
                        cleaned = cleaned.replace(/\s*(?:第\s*[一二三四五六七八九十百\d]+(?:\s*-\s*\d+)?\s*[集期话季]|更新至\s*\d+\s*[集期话]|全\s*\d+\s*[集期话]).*$/g, '').trim();
                        if (cleaned) {
                            cnName = cleaned;
                            break;
                        }
                    }
                }
            }

            // 2. 提取英文剧名 + E\d+(兼容 S01E02 连写截断,零 \b 隐患)
            let rawName = title;
            const cutMatch = title.match(/^(.*?)(?:[\s.\-_]+(?:S\d{1,2}(?:E\d+)?|E\d+|(?:19|20)\d{2}|2160p|1080p|720p))(?:[\s.\-_]|$)/i);
            if (cutMatch && cutMatch[1].trim()) {
                rawName = cutMatch[1].trim();
            }
            rawName = rawName.replace(/[\.\-_]+/g, ' ').replace(/\s+/g, ' ').trim();
            let showCore = rawName + '.*E' + BS + 'd+';

            // 3. 提取所有命中的要素,并按在原标题中的真实先后位置排序
            const specs = [];
            const allDefs = [
                {label: '2160p', test: /(?:^|[\s.\-_])(2160p|4K)(?:$|[\s.\-_])/i, regex: '2160p', active: true, inName: false, syncTag: false},
                {label: '1080p', test: /(?:^|[\s.\-_])1080p(?:$|[\s.\-_])/i, regex: '1080p', active: true, inName: false, syncTag: false},
                {label: 'HFR', test: /(?:^|[\s.\-_])(60fps|HFR)(?:$|[\s.\-_])/i, regex: '(?:60fps|HFR)', active: true, inName: true, syncTag: false},
                {label: '50fps', test: /(?:^|[\s.\-_])50fps(?:$|[\s.\-_])/i, regex: '50fps', active: true, inName: false, syncTag: false},
                {label: '30fps', test: /(?:^|[\s.\-_])30fps(?:$|[\s.\-_])/i, regex: '30fps', active: true, inName: false, syncTag: false},
                {label: 'MAXPLUS', test: /(?:^|[\s.\-_])MAXPLUS(?:$|[\s.\-_])/i, regex: 'MAXPLUS', active: true, inName: false, syncTag: false},
                {label: 'HQ', test: /(?:^|[\s.\-_])HQ(?:$|[\s.\-_])/i, regex: 'HQ', active: true, inName: true, syncTag: true},
                {label: 'HDR', test: /(?:^|[\s.\-_])(HDR|HDRVivid|HDR10\+?)(?:$|[\s.\-_])/i, regex: '(?:HDR|HDRVivid)', active: true, inName: true, syncTag: true},
                {label: 'SDR', test: /(?:^|[\s.\-_])SDR(?:$|[\s.\-_])/i, regex: 'SDR', active: true, inName: true, syncTag: true},
                {label: 'DV', test: /(?:^|[\s.\-_])(DV|DoVi)(?:$|[\s.\-_])/i, regex: '(?:DV|DoVi)', active: true, inName: true, syncTag: true},
                {label: 'H265', test: /H\.?265|HEVC|x265/i, regex: '(?:265|HEVC)', active: false, inName: false, syncTag: false},
                {label: 'H264', test: /H\.?264|AVC|x264/i, regex: '(?:264|AVC)', active: false, inName: false, syncTag: false}
            ];

            allDefs.forEach(d => {
                const pos = title.search(d.test);
                if (pos !== -1) {
                    specs.push({label: d.label, regex: d.regex, active: d.active, inName: d.inName, syncTag: d.syncTag, pos: pos});
                }
            });

            specs.sort((a, b) => a.pos - b.pos);

            // 制作组永远排在最后(保留原始大小写)
            if (grp) {
                const safeGrp = grp.replace(/[^A-Za-z0-9_@]/g, '');
                if (safeGrp) specs.push({label: safeGrp, regex: safeGrp, active: true, inName: false, syncTag: false, pos: 9999});
            }

            rssBaseCnName = cnName || rawName;
            rssSpecState = specs;
            document.getElementById('rssShowCore').value = showCore;
            renderRssSpecPills();
            rebuildRssRegex();
        }

        function renderRssSpecPills() {
            const box = document.getElementById('rssSpecPills');
            box.innerHTML = rssSpecState.map((s, idx) => 
                `<div class="qbt-pill spec-pill ${s.active ? 'active' : ''}" onclick="toggleRssSpec(${idx})">${s.active ? '✓ ' : ''}${s.label}</div>`
            ).join('');
        }

        function toggleRssSpec(idx) {
            rssSpecState[idx].active = !rssSpecState[idx].active;
            renderRssSpecPills();
            rebuildRssRegex();
        }

        function rebuildRssRegex() {
            const core = document.getElementById('rssShowCore').value.trim();
            const activeSpecs = rssSpecState.filter(s => s.active);
            const activeLabels = activeSpecs.map(s => s.label);
            
            // 1. 生成安全括号包裹的正向正则
            const parts = [core, ...activeSpecs.map(s => {
                if (s.regex.includes('|') && !s.regex.startsWith('(')) return `(?:${s.regex})`;
                return s.regex;
            })].filter(Boolean);
            document.getElementById('rssFinalRegex').value = parts.join('.*');

            // 2. 动态排他排除词 (mustNotContain):未选中的版本特性全部自动拉黑
            const baseExcludes = ['合集', 'Complete', 'Pack', '全集', '招募'];
            const exclusivePool = [
                {label: 'DV', exclude: 'DV|DoVi'},
                {label: 'HDR', exclude: 'HDR|HDRVivid'},
                {label: 'HQ', exclude: 'HQ'},
                {label: 'HFR', exclude: '60fps|HFR'},
                {label: 'MAXPLUS', exclude: 'MAXPLUS'}
            ];
            const autoExcludes = exclusivePool
                .filter(item => !activeLabels.includes(item.label))
                .map(item => item.exclude);
            document.getElementById('rssExcludeRegex').value = [...baseExcludes, ...autoExcludes].join('|');

            // 3. 规则名称:纯中文剧名 + 允许的版本要素 (DV/HDR/SDR/HQ/HFR)
            const nameLabels = activeSpecs.filter(s => s.inName).map(s => s.label);
            const nameParts = [rssBaseCnName, ...nameLabels].filter(Boolean);
            document.getElementById('rssRuleName').value = nameParts.join(' ');

            // 4. 仅在未手动修改时,按优先级同步【唯一一个】版本标签到 qB (DV > HDR > HQ > SDR)
            if (!isTagsManuallyEdited) {
                const verPriority = ['DV', 'HDR', 'HQ', 'SDR'];
                const matchedVers = activeSpecs.filter(s => s.syncTag).map(s => s.label);
                const singleVer = verPriority.find(v => matchedVers.includes(v));

                const customTagInp = document.getElementById('qbtCustomTags');
                let baseTags = customTagInp.value.split(/[,,]/).map(s => s.trim()).filter(Boolean);
                baseTags = baseTags.filter(t => !verPriority.includes(t));
                if (baseTags.length === 0) baseTags = ['洗码'];
                if (singleVer) baseTags.push(singleVer);
                customTagInp.value = baseTags.join(',');
            }
        }

        function openQbtFromBtn(btn) {
            const tid = btn.getAttribute('data-tid');
            const title = btn.getAttribute('data-title');
            const sub = btn.getAttribute('data-sub') || (document.getElementById('sub-' + tid) ? document.getElementById('sub-' + tid).innerText : '');
            const grp = btn.getAttribute('data-grp');
            openQbtModal(tid, title, sub, grp);
        }

        function openQbtModal(tid, title, sub, grp) {
            currentPushTid = tid;
            document.getElementById('qbtSheetTitle').innerText = title || ('种子 #' + tid);
            document.getElementById('qbtDirectBtn').href = '/download/' + tid;
            document.getElementById('qbtCustomTags').value = '洗码';
            isTagsManuallyEdited = false;

            parseTitleForRss(title || '', sub || '', grp || '');
            switchModalMode('push');

            document.getElementById('qbtMask').classList.add('open');
            document.getElementById('qbtSheet').classList.add('open');
            selectQbtServer(currentQbtServer);
        }

        function closeQbtModal() {
            document.getElementById('qbtMask').classList.remove('open');
            document.getElementById('qbtSheet').classList.remove('open');
        }

        function renderFeedPills() {
            const box = document.getElementById('rssFeedPills');
            const keys = Object.keys(nodeRssFeeds);
            if (keys.length === 0) {
                box.innerHTML = `<div class="qbt-pill feed-pill active">未配置固定源(将匹配全部)</div>`;
                return;
            }
            if (!keys.includes(currentFeedKey) && currentFeedKey !== 'ALL') {
                currentFeedKey = keys[0];
            }
            let html = keys.map(k => {
                const icon = k.includes('动漫') ? '🌸 ' : '📺 ';
                const isAct = (currentFeedKey === k);
                return `<div class="qbt-pill feed-pill ${isAct ? 'active' : ''}" onclick="selectRssFeed('${k}')">${icon}${k}</div>`;
            }).join('');
            if (keys.length > 1) {
                html += `<div class="qbt-pill feed-pill ${currentFeedKey === 'ALL' ? 'active' : ''}" onclick="selectRssFeed('ALL')">🔗 同时绑定全部(${keys.length}个)</div>`;
            }
            box.innerHTML = html;
        }

        function selectRssFeed(feedKey) {
            currentFeedKey = feedKey;
            localStorage.setItem('cspt_qbt_feed_' + currentQbtServer, feedKey);
            renderFeedPills();
        }

        function selectQbtServer(srvId) {
            currentQbtServer = srvId;
            localStorage.setItem('cspt_qbt_srv', srvId);
            currentQbtCat = localStorage.getItem('cspt_qbt_cat_' + srvId) || '';
            currentFeedKey = localStorage.getItem('cspt_qbt_feed_' + srvId) || '电视剧';

            document.querySelectorAll('#qbtServerPills .qbt-pill').forEach(el => {
                el.classList.toggle('active', el.getAttribute('data-srv') === srvId);
            });

            const statusEl = document.getElementById('qbtConnStatus');
            const catBox = document.getElementById('qbtCatPills');
            const tagBox = document.getElementById('qbtTagPills');
            statusEl.innerText = '正在读取节点配置...';
            statusEl.style.color = '#71717a';

            fetch('/api/qbt/meta?server=' + encodeURIComponent(srvId))
                .then(r => r.json())
                .then(d => {
                    if (!d.ok) {
                        statusEl.innerText = '⚠️ ' + d.msg;
                        statusEl.style.color = '#ef4444';
                        return;
                    }
                    statusEl.innerText = '🟢 在线 (' + d.version + ')';
                    statusEl.style.color = '#16a34a';

                    nodeRssFeeds = d.rss_feeds || {};
                    renderFeedPills();

                    let catHtml = `<div class="qbt-pill ${currentQbtCat === '' ? 'active' : ''}" data-cat="" onclick="selectQbtCat('', '')">不设分类(默认)</div>`;
                    let matchedPath = '';
                    (d.categories || []).forEach(c => {
                        const isAct = (c.name === currentQbtCat);
                        if (isAct) matchedPath = c.savePath || '';
                        catHtml += `<div class="qbt-pill ${isAct ? 'active' : ''}" data-cat="${c.name}" onclick="selectQbtCat('${c.name}', '${c.savePath || ''}')">📁 ${c.name}</div>`;
                    });
                    catBox.innerHTML = catHtml;
                    document.getElementById('qbtCatPath').innerText = matchedPath ? ('路径: ' + matchedPath) : '';

                    let tagHtml = '';
                    (d.tags || []).forEach(t => {
                        tagHtml += `<div class="qbt-pill" onclick="toggleInputTag('${t}')">🏷️ ${t}</div>`;
                    });
                    tagBox.innerHTML = tagHtml;
                })
                .catch(e => {
                    statusEl.innerText = '❌ 连接节点失败';
                    statusEl.style.color = '#ef4444';
                });
        }

        function selectQbtCat(catName, savePath) {
            currentQbtCat = catName;
            localStorage.setItem('cspt_qbt_cat_' + currentQbtServer, catName);
            document.querySelectorAll('#qbtCatPills .qbt-pill').forEach(el => {
                el.classList.toggle('active', el.getAttribute('data-cat') === catName);
            });
            document.getElementById('qbtCatPath').innerText = savePath ? ('路径: ' + savePath) : '';

            if (catName.includes('动漫') || catName.includes('国漫')) {
                if (nodeRssFeeds['动漫']) selectRssFeed('动漫');
            } else if (catName.includes('剧')) {
                if (nodeRssFeeds['电视剧']) selectRssFeed('电视剧');
            }
        }

        function toggleInputTag(tag) {
            isTagsManuallyEdited = true;
            const inp = document.getElementById('qbtCustomTags');
            let arr = inp.value.split(/[,,]/).map(s => s.trim()).filter(Boolean);
            const singleVerGroup = ['DV', 'HDR', 'SDR', 'HQ', 'HFR', 'IQ', 'HDV', 'HHDR'];
            if (arr.includes(tag)) {
                arr = arr.filter(x => x !== tag);
            } else {
                if (singleVerGroup.includes(tag)) {
                    arr = arr.filter(x => !singleVerGroup.includes(x));
                }
                arr.push(tag);
            }
            inp.value = arr.join(',');
        }

        function handleModalSubmit() {
            if (currentModalMode === 'rss') submitRssRule();
            else submitQbtPush();
        }

        function submitRssRule() {
            const btn = document.getElementById('qbtSubmitBtn');
            const ruleName = document.getElementById('rssRuleName').value.trim();
            const mustContain = document.getElementById('rssFinalRegex').value.trim();
            const mustNotContain = document.getElementById('rssExcludeRegex').value.trim();
            const smartFilter = document.getElementById('rssSmartFilter').checked;
            const tags = document.getElementById('qbtCustomTags').value.split(/[,,]/).map(s => s.trim()).filter(Boolean).join(',');

            if (!ruleName || !mustContain) {
                alert('⚠️ 规则名称和匹配正则不能为空!');
                return;
            }

            let selectedFeeds = [];
            if (currentFeedKey === 'ALL') {
                selectedFeeds = Object.values(nodeRssFeeds).filter(Boolean);
            } else if (nodeRssFeeds[currentFeedKey]) {
                selectedFeeds = [nodeRssFeeds[currentFeedKey]];
            }

            btn.innerText = '正在下发规则并推送当前集...';
            btn.disabled = true;

            fetch('/api/qbt/rss/add', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    server: currentQbtServer,
                    name: ruleName,
                    mustContain: mustContain,
                    mustNotContain: mustNotContain,
                    smartFilter: smartFilter,
                    category: currentQbtCat,
                    tags: tags,
                    affectedFeeds: selectedFeeds
                })
            }).then(r => r.json()).then(d => {
                if (!d.ok) {
                    btn.disabled = false;
                    btn.innerText = '📡 保存并下发 RSS 追更规则';
                    alert('❌ ' + d.msg);
                    return;
                }
                if (currentPushTid) {
                    fetch('/api/qbt/push', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({
                            tid: currentPushTid,
                            server: currentQbtServer,
                            category: currentQbtCat,
                            tags: tags
                        })
                    }).then(r2 => r2.json()).then(d2 => {
                        btn.disabled = false;
                        btn.innerText = '📡 保存并下发 RSS 追更规则';
                        closeQbtModal();
                        alert('✅ ' + d.msg + '\\n' + (d2.ok ? '🚀 当前种子已同步推送到下载队列!' : '⚠️ 当前种子推送失败: ' + d2.msg));
                    }).catch(() => {
                        btn.disabled = false;
                        btn.innerText = '📡 保存并下发 RSS 追更规则';
                        closeQbtModal();
                        alert('✅ ' + d.msg + '\\n⚠️ 当前种子自动推送请求超时');
                    });
                } else {
                    btn.disabled = false;
                    btn.innerText = '📡 保存并下发 RSS 追更规则';
                    closeQbtModal();
                    alert('✅ ' + d.msg);
                }
            }).catch(e => {
                btn.disabled = false;
                btn.innerText = '📡 保存并下发 RSS 追更规则';
                alert('❌ 下发请求异常');
            });
        }

        function submitQbtPush() {
            if (!currentPushTid) return;
            const btn = document.getElementById('qbtSubmitBtn');
            const tags = document.getElementById('qbtCustomTags').value.split(/[,,]/).map(s => s.trim()).filter(Boolean).join(',');
            btn.innerText = '正在抓取种子并推送...';
            btn.disabled = true;

            fetch('/api/qbt/push', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    tid: currentPushTid,
                    server: currentQbtServer,
                    category: currentQbtCat,
                    tags: tags
                })
            }).then(r => r.json()).then(d => {
                btn.disabled = false;
                btn.innerText = '🚀 立即推送到 qB';
                if (d.ok) {
                    closeQbtModal();
                    alert('✅ ' + d.msg);
                } else {
                    alert('❌ ' + d.msg);
                }
            }).catch(e => {
                btn.disabled = false;
                btn.innerText = '🚀 立即推送到 qB';
                alert('❌ 请求异常');
            });
        }

        function renderGroupBadge(g) {
            if (!g) return '';
            const gu = g.toUpperCase();
            if (gu === 'CS') return `<span class="badge-csweb">💎 CS</span>`;
            if (gu === 'UB' || gu === 'US') return `<span class="badge-ubweb">🔥 ${gu}</span>`;
            return `<span class="badge-group">${g}</span>`;
        }

        document.addEventListener("DOMContentLoaded", function() {
            if ('IntersectionObserver' in window) {
                window.lazyObserver = new IntersectionObserver((entries, obs) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            const tid = img.getAttribute('data-tid');
                            if (tid) {
                                fetch('/api/extra/' + tid).then(r => r.json()).then(data => {
                                    img.src = data.img || "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='140'><rect width='100%' height='100%' fill='%23f4f4f5'/><text x='50%' y='50%' fill='%23a1a1aa' font-size='12' text-anchor='middle' dominant-baseline='middle'>暂无海报</text></svg>";
                                    img.classList.remove('lazy-load');
                                    if (data.size && data.size !== '未知') {
                                        const sz = document.getElementById('size-' + tid);
                                        if (sz) sz.innerText = '📄 ' + data.size;
                                    }
                                    if (data.subtitle) {
                                        const sb = document.getElementById('sub-' + tid);
                                        if (sb && !sb.innerText.trim()) sb.innerText = data.subtitle;
                                    }
                                    if (data.seeders && data.seeders !== '') {
                                        const sd = document.getElementById('seed-' + tid);
                                        if (sd && (sd.innerText === '0' || sd.innerText === '-')) sd.innerText = data.seeders;
                                    }
                                    if (data.leechers && data.leechers !== '') {
                                        const lc = document.getElementById('leech-' + tid);
                                        if (lc && (lc.innerText === '0' || lc.innerText === '-')) lc.innerText = data.leechers;
                                    }
                                    const pw = document.getElementById('pw-' + tid);
                                    if (pw && data.tags && data.tags.join(' ').toUpperCase().includes('FREE') && !pw.querySelector('.tag-free')) {
                                        pw.insertAdjacentHTML('beforeend', '<div class="tag-free">FREE</div>');
                                    }
                                    const tw = document.getElementById('tags-' + tid);
                                    if (tw) {
                                        const tb = tw.querySelector('.tags-bottom');
                                        if (tb && data.clock_tag && !tw.innerText.includes('🕒')) {
                                            tb.insertAdjacentHTML('afterbegin', `<span class="badge" style="background:#64748b;">${data.clock_tag}</span>`);
                                        }
                                        if (tb && data.time_tag && !tw.innerText.includes('剩余')) {
                                            tb.insertAdjacentHTML('afterbegin', `<span class="badge-discount">${data.time_tag}</span>`);
                                        }
                                    }
                                }).catch(e => {});
                                img.removeAttribute('data-tid');
                                obs.unobserve(img);
                            }
                        }
                    });
                }, { rootMargin: "300px" });
                document.querySelectorAll('.lazy-load').forEach(img => window.lazyObserver.observe(img));
            }
        });

        let currentPage = {{ next_page }};
        let isLoading = false;
        function loadNext() {
            if(isLoading) return;
            const btn = document.getElementById('load-btn');
            isLoading = true;
            btn.innerText = `正在拉取第 ${currentPage} 页...`;
            const p = new URLSearchParams(window.location.search);
            fetch(`/api/load_more?tab=${p.get('tab')||'official'}&cat=${p.get('cat')||'all'}&q=${encodeURIComponent(p.get('q')||'')}&page=${currentPage}`)
                .then(r => r.json()).then(data => {
                    currentPage = data.next_page; isLoading = false;
                    if (data.error) { btn.innerText = data.error; return; }
                    if (data.raw_count === 0) { btn.innerText = "数据已全部加载完毕"; btn.onclick = null; return; }
                    const list = document.getElementById('torrent-list');
                    data.torrents.forEach(item => {
                        let tTop = '', tBot = '';
                        item.top_pri.forEach(t => tTop += `<span class="badge-tech">${t}</span>`);
                        item.top_sec.forEach(t => tTop += `<span class="badge-tech secondary-tag">${t}</span>`);
                        if (item.time_tag) tBot += `<span class="badge-discount">${item.time_tag}</span>`;
                        if (item.clock_tag) tBot += `<span class="badge" style="background:#64748b;">${item.clock_tag}</span>`;
                        item.bot_disc.forEach(t => tBot += `<span class="badge-discount">${t}</span>`);
                        item.bot_pri.forEach(t => tBot += `<span class="badge">${t}</span>`);
                        item.bot_sec.forEach(t => tBot += `<span class="badge-lang secondary-tag">${t}</span>`);
                        if (item.top_sec.length || item.bot_sec.length) tBot += `<span class="badge-toggle" onclick="toggleTags(this)">... ▾</span>`;
                        let grp = renderGroupBadge(item.group);
                        let free = item.tags.join(' ').toUpperCase().includes('FREE') ? `<div class="tag-free">FREE</div>` : '';
                        let img = item.img || "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='140'><rect width='100%' height='100%' fill='%23e6e6e6'/><text x='50%' y='50%' fill='%23a1a1aa' font-size='12' text-anchor='middle' dominant-baseline='middle'>加载海报</text></svg>";
                        const safeTitle = (item.title || '').replace(/"/g, '&quot;');
                        const safeSub = (item.subtitle || '').replace(/"/g, '&quot;');
                        list.insertAdjacentHTML('beforeend', `<div class="list-item" id="item-${item.id}"><div class="poster-wrapper" id="pw-${item.id}"><img class="poster ${!item.img?'lazy-load':''}" src="${img}" ${!item.img?`data-tid="${item.id}"`:''} referrerpolicy="no-referrer" onclick="window.open('${item.link}', '_blank')">${free}</div><div class="info"><a class="title" href="${item.link}" target="_blank">${item.title}</a><div class="subtitle" id="sub-${item.id}">${item.subtitle||''}</div><div class="stats-and-download"><div class="stats-row"><span class="stat-item" id="size-${item.id}">📄 ${item.size}</span><span class="stat-item"><span class="seed-icon">▲</span> <span id="seed-${item.id}">${item.seeders}</span></span><span class="stat-item"><span class="leech-icon">▼</span> <span id="leech-${item.id}">${item.leechers}</span></span><span id="group-${item.id}" style="display:inline-flex;">${grp}</span></div><button type="button" class="download-btn" data-tid="${item.id}" data-title="${safeTitle}" data-sub="${safeSub}" data-grp="${item.raw_group||''}" onclick="openQbtFromBtn(this)">推送</button></div><div class="tags-wrapper" id="tags-${item.id}"><div class="tags-top">${tTop}</div><div class="tags-bottom">${tBot}</div></div></div></div>`);
                    });
                    document.querySelectorAll('.lazy-load:not([data-observed])').forEach(img => { img.setAttribute('data-observed', '1'); if(window.lazyObserver) window.lazyObserver.observe(img); });
                    btn.innerText = `👇 点击加载第 ${currentPage} 页 👇`;
                }).catch(e => { isLoading = false; btn.innerText = "点击重试"; });
        }
    </script>
</body>
</html>
"""

def process_torrent_tags(item):
    tpri, tsec, bdisc, bpri, bsec = sort_tags(item['tags'])
    item['time_tag'], item['clock_tag'] = "", ""
    for arr in [tpri, tsec, bdisc, bpri, bsec]:
        for t in list(arr):
            if '剩余' in t: item['time_tag'] = t; arr.remove(t)
            elif '🕒' in t: item['clock_tag'] = t; arr.remove(t)
    item['top_pri'], item['top_sec'], item['bot_disc'], item['bot_pri'], item['bot_sec'] = tpri, tsec, bdisc, bpri, bsec

@app.route('/')
def index():
    tab, cat, query = request.args.get('tab', 'official'), request.args.get('cat', 'all'), request.args.get('q', '')
    torrents, user_info, error_msg = [], {}, None
    today = datetime.date.today().isoformat()
    sign_done = (AUTO_SIGN_DATE == today)
    
    try:
        if tab == 'rss':
            pass
        elif tab == 'account':
            user_info = parse_user_account()
        else:
            torrents, error_msg, _ = parse_torrents_page(set(), cat=cat, is_search=(tab=='search'), skip_sticky=(tab=='recent'), page=0, query=query)
            if torrents:
                for item in torrents: process_torrent_tags(item)
            else: torrents = []
    except Exception as e: error_msg = f"服务器内部错误: {str(e)}"
    return render_template_string(
        HTML_TEMPLATE, tab=tab, cat=cat, query=query, torrents=torrents, 
        user_info=user_info, error=error_msg, next_page=1,
        sign_done=sign_done, sign_msg=(f"✅ {AUTO_SIGN_MSG}" if sign_done else "⏳ 今日待自动签到"),
        next_sign=NEXT_SIGN_TIME, qbt_servers=QBT_SERVERS
    )

@app.route('/api/qbt/meta')
def api_qbt_meta():
    """实时拉取所选 qBittorrent 节点的版本号、分类列表、标签列表与双 RSS 源配置"""
    srv_id = request.args.get('server', '188')
    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})
    try:
        ver_r = sess.get(f"{base_url}/api/v2/app/version", timeout=4)
        cats_r = sess.get(f"{base_url}/api/v2/torrents/categories", timeout=4)
        tags_r = sess.get(f"{base_url}/api/v2/torrents/tags", timeout=4)

        cats_dict = cats_r.json() if cats_r.status_code == 200 else {}
        categories = [{"name": k, "savePath": v.get("savePath", "")} for k, v in cats_dict.items()]
        tags = tags_r.json() if tags_r.status_code == 200 else []
        rss_feeds = QBT_SERVERS.get(srv_id, {}).get('rss_feeds', {})
        return jsonify({
            "ok": True,
            "version": ver_r.text.strip(),
            "categories": categories,
            "tags": tags,
            "rss_feeds": rss_feeds
        })
    except Exception as e:
        return jsonify({"ok": False, "msg": f"读取节点元数据失败: {str(e)}"})

# ================= 📡 qBittorrent 原生 RSS 自动下载规则管理接口 =================
@app.route('/api/qbt/rss/rules')
def api_qbt_rss_rules():
    srv_id = request.args.get('server', '188')
    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})
    try:
        r = sess.get(f"{base_url}/api/v2/rss/rules", timeout=5)
        if r.status_code != 200:
            return jsonify({"ok": False, "msg": f"获取规则失败,状态码: {r.status_code}"})
        rules_dict = r.json()
        feeds_cfg = QBT_SERVERS.get(srv_id, {}).get('rss_feeds', {})
        url_to_label = {v: k for k, v in feeds_cfg.items() if v}

        rules_list = []
        for name, defn in rules_dict.items():
            defn['name'] = name
            aff = defn.get('affectedFeeds', [])
            labels = [url_to_label.get(u, u[:25] + '...') for u in aff]
            defn['feedLabel'] = ' + '.join(labels) if labels else '全部源'
            rules_list.append(defn)
        return jsonify({"ok": True, "rules": rules_list})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"读取 RSS 规则异常: {str(e)}"})

@app.route('/api/qbt/rss/add', methods=['POST'])
def api_qbt_rss_add():
    data = request.get_json(force=True)
    srv_id = data.get('server', '188')
    rule_name = data.get('name', '').strip()
    must_contain = data.get('mustContain', '').strip()
    must_not_contain = data.get('mustNotContain', '').strip()
    smart_filter = bool(data.get('smartFilter', False))
    category = data.get('category', '').strip()
    tags_str = data.get('tags', '').strip()
    affected_feeds = [u.strip() for u in data.get('affectedFeeds', []) if u and u.strip()]

    if not rule_name or not must_contain:
        return jsonify({"ok": False, "msg": "规则名称与匹配正则不能为空"})

    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})

    try:
        sess.post(f"{base_url}/api/v2/app/setPreferences", data={
            "json": json.dumps({"rss_processing_enabled": True, "rss_auto_downloading_enabled": True})
        }, timeout=5)

        # 自动检测:qB 里不存在该 RSS 源时才自动添加,已存在则跳过,绝不重复
        if affected_feeds:
            items_r = sess.get(f"{base_url}/api/v2/rss/items", timeout=5)
            existing_urls = set()
            def collect_urls(obj):
                if isinstance(obj, dict):
                    if "url" in obj and isinstance(obj["url"], str):
                        existing_urls.add(obj["url"].strip())
                    for v in obj.values():
                        collect_urls(v)
            if items_r.status_code == 200:
                collect_urls(items_r.json())

            feeds_cfg = QBT_SERVERS.get(srv_id, {}).get('rss_feeds', {})
            url_to_label = {v.strip(): k for k, v in feeds_cfg.items() if v}

            for feed_url in affected_feeds:
                if feed_url not in existing_urls:
                    label = url_to_label.get(feed_url, "")
                    # 财神用 CSPT,织梦改成 ZmPT,龙站改成 LongPT
                    feed_path = f"CSPT-{label}" if label else "CSPT"
                    sess.post(f"{base_url}/api/v2/rss/addFeed", data={
                        "url": feed_url,
                        "path": feed_path
                    }, timeout=5)

        tags_list = [t.strip() for t in tags_str.split(',') if t.strip()]

        rule_def = {
            "enabled": True,
            "mustContain": must_contain,
            "mustNotContain": must_not_contain,
            "useRegex": True,
            "episodeFilter": "",
            "smartFilter": smart_filter,
            "previouslyMatchedEpisodes": [],
            "affectedFeeds": affected_feeds,
            "ignoreDays": 0,
            "lastMatch": "",
            "addPaused": False,
            "assignedCategory": category,
            "savePath": "",
            "torrentParams": {
                "category": category,
                "tags": tags_list,
                "paused": False
            }
        }

        res = sess.post(f"{base_url}/api/v2/rss/setRule", data={
            "ruleName": rule_name,
            "ruleDef": json.dumps(rule_def, ensure_ascii=False)
        }, timeout=6)

        if res.status_code == 200:
            srv_name = QBT_SERVERS[srv_id]['name']
            return jsonify({"ok": True, "msg": f"RSS 追剧规则【{rule_name}】已成功下发至 {srv_name}!"})
        return jsonify({"ok": False, "msg": f"qB 拒绝保存规则: {res.text}"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"下发 RSS 规则异常: {str(e)}"})

@app.route('/api/qbt/rss/toggle', methods=['POST'])
def api_qbt_rss_toggle():
    data = request.get_json(force=True)
    srv_id = data.get('server', '188')
    rule_name = data.get('name', '')
    enabled = bool(data.get('enabled', True))

    sess, base_url, err = get_qbt_session(srv_id)
    if err: return jsonify({"ok": False, "msg": err})
    try:
        r = sess.get(f"{base_url}/api/v2/rss/rules", timeout=5)
        rules = r.json()
        if rule_name not in rules:
            return jsonify({"ok": False, "msg": "未找到该规则"})
        rules[rule_name]['enabled'] = enabled
        res = sess.post(f"{base_url}/api/v2/rss/setRule", data={
            "ruleName": rule_name,
            "ruleDef": json.dumps(rules[rule_name], ensure_ascii=False)
        }, timeout=5)
        return jsonify({"ok": res.status_code == 200, "msg": "状态已更新"})
    except Exception as e:
        return jsonify({"ok": False, "msg": str(e)})

@app.route('/api/qbt/rss/delete', methods=['POST'])
def api_qbt_rss_delete():
    data = request.get_json(force=True)
    srv_id = data.get('server', '188')
    rule_name = data.get('name', '')

    sess, base_url, err = get_qbt_session(srv_id)
    if err: return jsonify({"ok": False, "msg": err})
    try:
        res = sess.post(f"{base_url}/api/v2/rss/removeRule", data={"ruleName": rule_name}, timeout=5)
        return jsonify({"ok": res.status_code == 200, "msg": "已删除"})
    except Exception as e:
        return jsonify({"ok": False, "msg": str(e)})
# ==============================================================================

@app.route('/api/qbt/push', methods=['POST'])
def api_qbt_push():
    """从 CSPT 下载种子字节流并直接推送至所选的 qBittorrent 节点"""
    data = request.get_json(force=True)
    tid = data.get('tid')
    srv_id = data.get('server', '188')
    category = data.get('category', '').strip()
    tags = data.get('tags', '').strip()

    if not tid:
        return jsonify({"ok": False, "msg": "缺少种子 ID"})

    sess, base_url, err = get_qbt_session(srv_id)
    if err:
        return jsonify({"ok": False, "msg": err})

    try:
        dl_r = requests.get(f"{BASE_URL}/download.php?id={tid}", headers=HEADERS, proxies=PROXIES, timeout=15)
        if dl_r.status_code != 200 or (b"d8:announce" not in dl_r.content[:100] and b"info" not in dl_r.content[:200]):
            if "登录" in dl_r.text:
                return jsonify({"ok": False, "msg": "CSPT Cookie 已失效,无法拉取种子文件"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"从 CSPT 下载种子失败: {str(e)}"})

    try:
        form_data = {}
        if category:
            form_data['category'] = category
        if tags:
            form_data['tags'] = tags

        files = {
            'torrents': (f'CSPT_{tid}.torrent', dl_r.content, 'application/x-bittorrent')
        }
        push_r = sess.post(f"{base_url}/api/v2/torrents/add", data=form_data, files=files, timeout=10)
        res_txt = push_r.text.strip()
        if push_r.status_code == 200 and ("Ok." in res_txt or '"success_count":1' in res_txt.replace(" ", "") or "added_torrent_ids" in res_txt):
            srv_name = QBT_SERVERS[srv_id]['name']
            cat_info = f" [分类: {category}]" if category else ""
            return jsonify({"ok": True, "msg": f"已成功推送到 {srv_name}{cat_info}!"})
        return jsonify({"ok": False, "msg": f"qB 推送未成功: {res_txt}"})
    except Exception as e:
        return jsonify({"ok": False, "msg": f"推送到 qB 失败: {str(e)}"})

@app.route('/api/load_more')
def api_load_more():
    tab, cat, query, page = request.args.get('tab', 'official'), request.args.get('cat', 'all'), request.args.get('q', ''), int(request.args.get('page', 1))
    torrents, err, raw_count = parse_torrents_page(set(), cat=cat, is_search=(tab=='search'), skip_sticky=(tab=='recent'), page=page, query=query)
    if torrents:
        for item in torrents: process_torrent_tags(item)
    return jsonify({"torrents": torrents or [], "next_page": page + 1, "raw_count": raw_count, "error": err})

@app.route('/api/extra/<int:tid>')
def api_extra(tid):
    img_src, size, extra_tags, release_group, sub_text, seeders, leechers, pub_time = fetch_details_info(tid)
    dummy = {'tags': list(extra_tags)}
    process_torrent_tags(dummy)
    return jsonify({ 
        "img": img_src, "size": size, "subtitle": sub_text, "tags": extra_tags, 
        "seeders": seeders, "leechers": leechers,
        "top_pri": dummy['top_pri'], "top_sec": dummy['top_sec'], 
        "bot_disc": dummy['bot_disc'], "bot_pri": dummy['bot_pri'], 
        "bot_sec": dummy['bot_sec'], "time_tag": dummy['time_tag'],
        "clock_tag": dummy['clock_tag'], "group": release_group 
    })

@app.route('/api/signin')
def api_signin():
    ok, msg = do_attendance()
    return jsonify({
        "ok": ok, 
        "msg": msg, 
        "status": f"✅ {AUTO_SIGN_MSG}" if ok else "⚠️ 签到失败",
        "next_time": NEXT_SIGN_TIME
    })

@app.route('/download/<int:tid>')
def download_torrent(tid):
    try:
        r = requests.get(f"{BASE_URL}/download.php?id={tid}", headers=HEADERS, proxies=PROXIES, timeout=10)
        return Response(r.content, mimetype="application/x-bittorrent", headers={"Content-Disposition": f"attachment;filename=CSPT_{tid}.torrent"})
    except Exception as e: return f"请求出错: {str(e)}"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5055)

也可以看看