"""it-tools relay: translate upstream + license check + card activation. Endpoints GET /translate?... -> proxy Google Translate via host proxy (CN workaround) GET /check -> license gate for nginx auth_request headers: X-Machine-Id (10-16 digits), X-Tool (protected tool key) 200 = allowed (IT-Tools project authorization OR trial window open) 403 = blocked POST /activate -> card activation proxy (body: card_key, machine_id, contact_qq) uses server-side CARD_AUTH_KEY for /public/verify pre-check, then /public/authorizations/activate. The key never leaves this container. Authorization rules * Query CardAuth /public/authorizations/query?bot_qq= (60s cache). * Only cards of the PROJECT_NAME project count as authorized (other projects' cards must not unlock this site). * Network failure -> fail OPEN (auth server down must not lock paying users). Trial state persisted to /app/data/trials.json (mounted volume). """ import cgi import io import json import os import re import shutil import subprocess import tempfile import threading import time import zipfile from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib import parse, request UPSTREAM = "https://translate.googleapis.com/translate_a/single" PROXY = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or "" TIMEOUT = float(os.environ.get("RELAY_TIMEOUT", "25")) AUTH_BASE = os.environ.get("AUTH_BASE", "https://auth.88531.cn/api") CARD_AUTH_KEY = os.environ.get("CARD_AUTH_KEY", "") # Optional admin login: cards bound to a user require a logged-in session to activate AUTH_USER = os.environ.get("AUTH_USER", "") AUTH_PASS = os.environ.get("AUTH_PASS", "") PROJECT_NAME = os.environ.get("PROJECT_NAME", "IT-Tools") TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json") TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000 PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "ai-chat", "copywriting", "screenshot-qa", "video-subtitle"} MACHINE_RE = re.compile(r"^\d{10,16}$") # verify() messages that unconditionally block activation BLOCK_WORDS = ("不存在", "已过期", "过期", "作废", "禁用", "停用", "已禁") _lock = threading.Lock() def _opener(with_proxy: bool): handlers = [] if with_proxy and PROXY: handlers.append(request.ProxyHandler({"http": PROXY, "https": PROXY})) elif not with_proxy: handlers.append(request.ProxyHandler({})) # force direct return request.build_opener(*handlers) OPENER_PROXY = _opener(True) OPENER_DIRECT = _opener(False) # ---- authorization cache: machine -> (authorized, fetched_at) ---- _auth_cache: dict = {} AUTH_CACHE_TTL = 60 def _list_has_ittools_auth(data: dict) -> bool: """Only cards of PROJECT_NAME with active status count. Falls back to has_valid_auth when the payload has no usable list (keeps working if CardAuth response shape changes). """ lst = data.get("list") if not isinstance(lst, list) or not lst: # empty list -> no cards at all if lst == []: return False return bool(data.get("has_valid_auth")) matched = False for item in lst: if not isinstance(item, dict): continue name = item.get("project_name") if name is None: # shape unknown -> do not filter return bool(data.get("has_valid_auth")) matched = True if ( name == PROJECT_NAME and item.get("status") == "active" and not item.get("is_expired", False) ): return True if matched: return False return bool(data.get("has_valid_auth")) def query_authorized(machine: str) -> bool: now = time.time() hit = _auth_cache.get(machine) if hit and now - hit[1] < AUTH_CACHE_TTL: return hit[0] ok = False try: url = f"{AUTH_BASE}/public/authorizations/query?bot_qq={machine}" with OPENER_DIRECT.open(url, timeout=10) as resp: data = json.loads(resp.read().decode("utf-8")) if data.get("code") == 200: ok = _list_has_ittools_auth(data.get("data") or {}) except Exception as exc: # noqa: BLE001 print(f"[check] auth query failed ({exc}) -> fail open", flush=True) _auth_cache.pop(machine, None) return True # fail open _auth_cache[machine] = (ok, now) return ok # ---- trial persistence ---- def _load_trials() -> dict: try: with open(TRIAL_FILE, "r", encoding="utf-8") as fh: return json.load(fh) except Exception: # noqa: BLE001 return {} def _save_trials(trials: dict) -> None: os.makedirs(os.path.dirname(TRIAL_FILE), exist_ok=True) tmp = TRIAL_FILE + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: json.dump(trials, fh) os.replace(tmp, TRIAL_FILE) def trial_allowed(machine: str, tool: str) -> bool: key = f"{machine}|{tool}" now_ms = int(time.time() * 1000) with _lock: trials = _load_trials() start = trials.get(key) if start is None: trials[key] = now_ms _save_trials(trials) return True return (now_ms - start) < TRIAL_MS def deactivate_card(machine_id: str) -> tuple[int, dict]: """Revoke authorization for this machine. Local revocation list takes effect immediately (no CardAuth dependency); syncing the revoke to CardAuth is best-effort. """ # 1) local blacklist - instant, offline-proof rev = _load_revoked() already = machine_id in rev rev.add(machine_id) _save_revoked(rev) _auth_cache.pop(machine_id, None) # 2) best-effort sync to CardAuth (ignored failures) synced = 0 tok = _admin_token() if tok: auth_hdr = {"Authorization": f"Bearer {tok}"} try: res = _get_json(f"/authorizations?bot_qq={machine_id}&status=active&page=1&page_size=20", auth_hdr) for item in ((res or {}).get("data") or {}).get("list") or []: if item.get("project_name") != PROJECT_NAME: continue try: r = _put_json(f"/authorizations/{item['id']}/revoke", {"reason": "用户在客户端自助撤销"}, auth_hdr) if (r or {}).get("code") == 200: synced += 1 except Exception: # noqa: BLE001 pass except Exception: # noqa: BLE001 pass else: print("[deactivate] admin login unavailable -> local revoke only", flush=True) if already: return 200, {"code": 200, "message": "本机已处于撤销状态", "data": {"synced": synced}} return 200, {"code": 200, "message": "已撤销授权", "data": {"synced": synced}} # ================= local revocation list (instant, no CardAuth needed) ========== REVOKED_FILE = "/app/data/revoked.json" def _load_revoked() -> set: try: with open(REVOKED_FILE, "r", encoding="utf-8") as fh: data = json.load(fh) return set(data) if isinstance(data, list) else set() except Exception: # noqa: BLE001 return set() def _save_revoked(s: set) -> None: tmp = REVOKED_FILE + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: json.dump(sorted(s), fh) os.replace(tmp, REVOKED_FILE) # ================= document format conversion (calibre ebook-convert) ========== CONVERT_FMTS = {"pdf", "docx", "txt", "rtf", "odt", "epub", "mobi", "azw3", "html"} CONVERT_TIMEOUT = 180 def _text_to_odt(text: str, out_path: str) -> None: """Build a minimal, valid ODT (OpenDocument Text) package from plain text.""" import html as _h paras = "\n".join( f'{_h.escape(line) or " "}' for line in text.splitlines() ) content = ( '' '' "" f"{paras}" "" ) manifest = ( '' '' '' '' "" ) styles = ( '' '' ) with zipfile.ZipFile(out_path, "w") as zf: zf.writestr("mimetype", "application/vnd.oasis.opendocument.text", zipfile.ZIP_STORED) zf.writestr("META-INF/manifest.xml", manifest) zf.writestr("content.xml", content) zf.writestr("styles.xml", styles) def _convert_files(tmpdir: str, src_names: list, fmt: str) -> list: """Run ebook-convert for each source file; returns converted file paths.""" done = [] for name in src_names: src = os.path.join(tmpdir, name) stem = os.path.splitext(name)[0] out = os.path.join(tmpdir, f"{stem}.{fmt}") env = {**os.environ, "QTWEBENGINE_CHROMIUM_FLAGS": "--no-sandbox"} def _run_convert(src_path: str, dst_path: str): try: proc = subprocess.run( ["ebook-convert", src_path, dst_path], capture_output=True, timeout=CONVERT_TIMEOUT, env=env, ) except subprocess.TimeoutExpired: raise RuntimeError(f"{name} 转换超时(>{CONVERT_TIMEOUT}s)") if proc.returncode != 0 or not os.path.exists(dst_path): tail = (proc.stderr or proc.stdout or b"").decode("utf-8", "ignore")[-300:] raise RuntimeError(f"{name} 转换失败:{tail or '未知错误'}") if fmt == "odt": # calibre has no odt exporter; convert to text first, then wrap a minimal ODT package tmp_txt = out + ".tmp.txt" _run_convert(src, tmp_txt) text = open(tmp_txt, "r", encoding="utf-8", errors="ignore").read() os.remove(tmp_txt) _text_to_odt(text, out) else: # calibre exports "htmlz" (zipped html) instead of bare html; unwrap it target = out + ("z" if fmt == "html" else "") _run_convert(src, target) if fmt == "html": with zipfile.ZipFile(target) as zf: names = zf.namelist() html_name = next((n for n in names if n.lower().endswith("index.html")), None) or next((n for n in names if n.lower().endswith(".html")), None) if not html_name: raise RuntimeError(f"{name} 转换失败:htmlz 内未找到 HTML 文件") with open(out, "wb") as fh: fh.write(zf.read(html_name)) os.remove(target) done.append(out) return done # ================= IT site bookmarks (shared, file-backed) ================= SITES_DIR_DEFAULT = "/app/data" SITES_CFG = os.path.join(SITES_DIR_DEFAULT, "sites-config.json") SEED_SITES = [ {"name": "GitHub", "url": "https://github.com", "category": "社区", "desc": "全球最大代码托管与开源社区"}, {"name": "Stack Overflow", "url": "https://stackoverflow.com", "category": "社区", "desc": "程序员问答社区"}, {"name": "V2EX", "url": "https://www.v2ex.com", "category": "社区", "desc": "开发者创意工作者社区"}, {"name": "Hacker News", "url": "https://news.ycombinator.com", "category": "社区", "desc": "硅谷科技资讯与讨论"}, {"name": "掘金", "url": "https://juejin.cn", "category": "社区", "desc": "中文开发者技术社区"}, {"name": "思否 SegmentFault", "url": "https://segmentfault.com", "category": "社区", "desc": "中文技术问答与专栏"}, {"name": "CSDN", "url": "https://www.csdn.net", "category": "社区", "desc": "中文IT技术社区"}, {"name": "博客园", "url": "https://www.cnblogs.com", "category": "社区", "desc": "老牌中文开发博客社区"}, {"name": "MDN Web Docs", "url": "https://developer.mozilla.org/zh-CN/", "category": "文档", "desc": "Web 标准权威文档(中文)"}, {"name": "Vue 3 文档", "url": "https://cn.vuejs.org", "category": "文档", "desc": "渐进式框架官方中文文档"}, {"name": "React 中文文档", "url": "https://zh-hans.react.dev", "category": "文档", "desc": "React 官方中文站"}, {"name": "TypeScript 手册", "url": "https://www.typescriptlang.org/zh/docs/", "category": "文档", "desc": "TS 官方中文 handbook"}, {"name": "Node.js 文档", "url": "https://nodejs.org/docs/latest/api/", "category": "文档", "desc": "Node.js API 官方文档"}, {"name": "Python 文档", "url": "https://docs.python.org/zh-cn/3/", "category": "文档", "desc": "Python 3 官方中文文档"}, {"name": "Rust 中文文档", "url": "https://doc.rust-lang.org/book/", "category": "文档", "desc": "Rust 程序设计语言"}, {"name": "Docker 文档", "url": "https://docs.docker.com/", "category": "文档", "desc": "Docker 官方文档"}, {"name": "Linux 命令大全", "url": "https://www.runoob.com/linux/linux-command-manual.html", "category": "文档", "desc": "菜鸟教程 Linux 命令手册"}, {"name": "Can I Use", "url": "https://caniuse.com", "category": "工具", "desc": "浏览器特性兼容性查询"}, {"name": "Regex101", "url": "https://regex101.com", "category": "工具", "desc": "正则表达式在线调试与解释"}, {"name": "JSON.cn", "url": "https://json.cn", "category": "工具", "desc": "JSON 在线解析与格式化"}, {"name": "CodePen", "url": "https://codepen.io", "category": "工具", "desc": "前端在线编辑与演示"}, {"name": "StackBlitz", "url": "https://stackblitz.com", "category": "工具", "desc": "浏览器里的完整 VS Code 项目环境"}, {"name": "npm", "url": "https://www.npmjs.com", "category": "工具", "desc": "Node 包注册与搜索"}, {"name": "PyPI", "url": "https://pypi.org", "category": "工具", "desc": "Python 包索引"}, {"name": "Docker Hub", "url": "https://hub.docker.com", "category": "工具", "desc": "容器镜像仓库"}, {"name": "crates.io", "url": "https://crates.io", "category": "工具", "desc": "Rust 包注册中心"}, {"name": "VS Code Web", "url": "https://vscode.dev", "category": "工具", "desc": "浏览器版 VS Code"}, {"name": "Git 官方", "url": "https://git-scm.com/doc", "category": "工具", "desc": "Git 版本控制文档与下载"}, {"name": "Postman 替代 Hoppscotch", "url": "https://hoppscotch.io", "category": "工具", "desc": "开源在线 API 调试工具"}, {"name": "ChatGPT", "url": "https://chat.openai.com", "category": "AI", "desc": "OpenAI 对话助手"}, {"name": "DeepSeek", "url": "https://chat.deepseek.com", "category": "AI", "desc": "深度求索对话助手"}, {"name": "Kimi", "url": "https://kimi.moonshot.cn", "category": "AI", "desc": "月之暗面长文本助手"}, {"name": "通义千问", "url": "https://tongyi.aliyun.com", "category": "AI", "desc": "阿里云大模型助手"}, {"name": "GitHub Copilot Chat", "url": "https://github.com/features/copilot", "category": "AI", "desc": "AI 结对编程"}, {"name": "阿里云", "url": "https://www.aliyun.com", "category": "云服务", "desc": "阿里云计算与开发者服务"}, {"name": "腾讯云", "url": "https://cloud.tencent.com", "category": "云服务", "desc": "腾讯云计算开发者工具"}, {"name": "Cloudflare", "url": "https://dash.cloudflare.com", "category": "云服务", "desc": "CDN/DNS/Workers 控制台"}, {"name": "Vercel", "url": "https://vercel.com", "category": "云服务", "desc": "前端部署与 Serverless"}, {"name": "Figma", "url": "https://www.figma.com", "category": "设计", "desc": "界面设计与协作"}, {"name": "Iconfont", "url": "https://www.iconfont.cn", "category": "设计", "desc": "阿里矢量图标库"}, {"name": "Ant Design", "url": "https://ant.design", "category": "设计", "desc": "企业级 UI 设计体系"}, {"name": "Element Plus", "url": "https://element-plus.org", "category": "设计", "desc": "Vue 3 组件库"}, {"name": "Tailwind CSS", "url": "https://tailwindcss.com", "category": "设计", "desc": "原子化 CSS 框架"}, {"name": "DeepL 翻译", "url": "https://www.deepl.com/translator", "category": "其他", "desc": "高质量机器翻译"}, {"name": "Bing", "url": "https://www.bing.com", "category": "其他", "desc": "微软搜索引擎"}, {"name": "百度", "url": "https://www.baidu.com", "category": "其他", "desc": "中文搜索引擎"}, ] def _sites_cfg_dir() -> str: try: with open(SITES_CFG, "r", encoding="utf-8") as fh: d = str(json.load(fh).get("dir") or "").strip() if d.startswith("/"): return d except Exception: # noqa: BLE001 pass return SITES_DIR_DEFAULT def _sites_file() -> str: return os.path.join(_sites_cfg_dir(), "sites.json") def _load_sites() -> list: try: with open(_sites_file(), "r", encoding="utf-8") as fh: data = json.load(fh) if isinstance(data, list): return data except Exception: # noqa: BLE001 pass return [dict(s, id=f"seed-{i:02d}") for i, s in enumerate(SEED_SITES)] def _save_sites(sites: list) -> None: path = _sites_file() os.makedirs(os.path.dirname(path), exist_ok=True) tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: json.dump(sites, fh, ensure_ascii=False, indent=2) os.replace(tmp, path) def sites_api(method: str, path: str, payload: dict) -> tuple[int, dict]: """Shared bookmarks CRUD. path is after /sites.""" if method == "GET" and path == "": sites = _load_sites() return 200, {"code": 200, "message": "ok", "data": {"dir": _sites_file(), "sites": sites}} if method == "POST" and path == "/config": d = str(payload.get("dir") or "").strip() if not d.startswith("/") or any(d.startswith(bad) for bad in ("/etc", "/usr", "/bin", "/sbin", "/boot", "/sys", "/proc", "/dev")): return 400, {"code": 400, "message": "目录必须是绝对路径,且不能指向系统目录", "data": None} try: os.makedirs(d, exist_ok=True) old = _load_sites() cfg_tmp = SITES_CFG + ".tmp" with open(cfg_tmp, "w", encoding="utf-8") as fh: json.dump({"dir": d}, fh) os.replace(cfg_tmp, SITES_CFG) _save_sites(old) # migrate current data into new dir except Exception as exc: # noqa: BLE001 return 400, {"code": 400, "message": f"设置失败: {exc}", "data": None} return 200, {"code": 200, "message": "目录已更新,数据已迁移", "data": {"dir": _sites_file()}} if method == "POST" and path == "": name = str(payload.get("name") or "").strip() url = str(payload.get("url") or "").strip() if not name or not url: return 400, {"code": 400, "message": "名称和网址不能为空", "data": None} if not url.startswith(("http://", "https://")): url = "https://" + url sites = _load_sites() item = { "id": f"u{int(time.time() * 1000)}", "name": name, "url": url, "category": str(payload.get("category") or "其他").strip() or "其他", "desc": str(payload.get("desc") or "").strip(), } sites.append(item) _save_sites(sites) return 200, {"code": 200, "message": "已添加", "data": item} sid = "" if method in ("PUT", "DELETE") and path.startswith("/"): sid = path[1:] if method == "PUT" and sid: sites = _load_sites() for it in sites: if it.get("id") == sid: for k in ("name", "url", "category", "desc"): if k in payload: it[k] = str(payload[k]).strip() if it["url"] and not it["url"].startswith(("http://", "https://")): it["url"] = "https://" + it["url"] _save_sites(sites) return 200, {"code": 200, "message": "已更新", "data": it} return 404, {"code": 404, "message": "条目不存在", "data": None} if method == "DELETE" and sid: sites = _load_sites() keep = [it for it in sites if it.get("id") != sid] if len(keep) == len(sites): return 404, {"code": 404, "message": "条目不存在", "data": None} _save_sites(keep) return 200, {"code": 200, "message": "已删除", "data": None} return 404, {"code": 404, "message": "not found", "data": None} def _int_str(v, lo, hi, default=0): try: return max(lo, min(hi, int(float(v)))) except Exception: return default def check(machine: str, tool: str) -> int: if not machine or not MACHINE_RE.match(machine): return 403 if tool not in PROTECTED_TOOLS: return 403 if machine in _load_revoked(): # user revoked on this client -> authorization ignored, trial applies return 200 if trial_allowed(machine, tool) else 403 if query_authorized(machine): return 200 # account-level license: this device belongs to a logged-in user whose card is active if _account_license_ok(machine): return 200 return 200 if trial_allowed(machine, tool) else 403 def _account_license_ok(machine: str) -> bool: """True when this device logged into an account holding an active card.""" try: conn = _db() rows = conn.execute("SELECT card_key, origin_machine, bound_machines FROM users").fetchall() conn.close() except Exception: return False for card_key, origin, bm_json in rows: if not card_key or not origin: continue try: machines = json.loads(bm_json or "[]") except Exception: machines = [] if machine in machines: if origin == machine or query_authorized(origin): return True return False # ---- card activation (server-side key) ---- _auth_state: dict = {"token": None} def _admin_token(force: bool = False) -> str | None: """Login to CardAuth as admin and cache the access token.""" if not (AUTH_USER and AUTH_PASS): return None if _auth_state["token"] and not force: return _auth_state["token"] try: res = _post_json("/auth/admin-login", {"username": AUTH_USER, "password": AUTH_PASS}, {}, timeout=15) tok = (((res or {}).get("data") or {}).get("token") or {}).get("access_token") if tok: _auth_state["token"] = tok return tok print(f"[login] no token in response: {res}", flush=True) except Exception as exc: # noqa: BLE001 print(f"[login] failed ({exc})", flush=True) return None def _get_json(path: str, headers: dict, timeout: int = 15) -> dict: req = request.Request(f"{AUTH_BASE}{path}", headers=headers, method="GET") with OPENER_DIRECT.open(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8")) def _put_json(path: str, payload: dict, headers: dict, timeout: int = 15) -> dict: data = json.dumps(payload).encode("utf-8") hdrs = {"Content-Type": "application/json", **headers} req = request.Request(f"{AUTH_BASE}{path}", data=data, headers=hdrs, method="PUT") with OPENER_DIRECT.open(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8")) def _post_json(path: str, payload: dict, headers: dict, timeout: int = 15) -> dict: data = json.dumps(payload).encode("utf-8") hdrs = {"Content-Type": "application/json", **headers} req = request.Request(f"{AUTH_BASE}{path}", data=data, headers=hdrs, method="POST") with OPENER_DIRECT.open(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8")) def activate_card(card_key: str, machine_id: str, contact_qq: str, replace: bool = False) -> tuple[int, dict]: """Pre-check with /public/verify (CARD_AUTH_KEY), then activate. Returns (http_status, body_dict). """ tok = _admin_token() auth_hdr = {"Authorization": f"Bearer {tok}"} if tok else {} # replace: revoke this machine's existing authorizations first (user is # swapping to a new card; confirmed on the client side) if replace: try: deactivate_card(machine_id) except Exception as exc: # noqa: BLE001 print(f"[activate] replace revoke failed ({exc}) -> continue", flush=True) # NOTE: do NOT call /public/verify with an unused card here - in this # CardAuth version the first verify call binds & consumes the card. # activate (web channel, with admin session if configured) payload = { "card_key": card_key, "bot_qq": machine_id, "contact_qq": contact_qq or machine_id, "device_info": "IT-Tools Web", } # Retry ONLY on explicit 401 (stale token). Any other failure is returned # as-is: re-sending an activate that already consumed the card would burn it. try: ares = _post_json("/public/authorizations/activate", payload, auth_hdr) except Exception as exc: # noqa: BLE001 return 502, {"code": 502, "message": f"授权服务器连接失败: {exc}", "data": None} if (ares or {}).get("code") == 401 and (AUTH_USER and AUTH_PASS): tok = _admin_token(force=True) auth_hdr = {"Authorization": f"Bearer {tok}"} if tok else {} try: ares = _post_json("/public/authorizations/activate", payload, auth_hdr) except Exception as exc: # noqa: BLE001 return 502, {"code": 502, "message": f"授权服务器连接失败: {exc}", "data": None} code = 200 if (ares or {}).get("code") == 200 else 400 if code == 200: _auth_cache.pop(machine_id, None) # invalidate cache -> fresh query rev = _load_revoked() if machine_id in rev: rev.discard(machine_id) _save_revoked(rev) # new activation lifts the local revocation return code, ares # ================= 用户系统(注册/登录/数据云同步/文件存储) ================= import hashlib import hmac import secrets import sqlite3 import uuid MAX_UPLOAD = int(os.environ.get("MAX_UPLOAD_MB", "50")) * 1024 * 1024 # storage model: admin panel edits the HOST path; the container sees it under HOST_PREFIX (-v /:/hostfs) HOST_PREFIX = os.environ.get("HOST_PREFIX", "/hostfs") DEFAULT_HOST_ROOT = os.environ.get("DEFAULT_HOST_ROOT", "/vol1/1000/HD1/docker/it-tools-relay/data") _BOOT_DATA_DIR = "/app/data" def _host_to_container(host_path: str) -> str: if os.path.isdir(HOST_PREFIX): return (HOST_PREFIX + host_path).rstrip("/") return host_path # fallback: legacy deployment without host root mount def _load_storage_root() -> str: cfg = os.path.join(_host_to_container(DEFAULT_HOST_ROOT), "config.json") try: with open(cfg) as f: root = json.load(f).get("storage_root") if root: container = _host_to_container(root) if os.path.isdir(container): return container except Exception: pass return _host_to_container(DEFAULT_HOST_ROOT) DATA_DIR = _load_storage_root() USER_DB = os.environ.get("USER_DB", os.path.join(DATA_DIR, "users.db")) SECRET_FILE = os.environ.get("SECRET_FILE", os.path.join(DATA_DIR, ".auth_secret")) USERS_ROOT = os.environ.get("USERS_ROOT", os.path.join(DATA_DIR, "users")) def _auth_secret(): if not os.path.exists(SECRET_FILE): os.makedirs(os.path.dirname(SECRET_FILE), exist_ok=True) with open(SECRET_FILE, "w") as f: f.write(secrets.token_hex(32)) with open(SECRET_FILE) as f: return f.read().strip() def _db(): conn = sqlite3.connect(USER_DB) conn.execute("CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, salt TEXT, pw_hash TEXT, created REAL)") conn.execute("CREATE TABLE IF NOT EXISTS files (id TEXT PRIMARY KEY, username TEXT, name TEXT, size INTEGER, mime TEXT, created REAL)") for stmt in ( "ALTER TABLE users ADD COLUMN card_key TEXT DEFAULT ''", "ALTER TABLE users ADD COLUMN origin_machine TEXT DEFAULT ''", "ALTER TABLE users ADD COLUMN bound_machines TEXT DEFAULT '[]'", "ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'user'", "ALTER TABLE users ADD COLUMN disabled INTEGER DEFAULT 0", ): try: conn.execute(stmt) except sqlite3.OperationalError: pass conn.commit() return conn DEFAULT_ADMIN = os.environ.get("DEFAULT_ADMIN_USER", "jinghui") DEFAULT_ADMIN_PW = os.environ.get("DEFAULT_ADMIN_PW", "a3396336") def _ensure_admin(): """create the default admin account on first boot""" try: conn = _db() row = conn.execute("SELECT username FROM users WHERE username=?", (DEFAULT_ADMIN,)).fetchone() if not row: salt = secrets.token_hex(16) conn.execute( "INSERT INTO users (username, salt, pw_hash, created, role) VALUES (?,?,?,?,'admin')", (DEFAULT_ADMIN, salt, _hash_pw(DEFAULT_ADMIN_PW, salt), time.time()), ) conn.commit() else: conn.execute("UPDATE users SET role='admin' WHERE username=?", (DEFAULT_ADMIN,)) conn.commit() conn.close() except Exception: pass def _bind_machine(username: str, machine: str): """remember devices that logged into this account (max 10)""" if not machine or not MACHINE_RE.match(machine): return conn = _db() row = conn.execute("SELECT bound_machines FROM users WHERE username=?", (username,)).fetchone() try: machines = json.loads(row[0] or "[]") if row else [] except Exception: machines = [] if machine in machines: machines.remove(machine) machines.insert(0, machine) conn.execute("UPDATE users SET bound_machines=? WHERE username=?", (json.dumps(machines[:10]), username)) conn.commit() conn.close() def _user_attr(username: str): """returns (role, disabled)""" try: conn = _db() row = conn.execute("SELECT role, disabled FROM users WHERE username=?", (username,)).fetchone() conn.close() if row: return (row[0] or "user"), bool(row[1]) except Exception: pass return "user", False def _user_disabled(username: str) -> bool: return _user_attr(username)[1] def _save_user_license(username: str, card_key: str, machine: str): """store the card bound to this account after a successful activation""" conn = _db() conn.execute("UPDATE users SET card_key=?, origin_machine=? WHERE username=?", (card_key, machine, username)) conn.commit() conn.close() _bind_machine(username, machine) def _hash_pw(pw, salt): return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 120000).hex() def _make_token(username): exp = str(int(time.time()) + 7 * 86400) payload = username + "." + exp sig = hmac.new(_auth_secret().encode(), payload.encode(), hashlib.sha256).hexdigest()[:32] return payload + "." + sig def _parse_token(tok): try: username, exp, sig = tok.rsplit(".", 2) payload = username + "." + exp expect = hmac.new(_auth_secret().encode(), payload.encode(), hashlib.sha256).hexdigest()[:32] if hmac.compare_digest(sig, expect) and int(exp) > time.time(): return username except Exception: pass return None def _user_dir(username): d = os.path.join(USERS_ROOT, username) os.makedirs(os.path.join(d, "files"), exist_ok=True) return d def _auth_user(handler): tok = handler.headers.get("Authorization", "") if tok.lower().startswith("bearer "): tok = tok[7:] return _parse_token(tok) if tok else None TURNSTILE_SECRET = os.environ.get("TURNSTILE_SECRET", "") ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "") USAGE_DB = os.environ.get("USAGE_DB", os.path.join(DATA_DIR, "usage.db")) def _usage_db(): conn = sqlite3.connect(USAGE_DB) conn.execute("CREATE TABLE IF NOT EXISTS usage (id INTEGER PRIMARY KEY AUTOINCREMENT, machine TEXT, username TEXT, tool TEXT, at REAL)") conn.execute("CREATE INDEX IF NOT EXISTS idx_usage_at ON usage(at)") conn.execute("CREATE INDEX IF NOT EXISTS idx_usage_tool ON usage(tool)") conn.commit() return conn def log_usage(machine: str, tool: str): """record a tool usage event (best-effort, never blocks the request)""" if not tool: return try: username = "" try: conn = _db() rows = conn.execute("SELECT username, bound_machines FROM users").fetchall() conn.close() for u, bm in rows: if machine in json.loads(bm or "[]"): username = u break except Exception: pass conn = _usage_db() conn.execute("INSERT INTO usage (machine, username, tool, at) VALUES (?,?,?,?)", (machine or "", username, tool, time.time())) conn.commit() conn.close() except Exception: pass def _dir_size(path: str) -> int: total = 0 for root, _dirs, files in os.walk(path): for f in files: try: total += os.path.getsize(os.path.join(root, f)) except OSError: pass return total def verify_turnstile(token: str) -> bool: """Cloudflare Turnstile human check. Skipped when secret is not configured.""" if not TURNSTILE_SECRET: return True if not token or len(token) > 4096: return False data = parse.urlencode({"secret": TURNSTILE_SECRET, "response": token}).encode() req = request.Request("https://challenges.cloudflare.com/turnstile/v0/siteverify", data=data) try: with _opener(True) as resp: body = json.loads(resp.read().decode("utf-8")) return bool(body.get("success")) except Exception: return True # fail-open on network issues (do not lock out users) USER_NAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5-]{3,32}$") def _admin_auth(handler) -> bool: # channel 1: configured admin token (bootstrap / emergency) tok = handler.headers.get("X-Admin-Token", "") if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN: return True # channel 2: logged-in admin account auth = handler.headers.get("Authorization", "") if auth.lower().startswith("bearer "): acc = _parse_token(auth[7:]) if acc: role, disabled = _user_attr(acc) if role == "admin" and not disabled: return True return False def admin_api(method: str, sub: str, payload: dict, handler): """returns (status, body)""" if not _admin_auth(handler): return 403, {"code": 403, "message": "管理员令牌无效"} if method == "GET" and sub == "/overview": conn = _db() users = conn.execute("SELECT username, created, card_key, bound_machines, role, disabled FROM users").fetchall() conn.close() out_users = [] total_files = 0 total_size = 0 for username, created, card_key, bm, role, disabled in users: udir = os.path.join(USERS_ROOT, username) fdir = os.path.join(udir, "files") fcount = 0 fsize = 0 for root, _d, files in os.walk(fdir): for f in files: fcount += 1 try: fsize += os.path.getsize(os.path.join(root, f)) except OSError: pass dsize = 0 dp = os.path.join(udir, "data.json") if os.path.exists(dp): try: dsize = os.path.getsize(dp) except OSError: pass total_files += fcount total_size += fsize + dsize try: machines = json.loads(bm or "[]") except Exception: machines = [] out_users.append({ "username": username, "created": int(created or 0), "files": fcount, "file_size": fsize, "data_size": dsize, "total_size": fsize + dsize, "devices": len(machines), "licensed": bool(card_key), "role": role or "user", "disabled": bool(disabled), }) out_users.sort(key=lambda x: -x["total_size"]) return 200, {"code": 200, "message": "ok", "data": { "users": out_users, "totals": {"users": len(out_users), "files": total_files, "size": total_size}, }} if method == "GET" and sub.startswith("/files"): qs = parse.parse_qs(parse.urlparse(handler.path).query) username = (qs.get("username") or [""])[0] if not username or "/" in username or ".." in username: return 400, {"code": 400, "message": "参数错误"} fdir = os.path.join(_user_dir(username), "files") files = [] total = 0 for root, _d, fs in os.walk(fdir): kind = os.path.basename(root) if root != fdir else "" for f in fs: fp = os.path.join(root, f) try: st = os.stat(fp) except OSError: continue total += st.st_size files.append({"id": f, "name": f, "kind": kind, "size": st.st_size, "mtime": int(st.st_mtime)}) files.sort(key=lambda x: -x["mtime"]) return 200, {"code": 200, "message": "ok", "data": {"files": files, "total_size": total, "count": len(files)}} if method == "POST" and sub == "/cleanup": before = int(payload.get("before") or 0) username = str(payload.get("username") or "") if before <= 0: return 400, {"code": 400, "message": "缺少时间参数"} removed = 0 freed = 0 roots = [] if username: roots.append((username, os.path.join(_user_dir(username), "files"))) else: if os.path.isdir(USERS_ROOT): for u in os.listdir(USERS_ROOT): roots.append((u, os.path.join(USERS_ROOT, u, "files"))) for _u, fdir in roots: if not os.path.isdir(fdir): continue for root, _d, fs in os.walk(fdir, topdown=False): for f in fs: fp = os.path.join(root, f) try: st = os.stat(fp) except OSError: continue if st.st_mtime < before: try: freed += st.st_size removed += 1 os.remove(fp) except OSError: pass try: if not os.listdir(root): os.rmdir(root) except OSError: pass return 200, {"code": 200, "message": "ok", "data": {"removed": removed, "freed": freed}} if method == "POST" and sub == "/delete-file": file_id = str(payload.get("id") or "") username = str(payload.get("username") or "") if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id) or not username: return 400, {"code": 400, "message": "参数错误"} base = os.path.join(_user_dir(username), "files") target = os.path.join(base, file_id) if not os.path.exists(target): # search kind subdirs target = None for d in os.listdir(base) if os.path.isdir(base) else []: p2 = os.path.join(base, d, file_id) if os.path.exists(p2): target = p2 break if not target or not os.path.exists(target): return 404, {"code": 404, "message": "文件不存在"} size = os.path.getsize(target) os.remove(target) conn = _db() conn.execute("DELETE FROM files WHERE id=?", (file_id,)) conn.commit() conn.close() return 200, {"code": 200, "message": "ok", "data": {"freed": size}} if method == "POST" and sub == "/user-create": username = str(payload.get("username") or "").strip() password = str(payload.get("password") or "") role = "admin" if payload.get("role") == "admin" else "user" if not USER_NAME_RE.match(username): return 400, {"code": 400, "message": "用户名需 3-32 位字母/数字/下划线/中文"} if len(password) < 6: return 400, {"code": 400, "message": "密码至少 6 位"} salt = secrets.token_hex(16) try: conn = _db() conn.execute("INSERT INTO users (username, salt, pw_hash, created, role) VALUES (?,?,?,?,?)", (username, salt, _hash_pw(password, salt), time.time(), role)) conn.commit() conn.close() except sqlite3.IntegrityError: return 409, {"code": 409, "message": "用户名已存在"} _user_dir(username) return 200, {"code": 200, "message": "ok"} if method == "POST" and sub == "/user-update": username = str(payload.get("username") or "").strip() if not username: return 400, {"code": 400, "message": "缺少用户名"} conn = _db() row = conn.execute("SELECT username FROM users WHERE username=?", (username,)).fetchone() if not row: conn.close() return 404, {"code": 404, "message": "用户不存在"} sets = [] args = [] new_pw = str(payload.get("password") or "") if new_pw: if len(new_pw) < 6: conn.close() return 400, {"code": 400, "message": "密码至少 6 位"} salt = secrets.token_hex(16) sets += ["salt=?", "pw_hash=?"] args += [salt, _hash_pw(new_pw, salt)] if "role" in payload: role = "admin" if payload.get("role") == "admin" else "user" # do not demote the default admin if username == DEFAULT_ADMIN and role != "admin": conn.close() return 400, {"code": 400, "message": "默认管理员不可降级"} sets += ["role=?"] args.append(role) if "disabled" in payload: disabled = 1 if payload.get("disabled") else 0 if username == DEFAULT_ADMIN and disabled: conn.close() return 400, {"code": 400, "message": "默认管理员不可禁用"} sets += ["disabled=?"] args.append(disabled) if not sets: conn.close() return 400, {"code": 400, "message": "没有要修改的内容"} args.append(username) conn.execute(f"UPDATE users SET {', '.join(sets)} WHERE username=?", args) conn.commit() conn.close() return 200, {"code": 200, "message": "ok"} if method == "POST" and sub == "/user-delete": username = str(payload.get("username") or "").strip() if not username: return 400, {"code": 400, "message": "缺少用户名"} if username == DEFAULT_ADMIN: return 400, {"code": 400, "message": "默认管理员不可删除"} conn = _db() row = conn.execute("SELECT username FROM users WHERE username=?", (username,)).fetchone() if not row: conn.close() return 404, {"code": 404, "message": "用户不存在"} conn.execute("DELETE FROM users WHERE username=?", (username,)) conn.execute("DELETE FROM files WHERE username=?", (username,)) conn.commit() conn.close() udir = os.path.join(USERS_ROOT, username) if os.path.isdir(udir): shutil.rmtree(udir, ignore_errors=True) return 200, {"code": 200, "message": "ok"} if method == "GET" and sub == "/storage": total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0 for extra in ("users.db", "usage.db", "trials.json"): fp = os.path.join(DATA_DIR, extra) if os.path.exists(fp): try: total += os.path.getsize(fp) except OSError: pass # current host path (strip prefix) host_root = DATA_DIR if os.path.isdir(HOST_PREFIX) and DATA_DIR.startswith(HOST_PREFIX): host_root = DATA_DIR[len(HOST_PREFIX):] or "/" return 200, {"code": 200, "message": "ok", "data": { "root": host_root, "container_root": DATA_DIR, "users_dir": USERS_ROOT, "size": total, "host_mounted": os.path.isdir(HOST_PREFIX), }} if method == "POST" and sub == "/storage": new_host_root = str(payload.get("root") or "").strip().rstrip("/") if not new_host_root or not new_host_root.startswith("/"): return 400, {"code": 400, "message": "请输入宿主机绝对路径,如 /vol1/xxx 或 /vol2/xxx"} # block dangerous roots banned = ("/bin", "/sbin", "/usr", "/etc", "/proc", "/sys", "/dev", "/boot", "/lib", "/root", "/home") for b in banned: if new_host_root == b or new_host_root.startswith(b + "/"): return 400, {"code": 400, "message": "不允许使用系统目录"} if not os.path.isdir(HOST_PREFIX): return 400, {"code": 400, "message": "容器未挂载宿主机根目录(缺少 -v /:/hostfs 挂载)"} new_root = _host_to_container(new_host_root) if new_root == DATA_DIR: return 400, {"code": 400, "message": "与当前路径相同,无需修改"} try: os.makedirs(new_root, exist_ok=True) probe = os.path.join(new_root, ".write-test") with open(probe, "w") as f: f.write("ok") os.remove(probe) except Exception as e: return 400, {"code": 400, "message": f"目标路径不可写: {e}"} # migrate existing data (users dir + db files) moved = [] old_root = DATA_DIR for item in ("users",): src = os.path.join(old_root, item) dst = os.path.join(new_root, item) if os.path.isdir(src) and not os.path.isdir(dst): shutil.move(src, dst) moved.append(item) for item in ("users.db", "usage.db", "trials.json"): src = os.path.join(old_root, item) dst = os.path.join(new_root, item) if os.path.exists(src) and not os.path.exists(dst): shutil.move(src, dst) moved.append(item) # persist config in the default host root (survives data root moves) cfg = os.path.join(_host_to_container(DEFAULT_HOST_ROOT), "config.json") try: os.makedirs(os.path.dirname(cfg), exist_ok=True) with open(cfg, "w") as f: json.dump({"storage_root": new_host_root}, f) except Exception: return 500, {"code": 500, "message": "配置写入失败"} # restart to take effect (restart always brings the container back) import threading as _th def _restart(): os._exit(0) _th.Timer(1.5, _restart).start() return 200, {"code": 200, "message": "ok", "data": {"root": new_root, "moved": moved, "restarting": True}} if method == "GET" and sub == "/usage": qs = parse.parse_qs(parse.urlparse(handler.path).query) days = _int_str((qs.get("days") or ["7"])[0], 1, 365, 7) since = time.time() - days * 86400 conn = _usage_db() by_tool = conn.execute("SELECT tool, COUNT(*) c FROM usage WHERE at>? GROUP BY tool ORDER BY c DESC LIMIT 30", (since,)).fetchall() by_user = conn.execute("SELECT username, COUNT(*) c, MAX(at) last FROM usage WHERE at>? AND username!='' GROUP BY username ORDER BY c DESC LIMIT 50", (since,)).fetchall() total = conn.execute("SELECT COUNT(*) FROM usage WHERE at>?", (since,)).fetchone()[0] conn.close() return 200, {"code": 200, "message": "ok", "data": { "days": days, "total": total, "by_tool": [{"tool": t, "count": c} for t, c in by_tool], "by_user": [{"username": u, "count": c, "last": int(l or 0)} for u, c, l in by_user], }} return 404, {"code": 404, "message": "unknown admin api"} def _req_machine(handler): return handler.headers.get("X-Machine-Id", "") if handler else "" def user_api(method, sub, payload, handler): """returns (status, body_dict)""" if method == "POST" and sub == "/register": if not verify_turnstile(str(payload.get("cf_token") or "")): return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"} username = str(payload.get("username") or "").strip() password = str(payload.get("password") or "") if not USER_NAME_RE.match(username): return 400, {"code": 400, "message": "用户名需 3-32 位字母/数字/下划线/中文"} if len(password) < 6: return 400, {"code": 400, "message": "密码至少 6 位"} conn = _db() try: salt = secrets.token_hex(16) conn.execute("INSERT INTO users VALUES (?,?,?,?)", (username, salt, _hash_pw(password, salt), time.time())) conn.commit() except sqlite3.IntegrityError: return 409, {"code": 409, "message": "用户名已被注册"} finally: conn.close() _user_dir(username) _bind_machine(username, _req_machine(handler)) return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}} if method == "POST" and sub == "/login": username = str(payload.get("username") or "").strip() password = str(payload.get("password") or "") # admin accounts skip the human check (admin panel login has no Turnstile widget) role, _disabled = _user_attr(username) if role != "admin" and not verify_turnstile(str(payload.get("cf_token") or "")): return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"} conn = _db() row = conn.execute("SELECT salt, pw_hash FROM users WHERE username=?", (username,)).fetchone() conn.close() if not row or _hash_pw(password, row[0]) != row[1]: return 401, {"code": 401, "message": "用户名或密码错误"} _user_dir(username) _bind_machine(username, _req_machine(handler)) role, disabled = _user_attr(username) if disabled: return 403, {"code": 403, "message": "账号已被禁用,请联系管理员"} return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username, "role": role or "user"}} # ---- below requires auth ---- username = _auth_user(handler) if not username: return 401, {"code": 401, "message": "请先登录"} if _user_disabled(username): return 403, {"code": 403, "message": "账号已被禁用,请联系管理员"} if method == "GET" and sub == "/me": role, _d = _user_attr(username) return 200, {"code": 200, "message": "ok", "data": {"username": username, "role": role}} if method == "GET" and sub == "/data": path = os.path.join(_user_dir(username), "data.json") if not os.path.exists(path): return 200, {"code": 200, "message": "ok", "data": {"data": {}, "updated": 0}} try: with open(path) as f: saved = json.load(f) except Exception: saved = {} return 200, {"code": 200, "message": "ok", "data": {"data": saved.get("data", {}), "updated": saved.get("updated", 0)}} if method == "POST" and sub == "/data": data = payload.get("data") if not isinstance(data, dict): return 400, {"code": 400, "message": "data 需为对象"} path = os.path.join(_user_dir(username), "data.json") tmp = path + ".tmp" with open(tmp, "w") as f: json.dump({"data": data, "updated": time.time()}, f, ensure_ascii=False) os.replace(tmp, path) return 200, {"code": 200, "message": "ok"} if method == "POST" and sub == "/files": files = payload.get("_files") or {} fields = payload.get("_fields") or {} fobj = files.get("file") if not fobj: return 400, {"code": 400, "message": "缺少 file 字段"} fname, fdata, fmime = fobj if len(fdata) > MAX_UPLOAD: return 413, {"code": 413, "message": "文件超过 " + str(MAX_UPLOAD // 1024 // 1024) + "MB 限制"} if not fdata: return 400, {"code": 400, "message": "文件为空"} file_id = uuid.uuid4().hex[:16] safe_name = os.path.basename(str(fname))[:120] or "file" kind = re.sub(r"[^A-Za-z0-9_-]", "", str(fields.get("kind") or ""))[:32] fdir = os.path.join(_user_dir(username), "files") os.makedirs(fdir, exist_ok=True) if kind: fdir = os.path.join(fdir, kind) os.makedirs(fdir, exist_ok=True) with open(os.path.join(fdir, file_id), "wb") as f: f.write(fdata) conn = _db() conn.execute("INSERT INTO files VALUES (?,?,?,?,?,?)", (file_id, username, safe_name, len(fdata), fmime, time.time())) conn.commit() conn.close() return 200, {"code": 200, "message": "ok", "data": {"id": file_id, "name": safe_name, "size": len(fdata), "kind": kind}} if method == "GET" and sub == "/files": conn = _db() rows = conn.execute("SELECT id, name, size, mime, created FROM files WHERE username=? ORDER BY created DESC LIMIT 200", (username,)).fetchall() conn.close() files = [{"id": r[0], "name": r[1], "size": r[2], "mime": r[3], "created": int(r[4])} for r in rows] return 200, {"code": 200, "message": "ok", "data": {"files": files}} if sub.startswith("/file/"): file_id = sub[len("/file/"):] if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id): return 400, {"code": 400, "message": "文件ID无效"} conn = _db() row = conn.execute("SELECT id, username, name, size, mime, created FROM files WHERE id=?", (file_id,)).fetchone() conn.close() if not row or row[1] != username: return 404, {"code": 404, "message": "文件不存在"} fpath = None base = os.path.join(_user_dir(username), "files") if os.path.exists(os.path.join(base, file_id)): fpath = os.path.join(base, file_id) else: for d in os.listdir(base): p = os.path.join(base, d, file_id) if os.path.exists(p): fpath = p break if not fpath: return 404, {"code": 404, "message": "文件不存在"} if method == "GET": if not os.path.exists(fpath): return 404, {"code": 404, "message": "文件不存在"} with open(fpath, "rb") as f: data = f.read() handler.send_response(200) handler.send_header("Content-Type", row[4] or "application/octet-stream") handler.send_header("Content-Length", str(len(data))) handler.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + parse.quote(row[2])) handler.end_headers() handler.wfile.write(data) return None, None if method == "DELETE": if fpath and os.path.exists(fpath): os.remove(fpath) conn = _db() conn.execute("DELETE FROM files WHERE id=?", (file_id,)) conn.commit() conn.close() return 200, {"code": 200, "message": "ok"} return 404, {"code": 404, "message": "unknown user api"} class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, fmt, *args): # quiet pass def _reply(self, status: int, body: bytes = b"", ctype="text/plain"): self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.end_headers() if body: self.wfile.write(body) # ---------- GET ---------- def _handle_user(self, method): parsed = parse.urlparse(self.path) sub = parsed.path[len("/user"):] payload = {} if method == "POST": try: ctype = self.headers.get("Content-Type", "") length = int(self.headers.get("Content-Length") or 0) if length > MAX_UPLOAD + 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "文件过大"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"{}" if ctype.startswith("multipart/form-data"): env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True) files = {} fields = {} for k in fs.keys(): item = fs[k] if getattr(item, "filename", None): files[k] = (item.filename, item.file.read(), item.type or "application/octet-stream") else: fields[k] = item.value payload = {"_fields": fields, "_files": files} else: payload = json.loads(raw.decode("utf-8") or "{}") except Exception: self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json") return status, body = user_api(method, sub, payload, self) if status is None: return # response already sent (file download) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") def _handle_admin(self, method): parsed = parse.urlparse(self.path) sub = parsed.path[len("/admin"):] payload = {} if method == "POST": try: length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"{}" payload = json.loads(raw.decode("utf-8") or "{}") except Exception: self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json") return status, body = admin_api(method, sub, payload, self) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") def do_GET(self): parsed = parse.urlparse(self.path) if parsed.path == "/ai/models": self._handle_ai_models() return if parsed.path.startswith("/admin"): self._handle_admin("GET") return if parsed.path.startswith("/user"): self._handle_user("GET") return if parsed.path == "/auth-status": qs = parse.parse_qs(parsed.query) machine = (qs.get("machine_id") or [""])[0] if not MACHINE_RE.match(machine): self._reply(400, json.dumps({"code": 400, "message": "机器码格式错误"}, ensure_ascii=False).encode(), "application/json") return authorized = False if machine not in _load_revoked(): authorized = query_authorized(machine) or _account_license_ok(machine) body = {"code": 200, "message": "ok", "data": {"authorized": authorized}} self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return if parsed.path == "/sites": status, body = sites_api("GET", "", {}) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return if parsed.path == "/check": machine = self.headers.get("X-Machine-Id", "") tool = self.headers.get("X-Tool", "") status = check(machine, tool) if status == 200: log_usage(machine, tool) self._reply(status, b"ok" if status == 200 else b"forbidden") return if parsed.path == "/translate": target = f"{UPSTREAM}?{parsed.query}" try: with OPENER_PROXY.open(target, timeout=TIMEOUT) as resp: body = resp.read() ctype = resp.headers.get("Content-Type", "application/json; charset=utf-8") self._reply(200, body, ctype) except Exception as exc: # noqa: BLE001 payload = f'{{"error":"relay error: {exc}"}}'.encode() self._reply(502, payload, "application/json") return self._reply(404, b"not found") # ---------- POST ---------- def _read_payload(self) -> dict: try: length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"{}" return json.loads(raw.decode("utf-8") or "{}") except Exception: # noqa: BLE001 return {} # ---------- AI 图片:抠图 / 放大 ---------- _bg_session = None def _handle_removebg(self): machine = self.headers.get("X-Machine-Id", "") if check(machine, "ai-image-tools") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return try: length = int(self.headers.get("Content-Length") or 0) if length > 30 * 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "图片超过 30MB 限制"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"" if not raw: self._reply(400, json.dumps({"code": 400, "message": "未收到图片数据"}, ensure_ascii=False).encode(), "application/json") return from rembg import new_session, remove as _bgremove cls = type(self) if cls._bg_session is None: cls._bg_session = new_session("u2net") out = _bgremove(raw, session=cls._bg_session) log_usage(machine, "ai-image-tools") self._reply(200, out, "image/png") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": f"抠图失败: {e}"}, ensure_ascii=False).encode(), "application/json") def _handle_upscale(self): machine = self.headers.get("X-Machine-Id", "") if check(machine, "ai-image-tools") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return try: q = parse.parse_qs(parse.urlparse(self.path).query) scale = (q.get("scale") or ["2"])[0] noise = (q.get("noise") or ["1"])[0] if scale not in ("2", "4"): scale = "2" if noise not in ("-1", "0", "1", "2", "3"): noise = "1" length = int(self.headers.get("Content-Length") or 0) if length > 30 * 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "图片超过 30MB 限制"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"" if not raw: self._reply(400, json.dumps({"code": 400, "message": "未收到图片数据"}, ensure_ascii=False).encode(), "application/json") return ctype = (self.headers.get("Content-Type") or "").split(";")[0].strip() ext = {"image/png": "png", "image/webp": "webp"}.get(ctype, "jpg") wd = "/tmp/up-" + uuid.uuid4().hex[:12] os.makedirs(wd, exist_ok=True) fin = os.path.join(wd, f"in.{ext}") fout = os.path.join(wd, f"out.{ext}") with open(fin, "wb") as f: f.write(raw) import subprocess as _sp r = _sp.run( ["/app/waifu2x/waifu2x-ncnn-vulkan", "-i", fin, "-o", fout, "-s", scale, "-n", noise, "-g", "-1", "-t", "128"], capture_output=True, text=True, timeout=180, ) if r.returncode != 0 or not os.path.exists(fout): raise RuntimeError((r.stderr or r.stdout or "waifu2x failed")[-300:]) with open(fout, "rb") as f: out = f.read() shutil.rmtree(wd, ignore_errors=True) log_usage(machine, "ai-image-tools") self._reply(200, out, ctype or "image/jpeg") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": f"放大失败: {e}"}, ensure_ascii=False).encode(), "application/json") # ---------- 共用 LLM 调用 ---------- def _llm_chat(self, messages: list, model: str = "") -> str: key = os.environ.get("NEWAPI_KEY", "") upstream = os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions") model = (model or os.environ.get("NEWAPI_MODEL", "qwen3.8-flash"))[:60] if not key: raise RuntimeError("AI 服务未配置") body = json.dumps({"model": model, "messages": messages, "temperature": 0.7, "max_tokens": 4096}).encode() req = request.Request(upstream, data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}) resp = request.urlopen(req, timeout=180) data = json.loads(resp.read()) if "error" in data: raise RuntimeError(data["error"].get("message", "upstream error")) return data["choices"][0]["message"]["content"] # ---------- 文案工具箱 ---------- COPY_SCENES = { "rewrite": "你是一名资深中文编辑。请改写用户提供的文字,保持原意但改变表达方式和句式结构,语言自然流畅,直接输出改写后的正文,不要解释。", "deaigc": "你是消除 AI 腔调的中文改写专家。把用户提供的文字改写得更像真人手写:加入口语化表达、长短句交错、具体细节,降低 AI 生成痕迹(避免排比、避免'首先其次最后'式结构、避免空洞套话),保持原意,直接输出改写后的正文。", "titles": "你是爆款标题专家。根据用户提供的主题,生成 10 个吸引点击的中文标题,要求:每行一个、不超过 30 字、风格多样(悬念/数字/痛点/对比/好奇),直接输出标题列表,不要其他文字。", "xhs": "你是小红书文案高手。根据用户提供的主题写一篇小红书笔记:开头抓人(1-2 句)、正文分段带 emoji、结尾加 5-8 个话题标签(#开头)。总字数 300-600 字,语气亲切接地气,直接输出笔记内容。", "moments": "你是朋友圈文案高手。根据用户提供的主题写 3 条不同风格的微信朋友圈短文案:一条文艺、一条幽默、一条简洁有梗,每条不超过 60 字、可带 1-2 个 emoji,直接输出 3 条文案(每条一行)。", } def _handle_copy(self): payload = self._read_payload() machine = str(payload.get("machine") or "") if check(machine, "copywriting") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return scene = str(payload.get("scene") or "") if scene not in self.COPY_SCENES: self._reply(400, json.dumps({"code": 400, "message": "无效的场景"}, ensure_ascii=False).encode(), "application/json") return text = str(payload.get("text") or "").strip()[:8000] if not text: self._reply(400, json.dumps({"code": 400, "message": "请输入内容"}, ensure_ascii=False).encode(), "application/json") return try: reply = self._llm_chat([ {"role": "system", "content": self.COPY_SCENES[scene]}, {"role": "user", "content": text}, ], model=(str(payload.get("model") or "") if str(payload.get("model") or "") in ("mimo-v2.6-flash", "glm-5.3-flash") else "")) log_usage(machine, "copywriting") self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": reply}}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json") # ---------- 文档翻译 ---------- def _handle_translate_doc(self): machine = self.headers.get("X-Machine-Id", "") if check(machine, "translator") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return try: ctype = self.headers.get("Content-Type", "") length = int(self.headers.get("Content-Length") or 0) if length > 20 * 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "文档超过 20MB 限制"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"" if not raw: self._reply(400, json.dumps({"code": 400, "message": "未收到文件"}, ensure_ascii=False).encode(), "application/json") return if "multipart" not in ctype: self._reply(400, json.dumps({"code": 400, "message": "请用表单上传文件"}, ensure_ascii=False).encode(), "application/json") return env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True) fitem = fs["file"] if "file" in fs.keys() else None if fitem is None or not fitem.filename: self._reply(400, json.dumps({"code": 400, "message": "缺少文件"}, ensure_ascii=False).encode(), "application/json") return to_lang = (fs["to"].value if "to" in fs.keys() else "") or "Chinese" fname = os.path.basename(fitem.filename or "doc") ext = os.path.splitext(fname)[1].lower() allowed = {".txt", ".md", ".docx", ".doc", ".pdf", ".html", ".htm", ".epub", ".rtf", ".odt"} if ext not in allowed: self._reply(400, json.dumps({"code": 400, "message": f"不支持的格式 {ext}(支持 txt/md/docx/pdf/html/epub/rtf/odt)"}, ensure_ascii=False).encode(), "application/json") return wd = "/tmp/tdoc-" + uuid.uuid4().hex[:12] os.makedirs(wd, exist_ok=True) src = os.path.join(wd, "in" + ext) with open(src, "wb") as f: f.write(fitem.file.read()) # 提取纯文本 if ext in (".txt", ".md"): rawb = open(src, "rb").read() text = None for enc in ("utf-8", "gb18030", "utf-16", "latin-1"): try: text = rawb.decode(enc) break except Exception: # noqa: BLE001 continue text = text or "" else: outtxt = os.path.join(wd, "out.txt") r = subprocess.run(["ebook-convert", src, outtxt], capture_output=True, timeout=180) if r.returncode != 0 or not os.path.exists(outtxt): shutil.rmtree(wd, ignore_errors=True) self._reply(400, json.dumps({"code": 400, "message": "文档解析失败,请确认文件未加密/损坏"}, ensure_ascii=False).encode(), "application/json") return text = open(outtxt, "r", encoding="utf-8", errors="ignore").read() text = re.sub(r"\n{4,}", "\n\n\n", text or "").strip() if not text: shutil.rmtree(wd, ignore_errors=True) self._reply(400, json.dumps({"code": 400, "message": "未从文档中提取到文字"}, ensure_ascii=False).encode(), "application/json") return if len(text) > 60000: shutil.rmtree(wd, ignore_errors=True) self._reply(413, json.dumps({"code": 413, "message": "文档过长(≤6万字符)"}, ensure_ascii=False).encode(), "application/json") return # 分块翻译(按段落聚合,每块约 1400 字) paras = text.split("\n") chunks = [] cur = "" for para in paras: if len(cur) + len(para) + 1 > 1400 and cur: chunks.append(cur) cur = para else: cur = cur + "\n" + para if cur else para if cur: chunks.append(cur) translated = [] for i, ch in enumerate(chunks): out = self._llm_chat([ {"role": "system", "content": f"你是专业文档翻译。把用户提供的文档片段翻译成{to_lang}:保留原有换行、段落结构、编号和列表格式;专有名词、数字、日期原样保留;只输出译文,不要解释。"}, {"role": "user", "content": ch}, ]) translated.append(out.strip()) result_text = "\n\n".join(translated) shutil.rmtree(wd, ignore_errors=True) log_usage(machine, "translator") self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"text": result_text, "chars": len(text), "blocks": len(chunks)}}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": f"文档翻译失败: {e}"}, ensure_ascii=False).encode(), "application/json") def _handle_txt_to_docx(self): payload = self._read_payload() machine = str(payload.get("machine") or "") if check(machine, "translator") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return text = str(payload.get("text") or "") if not text.strip() or len(text) > 400000: self._reply(400, json.dumps({"code": 400, "message": "文本内容无效"}, ensure_ascii=False).encode(), "application/json") return try: wd = "/tmp/tdocx-" + uuid.uuid4().hex[:12] os.makedirs(wd, exist_ok=True) src = os.path.join(wd, "doc.txt") dst = os.path.join(wd, "doc.docx") with open(src, "w", encoding="utf-8") as f: f.write(text) r = subprocess.run(["ebook-convert", src, dst], capture_output=True, timeout=120) if r.returncode != 0 or not os.path.exists(dst): shutil.rmtree(wd, ignore_errors=True) self._reply(500, json.dumps({"code": 500, "message": "DOCX 转换失败"}, ensure_ascii=False).encode(), "application/json") return with open(dst, "rb") as f: out = f.read() shutil.rmtree(wd, ignore_errors=True) self.send_response(200) self.send_header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document") self.send_header("Content-Disposition", "attachment; filename*=UTF-8''%E8%AF%91%E6%96%87.docx") self.send_header("Content-Length", str(len(out))) self.end_headers() self.wfile.write(out) except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": f"转换失败: {e}"}, ensure_ascii=False).encode(), "application/json") # ---------- 可用模型列表(透传 NewAPI) ---------- def _handle_ai_models(self): try: key = os.environ.get("NEWAPI_KEY", "") base = os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions").replace("/chat/completions", "") + "/models" if not key: raise RuntimeError("AI 服务未配置") req = request.Request(base, headers={"Authorization": "Bearer " + key}) resp = request.urlopen(req, timeout=20) data = json.loads(resp.read()) ids = [m.get("id", "") for m in data.get("data", [])] # 过滤:排除生图/视频等非对话模型 skip = ("flux", "dall-e", "schnell", "sana", "-anime", "image", "video", "turbo-any-dark") chat_models = [i for i in ids if i and not any(s in i.lower() for s in skip)] self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"models": chat_models}}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(502, json.dumps({"code": 502, "message": f"模型列表获取失败: {e}"}, ensure_ascii=False).encode(), "application/json") # ---------- 截图理解 ---------- def _handle_vision(self): payload = self._read_payload() machine = str(payload.get("machine") or "") if check(machine, "image-tools") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return b64 = str(payload.get("image") or "") question = str(payload.get("question") or "").strip()[:1000] or "提取图片中的所有文字和关键信息,结构化整理输出。" if not b64: self._reply(400, json.dumps({"code": 400, "message": "未收到图片"}, ensure_ascii=False).encode(), "application/json") return if len(b64) > 20 * 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "图片过大(≤15MB)"}, ensure_ascii=False).encode(), "application/json") return try: reply = self._llm_chat([ {"role": "system", "content": "你是截图理解助手,能看懂图片内容(截图、票据、合同、表格、报错)。用中文简洁准确地回答,涉及金额/日期/编号等关键信息必须原样保留。"}, {"role": "user", "content": [ {"type": "text", "text": question}, {"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64}}, ]}, ]) log_usage(machine, "image-tools") self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": reply}}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json") # ---------- 视频字幕:转录 + 翻译 ---------- def _handle_subtitle(self): machine = self.headers.get("X-Machine-Id", "") if check(machine, "video-tools") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return try: ctype = self.headers.get("Content-Type", "") length = int(self.headers.get("Content-Length") or 0) if length > 500 * 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "视频超过 500MB 限制"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"" if not raw: self._reply(400, json.dumps({"code": 400, "message": "未收到视频数据"}, ensure_ascii=False).encode(), "application/json") return import cgi as _cgi import audio_ops wd = "/tmp/sub-" + uuid.uuid4().hex[:12] os.makedirs(wd, exist_ok=True) video_bytes = raw if "multipart" in ctype: env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} fs = _cgi.FieldStorage(fp=__import__("io").BytesIO(raw), environ=env, keep_blank_values=True) fitem = fs["file"] if "file" in fs.keys() else None if fitem is not None and fitem.filename: video_bytes = fitem.file.read() vin = os.path.join(wd, "in.mp4") with open(vin, "wb") as f: f.write(video_bytes) wav = os.path.join(wd, "audio.wav") r = subprocess.run( ["ffmpeg", "-y", "-i", vin, "-vn", "-ac", "1", "-ar", "16000", wav], capture_output=True, timeout=600, ) if r.returncode != 0 or not os.path.exists(wav): shutil.rmtree(wd, ignore_errors=True) self._reply(400, json.dumps({"code": 400, "message": "视频无音轨或格式不支持"}, ensure_ascii=False).encode(), "application/json") return q = parse.parse_qs(parse.urlparse(self.path).query) lang = (q.get("lang") or [""])[0] result = audio_ops.run_asr(wav, lang) shutil.rmtree(wd, ignore_errors=True) log_usage(machine, "video-tools") self._reply(200, json.dumps({"code": 200, "message": "ok", "data": result}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 import traceback traceback.print_exc() self._reply(500, json.dumps({"code": 500, "message": f"字幕生成失败: {e}"}, ensure_ascii=False).encode(), "application/json") def _handle_translate_srt(self): payload = self._read_payload() machine = str(payload.get("machine") or "") if check(machine, "video-tools") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return srt = str(payload.get("srt") or "").strip() target = str(payload.get("target") or "en") if not srt or len(srt) > 60000: self._reply(400, json.dumps({"code": 400, "message": "字幕内容无效"}, ensure_ascii=False).encode(), "application/json") return tname = "英文" if target == "en" else "日文" if target == "ja" else "英文" try: reply = self._llm_chat([ {"role": "system", "content": f"你是专业字幕翻译。把用户提供的 SRT 字幕翻译成{tname}:保留序号、时间轴和空行结构完全不变,只翻译每条字幕的文字部分;译文保持口语化、简洁(每行尽量不超过原长的 1.3 倍)。只输出翻译后的 SRT,不要解释。"}, {"role": "user", "content": srt}, ]) log_usage(machine, "video-tools") self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": reply}}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(502, json.dumps({"code": 502, "message": f"翻译失败: {e}"}, ensure_ascii=False).encode(), "application/json") # ---------- AI 问答 ---------- def _handle_aichat(self): payload = self._read_payload() machine = str(payload.get("machine") or "") if check(machine, "ai-chat") != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return prompt = str(payload.get("prompt") or "").strip()[:4000] if not prompt: self._reply(400, json.dumps({"code": 400, "message": "请输入问题"}, ensure_ascii=False).encode(), "application/json") return history = payload.get("history") or [] if not isinstance(history, list): history = [] history = [m for m in history[-8:] if isinstance(m, dict) and m.get("role") in ("user", "assistant") and isinstance(m.get("content"), str)] messages = [{"role": "system", "content": "你是 IT-TOOLS-PRO 工具站的 AI 助手,用简体中文简洁、直接地回答,代码用代码块包裹。"}] + history + [{"role": "user", "content": prompt}] key = os.environ.get("NEWAPI_KEY", "") upstream = os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions") model = os.environ.get("NEWAPI_MODEL", "big-pickle") if not key: self._reply(500, json.dumps({"code": 500, "message": "AI 服务未配置"}, ensure_ascii=False).encode(), "application/json") return want = str(payload.get("model") or "") if want in ("mimo-v2.6-flash", "glm-5.3-flash"): model = want try: body = json.dumps({"model": model, "messages": messages, "temperature": 0.7, "max_tokens": 2048}).encode() req = request.Request(upstream, data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}) resp = request.urlopen(req, timeout=180) data = json.loads(resp.read()) text = data["choices"][0]["message"]["content"] log_usage(machine, "ai-chat") self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": text}}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json") def _handle_video(self): import uuid as _uuid import video_ops machine = self.headers.get("X-Machine-Id", "") status = check(machine, "video-tools") if status != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return log_usage(machine, "video-tools") try: ctype = self.headers.get("Content-Type", "") length = int(self.headers.get("Content-Length") or 0) if length > video_ops.MAX_INPUT + 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "文件超过 2GB 限制"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"" env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True) fobj = fs["file"] if ("file" in fs.keys()) else None if fobj is None or not fobj.filename: self._reply(400, json.dumps({"code": 400, "message": "缺少视频文件"}, ensure_ascii=False).encode(), "application/json") return fname = os.path.basename(fobj.filename or "video") ext = os.path.splitext(fname)[1].lower() if ext not in video_ops.ALLOWED_EXT: self._reply(400, json.dumps({"code": 400, "message": "不支持的文件类型 " + ext}, ensure_ascii=False).encode(), "application/json") return op = (fs["op"].value if "op" in fs.keys() else "") or "" params = {} wm_bytes = None wm_name = "" for k in fs.keys(): item = fs[k] if k == "file" or k == "op": continue if getattr(item, "filename", None): if k == "wm_file": wm_bytes = item.file.read() wm_name = os.path.basename(item.filename or "wm.png") continue params[k] = item.value fdata = fobj.file.read() if not fdata: self._reply(400, json.dumps({"code": 400, "message": "文件为空"}, ensure_ascii=False).encode(), "application/json") return workdir = "/tmp/video-" + _uuid.uuid4().hex[:12] os.makedirs(workdir, exist_ok=True) fin = os.path.join(workdir, "in" + ext) with open(fin, "wb") as f: f.write(fdata) duration = video_ops.probe_duration(fin) argv, out_ext = video_ops.build_cmd(op, fin, None, params) fout = os.path.join(workdir, "out." + out_ext) argv[argv.index(fout) if fout in argv else len(argv) - 1] = fout video_ops.run_ffmpeg(argv) with open(fout, "rb") as f: out = f.read() base = os.path.splitext(fname)[0][:80] out_name = base + "-out." + out_ext self.send_response(200) self.send_header("Content-Type", "application/octet-stream") self.send_header("Content-Length", str(len(out))) self.send_header("Content-Disposition", "attachment; filename=\"result." + out_ext + "\"; filename*=UTF-8''" + parse.quote(out_name)) self.send_header("X-Duration-Seconds", str(round(duration, 2))) self.end_headers() self.wfile.write(out) except ValueError as e: self._reply(400, json.dumps({"code": 400, "message": str(e)}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": "处理失败: " + str(e)[:300]}, ensure_ascii=False).encode("utf-8"), "application/json") finally: try: if "workdir" in dir() and workdir and os.path.isdir(workdir): shutil.rmtree(workdir, ignore_errors=True) except Exception: pass def _handle_tts(self): import audio_ops machine = self.headers.get("X-Machine-Id", "") status = check(machine, "audio-tools") if status != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return log_usage(machine, "audio-tools-tts") try: length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"{}" payload = json.loads(raw.decode("utf-8") or "{}") import uuid as _uuid out_path = "/tmp/tts-" + _uuid.uuid4().hex[:10] + ".mp3" try: audio_ops.run_tts( str(payload.get("text") or ""), str(payload.get("voice") or ""), _int_str(payload.get("rate"), -50, 100, 0), _int_str(payload.get("pitch"), -50, 50, 0), out_path, ) with open(out_path, "rb") as f: out = f.read() finally: try: os.remove(out_path) except Exception: pass self.send_response(200) self.send_header("Content-Type", "audio/mpeg") self.send_header("Content-Length", str(len(out))) self.end_headers() self.wfile.write(out) except ValueError as e: self._reply(400, json.dumps({"code": 400, "message": str(e)}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": "合成失败: " + str(e)[:200]}, ensure_ascii=False).encode("utf-8"), "application/json") def _handle_clone(self): import audio_ops import uuid as _uuid parsed = parse.urlparse(self.path) machine = self.headers.get("X-Machine-Id", "") status = check(machine, "audio-tools") if status != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return if parsed.path == "/clone/prepare": # multipart: reference audio -> stored for the voice-clone pipeline try: ctype = self.headers.get("Content-Type", "") length = int(self.headers.get("Content-Length") or 0) if length > 35 * 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "参考音频过大"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"" env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True) fobj = fs["file"] if ("file" in fs.keys()) else None if fobj is None or not fobj.filename: self._reply(400, json.dumps({"code": 400, "message": "缺少参考音频文件"}, ensure_ascii=False).encode(), "application/json") return ref = audio_ops.clone_prepare(fobj.file.read(), os.path.basename(fobj.filename)) log_usage(machine, "audio-tools-clone") body = {"code": 200, "message": "ok", "data": {"ref_file": ref}} self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") except ValueError as e: self._reply(400, json.dumps({"code": 400, "message": str(e)}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": "上传失败: " + str(e)[:200]}, ensure_ascii=False).encode("utf-8"), "application/json") return if parsed.path == "/clone/tts": try: length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"{}" pl = json.loads(raw.decode("utf-8") or "{}") out_path = "/tmp/clone-" + _uuid.uuid4().hex[:10] + ".wav" try: audio_ops.clone_tts( str(pl.get("ref_file") or ""), str(pl.get("prompt_text") or ""), str(pl.get("text") or ""), str(pl.get("text_lang") or "zh"), str(pl.get("prompt_lang") or "zh"), out_path, ) with open(out_path, "rb") as f: out = f.read() finally: try: os.remove(out_path) except Exception: pass self.send_response(200) self.send_header("Content-Type", "audio/wav") self.send_header("Content-Length", str(len(out))) self.end_headers() self.wfile.write(out) except ValueError as e: self._reply(400, json.dumps({"code": 400, "message": str(e)}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": "克隆合成失败: " + str(e)[:200]}, ensure_ascii=False).encode("utf-8"), "application/json") return self._reply(404, b"not found") def _handle_asr(self): import audio_ops import uuid as _uuid import video_ops machine = self.headers.get("X-Machine-Id", "") status = check(machine, "audio-tools") if status != 200: self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return log_usage(machine, "audio-tools-asr") workdir = None try: ctype = self.headers.get("Content-Type", "") length = int(self.headers.get("Content-Length") or 0) if length > audio_ops.MAX_ASR_MB * 1024 * 1024 + 1024 * 1024: self._reply(413, json.dumps({"code": 413, "message": "音频超过 " + str(audio_ops.MAX_ASR_MB) + "MB 限制"}, ensure_ascii=False).encode(), "application/json") return raw = self.rfile.read(length) if length else b"" env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True) fobj = fs["file"] if ("file" in fs.keys()) else None if fobj is None or not fobj.filename: self._reply(400, json.dumps({"code": 400, "message": "缺少音频文件"}, ensure_ascii=False).encode(), "application/json") return fname = os.path.basename(fobj.filename or "audio") ext = os.path.splitext(fname)[1].lower() if ext not in (".mp3", ".wav", ".m4a", ".ogg", ".flac", ".aac", ".webm", ".mp4", ".wma", ".opus"): self._reply(400, json.dumps({"code": 400, "message": "不支持的音频格式 " + ext}, ensure_ascii=False).encode(), "application/json") return lang = fs["language"].value if "language" in fs.keys() else "" workdir = "/tmp/asr-" + _uuid.uuid4().hex[:10] os.makedirs(workdir, exist_ok=True) fpath = os.path.join(workdir, "in" + ext) with open(fpath, "wb") as f: f.write(fobj.file.read()) # normalize to wav mono 16k for whisper (handles mp4/m4a containers too) wav = os.path.join(workdir, "in.wav") argv, _ = video_ops.build_cmd("audio", fpath, None, {"fmt": "wav"}) fout = os.path.join(workdir, "tmp.wav") argv[argv.index(fout) if fout in argv else len(argv) - 1] = fout video_ops.run_ffmpeg(argv, timeout=600) result = audio_ops.run_asr(fout, lang) body = json.dumps({"code": 200, "message": "ok", "data": result}, ensure_ascii=False).encode("utf-8") self._reply(200, body, "application/json") except Exception as e: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": "识别失败: " + str(e)[:200]}, ensure_ascii=False).encode("utf-8"), "application/json") finally: if workdir and os.path.isdir(workdir): shutil.rmtree(workdir, ignore_errors=True) def do_POST(self): parsed = parse.urlparse(self.path) if parsed.path.startswith("/admin"): self._handle_admin("POST") return if parsed.path.startswith("/user"): self._handle_user("POST") return if parsed.path == "/tts": self._handle_tts() return if parsed.path == "/asr": self._handle_asr() return if parsed.path.startswith("/clone"): self._handle_clone() return if parsed.path == "/video": self._handle_video() return if parsed.path == "/remove-bg": self._handle_removebg() return if parsed.path.startswith("/upscale"): self._handle_upscale() return if parsed.path == "/ai/chat": self._handle_aichat() return if parsed.path == "/ai/copy": self._handle_copy() return if parsed.path == "/ai/models": self._handle_ai_models() return if parsed.path == "/translate-doc": self._handle_translate_doc() return if parsed.path == "/txt-to-docx": self._handle_txt_to_docx() return if parsed.path == "/ai/vision": self._handle_vision() return if parsed.path == "/subtitle": self._handle_subtitle() return if parsed.path == "/ai/translate-srt": self._handle_translate_srt() return if parsed.path == "/convert": self._handle_convert() return if parsed.path == "/sites" or parsed.path == "/sites/config": sub = parsed.path[len("/sites"):] status, body = sites_api("POST", sub, self._read_payload()) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return if parsed.path == "/deactivate": try: length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"{}" payload = json.loads(raw.decode("utf-8") or "{}") except Exception: # noqa: BLE001 self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json") return machine_id = str(payload.get("machine_id") or "").strip() if not MACHINE_RE.match(machine_id): self._reply(400, json.dumps({"code": 400, "message": "机器码格式错误"}, ensure_ascii=False).encode(), "application/json") return status, body = deactivate_card(machine_id) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return if parsed.path == "/activate": try: length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"{}" payload = json.loads(raw.decode("utf-8") or "{}") except Exception: # noqa: BLE001 self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json") return card_key = str(payload.get("card_key") or "").strip() machine_id = str(payload.get("machine_id") or "").strip() contact_qq = str(payload.get("contact_qq") or "").strip() replace = bool(payload.get("replace")) if not card_key: self._reply(400, json.dumps({"code": 400, "message": "请输入卡密"}, ensure_ascii=False).encode(), "application/json") return if not MACHINE_RE.match(machine_id): self._reply(400, json.dumps({"code": 400, "message": "机器码格式错误"}, ensure_ascii=False).encode(), "application/json") return status, body = activate_card(card_key, machine_id, contact_qq, replace=replace) if status == 200: # bind card to the logged-in account so it follows the user across devices tok = self.headers.get("Authorization", "") if tok.lower().startswith("bearer "): acc = _parse_token(tok[7:]) if acc: try: _save_user_license(acc, card_key, machine_id) except Exception: pass self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return self._reply(404, b"not found") # ---------- conversion ---------- def _handle_convert(self): try: machine = self.headers.get("X-Machine-Id", "") tool = self.headers.get("X-Tool", "") if check(machine, tool) != 200: self._reply(403, json.dumps({"code": 403, "message": "授权校验未通过或试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json") return ctype = self.headers.get("Content-Type", "") if "multipart/form-data" not in ctype: self._reply(400, json.dumps({"code": 400, "message": "需要 multipart 上传"}, ensure_ascii=False).encode("utf-8"), "application/json") return form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype}) fmt = (form.getvalue("format") or "").lower() if fmt not in CONVERT_FMTS: self._reply(400, json.dumps({"code": 400, "message": f"不支持的目标格式:{fmt}"}, ensure_ascii=False).encode("utf-8"), "application/json") return items = form["files"] if "files" in form else [] if not isinstance(items, list): items = [items] items = [it for it in items if getattr(it, "filename", None)] if not items: self._reply(400, json.dumps({"code": 400, "message": "请选择要转换的文件"}, ensure_ascii=False).encode("utf-8"), "application/json") return tmpdir = tempfile.mkdtemp(prefix="convert-") try: src_names = [] for it in items: safe = os.path.basename(it.filename).replace("\\", "_") safe = re.sub(r"[^\w.\-()\u4e00-\u9fa5]+", "_", safe) or "file" with open(os.path.join(tmpdir, safe), "wb") as fh: shutil.copyfileobj(it.file, fh) src_names.append(safe) outs = _convert_files(tmpdir, src_names, fmt) if len(outs) == 1: data = open(outs[0], "rb").read() fname = os.path.basename(outs[0]) self.send_response(200) self.send_header("Content-Type", "application/octet-stream") self.send_header("Content-Disposition", f"attachment; filename*=UTF-8''{parse.quote(fname)}") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) else: buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: for o in outs: zf.write(o, os.path.basename(o)) data = buf.getvalue() self.send_response(200) self.send_header("Content-Type", "application/zip") self.send_header("Content-Disposition", "attachment; filename=converted.zip") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) finally: shutil.rmtree(tmpdir, ignore_errors=True) except RuntimeError as exc: self._reply(400, json.dumps({"code": 400, "message": str(exc)}, ensure_ascii=False).encode("utf-8"), "application/json") except Exception as exc: # noqa: BLE001 self._reply(500, json.dumps({"code": 500, "message": f"转换服务错误:{exc}"}, ensure_ascii=False).encode("utf-8"), "application/json") # ---------- PUT / DELETE ---------- def do_PUT(self): parsed = parse.urlparse(self.path) if parsed.path.startswith("/sites/"): sub = parsed.path[len("/sites"):] status, body = sites_api("PUT", sub, self._read_payload()) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return self._reply(404, b"not found") def do_DELETE(self): parsed = parse.urlparse(self.path) if parsed.path.startswith("/user"): self._handle_user("DELETE") return if parsed.path.startswith("/sites/"): sub = parsed.path[len("/sites"):] status, body = sites_api("DELETE", sub, {}) self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return self._reply(404, b"not found") if __name__ == "__main__": _ensure_admin() ThreadingHTTPServer(("0.0.0.0", 8091), Handler).serve_forever()