# -*- coding: utf-8 -*- """Cookie 读取与解析。 (自 music_api.py 拆出,行为与原实现一致。) """ import os # ============ Cookie 工具 ============ DEFAULT_COOKIE_FILE = "cookie.txt" def load_cookies(path: str = DEFAULT_COOKIE_FILE) -> dict[str, str]: """从 cookie.txt 直接读取并解析为 dict 支持标准 ``NMTID=xxx; _ntes_nnid=xxx; ...`` 格式。 文件不存在或解析失败返回空 dict(不抛异常,调用方决定如何处理)。 utf-8-sig 剥记事本 BOM(BOM 会让首键变成 \\ufeffMUSIC_U 静默 丢 Cookie);解析改逐行再按 ``;`` 切(原实现 ';|\\n' 二选一,混排时丢键值对)。 """ if not os.path.isfile(path): return {} try: with open(path, encoding="utf-8-sig") as f: content = f.read() except OSError: return {} return parse_cookie_string(content) def parse_cookie_string(cookie_string: str) -> dict[str, str]: """把 ``k1=v1; k2=v2`` 格式字符串解析为 dict 支持 ``;`` 或 ``\\n`` 作为分隔符。 """ cookies: dict[str, str] = {} if not cookie_string: return cookies cookie_string = cookie_string.strip() if not cookie_string: return cookies # 先逐行再按 ; 切——原实现 ";|\\n" 二选一,混排时行内 \\n # 会混进 value、后半段键值对丢失 pairs = [] for line in cookie_string.splitlines(): for part in line.split(";"): part = part.strip() if part: pairs.append(part) for pair in pairs: pair = pair.strip() if not pair or "=" not in pair: continue key, value = pair.split("=", 1) key = key.strip() value = value.strip() if key and value: cookies[key] = value return cookies