Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.

Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-04 22:42:40 -05:00
parent c1501f6e16
commit d409e416da
867 changed files with 123573 additions and 667 deletions

196
README.md
View File

@ -26,12 +26,144 @@ cd desktop && npm install && npm run electron:dev
**文档不写死任何生产域名或公网 IP。** 每台机器 / 每个环境用你自己的变量;下面用占位符说明。
本仓库有两种 **Linux 生产形态**(另有 Windows 桌面端,见上节):
| 形态 | 说明 | 文档 |
|------|------|------|
| **VPS 本机** | 应用与 TLS 反代在**同一台**海外 VPS;浏览器直打该机 443 | [INSTALL.md](docs/INSTALL.md) · `bootstrap_vps.sh` |
| **物理机** | 应用在家里 Ubuntu / PVE 客户机;**边缘机**只做 HTTPS + WireGuard(可 1~2 台边缘) | [INSTALL.md](docs/INSTALL.md) · [PHYSICAL_DEPLOY.md](docs/PHYSICAL_DEPLOY.md) |
> **先认形态再改配置。** 纯 VPS:没有 `wg-dy` / 国内边缘 / ShellCrash `:7890` 假设。物理机:不要在家里再跑公网证书,也不要把 `DY_PUBLIC_BASE_URL` 写成 WG IP。
| 占位符 | 含义 | 典型来源 |
|--------|------|----------|
| `${DOMAIN}` | 对外 HTTPS 域名 | `bootstrap_vps.sh` 必填 |
| `${PUBLIC_BASE}` | 站点根 URL | 默认 `https://${DOMAIN}`,写入 `DY_PUBLIC_BASE_URL` |
| `${APP_DIR}` | 代码目录 | 默认 `/opt/douyinWEB` |
| `${API_PORT}` / `${WEB_PORT}` | 本机监听端口 | 默认 `8014` / `4015`(仅 `127.0.0.1`) |
| `${API_PORT}` / `${WEB_PORT}` | 本机监听端口 | 默认 `8014` / `4015`(VPS 本机多为 `127.0.0.1`;物理机需 `0.0.0.0` 供 WG 访问) |
### 双形态对照(共用 · 纯 VPS · 物理机)
同一套代码,**两种生产形状**。改配置时先认清自己在哪一列;**不要**把物理机经验套到纯 VPS,也不要把 VPS 的 sing-box 住宅方案硬套到家里。
#### 共用(两边都兼容)
| 项 | 说明 |
|----|------|
| 代码 / systemd 单元名 | `douyinweb-web` / `api` / `pb` / `yt` / `s3*` |
| Next ↔ API | 始终 `DY_INTERNAL_API_URL=http://127.0.0.1:8014`(同机) |
| 公网站点根 | `DY_PUBLIC_BASE_URL=https://${DOMAIN}`(**禁止**写成 `127.0.0.1` / WG IP) |
| 登录 / Shorts / YouTube / OAuth 路径 | `${PUBLIC_BASE}/…`、`${PUBLIC_BASE}/api/shorts/oauth/callback` |
| 新装零房间 | 不打包、不恢复 `monitor.db`;见 fresh-install 规则 |
| 抖音相关 | 监控轮询、拉流:**尽量 DIRECT**(不走翻墙);物理机靠 Clash 规则,VPS 靠直连出口 |
| 安装入口 | `sudo bash scripts/install.sh` → 选形态 |
#### 仅纯 VPS(应用 + TLS 同机)
| 项 | 说明 |
|----|------|
| 脚本 | `scripts/bootstrap_vps.sh` |
| TLS | 本机 Nginx / 宝塔 / Caddy → `127.0.0.1:4015/8014` |
| 进程绑定 | 通常 `127.0.0.1` |
| 业务出海(可选) | 文档后文「全局 SOCKS5 / DouyinWEB 专用 sing-box」规划;**勿动** VPS 上已有 v2ray-agent `sing-box` |
| ShellCrash | **不是**默认栈;不要在纯 VPS 上假设有 `:7890` ShellCrash |
| Neko WebRTC | `NEKO_WEBRTC_NAT1TO1` / `DY_NEKO_NAT1TO1` = **本机公网 IP**;UDP/TCP mux 在本机安全组放行(无第二跳 DNAT) |
| 边缘 Caddy | 不需要 `bootstrap_physical_edge.sh` |
#### 仅物理机(应用在家;TLS 在边缘机)
| 项 | 说明 |
|----|------|
| 脚本 | 应用:`bootstrap_physical.sh`;海外边缘:`bootstrap_physical_edge.sh` |
| TLS(单边缘,基础) | **海外 VPS** Caddy → `wg-dy` → `10.8.0.2:4015/8014`;只 `reload caddy`,勿乱 restart 整机业务 |
| TLS(双边缘,推荐国内访问) | 见下节「物理机双边缘」:海外域名走 `wg-dy`,国内域名走 `wg-dy-cn` |
| 进程绑定 | **`0.0.0.0`**(供 WG 访问) |
| WireGuard | `wg-dy`(海外,示例 `10.8.0.0/24`);可选 `wg-dy-cn`(国内 hub,示例 `10.9.0.0/24`)。AllowedIPs **仅** VPN 网段,禁止 `0.0.0.0/0`(会抢 ShellCrash) |
| 业务出海 | **默认 ShellCrash mixed `:7890`**(见下节);非抖音(Google / YouTube / OAuth / Neko / 上传等)走代理 |
| ShellCrash Web 面板 | 公网:`${PUBLIC_BASE}/ui/#/proxies`(边缘把 `/ui` + Clash API 反代到物理机 `:9999`);WG 直连:`http://10.8.0.2:9999/ui/#/proxies` |
| Neko HTTP | **原生边缘反代**(默认):`${PUBLIC_BASE}/neko/{1..N}/` → WG `:9200+(N-1)`;`DY_NEKO_GATEWAY_ENABLED=0`;`DY_NEKO_MAX_INSTANCES` 默认 **64**(须与边缘已发布的 `/neko/N` 条数对齐);**务必带尾斜杠**(`/neko/5/`,裸 `/neko/5` 会相对资源 404) |
| Neko 网关模式 | 可选 `DY_NEKO_GATEWAY_ENABLED=1` → 边缘只反代到物理机 `:9199`;物理双边缘当前推荐 **关网关、开原生 `/neko/{id}`** |
| Neko WebRTC | `DY_NEKO_NAT1TO1` = **国内边缘公网 IP**(双边缘)或海外边缘公网 IP(单边缘);**禁止**写成 WG/`127.0.0.1`;mux/UDP 在该边缘 DNAT → 物理机;容器 `NEKO_BROWSER_PROXY=http://host.docker.internal:7890` |
| Neko 启停 | 新建/删除分组、切换启用:**不**全量 reconcile 停兄弟实例(避免独占直播误杀 Studio);面板「停止」会持久化 `neko_enabled=false`,避免开机复活 |
| Neko 黑屏排查 | 先确认 URL 有尾斜杠 → WebRTC(安全组 UDP)→ `supervisorctl status google-chrome`;`browser-launch.sh` 须 **可执行** |
| OAuth | 换 token / 拉频道资料必须经 `:7890`;直连 Google 会超时 →「授权失败 / 订阅 —」;同一 `youtube_channel_id` 挂两张 Shorts 卡时会软警告 |
| 登录跳转 | Next middleware **优先用请求 Host**(`.cn` 不会被 `DY_PUBLIC_BASE_URL` 强跳到 `.com`);CORS 需包含所有公网域名 |
| 细节全文 | [PHYSICAL_DEPLOY.md](docs/PHYSICAL_DEPLOY.md) |
#### 物理机双边缘(海外 + 国内 TLS,可选)
适用:应用仍只跑在**一台物理机**;希望海外用户与国内用户各走就近 HTTPS / WebRTC。
```text
浏览器 (海外)
│ HTTPS ${DOMAIN} 例:*.com
▼
海外 VPS Caddy
│ wg-dy 10.8.0.0/24
▼
物理机 10.8.0.2 Next/API/Neko …
浏览器 (国内)
│ HTTPS ${DOMAIN_CN} 例:*.cn
▼
国内云 Nginx/Caddy(宝塔等)
│ wg-dy-cn 10.9.0.0/24
▼
物理机 10.9.0.2 (同一台应用)
```
| 项 | 海外边缘 | 国内边缘 |
|----|----------|----------|
| DNS A | `${DOMAIN}` → 海外 VPS | `${DOMAIN_CN}` → 国内云 |
| TLS | Caddy site → `10.8.0.2` | 宝塔 Nginx / Caddy → `10.9.0.2`(勿与已有 80/443 抢端口再装第二套) |
| WG | `wg-dy`(VPS `10.8.0.1` ↔ 物理 `10.8.0.2`) | `wg-dy-cn`(国内 hub `10.9.0.1` ↔ 物理 `10.9.0.2`;海外 VPS 可作 peer `10.9.0.3` 备用) |
| 改配置 | 只动本站 Caddy;**先**验证旧站 health | 只新增站点;UFW + **云安全组** 放行业务口 |
| Neko HTTP | 原生 `handle_path /neko/{1..64}/*` → `10.8.0.2:920x`;裸 `/neko/N` → 308 `/neko/N/` | Nginx 等价 → `10.9.0.2:920x` + 尾斜杠重定向 |
| Neko WebRTC | DNAT mux/UDP → `10.8.0.2`(海外客户端备用) | DNAT → `10.9.0.2`;**ICE 主用国内公网 IP**(`DY_NEKO_NAT1TO1`) |
物理机环境建议:
```bash
# /etc/systemd/system/douyinweb-api.service(或 /etc/douyinweb.env)
DY_PUBLIC_BASE_URL=https://${DOMAIN} # OAuth 主登记域名仍用一个
DY_CORS_ORIGINS=https://${DOMAIN},https://${DOMAIN_CN},http://127.0.0.1:4015
DY_NEKO_HTTP_BIND=0.0.0.0
DY_NEKO_GATEWAY_ENABLED=0 # 物理双边缘:原生 /neko/{id},勿开 :9199 网关
DY_NEKO_MAX_INSTANCES=64 # 须 ≤ 边缘已发布的 /neko/N 条数
DY_NEKO_EDGE_UPSTREAM=10.8.0.2 # 生成 snippet 默认上游;国内站手写 10.9.0.2
DY_NEKO_NAT1TO1=<国内边缘公网IP> # 改后清 nat1to1 缓存并 force-recreate 容器
```
边缘 WebRTC(按实例 `i=1..64`,基址可配 `DY_NEKO_WEBRTC_MUX_BASE`,默认 `52300`):
| 流量 | 公网口(边缘) | DNAT 目标 |
|------|----------------|-----------|
| mux TCP/UDP | `52300+(i-1)` | 物理机同端口(海外→`10.8.0.2`,国内→`10.9.0.2`) |
| EPR UDP | 每实例一段(常见 `52500+` 起,按 compose 实际为准) | 同上 |
**云安全组**须放行上述 UDP/TCP(本机 UFW 开了 ≠ 安全组已开)。画面一直转圈、HTTP 正常 → 优先查 WebRTC DNAT / 安全组,不是 Next 构建。
> **纯 VPS 没有这一节。** 应用与 TLS 同机时,Neko `NAT1TO1` = 该 VPS 本机公网 IP,WebRTC 口直接在本机安全组放行即可。
#### 物理机业务出口(ShellCrash)— 当前实现
```text
抖音监控 / 抖音 CDN → DIRECT(Clash 规则强制,不可改坏)
其余业务(Google OAuth、YouTube API/上传、Neko 浏览器、
Studio、海外探测等)→ 127.0.0.1:7890(ShellCrash mixed)
可选「住宅落地」 → ShellCrash dialer-proxy 链式(家宽→前置节点→住宅 SOCKS)
```
| 项 | 值 |
|----|------|
| 默认 `egress_mode` | `shellcrash`(显式 `off` 才关) |
| 代理入口 | `http://127.0.0.1:7890` |
| Neko 浏览器 | `http://host.docker.internal:7890`(容器 → 宿主机) |
| FFmpeg 推流等 | `proxychains4` → `127.0.0.1:7890`(与开关联动) |
| UI | 控制台 **网络** 页:启停 ShellCrash、住宅链、WireGuard、FRP |
| 透明劫持 | ShellCrash `firewall_area=0`,避免 nft 透明代理打断 WG |
> **与后文「全局 SOCKS5 / DouyinWEB 专用 sing-box」的关系**:那一节描述的是 **纯 VPS / 可选住宅** 规划,监听多为 `127.0.0.1:17891`,且须与 v2ray-agent 隔离。**物理机当前以 ShellCrash `:7890` 为准**,不要混用两套默认出口。
部署完成后,控制台与 API 路径为:
@ -47,11 +179,37 @@ cd desktop && npm install && npm run electron:dev
| 运维 | `${PUBLIC_BASE}/ops` |
| Web 分析 | `${PUBLIC_BASE}/web` |
| Netdata(可选,需登录) | `${PUBLIC_BASE}/netdata/`(反代 `127.0.0.1:19999`,见 [运维与 Netdata](#运维与-netdata)) |
| ShellCrash 面板(**物理机**) | `${PUBLIC_BASE}/ui/#/proxies`(纯 VPS 无此路径,除非自建) |
| Neko 虚拟浏览器 | `${PUBLIC_BASE}/neko/1/` … `/neko/N/`(`N≤DY_NEKO_MAX_INSTANCES`,**带尾斜杠**) |
| S3 封面(若启用) | `${PUBLIC_BASE}/${S3_BUCKET}/…` 或独立 `DY_S3_PUBLIC_BASE` |
> **OAuth / 回调**:Google、TikTok 等第三方控制台里登记的 redirect URI 必须与 **`DY_PUBLIC_BASE_URL`** 一致,例如 `${PUBLIC_BASE}/api/shorts/oauth/callback`。换域名后需同步改 Google Cloud 与设置页里的 OAuth 配置。
### 新 VPS 一键引导(推荐)
### 新机器一键安装(配置化,不依赖 AI)
完整说明:[docs/INSTALL.md](docs/INSTALL.md)。
```bash
# 目标机 root;交互选择 VPS / 物理机 / 边缘 Caddy
sudo bash scripts/install.sh
# 或先填配置再跑
cp scripts/install.env.example /etc/douyinweb.install.env
# 编辑 DOMAIN、ADMIN_USER、ADMIN_PASS、GIT_URL、INSTALL_SHAPE=…
sudo bash scripts/install.sh
```
| 形态 | 脚本 |
|------|------|
| VPS 本机(应用+Nginx) | `scripts/bootstrap_vps.sh` |
| 物理机应用(PVE/家宽 Ubuntu) | `scripts/bootstrap_physical.sh` |
| 物理机边缘(海外 Caddy→WG) | `scripts/bootstrap_physical_edge.sh` |
> 家里物理机 + 海外 TLS:不要只用 VPS 脚本;按 [INSTALL.md](docs/INSTALL.md) 物理机顺序,细节约束见 [PHYSICAL_DEPLOY.md](docs/PHYSICAL_DEPLOY.md)。
### 新 VPS 一键引导(环境变量,兼容旧用法)
> 若目标是 **家里物理机 / PVE Ubuntu,海外 VPS 只做 HTTPS**,不要用本节;请看 **[安装指南](docs/INSTALL.md)** / **[物理机部署](docs/PHYSICAL_DEPLOY.md)**。
在目标机器上以 root 执行(**先设好域名 DNS 与 TLS 证书**,脚本只加 vhost、不装 Caddy):
@ -65,11 +223,14 @@ bash scripts/bootstrap_vps.sh
```
可选环境变量见脚本头部注释:`APP_DIR`、`PUBLIC_BASE`、`WEB_PORT`、`API_PORT`、`PB_PORT`、`YT_PORT`、`S3_PORT` 等。
引导会生成 **`/etc/douyinweb.env`**(含 `SESSION_SECRET`、`S3_SECRET`),并创建 systemd 单元;**不会**打包或恢复 `monitor.db`(新装零房间,见仓库规则)。
引导会生成 **`/etc/douyinweb.env`**(含 `SESSION_SECRET`、`S3_SECRET`),并创建 systemd 单元;**不会**打包或恢复 `monitor.db`(新装零房间,见仓库规则)。缺省必填项时也会进入交互向导。
### 本机进程端口(默认)
应用进程绑定 **127.0.0.1**,由 Nginx / 宝塔反代对外;公网只暴露 443(及 WebRTC 等按需放行)。
| 形态 | 绑定 | 对外 |
|------|------|------|
| **纯 VPS** | 多为 `127.0.0.1` | 本机 Nginx / 宝塔 / Caddy → 公网 443 |
| **物理机** | **`0.0.0.0`** | 海外 VPS Caddy 经 WG 访问;公网 443 只在边缘 VPS |
| 服务 | 默认端口 | systemd 单元名 |
|------|----------|----------------|
@ -78,6 +239,8 @@ bash scripts/bootstrap_vps.sh
| PocketBase | `8092` | `douyinweb-pb` |
| youtube-svc | `8020` | `douyinweb-yt` |
| SeaweedFS S3 | `8333` | `douyinweb-s3` (+ master/volume/filer) |
| ShellCrash mixed / 面板(**物理机**) | `7890` / `9999` | ShellCrash 自带 |
| Neko Chrome(物理机,按实例) | `9200+(N-1)` HTTP;`52300+(N-1)` mux | Docker |
| Netdata(可选) | `19999` | `netdata` |
时区建议:`TZ=Asia/Shanghai`(界面与「北京日」配额逻辑使用北京时间)。
@ -148,14 +311,14 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
### YouTube Pro 转播(Douyin → YouTube RTMPS)
控制台 **`/youtube` → 分配**:按频道分组配置直播 KEY、精选抖音源、可选 **Neko 工作室**(Docker 内 Chrome 打开 YouTube Studio),由后台 **FFmpeg** 将抖音 FLV 转码后推到 YouTube RTMP/RTMPS。
控制台 **`/youtube` → 分配**:按已授权 Shorts 频道分组配置直播 KEY、精选抖音源、可选 **Neko 工作室**(Docker 内 Chrome 打开 YouTube Studio),由后台 **FFmpeg** 将抖音 FLV 转码后推到 YouTube RTMP/RTMPS。同一 `channel_pk` / `youtube_channel_id` 只能建一组;标题上传会剥离 `<>`(YouTube `invalidTitle`)。
| 概念 | 说明 |
|------|------|
| **自动推流** | 设置 `youtube_relay_enabled=true` 或 UI「自动推流」;Worker 约 7s 轮询 |
| **手动开始/停止** | 单频道「开始」= 武装监听(`manual_hold`),开播后自动推;「停止」释放 |
| **时间段模式** | `youtube_relay_time_slot_mode`;**与自动推流独立开关**。开启后:仅 **已配置 KEY 的 N 个频道** 按北京时 **24/N 小时** 轮播独占;**源 = 监控库当前在播抖音房**(非精选列表);非当前时段自动停 FFmpeg + Neko |
| **单频道独占** | 时间段模式强制开启;同一时刻仅一个分组推流 + 一个 Neko 运行 |
| **时间段模式** | `youtube_relay_time_slot_mode`;**与自动推流、单路独占独立**。开启后:有 KEY 的 N 个频道按北京时 **24/N** 轮播;**源 = 监控库当前在播抖音房**(非精选列表);非当前时段停 FFmpeg |
| **单路独占** | `youtube_relay_exclusive_live`(默认开,偏 VPS)。开:开播时只留一路 FFmpeg 并停兄弟 Neko。**物理机建议关**,可与时间段并用,Neko 常驻预热 |
| **画质预设** | `youtube_relay_quality_preset`(如 `720p`、`vps_ultra`);含分辨率、码率、AAC **128k** |
| **Cookie** | 解析拉流地址依赖 `dy_cookie`(同 sh2 `[Cookie]抖音cookie`);缺失时保持监听、不退出 Worker |
@ -382,16 +545,18 @@ python scripts\_deploy.py
- 多 Google 项目:Shorts 频道绑定 OAuth Client **A/B/C/D**,各 Client 独立计数、互不影响
- 实现:`backend/app/shorts_yt_quota.py`(按 Client 计数展示、429 识别);Shorts 页展示用量提示与接口错误,**禁止本地自设上传暂停**
## 全局 SOCKS5(sing-box + proxychains)
## 全局 SOCKS5(sing-box + proxychains)— 主要针对纯 VPS
> **文档状态**:以下为推荐生产架构(静态住宅 IP + 与 [mack-a/v2ray-agent](https://github.com/mack-a/v2ray-agent) 翻墙 sing-box **隔离共存**)。代码按此方案迭代;**当前仓库实现可能仍为「仅 Shorts 上传可选 SOCKS」**,以 `backend/app/shorts_socks.py` 为准。
> **形态**:本节是 **纯 VPS** 上「静态住宅 IP + 与 v2ray-agent 翻墙隔离」的规划。
> **物理机请用上一节「ShellCrash `:7890`」**,不要默认改成 `17891` sing-box。
> 代码仍在演进;以 `egress_hub` / `shellcrash_hub`(物理)与 `shorts_socks` / 规划中的 `douyinweb-singbox`(VPS)为准。
### 目标
| 开关 | 行为 |
| 开关 | 行为(纯 VPS) |
|------|------|
| **开启** | Shorts / 长视频 / TikTok / X / OAuth / Neko 浏览器 / FFmpeg 拉流与推流等业务出站,尽量统一走 **静态住宅 SOCKS5** |
| **关闭** | 停止 DouyinWEB 专用代理组件,**本机业务直连 VPS 出口**(不影响 v2ray-agent 翻墙) |
| **开启** | Shorts / 长视频 / TikTok / X / OAuth / Neko / FFmpeg 等尽量走 **静态住宅 SOCKS5**(经本机 mixed) |
| **关闭** | 停 DouyinWEB 专用代理组件,业务直连 **VPS 出口**(不影响 v2ray-agent 翻墙) |
设置页规划名称:**全局 SOCKS5**(不再叫「仅 Shorts 上传 SOCKS」)。
@ -564,7 +729,12 @@ proxychains4 -f /opt/douyinWEB/config/proxychains.conf \
| `DY_YOUTUBE_SVC_URL` | InnerTube sidecar,默认 `http://127.0.0.1:8020` |
| `DY_AUTH_ENABLED` | 站点登录,默认 `true`;本地调试可 `false` |
| `DY_API_KEY` | 非空时写操作需 `X-API-Key` |
| `DY_NEKO_NAT1TO1` | Neko WebRTC 对外 IP(留空则自动探测) |
| `DY_NEKO_NAT1TO1` | Neko WebRTC ICE 对外 IP;物理双边缘填**国内边缘公网 IP**;纯 VPS 填本机公网 IP;**勿**填 WG/`127.0.0.1`(留空仅作探测,失败则空) |
| `DY_NEKO_HTTP_BIND` | Neko HTTP 绑定;物理机 **`0.0.0.0`**;纯 VPS 可 `127.0.0.1` |
| `DY_NEKO_GATEWAY_ENABLED` | 默认 `false`;`true` 时走本机 `:9199` 路径网关(物理双边缘一般保持 `0`) |
| `DY_NEKO_MAX_INSTANCES` | 软上限,默认 `64`;须与边缘 `/neko/{1..N}` 发布容量一致 |
| `DY_NEKO_EDGE_UPSTREAM` | 生成 Caddy snippet 时的 WG 上游(例 `10.8.0.2`) |
| `DY_CORS_ORIGINS` | 逗号分隔公网 origin;双边缘须含 `${DOMAIN}` 与 `${DOMAIN_CN}` |
| `TZ` | 建议 `Asia/Shanghai` |
示例(**请替换占位符,勿照抄到生产**):

View File

@ -313,42 +313,43 @@ proxy-groups:
- type: select
name: 🚀 节点选择
proxies:
- 1d2da142-singbox_hysteria5
- 1d2da142-singbox_tuic5
- 1d2da142-VLESS_Reality_Vision5
- ⚡ 自动选择
- DIRECT
- REJECT
- ⚡ 自动选择
- proxycheap
- e3ea3b30-singbox_hysteria_vultr
- e3ea3b30-singbox_tuic_vultr
- e3ea3b30-VLESS_Reality_Vision_vultr
- 242af835-singbox_hysteria
- hackrobot-singbox_tuic
- VLESS_Reality_Vision
- 242af835-singbox_hysteria2
- hackrobot-singbox_tuic2
- VLESS_Reality_Vision2
- 1d2da142-singbox_hysteria5
- 1d2da142-VLESS_Reality_Vision5
- 1d2da142-singbox_tuic5
- e3ea3b30-singbox_hysteria_vultr
- e3ea3b30-VLESS_Reality_Vision_vultr
- e3ea3b30-singbox_tuic_vultr
- proxycheap
- socks5
- name: dialer
type: select
proxies:
- 1d2da142-singbox_hysteria5
- 1d2da142-singbox_tuic5
- 1d2da142-VLESS_Reality_Vision5
- e3ea3b30-singbox_hysteria_vultr
- e3ea3b30-singbox_tuic_vultr
- e3ea3b30-VLESS_Reality_Vision_vultr
- 242af835-singbox_hysteria
- hackrobot-singbox_tuic
- VLESS_Reality_Vision
- 242af835-singbox_hysteria2
- hackrobot-singbox_tuic2
- VLESS_Reality_Vision2
- 1d2da142-singbox_hysteria5
- 1d2da142-VLESS_Reality_Vision5
- 1d2da142-singbox_tuic5
- e3ea3b30-singbox_hysteria_vultr
- e3ea3b30-VLESS_Reality_Vision_vultr
- e3ea3b30-singbox_tuic_vultr
- name: ⚡ 自动选择
type: url-test
proxies:
- 1d2da142-singbox_tuic5
- 1d2da142-singbox_hysteria5
- 1d2da142-singbox_tuic5
- 1d2da142-VLESS_Reality_Vision5
- e3ea3b30-singbox_hysteria_vultr
- e3ea3b30-VLESS_Reality_Vision_vultr
@ -389,6 +390,14 @@ proxy-groups:
- ⚡ 自动选择
- 242af835-singbox_hysteria2
rules:
# 抖音必须直连(物理机家宽);经 ShellCrash/proxychains 时也由规则打回 DIRECT
- DOMAIN-SUFFIX,douyin.com,DIRECT
- DOMAIN-SUFFIX,douyincdn.com,DIRECT
- DOMAIN-SUFFIX,douyinpic.com,DIRECT
- DOMAIN-SUFFIX,douyinvod.com,DIRECT
- DOMAIN-SUFFIX,douyinstatic.com,DIRECT
- DOMAIN-SUFFIX,iesdouyin.com,DIRECT
- DOMAIN-KEYWORD,douyin,DIRECT
- RULE-SET,geolocation-cn,🔒 国内服务
- RULE-SET,geolocation-!cn,🌐 非中国
- RULE-SET,private,🏠 私有网络,no-resolve

View File

@ -66,6 +66,13 @@ class Settings(BaseSettings):
# Neko browser (per YouTube assign group) — US VPS direct, no ShellClash
neko_enabled: bool = True
neko_http_port_base: int = 9200
# Soft cap for docker compose / instance ids (keep ≤ edge Caddy/Nginx published /neko/N).
neko_max_instances: int = 64
# Path gateway :9199 — optional; dual-edge physical uses native Caddy/Nginx /neko/{id}.
neko_gateway_enabled: bool = False
neko_gateway_port: int = 9199
# 127.0.0.1 = VPS colocated; 0.0.0.0 = physical (reachable via WireGuard)
neko_http_bind: str = "127.0.0.1"
neko_webrtc_mux_base: int = 52300
neko_user_pass: str = "douyinweb"
neko_admin_pass: str = "Xiao4669805@"

View File

@ -365,6 +365,8 @@ def init_db() -> None:
("oauth_email", "TEXT NOT NULL DEFAULT ''"),
("yt_profile_json", "TEXT NOT NULL DEFAULT ''"),
("yt_profile_at", "REAL NOT NULL DEFAULT 0"),
("ypp_ok", "INTEGER NOT NULL DEFAULT -1"),
("ypp_checked_at", "REAL NOT NULL DEFAULT 0"),
]:
if col not in sc_cols:
conn.execute(f"ALTER TABLE shorts_channels ADD COLUMN {col} {ddl}")
@ -491,18 +493,15 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"shorts_yt_uploads_pt_count": 0,
# Shorts upload SOCKS5 (optional, default off — does not affect monitor)
"shorts_upload_socks_enabled": False,
"shorts_upload_socks_profile_id": "residential-1",
"shorts_upload_socks_profiles": [
{
"id": "residential-1",
"label": "静态住宅 IP",
"type": "socks5",
"server": "185.124.61.35",
"port": 43676,
"username": "V0sI3BsI1bxgKRx",
"password": "QGwGeRTAa9YcVhM",
}
],
"shorts_upload_socks_profile_id": "",
"shorts_upload_socks_profiles": [],
"global_socks_enabled": False,
"global_socks_profile_id": "",
"global_socks_profiles": [],
"egress_mode": "off",
"egress_cover_neko": True,
"egress_cover_relay": True,
"egress_cover_uploads": True,
# TikTok pipeline (fully isolated from Shorts)
"tiktok_enabled": False,
"tiktok_clip_sec": 75,
@ -649,7 +648,10 @@ def monitor_status_data(*, light: bool = False) -> dict[str, Any]:
cfg = _settings_map_from_conn(conn)
rooms = int(conn.execute("SELECT COUNT(*) AS c FROM rooms").fetchone()["c"] or 0)
live = int(
conn.execute("SELECT COUNT(*) AS c FROM rooms WHERE last_status = 'live'").fetchone()["c"] or 0
conn.execute(
"SELECT COUNT(*) AS c FROM rooms WHERE enabled = 1 AND last_status = 'live'"
).fetchone()["c"]
or 0
)
bl = int(conn.execute("SELECT COUNT(*) AS c FROM blacklist").fetchone()["c"] or 0)
events = int(conn.execute("SELECT COUNT(*) AS c FROM events").fetchone()["c"] or 0)
@ -1244,12 +1246,32 @@ def update_room(
new_clip = 0
if new_clip > 120:
new_clip = 120
now = time.time()
extra_sql = ""
extra_args: list[Any] = []
if enabled is False and int(row["enabled"] or 0) == 1:
extra_sql = ", last_status = 'offline'"
sid = str(row["active_session_id"] or "").strip()
if sid:
sess = conn.execute(
"SELECT * FROM sessions WHERE id = ? AND ended_at IS NULL", (sid,)
).fetchone()
if sess:
duration = max(0.0, now - float(sess["started_at"]))
conn.execute(
"""
UPDATE sessions SET ended_at = ?, duration_seconds = ?, status = 'ended',
end_reason = 'room_disabled', updated_at = ? WHERE id = ?
""",
(now, duration, now, sid),
)
extra_sql += ", active_session_id = ''"
conn.execute(
"""
UPDATE rooms SET url = ?, room_id = ?, note = ?, enabled = ?, tags = ?, clip_sec = ?, updated_at = ?
f"""
UPDATE rooms SET url = ?, room_id = ?, note = ?, enabled = ?, tags = ?, clip_sec = ?, updated_at = ?{extra_sql}
WHERE id = ?
""",
(new_url, new_rid, new_note, new_enabled, new_tags, new_clip, time.time(), room_pk),
(new_url, new_rid, new_note, new_enabled, new_tags, new_clip, now, room_pk),
)
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM rooms WHERE id = ?", (room_pk,)).fetchone()) # type: ignore
@ -1580,7 +1602,7 @@ def add_blacklist(value: str, reason: str = "") -> dict[str, Any]:
if not hit:
continue
conn.execute(
"UPDATE rooms SET enabled = 0, updated_at = ? WHERE id = ?",
"UPDATE rooms SET enabled = 0, last_status = 'offline', updated_at = ? WHERE id = ?",
(now, room["id"]),
)
disabled_ids.append(room["id"])
@ -3723,7 +3745,12 @@ def list_live_douyin_rooms_for_shorts(*, limit: int = 300) -> list[dict[str, Any
""",
(max(1, min(int(limit), 1000)),),
).fetchall()
return [_row_to_dict(r) for r in rows]
out: list[dict[str, Any]] = []
for r in rows:
item = _row_to_dict(r)
if item and not _is_blacklisted_conn(conn, str(item.get("room_id") or ""), str(item.get("url") or "")):
out.append(item)
return out
finally:
conn.close()

View File

@ -0,0 +1,147 @@
# -*- coding: utf-8 -*-
"""Unified Douyin live-URL ingest → rooms (直播池).
All UI surfaces that accept Douyin live URLs should call ensure_in_live_pool
so overview / monitor / live-map stay in sync with assign pools.
"""
from __future__ import annotations
import time
import uuid
from typing import Any, Optional
from .db import _connect, _is_blacklisted_conn, _lock, _row_to_dict
from .models import extract_room_id, normalize_room_url
def parse_douyin_line(raw: str) -> dict[str, str]:
"""Parse paste line → {url, title, room_id}. Reuses assign pool parser."""
from .yt_assign_db import parse_pool_line
return parse_pool_line(raw)
def ensure_in_live_pool_conn(
conn,
url: str,
*,
note: str = "",
title: str = "",
enabled: bool = True,
tags: str = "",
) -> dict[str, Any]:
"""Insert or soft-update a rooms row. Caller holds db._lock / open conn.
Returns {ok, created, skipped_blacklist, room, reason}.
"""
normalized = normalize_room_url(str(url or "").strip()) or str(url or "").strip()
rid = extract_room_id(normalized)
if not rid:
return {"ok": False, "created": False, "reason": "无法解析抖音直播间 URL / 房间号"}
blocked = _is_blacklisted_conn(conn, rid, normalized)
if blocked:
return {
"ok": False,
"created": False,
"skipped_blacklist": True,
"reason": f"黑名单:{blocked.get('reason') or blocked.get('value') or ''}",
}
label = (str(title or "").strip() or str(note or "").strip())[:120]
now = time.time()
existing = conn.execute(
"SELECT * FROM rooms WHERE room_id = ? OR url = ? LIMIT 1",
(rid, normalized),
).fetchone()
if existing:
row = _row_to_dict(existing) or {}
pk = str(row.get("id") or "")
cur_note = str(row.get("note") or "").strip()
cur_anchor = str(row.get("last_anchor") or "").strip()
new_note = cur_note or label
new_anchor = cur_anchor or label
# Kick monitor sooner so overview/live-map refresh.
conn.execute(
"""
UPDATE rooms SET
note = CASE WHEN TRIM(COALESCE(note, '')) = '' AND ? != '' THEN ? ELSE note END,
last_anchor = CASE WHEN TRIM(COALESCE(last_anchor, '')) = '' AND ? != '' THEN ? ELSE last_anchor END,
next_check_at = MIN(COALESCE(next_check_at, ?), ?),
updated_at = ?
WHERE id = ?
""",
(label, new_note, label, new_anchor, now, now, now, pk),
)
fresh = conn.execute("SELECT * FROM rooms WHERE id = ?", (pk,)).fetchone()
return {"ok": True, "created": False, "room": _row_to_dict(fresh), "reason": "exists"}
pk = str(uuid.uuid4())
conn.execute(
"""
INSERT INTO rooms(
id, url, room_id, note, enabled, last_status, last_anchor, tags,
created_at, updated_at, next_check_at
) VALUES (?, ?, ?, ?, ?, 'unknown', ?, ?, ?, ?, ?)
""",
(
pk,
normalized,
rid,
label,
1 if enabled else 0,
label,
tags or "",
now,
now,
now,
),
)
fresh = conn.execute("SELECT * FROM rooms WHERE id = ?", (pk,)).fetchone()
return {"ok": True, "created": True, "room": _row_to_dict(fresh), "reason": "created"}
def ensure_in_live_pool(
url: str,
*,
note: str = "",
title: str = "",
enabled: bool = True,
tags: Any = None,
) -> dict[str, Any]:
"""Public wrapper with lock — for API handlers outside assign txn."""
from .db import _normalize_tags
tags_s = _normalize_tags(tags) if tags is not None else ""
with _lock:
conn = _connect()
try:
result = ensure_in_live_pool_conn(
conn,
url,
note=note,
title=title,
enabled=enabled,
tags=tags_s,
)
conn.commit()
return result
finally:
conn.close()
def sync_pool_titles_from_anchor_conn(conn, room_id: str, anchor: str) -> int:
"""Fill empty yt_assign_pool_urls.title from rooms.last_anchor."""
rid = str(room_id or "").strip()
name = str(anchor or "").strip()[:120]
if not rid or not name:
return 0
cur = conn.execute(
"""
UPDATE yt_assign_pool_urls
SET title = ?, updated_at = ?
WHERE room_id = ? AND TRIM(COALESCE(title, '')) = ''
""",
(name, time.time(), rid),
)
return int(cur.rowcount or 0)

View File

@ -11,20 +11,32 @@ _CACHE: dict[str, Any] = {"at": 0.0, "payload": None, "key": ""}
_CACHE_TTL_SEC = 12.0
def _counts_as_live(row: dict[str, Any]) -> bool:
if not row.get("enabled", True):
return False
rid = str(row.get("room_id") or "").strip()
url = str(row.get("url") or "").strip()
if db.is_blacklisted(rid, url):
return False
return str(row.get("last_status") or "").strip() == "live"
def _entry(row: dict[str, Any]) -> dict[str, Any]:
status = str(row.get("last_status") or "unknown").strip() or "unknown"
rid = str(row.get("room_id") or "").strip()
url = str(row.get("url") or "").strip()
anchor = str(row.get("last_anchor") or row.get("note") or "").strip()
avatar = str(row.get("avatar_url") or "").strip()
live = _counts_as_live(row)
return {
"is_live": status == "live",
"last_status": status,
"is_live": live,
"last_status": "live" if live else (status if status != "live" else "offline"),
"anchor": anchor,
"url": url,
"avatar_url": avatar,
"last_checked_at": row.get("last_checked_at"),
"active_session_id": str(row.get("active_session_id") or ""),
"enabled": bool(row.get("enabled", True)),
}

461
backend/app/egress_hub.py Normal file
View File

@ -0,0 +1,461 @@
# -*- coding: utf-8 -*-
"""Business egress — always via ShellCrash on China physical hosts.
Correct model (虚空终端 dialer-proxy):
App → 127.0.0.1:7890 (ShellCrash mixed)
├─ 默认:选机场节点直接出海
└─ 勾选「住宅落地」:选 dy-residential(socks5 + dialer-proxy)
→ 先经 ShellCrash 前置节点拨号,再连住宅 SOCKS 落地
(家宽无法直连海外住宅 SOCKS)
Docs: https://wiki.metacubex.one/config/proxies/dialer-proxy/
"""
from __future__ import annotations
import shutil
import subprocess
import time
from pathlib import Path
from typing import Any
from .config import BACKEND, ROOT
from .global_socks import CONFIG_DIR
MODES = ("off", "shellcrash")
PROXYCHAINS_CONF = CONFIG_DIR / "proxychains.conf"
RESIDENTIAL_PROXY_NAME = "dy-residential"
DEFAULT_DIALER = "dialer"
_MODE_KEY = "egress_mode"
_CHAIN_KEY = "egress_chain_residential"
_NEKO_KEY = "egress_cover_neko"
_RELAY_KEY = "egress_cover_relay"
_UPLOADS_KEY = "egress_cover_uploads"
def _settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
if cfg is not None:
return dict(cfg)
from . import db
return dict(db.get_settings_map())
def get_mode(cfg: dict[str, Any] | None = None) -> str:
s = _settings(cfg)
raw = str(s.get(_MODE_KEY) or "").strip().lower()
# Legacy: "residential" meant chain-on ShellCrash, never direct SOCKS.
if raw == "residential":
return "shellcrash"
if raw in MODES:
return raw
if s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"):
return "shellcrash"
# Default ON for China physical: all non-Douyin business via ShellCrash.
# Explicit "off" in settings still wins (handled above via MODES).
return "shellcrash"
def google_http_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT via Clash rules.
- shellcrash mode → mixed :7890
- mode off but ShellCrash still running → still use it (physical soft path)
- mode off + no ShellCrash → empty string (pure VPS direct)
"""
if get_mode(cfg) == "shellcrash":
return _host_http_proxy(cfg)
try:
from . import shellcrash_hub
st = shellcrash_hub.status() or {}
if st.get("running"):
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
except Exception:
pass
return ""
def google_httpx_kwargs(*, timeout: float = 45.0, cfg: dict[str, Any] | None = None) -> dict[str, Any]:
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
proxy = google_http_proxy(cfg)
if proxy:
kw["proxy"] = proxy
return kw
# Alias — overseas APIs (TikTok Open API, etc.) share the same egress.
overseas_httpx_kwargs = google_httpx_kwargs
overseas_http_proxy = google_http_proxy
def chain_residential(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _CHAIN_KEY in s:
return bool(s.get(_CHAIN_KEY))
# Legacy residential mode / socks toggle → chain on
raw = str(s.get(_MODE_KEY) or "").strip().lower()
if raw == "residential":
return True
return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"))
def cover_neko(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _NEKO_KEY in s:
return bool(s.get(_NEKO_KEY))
return get_mode(s) != "off"
def cover_relay(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _RELAY_KEY in s:
return bool(s.get(_RELAY_KEY))
return get_mode(s) == "shellcrash"
def cover_uploads(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _UPLOADS_KEY in s:
return bool(s.get(_UPLOADS_KEY))
return get_mode(s) != "off"
def shellcrash_mixed_port(cfg: dict[str, Any] | None = None) -> int:
try:
from . import shellcrash_hub
st = shellcrash_hub.status()
port = int(st.get("mixed_port") or 7890)
return port if port > 0 else 7890
except Exception:
return 7890
def _host_http_proxy(cfg: dict[str, Any] | None = None) -> str:
if get_mode(cfg) != "shellcrash":
return ""
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
def resolve_http_proxy(cfg: dict[str, Any] | None = None) -> str:
if get_mode(cfg) == "off":
return ""
return _host_http_proxy(cfg)
def resolve_upload_proxy(cfg: dict[str, Any] | None = None) -> str:
if get_mode(cfg) == "off" or not cover_uploads(cfg):
return ""
return _host_http_proxy(cfg)
def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Chromium inside Neko → host ShellCrash.
Physical (DY_NEKO_EDGE_UPSTREAM set): always inject proxy unless egress mode is explicit off.
"""
import os
physical = bool(str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip())
if get_mode(cfg) == "off":
return ""
if not cover_neko(cfg) and not physical:
return ""
return f"http://host.docker.internal:{shellcrash_mixed_port(cfg)}"
def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path:
"""Always point proxychains at ShellCrash mixed SOCKS — never raw residential."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
if get_mode(cfg) != "shellcrash":
PROXYCHAINS_CONF.write_text(
"# egress off\nstrict_chain\nproxy_dns\n[ProxyList]\n",
encoding="utf-8",
)
return PROXYCHAINS_CONF
port = shellcrash_mixed_port(cfg)
text = (
"strict_chain\n"
"proxy_dns\n"
"tcp_read_time_out 15000\n"
"tcp_connect_time_out 8000\n"
"localnet 127.0.0.0/8\n"
"localnet 10.0.0.0/8\n"
"localnet 192.168.0.0/16\n"
"[ProxyList]\n"
f"socks5 127.0.0.1 {port}\n"
)
PROXYCHAINS_CONF.write_text(text, encoding="utf-8")
return PROXYCHAINS_CONF
def proxychains_bin() -> str:
return shutil.which("proxychains4") or shutil.which("proxychains") or ""
def wrap_ffmpeg_cmd(cmd: list[str], cfg: dict[str, Any] | None = None) -> list[str]:
if get_mode(cfg) == "off" or not cover_relay(cfg):
return list(cmd)
pc = proxychains_bin()
if not pc:
return list(cmd)
write_proxychains_conf(cfg)
return [pc, "-q", "-f", str(PROXYCHAINS_CONF), *cmd]
def ffmpeg_uses_proxy(cfg: dict[str, Any] | None = None) -> bool:
return get_mode(cfg) != "off" and cover_relay(cfg) and bool(proxychains_bin())
def apply_mode(
mode: str,
*,
chain: bool | None = None,
cover_neko_flag: bool | None = None,
cover_relay_flag: bool | None = None,
cover_uploads_flag: bool | None = None,
refresh_neko: bool = True,
dialer: str | None = None,
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
from . import db
from . import shellcrash_hub
from . import singbox_manager
raw = str(mode or "off").strip().lower()
if raw == "residential":
mode = "shellcrash"
if chain is None:
chain = True
elif raw not in MODES:
raise ValueError(f"unsupported egress mode: {raw}")
else:
mode = raw
s = _settings(cfg)
if chain is None:
chain = chain_residential(s) if mode == "shellcrash" else False
chain = bool(chain) and mode == "shellcrash"
if cover_neko_flag is None:
cover_neko_flag = mode != "off"
if cover_relay_flag is None:
cover_relay_flag = mode == "shellcrash"
if cover_uploads_flag is None:
cover_uploads_flag = mode != "off"
updates: dict[str, Any] = {
_MODE_KEY: mode,
_CHAIN_KEY: chain,
_NEKO_KEY: bool(cover_neko_flag),
_RELAY_KEY: bool(cover_relay_flag),
_UPLOADS_KEY: bool(cover_uploads_flag),
# Keep legacy flags aligned with «住宅链式» checkbox only (not a separate engine).
"global_socks_enabled": chain,
"shorts_upload_socks_enabled": chain,
}
db.update_settings_map(updates)
s = db.get_settings_map()
# Never run douyinweb-singbox as China residential path — stop if leftover.
try:
singbox_manager.stop()
except Exception:
pass
chain_result: dict[str, Any] = {"skipped": True}
if mode == "shellcrash":
if chain:
from . import global_socks
prof = global_socks.active_profile(s)
if not prof:
raise ValueError("已勾选住宅落地,但未配置 SOCKS5 账号(在下方业务 SOCKS 填写)")
chain_result = shellcrash_hub.apply_residential_chain(
prof,
dialer=(dialer or DEFAULT_DIALER).strip() or DEFAULT_DIALER,
)
else:
# Normal ShellCrash node (not residential landing).
try:
chain_result = shellcrash_hub.apply_profile(
shellcrash_hub.DEFAULT_PROFILE,
shellcrash_hub.DEFAULT_NODE,
)
except Exception as exc:
chain_result = {"ok": False, "error": str(exc)}
pc_path = ""
if mode == "shellcrash" and (cover_relay_flag or cover_uploads_flag):
pc_path = str(write_proxychains_conf(s))
neko_result: dict[str, Any] = {"skipped": True}
if refresh_neko:
try:
from . import youtube_neko
neko_result = youtube_neko.refresh_compose_for_egress()
except Exception as exc:
neko_result = {"ok": False, "error": str(exc)}
return {
"ok": True,
"egress": status(s),
"chain": chain_result,
"proxychains_conf": pc_path,
"neko": neko_result,
}
def probe(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
mode = get_mode(cfg)
proxy = _host_http_proxy(cfg) if mode != "off" else ""
targets = [
("google", "https://www.google.com/generate_204"),
("youtube", "https://www.youtube.com/"),
("douyin", "https://www.douyin.com/"),
]
rows = []
for name, url in targets:
# Douyin: always probe DIRECT; also via proxy to show rule should still work for pull via ShellCrash
if name == "douyin":
rows.append(_curl_probe("douyin_direct", url, proxy=""))
if proxy:
rows.append(_curl_probe("douyin_via_sc", url, proxy=proxy))
continue
rows.append(_curl_probe(name, url, proxy=proxy))
rows.append(_curl_probe(f"{name}_direct", url, proxy=""))
return {
"ok": True,
"mode": mode,
"chain_residential": chain_residential(cfg),
"proxy": proxy,
"probes": rows,
"policy": {"douyin": "DIRECT", "domains": ["*.douyin.com", "*.douyincdn.com", "…"]},
"at": int(time.time()),
}
def _curl_probe(name: str, url: str, *, proxy: str) -> dict[str, Any]:
cmd = ["curl", "-sS", "-m", "10", "-o", "/dev/null", "-w", "%{http_code}"]
if proxy:
cmd.extend(["-x", proxy])
cmd.append(url)
t0 = time.time()
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=14, check=False)
code = (p.stdout or "").strip() or "000"
ok = code in {"200", "204", "301", "302"}
return {
"target": name,
"ok": ok,
"http_code": code,
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"error": (p.stderr or "").strip()[:160] if not ok else "",
}
except Exception as exc:
return {
"target": name,
"ok": False,
"http_code": "000",
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"error": str(exc)[:160],
}
def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
from . import shellcrash_hub
s = _settings(cfg)
mode = get_mode(s)
chain = chain_residential(s) if mode == "shellcrash" else False
sc = shellcrash_hub.status()
host_proxy = _host_http_proxy(s)
neko_proxy = neko_browser_proxy(s)
pc = proxychains_bin()
exit_label = RESIDENTIAL_PROXY_NAME if chain else (sc.get("selected_node") or shellcrash_hub.DEFAULT_NODE)
return {
"mode": mode,
"chain_residential": chain,
"modes": [
{"id": "off", "label": "直连", "description": "不经 ShellCrash"},
{
"id": "shellcrash",
"label": "ShellCrash",
"description": "业务统一走本机 :7890;可选住宅链式落地",
"ready": bool(sc.get("running") or sc.get("installed")),
},
],
"cover": {
"neko": cover_neko(s),
"relay": cover_relay(s),
"uploads": cover_uploads(s),
},
"host_proxy": host_proxy,
"neko_proxy": neko_proxy,
"exit_node": exit_label,
"dialer": DEFAULT_DIALER,
"residential_proxy_name": RESIDENTIAL_PROXY_NAME,
"socks_url": f"socks5://127.0.0.1:{shellcrash_mixed_port(s)}" if mode == "shellcrash" else "",
"proxychains": {
"installed": bool(pc),
"bin": pc,
"conf": str(PROXYCHAINS_CONF) if PROXYCHAINS_CONF.is_file() else "",
"relay_active": ffmpeg_uses_proxy(s),
},
"shellcrash": {
"running": bool(sc.get("running")),
"mixed_port": sc.get("mixed_port") or "7890",
"selected_node": sc.get("selected_node"),
},
"matrix": [
{
"id": "neko",
"label": "Neko Chrome",
"active": bool(neko_proxy),
"detail": (neko_proxy + (f" → {exit_label}" if chain else "")) if neko_proxy else "直连",
},
{
"id": "relay",
"label": "直播推流 FFmpeg",
"active": ffmpeg_uses_proxy(s),
"detail": (
f"proxychains → ShellCrash → {exit_label}"
if ffmpeg_uses_proxy(s)
else ("缺 proxychains" if cover_relay(s) and not pc else "直连")
),
},
{
"id": "uploads",
"label": "Shorts / 长视频 / 上传",
"active": bool(resolve_upload_proxy(s)),
"detail": (host_proxy + (f" → {exit_label}" if chain else "")) if resolve_upload_proxy(s) else "直连",
},
],
"hints": _hints(mode, chain, sc, pc),
"app_root": str(ROOT),
"backend": str(BACKEND),
}
def _hints(mode: str, chain: bool, sc: dict[str, Any], pc: str) -> list[str]:
out: list[str] = []
if mode == "shellcrash":
out.append("硬规则:*.douyin.com / 抖音 CDN 必须 DIRECT(拉流与监控不可走机场)")
if mode == "shellcrash" and not sc.get("running"):
out.append("ShellCrash 未运行 — 先启动,再应用出海")
if mode == "shellcrash" and chain:
out.append(
"住宅落地 = ShellCrash 链式(dialer-proxy):家宽 → 前置节点 → 住宅 SOCKS。"
"详见虚空终端 docs:dialer-proxy"
)
if mode == "shellcrash" and not chain:
out.append("当前用 ShellCrash 机场线路出海;勾选「住宅落地」才会链式到 SOCKS5")
if mode != "off" and not pc:
out.append("未安装 proxychains4 — 直播推流无法走代理")
if mode == "off":
out.append("直连:国内物理机上 YouTube Studio / 推流通常不可用")
return out

291
backend/app/global_socks.py Normal file
View File

@ -0,0 +1,291 @@
# -*- coding: utf-8 -*-
"""Global SOCKS5 via local sing-box mixed inbound (Linux best practice).
Architecture:
App / FFmpeg / Neko / httpx → 127.0.0.1:MIXED_PORT (HTTP+SOCKS)
↓ sing-box
remote static residential SOCKS5
When disabled: sing-box stopped, no proxy env injected — direct egress.
"""
from __future__ import annotations
import uuid
from typing import Any
from urllib.parse import quote
from .config import BACKEND
DEFAULT_PROFILE_ID = "residential-1"
LOCAL_MIXED_HOST = "127.0.0.1"
LOCAL_MIXED_PORT = 17891
CONFIG_DIR = BACKEND.parent / "config"
SINGBOX_CONFIG_PATH = CONFIG_DIR / "sing-box.json"
DEFAULT_PROFILES: list[dict[str, Any]] = []
# Fresh installs start with zero SOCKS profiles — operators add their own.
# Never ship another project's residential credentials here.
# Legacy DB keys kept in sync on save.
_LEGACY_ENABLED_KEY = "shorts_upload_socks_enabled"
_LEGACY_PROFILE_ID_KEY = "shorts_upload_socks_profile_id"
_LEGACY_PROFILES_KEY = "shorts_upload_socks_profiles"
_ENABLED_KEY = "global_socks_enabled"
_PROFILE_ID_KEY = "global_socks_profile_id"
_PROFILES_KEY = "global_socks_profiles"
def _norm_profile(raw: Any) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
pid = str(raw.get("id") or "").strip() or str(uuid.uuid4())
server = str(raw.get("server") or "").strip()
try:
port = int(raw.get("port") or 0)
except Exception:
port = 0
ptype = str(raw.get("type") or "socks5").strip().lower() or "socks5"
if ptype not in {"socks5", "socks5h"}:
ptype = "socks5"
return {
"id": pid,
"label": str(raw.get("label") or server or pid).strip() or pid,
"type": ptype,
"server": server,
"port": port,
"username": str(raw.get("username") or ""),
"password": str(raw.get("password") or ""),
}
def _settings_dict(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
if cfg is not None:
return dict(cfg)
from . import db
return dict(db.get_settings_map())
def is_global_socks_enabled(cfg: dict[str, Any] | None = None) -> bool:
settings = _settings_dict(cfg)
if settings.get(_ENABLED_KEY) is not None:
return bool(settings.get(_ENABLED_KEY))
return bool(settings.get(_LEGACY_ENABLED_KEY))
def list_socks_profiles(cfg: dict[str, Any] | None = None, *, public: bool = False) -> list[dict[str, Any]]:
settings = _settings_dict(cfg)
raw = settings.get(_PROFILES_KEY)
if not isinstance(raw, list) or not raw:
raw = settings.get(_LEGACY_PROFILES_KEY)
rows: list[dict[str, Any]] = []
if isinstance(raw, list):
for item in raw:
p = _norm_profile(item)
if p and p["server"] and p["port"] > 0:
rows.append(p)
if not rows:
rows = [dict(x) for x in DEFAULT_PROFILES]
if not public:
return rows
out = []
for p in rows:
pwd = str(p.get("password") or "")
q = dict(p)
q["has_password"] = bool(pwd.strip())
q["password"] = ("***" + pwd[-4:]) if len(pwd) > 4 else ("***" if pwd else "")
out.append(q)
return out
def get_socks_profile(profile_id: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
pid = str(profile_id or "").strip()
for p in list_socks_profiles(cfg, public=False):
if str(p.get("id") or "") == pid:
return p
return None
def active_profile_id(cfg: dict[str, Any] | None = None) -> str:
settings = _settings_dict(cfg)
pid = str(settings.get(_PROFILE_ID_KEY) or settings.get(_LEGACY_PROFILE_ID_KEY) or "").strip()
if pid:
return pid
rows = list_socks_profiles(cfg, public=False)
if rows:
return str(rows[0].get("id") or "").strip()
return ""
def active_profile(cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
prof = get_socks_profile(active_profile_id(cfg), cfg)
if prof:
return prof
rows = list_socks_profiles(cfg, public=False)
return rows[0] if rows else None
def upstream_socks_url(profile: dict[str, Any] | None) -> str:
"""Direct socks5h URL to residential provider (sing-box upstream)."""
if not profile:
return ""
server = str(profile.get("server") or "").strip()
try:
port = int(profile.get("port") or 0)
except Exception:
port = 0
if not server or port <= 0:
return ""
user = str(profile.get("username") or "")
pwd = str(profile.get("password") or "")
if user or pwd:
return f"socks5h://{quote(user, safe='')}:{quote(pwd, safe='')}@{server}:{port}"
return f"socks5h://{server}:{port}"
def local_mixed_url() -> str:
"""Local sing-box mixed inbound — preferred for httpx / curl / ffmpeg -http_proxy."""
return f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}"
def local_socks_url() -> str:
return f"socks5://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}"
def resolve_app_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Return local mixed proxy URL when global SOCKS is on and sing-box is up; else ''."""
if not is_global_socks_enabled(cfg):
return ""
from . import singbox_manager
if not singbox_manager.is_running():
# Best-effort start (settings save should have started it already).
try:
singbox_manager.apply_from_settings(cfg)
except Exception:
pass
if singbox_manager.is_running():
return local_mixed_url()
# Fallback: direct socks5h if sing-box binary missing.
return upstream_socks_url(active_profile(cfg))
def httpx_proxy(cfg: dict[str, Any] | None = None) -> str | None:
url = resolve_app_proxy(cfg)
return url or None
def requests_proxies(cfg: dict[str, Any] | None = None) -> dict[str, str]:
url = resolve_app_proxy(cfg)
if not url:
return {}
return {"http": url, "https": url}
def subprocess_env(cfg: dict[str, Any] | None = None, base: dict[str, str] | None = None) -> dict[str, str]:
"""Linux convention: ALL_PROXY / HTTP_PROXY / HTTPS_PROXY for child processes."""
env = dict(base or {})
url = resolve_app_proxy(cfg)
if not url:
for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
env.pop(key, None)
return env
env["HTTP_PROXY"] = url
env["HTTPS_PROXY"] = url
env["ALL_PROXY"] = local_socks_url()
env["http_proxy"] = url
env["https_proxy"] = url
env["all_proxy"] = local_socks_url()
# Never proxy loopback / local services.
no_proxy = "127.0.0.1,localhost,::1"
env["NO_PROXY"] = no_proxy
env["no_proxy"] = no_proxy
return env
def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Chromium proxy for Neko containers — delegates to egress_hub."""
try:
from . import egress_hub
return egress_hub.neko_browser_proxy(cfg)
except Exception:
return resolve_app_proxy(cfg) if is_global_socks_enabled(cfg) else ""
def merge_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
existing = {str(p["id"]): p for p in list_socks_profiles(existing_cfg, public=False)}
out: list[dict[str, Any]] = []
if not isinstance(incoming, list):
return list(existing.values()) or [dict(x) for x in DEFAULT_PROFILES]
# Explicit empty list clears all profiles (fresh install / wipe).
if len(incoming) == 0:
return []
for item in incoming:
p = _norm_profile(item)
if not p:
continue
pid = str(p["id"])
old = existing.get(pid) or {}
pwd = str(p.get("password") or "")
if (not pwd.strip()) or pwd.startswith("***"):
p["password"] = str(old.get("password") or "")
if not p["server"] or int(p.get("port") or 0) <= 0:
continue
out.append(p)
return out or [dict(x) for x in DEFAULT_PROFILES]
def normalize_settings_patch(patch: dict[str, Any], existing: dict[str, Any] | None = None) -> dict[str, Any]:
"""Sync global + legacy keys; apply sing-box when toggled."""
out = dict(patch)
ex = dict(existing or {})
# Accept either global_* or legacy shorts_upload_socks_* from UI.
if "global_socks_enabled" in out:
out[_LEGACY_ENABLED_KEY] = bool(out["global_socks_enabled"])
elif _LEGACY_ENABLED_KEY in out:
out["global_socks_enabled"] = bool(out[_LEGACY_ENABLED_KEY])
if "global_socks_profile_id" in out:
out[_LEGACY_PROFILE_ID_KEY] = str(out["global_socks_profile_id"] or "")
elif _LEGACY_PROFILE_ID_KEY in out:
out["global_socks_profile_id"] = str(out[_LEGACY_PROFILE_ID_KEY] or "")
if "global_socks_profiles" in out:
merged = merge_profiles_patch(out.get("global_socks_profiles"), ex)
out["global_socks_profiles"] = merged
out[_LEGACY_PROFILES_KEY] = merged
elif _LEGACY_PROFILES_KEY in out:
merged = merge_profiles_patch(out.get(_LEGACY_PROFILES_KEY), ex)
out["global_socks_profiles"] = merged
out[_LEGACY_PROFILES_KEY] = merged
return out
def apply_runtime(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
from . import singbox_manager
return singbox_manager.apply_from_settings(cfg)
def public_settings(cfg: dict[str, Any]) -> dict[str, Any]:
from . import singbox_manager
enabled = is_global_socks_enabled(cfg)
st = singbox_manager.status()
return {
"global_socks_enabled": enabled,
"global_socks_profile_id": active_profile_id(cfg),
"global_socks_profiles": list_socks_profiles(cfg, public=True),
"global_socks_local_mixed": local_mixed_url(),
"global_socks_engine": "sing-box",
"global_socks_running": bool(st.get("running")),
"global_socks_error": str(st.get("error") or ""),
# Legacy aliases for older UI / API clients.
"shorts_upload_socks_enabled": enabled,
"shorts_upload_socks_profile_id": active_profile_id(cfg),
"shorts_upload_socks_profiles": list_socks_profiles(cfg, public=True),
}

View File

@ -19,7 +19,7 @@ if sys.platform == "win32":
except Exception:
pass
from fastapi import FastAPI, HTTPException, Query, Request, WebSocket, WebSocketDisconnect
from fastapi import Body, FastAPI, HTTPException, Query, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
@ -143,6 +143,18 @@ async def lifespan(_: FastAPI):
if not _desktop_light:
asyncio.create_task(_live_map_refresh_loop())
async def _studio_cdp_poll_loop() -> None:
"""Host-side CDP backup for YouTube Studio on-air + minute reports (never restarts Chrome)."""
try:
await youtube_neko.studio_cdp_poll_loop()
except asyncio.CancelledError:
raise
except Exception:
pass
if not _desktop_light:
asyncio.create_task(_studio_cdp_poll_loop())
async def _ops_background_loops() -> None:
if _desktop_light:
return
@ -181,13 +193,32 @@ async def lifespan(_: FastAPI):
await _boot("youtube_relay", youtube_relay_pipeline.start)
async def _neko_boot() -> None:
groups = await asyncio.to_thread(yt_assign_db.list_groups, False)
await asyncio.to_thread(youtube_neko.sync_for_groups, groups)
try:
from . import neko_edge_gateway
await neko_edge_gateway.start_gateway()
except Exception as exc:
db.add_event(
kind="ops",
level="warn",
message=f"Neko 边缘网关启动失败:{str(exc)[:160]}",
)
groups = await asyncio.to_thread(yt_assign_db.list_groups, include_urls=False)
# Physical keep-warm: never stop already-running Studio browsers on API boot.
await asyncio.to_thread(
lambda: youtube_neko.sync_for_groups(groups, reconcile_running=False)
)
await _boot("neko", _neko_boot)
asyncio.create_task(_start_workers())
yield
try:
from . import neko_edge_gateway
await neko_edge_gateway.stop_gateway()
except Exception:
pass
try:
await youtube_relay_pipeline.stop()
except Exception:
@ -569,21 +600,35 @@ def _public_settings(cfg: dict[str, Any]) -> dict[str, Any]:
return out
def _host_is_private(host: str) -> bool:
h = (host or "").split(",")[0].strip().split(":")[0].lower()
if not h or h in {"localhost", "127.0.0.1", "::1"}:
return True
if h.startswith("10.") or h.startswith("192.168.") or h.startswith("172."):
return True
return False
def _request_public_base(request: Request) -> str:
"""Prefer reverse-proxy headers for OAuth redirect base (whichever host user opened)."""
"""Public HTTPS origin for OAuth redirects.
Prefer DY_PUBLIC_BASE_URL when the request Host is loopback / WG private
(physical edge: API sees 10.8.0.2 or 127.0.0.1 without proper Host header).
"""
pub = str(settings.public_base_url or "").strip().rstrip("/")
proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "https").split(",")[0].strip()
host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "").split(",")[0].strip()
if host:
# strip port from Host if present for standard :443
if host.endswith(":443") and proto == "https":
host = host[:-4]
elif host.endswith(":80") and proto == "http":
host = host[:-3]
return f"{proto}://{host}"
pub = str(settings.public_base_url or "").strip().rstrip("/")
if pub:
return pub
return ""
if _host_is_private(host):
if pub:
return pub
else:
return f"{proto}://{host}"
return pub or ""
def _enrich_shorts_job(
@ -714,7 +759,11 @@ async def shorts_live_analytics(
row["authorized"] = bool(str(ch.get("refresh_token") or "").strip())
row["oauth_ok"] = ch.get("oauth_ok")
row["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper()
row["ypp_ok"] = ypp_by_shorts.get(pk, -1)
try:
sc_ypp = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1)
except Exception:
sc_ypp = -1
row["ypp_ok"] = sc_ypp if sc_ypp in (0, 1) else ypp_by_shorts.get(pk, -1)
enriched.append(row)
channels = enriched
except Exception:
@ -771,6 +820,9 @@ async def shorts_oauth_callback(
handle = quote(str(result.get("youtube_handle") or ""))
ret = str(result.get("return_to") or "").strip()
extra = f"&title={title}" + (f"&handle={handle}" if handle else "")
dup = str(result.get("duplicate_channel_warning") or "").strip()
if dup:
extra += f"&dup=1&dup_msg={quote(dup[:240])}"
if ret:
sep = "&" if "?" in ret else "?"
return RedirectResponse(f"{base}{ret}{sep}oauth=ok{extra}", status_code=302)
@ -778,10 +830,16 @@ async def shorts_oauth_callback(
except Exception as exc:
ret = str(request.query_params.get("return_to") or "").strip()
msg = quote(str(exc)[:320])
# Best-effort: stamp error on channel if state still maps (popped already inside exchange).
try:
# state already consumed; error text is enough in redirect query
pass
except Exception:
pass
if ret and ret.startswith("/") and not ret.startswith("//"):
sep = "&" if "?" in ret else "?"
return RedirectResponse(f"{base}{ret}{sep}oauth=error&msg={msg}", status_code=302)
return RedirectResponse(f"{base}/shorts?oauth=error&msg={quote(str(exc)[:320])}", status_code=302)
return RedirectResponse(f"{base}/shorts?oauth=error&msg={msg}", status_code=302)
@app.post("/api/shorts/start")
@ -3092,7 +3150,7 @@ async def youtube_relay_session_detail(session_id: int) -> dict[str, Any]:
@app.get("/api/youtube/neko/status")
async def youtube_neko_status() -> dict[str, Any]:
"""Read-only Neko status — no compose/nginx sync (avoids 12s poll thrash)."""
groups = await asyncio.to_thread(yt_assign_db.list_groups, False)
groups = await asyncio.to_thread(yt_assign_db.list_groups, include_urls=False)
ids = [int(g.get("neko_instance_id") or 0) for g in groups]
desired = max(ids) if ids else 0
return await asyncio.to_thread(youtube_neko.status_summary, desired=desired)
@ -3135,6 +3193,9 @@ async def youtube_assign_group_neko(group_id: str, body: dict[str, Any] | None =
if action in {"start", "stop", "restart"}:
if action == "start" and not g.get("neko_enabled"):
g = yt_assign_db.update_group(group_id, neko_enabled=True)
elif action == "stop" and g.get("neko_enabled") and "enabled" not in body:
# Persist stop so boot/restore does not revive the container.
g = yt_assign_db.update_group(group_id, neko_enabled=False)
try:
neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, action)
except (ValueError, RuntimeError) as exc:
@ -3687,6 +3748,287 @@ async def clash_catalog() -> dict[str, Any]:
return await _db(clash_dl.catalog)
@app.get("/api/network")
async def network_hub_status() -> dict[str, Any]:
"""WireGuard / FRP / ShellCrash / SOCKS overview (SH2-adapted controls)."""
from . import network_hub
return await asyncio.to_thread(network_hub.network_overview)
@app.get("/api/network/socks")
async def network_socks_get() -> dict[str, Any]:
from . import network_hub
return await asyncio.to_thread(network_hub.socks_status)
@app.patch("/api/network/socks")
async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]:
"""Update global SOCKS profiles — empty list allowed (fresh install)."""
from . import db
from . import global_socks
from . import singbox_manager
cfg = await asyncio.to_thread(db.get_settings_map)
updates: dict[str, Any] = {}
if "enabled" in body:
updates["global_socks_enabled"] = bool(body.get("enabled"))
updates["shorts_upload_socks_enabled"] = bool(body.get("enabled"))
# 住宅 SOCKS 勾选 = ShellCrash 链式落地,不是独立引擎
updates["egress_chain_residential"] = bool(body.get("enabled"))
if bool(body.get("enabled")):
updates["egress_mode"] = "shellcrash"
elif str(cfg.get("egress_mode") or "") == "residential":
updates["egress_mode"] = "shellcrash"
if "active_profile_id" in body:
updates["global_socks_profile_id"] = str(body.get("active_profile_id") or "").strip()
updates["shorts_upload_socks_profile_id"] = updates["global_socks_profile_id"]
if "profiles" in body:
raw = body.get("profiles")
rows = []
if isinstance(raw, list):
for item in raw:
p = global_socks._norm_profile(item)
if p and p["server"] and p["port"] > 0:
# Keep existing password if client sent masked ***
old = global_socks.get_socks_profile(str(p["id"]), cfg)
pwd = str(p.get("password") or "")
if old and (not pwd or pwd.startswith("***")):
p["password"] = str(old.get("password") or "")
rows.append(p)
updates["global_socks_profiles"] = rows
updates["shorts_upload_socks_profiles"] = rows
if updates:
await asyncio.to_thread(db.update_settings_map, updates)
cfg = await asyncio.to_thread(db.get_settings_map)
try:
await asyncio.to_thread(singbox_manager.apply_from_settings, cfg)
except Exception:
pass
from . import network_hub
return await asyncio.to_thread(network_hub.socks_status)
@app.get("/api/network/egress")
async def network_egress_get() -> dict[str, Any]:
from . import egress_hub
return {"ok": True, "egress": await asyncio.to_thread(egress_hub.status)}
@app.patch("/api/network/egress")
async def network_egress_patch(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
from . import egress_hub
mode = str(body.get("mode") or "").strip().lower()
if not mode:
raise HTTPException(status_code=400, detail="mode required")
cover = body.get("cover") if isinstance(body.get("cover"), dict) else {}
chain = body.get("chain_residential")
if chain is None:
chain = body.get("chain")
try:
result = await asyncio.to_thread(
egress_hub.apply_mode,
mode,
chain=None if chain is None else bool(chain),
cover_neko_flag=cover.get("neko") if "neko" in cover else body.get("cover_neko"),
cover_relay_flag=cover.get("relay") if "relay" in cover else body.get("cover_relay"),
cover_uploads_flag=cover.get("uploads") if "uploads" in cover else body.get("cover_uploads"),
refresh_neko=bool(body.get("refresh_neko", True)),
dialer=str(body.get("dialer") or "") or None,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return result
@app.post("/api/network/egress/probe")
async def network_egress_probe() -> dict[str, Any]:
from . import egress_hub
return await asyncio.to_thread(egress_hub.probe)
@app.get("/api/network/wireguard/status")
async def network_wireguard_status() -> dict[str, Any]:
from . import wireguard_hub
return {"ok": True, "wireguard": await asyncio.to_thread(wireguard_hub.runtime_status)}
@app.post("/api/network/wireguard/save")
async def network_wireguard_save(body: dict[str, Any]) -> dict[str, Any]:
"""Import WireGuard conf (default overlay — strip 0.0.0.0/0). apply=true installs + starts."""
from . import wireguard_hub
content = str(body.get("content") or "")
name = str(body.get("name") or wireguard_hub.PREFERRED_IFACE).strip() or wireguard_hub.PREFERRED_IFACE
route_mode = str(body.get("route_mode") or "overlay").strip() or "overlay"
apply = bool(body.get("apply"))
try:
if apply:
result = await asyncio.to_thread(
wireguard_hub.apply_wireguard_config,
content,
name=name,
route_mode=route_mode,
)
return {"ok": True, "message": "applied", "wireguard": result}
result = await asyncio.to_thread(
wireguard_hub.save_imported_wireguard_config,
content,
name=name,
route_mode=route_mode,
)
return {"ok": True, "message": "saved", "wireguard": result}
except wireguard_hub.WireGuardConfigError as exc:
raise HTTPException(400, str(exc)) from exc
except OSError as exc:
raise HTTPException(500, f"WireGuard 保存失败: {exc}") from exc
@app.post("/api/network/wireguard/apply")
async def network_wireguard_apply(body: dict[str, Any]) -> dict[str, Any]:
next_body = {**(body or {}), "apply": True, "route_mode": (body or {}).get("route_mode") or "overlay"}
return await network_wireguard_save(next_body)
@app.get("/api/network/wireguard/config/{name}")
async def network_wireguard_config(name: str) -> dict[str, Any]:
from . import wireguard_hub
try:
return {"ok": True, **(await asyncio.to_thread(wireguard_hub.read_config, name))}
except wireguard_hub.WireGuardConfigError as exc:
raise HTTPException(404, str(exc)) from exc
@app.delete("/api/network/wireguard/config/{name}")
async def network_wireguard_config_delete(name: str) -> dict[str, Any]:
"""Delete an imported (non-system) WireGuard conf leftover."""
from . import wireguard_hub
try:
return await asyncio.to_thread(wireguard_hub.delete_imported_config, name)
except wireguard_hub.WireGuardConfigError as exc:
raise HTTPException(400, str(exc)) from exc
@app.post("/api/network/wireguard/{name}/{action}")
async def network_wireguard_iface_action(name: str, action: str) -> dict[str, Any]:
"""start / stop / restart / status for wg-quick@{name}."""
from . import wireguard_hub
try:
return await asyncio.to_thread(wireguard_hub.iface_action, name, action)
except wireguard_hub.WireGuardConfigError as exc:
raise HTTPException(400, str(exc)) from exc
@app.get("/api/network/shellcrash/status")
async def network_shellcrash_status() -> dict[str, Any]:
from . import shellcrash_hub
return {"ok": True, "shellcrash": await asyncio.to_thread(shellcrash_hub.status)}
@app.get("/api/network/shellcrash/files")
async def network_shellcrash_files(root: str = Query("shellcrash-yamls")) -> dict[str, Any]:
from . import shellcrash_hub
try:
return await asyncio.to_thread(shellcrash_hub.list_files, root)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
@app.get("/api/network/shellcrash/file")
async def network_shellcrash_file_get(
root: str = Query("shellcrash-yamls"),
path: str = Query(...),
) -> dict[str, Any]:
from . import shellcrash_hub
try:
return await asyncio.to_thread(shellcrash_hub.read_file, root, path)
except FileNotFoundError as exc:
raise HTTPException(404, str(exc)) from exc
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
@app.put("/api/network/shellcrash/file")
async def network_shellcrash_file_put(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
from . import shellcrash_hub
root = str(body.get("root") or "shellcrash-yamls")
path = str(body.get("path") or "").strip()
content = str(body.get("content") or "")
if not path:
raise HTTPException(400, "path required")
try:
return await asyncio.to_thread(shellcrash_hub.write_file, root, path, content)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(500, str(exc)) from exc
@app.delete("/api/network/shellcrash/file")
async def network_shellcrash_file_delete(
root: str = Query("shellcrash-yamls"),
path: str = Query(...),
) -> dict[str, Any]:
from . import shellcrash_hub
try:
return await asyncio.to_thread(shellcrash_hub.delete_file, root, path)
except FileNotFoundError as exc:
raise HTTPException(404, str(exc)) from exc
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
@app.post("/api/network/shellcrash/apply_profile")
async def network_shellcrash_apply_profile(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
from . import shellcrash_hub
path = str(body.get("path") or shellcrash_hub.default_profile())
node = str(body.get("target_node") or shellcrash_hub.default_node())
try:
return await asyncio.to_thread(shellcrash_hub.apply_profile, path, node)
except FileNotFoundError as exc:
raise HTTPException(404, str(exc)) from exc
except Exception as exc:
raise HTTPException(500, f"应用失败: {exc}") from exc
@app.post("/api/network/shellcrash/web_panel")
async def network_shellcrash_web_panel() -> dict[str, Any]:
from . import shellcrash_hub
try:
return await asyncio.to_thread(shellcrash_hub.web_panel)
except Exception as exc:
raise HTTPException(500, str(exc)) from exc
@app.post("/api/network/shellcrash/{action}")
async def network_shellcrash_action(action: str) -> dict[str, Any]:
"""start / stop / restart / pick / status ShellCrash (SH2-compatible)."""
from . import shellcrash_hub
try:
return await asyncio.to_thread(shellcrash_hub.action, action)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(400, str(exc)) from exc
@app.post("/api/clash/sync")
async def clash_sync(force: bool = Query(False)) -> dict[str, Any]:
"""Pull latest Clash Verge Rev Win x64 from GitHub and publish clash.yaml to S3."""

View File

@ -0,0 +1,296 @@
# -*- coding: utf-8 -*-
"""Unlimited Neko HTTP/WebSocket gateway.
Public edges should reverse_proxy ALL `/neko/*` to this listener (default :9199).
Path `/neko/{id}/…` is stripped and forwarded to `127.0.0.1:{base+id-1}/…`.
This removes the hard-coded /neko/1…N blocks on Caddy/Nginx edges.
"""
from __future__ import annotations
import asyncio
import logging
import re
from typing import Any
import httpx
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route, WebSocketRoute
from starlette.websockets import WebSocket, WebSocketDisconnect
from .config import settings
log = logging.getLogger("neko_gateway")
_PATH_RE = re.compile(r"^/neko/(\d+)(/.*)?$")
_HOP_BY_HOP = {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
"host",
"content-length",
}
def _max_instances() -> int:
raw = getattr(settings, "neko_max_instances", None)
try:
n = int(raw or 0)
except Exception:
n = 0
return max(1, n) if n else 256
def _http_port(instance_id: int) -> int:
base = int(getattr(settings, "neko_http_port_base", 9200) or 9200)
return base + instance_id - 1
def _parse(path: str) -> tuple[int, str] | None:
m = _PATH_RE.match(path or "")
if not m:
return None
idx = int(m.group(1))
if idx < 1 or idx > _max_instances():
return None
rest = m.group(2) or "/"
if not rest.startswith("/"):
rest = "/" + rest
return idx, rest
def _upstream(idx: int, rest: str, query: str = "") -> str:
url = f"http://127.0.0.1:{_http_port(idx)}{rest}"
if query:
url = f"{url}?{query}"
return url
async def _proxy_http(request: Request) -> Response:
path = request.url.path or ""
# Relative asset URLs in Neko HTML require a trailing slash on /neko/{id}
m_bare = re.match(r"^/neko/(\d+)$", path)
if m_bare:
dest = f"/neko/{m_bare.group(1)}/"
if request.url.query:
dest = f"{dest}?{request.url.query}"
return Response(status_code=308, headers={"location": dest})
parsed = _parse(path)
if not parsed:
return Response("Neko gateway: bad path (expect /neko/{id}/…)", status_code=404)
idx, rest = parsed
url = _upstream(idx, rest, request.url.query)
headers = {
k: v
for k, v in request.headers.items()
if k.lower() not in _HOP_BY_HOP
}
headers["host"] = f"127.0.0.1:{_http_port(idx)}"
body = await request.body()
try:
async with httpx.AsyncClient(timeout=None, follow_redirects=False) as client:
upstream = await client.request(
request.method,
url,
headers=headers,
content=body,
)
except httpx.ConnectError:
return Response(
f"Neko instance {idx} not reachable on :{_http_port(idx)}",
status_code=502,
)
except Exception as exc:
log.exception("neko gateway http error idx=%s", idx)
return Response(f"Neko gateway error: {exc}", status_code=502)
out_headers = {
k: v
for k, v in upstream.headers.multi_items()
if k.lower() not in _HOP_BY_HOP and k.lower() != "content-encoding"
}
return Response(
content=upstream.content,
status_code=upstream.status_code,
headers=out_headers,
media_type=upstream.headers.get("content-type"),
)
async def _proxy_ws(websocket: WebSocket) -> None:
parsed = _parse(websocket.url.path)
if not parsed:
await websocket.close(code=1008)
return
idx, rest = parsed
qs = websocket.url.query
# Prefer websockets lib (uvicorn[standard]); fall back closes.
try:
import websockets
except ImportError:
await websocket.close(code=1011)
return
upstream_url = _upstream(idx, rest, qs).replace("http://", "ws://", 1)
headers = {
k: v
for k, v in websocket.headers.items()
if k.lower()
not in {
"host",
"connection",
"upgrade",
"sec-websocket-key",
"sec-websocket-version",
"sec-websocket-extensions",
"sec-websocket-protocol",
"content-length",
}
}
await websocket.accept(
subprotocol=websocket.headers.get("sec-websocket-protocol")
)
connect_kwargs: dict = {"max_size": None, "ping_interval": 20, "ping_timeout": 20}
try:
async with websockets.connect(
upstream_url, additional_headers=headers, **connect_kwargs
) as upstream:
await _bridge(websocket, upstream)
return
except TypeError:
# websockets<14
async with websockets.connect(
upstream_url, extra_headers=headers, **connect_kwargs
) as upstream:
await _bridge(websocket, upstream)
return
except Exception as exc:
log.warning("neko gateway ws idx=%s err=%s", idx, exc)
try:
await websocket.close(code=1011)
except Exception:
pass
async def _bridge(websocket: WebSocket, upstream) -> None:
async def client_to_up() -> None:
try:
while True:
msg = await websocket.receive()
if msg["type"] == "websocket.disconnect":
break
if msg.get("text") is not None:
await upstream.send(msg["text"])
elif msg.get("bytes") is not None:
await upstream.send(msg["bytes"])
except WebSocketDisconnect:
pass
except Exception:
pass
async def up_to_client() -> None:
try:
async for message in upstream:
if isinstance(message, bytes):
await websocket.send_bytes(message)
else:
await websocket.send_text(message)
except Exception:
pass
t1 = asyncio.create_task(client_to_up())
t2 = asyncio.create_task(up_to_client())
_done, pending = await asyncio.wait({t1, t2}, return_when=asyncio.FIRST_COMPLETED)
for t in pending:
t.cancel()
def build_app() -> Starlette:
async def http_catchall(request: Request) -> Response:
return await _proxy_http(request)
async def ws_catchall(websocket: WebSocket) -> None:
await _proxy_ws(websocket)
return Starlette(
routes=[
WebSocketRoute("/neko/{path:path}", ws_catchall),
WebSocketRoute("/neko/{instance_id:int}", ws_catchall),
WebSocketRoute("/neko/{instance_id:int}/{path:path}", ws_catchall),
Route("/neko/{path:path}", http_catchall, methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]),
Route("/neko/{instance_id:int}", http_catchall, methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]),
Route("/neko/{instance_id:int}/{path:path}", http_catchall, methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]),
Route(
"/",
lambda r: Response(
"neko gateway ok — use /neko/{id}/",
media_type="text/plain",
),
),
]
)
_server: Any = None
_serve_task: asyncio.Task | None = None
def gateway_port() -> int:
try:
return int(getattr(settings, "neko_gateway_port", 9199) or 9199)
except Exception:
return 9199
def gateway_enabled() -> bool:
raw = getattr(settings, "neko_gateway_enabled", True)
if isinstance(raw, str):
return raw.strip().lower() not in {"0", "false", "no", "off"}
return bool(raw)
async def start_gateway() -> dict[str, Any]:
"""Start gateway on 0.0.0.0:DY_NEKO_GATEWAY_PORT (idempotent)."""
global _server, _serve_task
if not gateway_enabled():
return {"ok": True, "skipped": True, "reason": "disabled"}
if _serve_task and not _serve_task.done():
return {"ok": True, "already": True, "port": gateway_port()}
import uvicorn
port = gateway_port()
config = uvicorn.Config(
build_app(),
host="0.0.0.0",
port=port,
log_level="warning",
ws="websockets",
access_log=False,
)
_server = uvicorn.Server(config)
_serve_task = asyncio.create_task(_server.serve(), name="neko-edge-gateway")
# Give it a moment to bind
await asyncio.sleep(0.3)
return {"ok": True, "port": port, "max_instances": _max_instances()}
async def stop_gateway() -> None:
global _server, _serve_task
if _server is not None:
_server.should_exit = True
if _serve_task is not None:
try:
await asyncio.wait_for(_serve_task, timeout=5)
except Exception:
_serve_task.cancel()
_server = None
_serve_task = None

265
backend/app/network_hub.py Normal file
View File

@ -0,0 +1,265 @@
# -*- coding: utf-8 -*-
"""Network hub — WireGuard primary + FRP auxiliary (SH2-adapted).
Physical dual-path policy:
- Primary: WireGuard (wg-dy) carries app traffic VPS Caddy → 10.8.0.2 and preferred SSH.
- Auxiliary: FRP (frpp :4014) is emergency SSH / ops only — never the app data path.
"""
from __future__ import annotations
import os
import re
import shutil
import time
from pathlib import Path
from typing import Any
from . import global_socks
from . import shellcrash_hub
from . import wireguard_hub
def _run(cmd: list[str], timeout: int = 12) -> tuple[int, str]:
import subprocess
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
return int(p.returncode), ((p.stdout or "") + (p.stderr or "")).strip()
except Exception as exc:
return 1, str(exc)
def _unit_active(name: str) -> str:
code, out = _run(["systemctl", "is-active", name], timeout=5)
return (out.splitlines()[0] if out else ("inactive" if code else "unknown")).strip()
def path_roles() -> dict[str, Any]:
"""Declare which transport is primary vs auxiliary."""
cn_up = Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False
wg_target = "10.9.0.2(wg-dy-cn 国内优先)" if cn_up else "10.8.0.2(wg-dy 海外)"
return {
"app_https": {
"primary": "wireguard",
"detail": f"VPS Caddy → WG {wg_target}:4015/8014;wg-dy 海外链路保留作备份",
},
"ops_ssh": {
"primary": "wireguard",
"auxiliary": "frp",
"detail": "优先 WG(wg-dy-cn → 10.9.0.1 或 wg-dy → 10.8.0.1);FRP :4014 仅应急",
},
"policy": "wg_cn_primary_wg_us_backup_frp_aux",
}
def frp_status() -> dict[str, Any]:
"""FRP is auxiliary — SSH/ops fallback only; do not carry app reverse_proxy."""
unit = None
for name in ("frpp", "frpc", "frp-panel"):
st = _unit_active(name)
if st in {"active", "activating"}:
unit = {"name": name, "state": st}
break
if unit is None and st not in {"inactive", "unknown", ""}:
unit = {"name": name, "state": st}
code, ps = _run(["bash", "-lc", "ps aux | grep -E '[f]rpc|[f]rpp|[f]rp-panel' | head -5"], timeout=8)
procs = [ln.strip() for ln in (ps or "").splitlines() if ln.strip()]
# Detect common SSH tunnel port hint
ports: list[int] = []
for ln in procs:
for m in re.finditer(r":(\d{2,5})\b", ln):
try:
ports.append(int(m.group(1)))
except ValueError:
pass
return {
"ok": True,
"role": "auxiliary",
"purpose": "ops_ssh_emergency",
"unit": unit,
"processes": procs[:5],
"hint_ports": sorted(set(ports))[:8],
"detail": "辅路径:仅应急 SSH/运维(如 VPS:4014→guest:22)。应用 HTTPS 必须走 WireGuard,勿把业务反代挂到 FRP。",
}
def socks_status() -> dict[str, Any]:
from . import db
cfg = db.get_settings_map()
enabled = global_socks.is_global_socks_enabled(cfg)
profiles = global_socks.list_socks_profiles(cfg, public=True)
active_id = global_socks.active_profile_id(cfg)
from . import singbox_manager
return {
"ok": True,
"enabled": enabled,
"active_profile_id": active_id,
"profiles": profiles,
"local_mixed": global_socks.local_mixed_url() if enabled else "",
"singbox_running": bool(singbox_manager.is_running()) if enabled else False,
"hint": "新装默认无住宅节点;自行添加 SOCKS5",
}
def _deploy_shape_hint() -> str:
if Path("/etc/wireguard/wg-dy.conf").is_file() or any(
p.name == "wg-dy" for p in Path("/sys/class/net").iterdir() if Path("/sys/class/net").is_dir()
):
return "physical_or_wg"
return "colocated_or_unknown"
def _wg_handshake_age_sec() -> int | None:
"""Seconds since latest handshake on primary WG iface (wg-dy-cn preferred)."""
for iface in ("wg-dy-cn", "wg-dy"):
code, out = _run(["wg", "show", iface, "latest-handshakes"], timeout=5)
if code != 0 or not out.strip():
continue
parts = out.split()
if len(parts) < 2:
continue
try:
ts = int(parts[-1])
except ValueError:
continue
if ts <= 0:
continue
return max(0, int(time.time()) - ts)
return None
def _ping_wg_peer() -> dict[str, Any]:
if Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False:
peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1"
else:
peer = str(os.environ.get("DY_WG_PEER_IP") or "10.8.0.1").strip() or "10.8.0.1"
code, out = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6)
ok = code == 0 and "1 received" in out.replace("packets ", "")
if not ok:
ok = code == 0 and ("bytes from" in out or "ttl=" in out.lower())
rtt = ""
m = re.search(r"time[=<]([0-9.]+)\s*ms", out)
if m:
rtt = m.group(1) + "ms"
return {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]}
def wireguard_watch_status() -> dict[str, Any]:
unit = _unit_active("douyinweb-wireguard-watch")
path = Path("/opt/douyinWEB/scripts/linux/wireguard_watch.sh")
return {
"unit": unit,
"installed": path.is_file(),
"path": str(path) if path.is_file() else "",
"hint": "stale handshake 自动重启 wg-dy-cn / wg-dy(主路径保活)",
}
def network_overview() -> dict[str, Any]:
wg = wireguard_hub.runtime_status()
age = _wg_handshake_age_sec()
ping = _ping_wg_peer()
wg["role"] = "primary"
wg["purpose"] = "app_https_and_ops_ssh"
wg["handshake_age_sec"] = age
wg["handshake_fresh"] = age is not None and age < 180
wg["peer_ping"] = ping
wg["watch"] = wireguard_watch_status()
if age is not None and age >= 300:
wg.setdefault("recommendations", []).append(
f"握手已 {age}s 未刷新 — watch 应重启 wg-dy;勿改用 FRP 扛业务"
)
frp = frp_status()
from . import egress_hub
return {
"ok": True,
"path_roles": path_roles(),
"wireguard": wg,
"frp": frp,
"shellcrash": shellcrash_hub.status(),
"socks": socks_status(),
"egress": egress_hub.status(),
"deploy_shape": _deploy_shape_hint(),
"physical_checklist": physical_checklist(wg=wg, frp=frp),
}
def physical_checklist(
*,
wg: dict[str, Any] | None = None,
frp: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Operator checklist — WireGuard primary, FRP auxiliary."""
checks: list[dict[str, Any]] = []
def add(name: str, ok: bool, detail: str = "") -> None:
checks.append({"name": name, "ok": bool(ok), "detail": detail})
pub = str(os.environ.get("DY_PUBLIC_BASE_URL") or "").strip()
add(
"public_base_url",
pub.startswith("https://") and "127.0.0.1" not in pub and not pub.startswith("http://10."),
pub or "missing DY_PUBLIC_BASE_URL",
)
bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "127.0.0.1").strip()
shape = _deploy_shape_hint()
if shape.startswith("physical"):
add("neko_http_bind", bind in {"0.0.0.0", "*"}, f"DY_NEKO_HTTP_BIND={bind} (physical needs 0.0.0.0)")
else:
add("neko_http_bind", True, f"DY_NEKO_HTTP_BIND={bind}")
docker_ok = bool(shutil.which("docker"))
add("docker", docker_ok, "docker binary" if docker_ok else "missing")
seed = Path(__file__).resolve().parent.parent / "neko" / "tampermonkey-seed" / "Default" / "Extensions"
add("neko_seed", seed.is_dir(), str(seed))
wg_up = Path("/sys/class/net/wg-dy").exists() if Path("/sys/class/net").is_dir() else False
add("wg_primary_link", wg_up or shape != "physical_or_wg", "wg-dy iface (主路径)" if wg_up else "no wg-dy")
wg = wg or {}
age = wg.get("handshake_age_sec")
if isinstance(age, int):
add("wg_handshake", age < 300, f"age={age}s (主路径保活)")
elif wg_up:
add("wg_handshake", False, "无法读取 handshake")
ping = wg.get("peer_ping") if isinstance(wg.get("peer_ping"), dict) else {}
if ping:
add("wg_peer_ping", bool(ping.get("ok")), f"{ping.get('peer')} {ping.get('rtt') or ''}".strip())
watch = wg.get("watch") if isinstance(wg.get("watch"), dict) else {}
if shape.startswith("physical"):
add(
"wg_watch",
watch.get("unit") == "active",
f"unit={watch.get('unit') or 'missing'} — douyinweb-wireguard-watch 保活主路径",
)
frp = frp or {}
frp_unit = (frp.get("unit") or {}) if isinstance(frp.get("unit"), dict) else {}
add(
"frp_aux_ssh",
True,
f"role=auxiliary state={frp_unit.get('state') or 'n/a'} — 仅应急 SSH,不扛业务",
)
sc = shellcrash_hub.status()
if shape.startswith("physical"):
add(
"shellcrash",
bool(sc.get("installed")) and bool(sc.get("running")),
f"installed={sc.get('installed')} unit={sc.get('unit')} mixed=:{sc.get('mixed_port') or '?'}",
)
failed = sum(1 for c in checks if not c["ok"])
return {
"ok": failed == 0,
"failed": failed,
"checks": checks,
"deploy_shape": shape,
"policy": "wg_primary_frp_aux",
}

View File

@ -85,7 +85,11 @@ def oauth_health_board(*, probe: bool = False) -> dict[str, Any]:
"brand_hint": brand,
"authorized": bool(meta.get("authorized")),
"enabled": bool(ch.get("enabled")),
"ypp_ok": ypp_map.get(pk, -1),
"ypp_ok": (
int(ch.get("ypp_ok"))
if ch.get("ypp_ok") is not None and int(ch.get("ypp_ok")) in (0, 1)
else ypp_map.get(pk, -1)
),
}
out.append(row)
return {"channels": out, "total": len(out)}
@ -93,8 +97,11 @@ def oauth_health_board(*, probe: bool = False) -> dict[str, Any]:
async def oauth_health_probe_all() -> dict[str, Any]:
from .shorts_oauth import probe_all_enabled_channels
from .yt_long_monetize import refresh_all_ypp_from_shorts
result = await probe_all_enabled_channels()
ypp = await refresh_all_ypp_from_shorts(limit=100)
board = oauth_health_board(probe=False)
board["probe"] = result
board["ypp_probe"] = ypp
return board

View File

@ -0,0 +1,618 @@
# -*- coding: utf-8 -*-
"""ShellCrash hub — SH2-compatible controls + managed files + apply_profile."""
from __future__ import annotations
import json
import os
import re
import shutil
import subprocess
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
CONTROLLER = "http://127.0.0.1:9999"
DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_hysteria5")
DEFAULT_PROFILE = os.environ.get("DY_SHELLCRASH_DEFAULT_PROFILE", "config.yaml")
CANDIDATE_NODES = (
"1d2da142-singbox_hysteria5",
"1d2da142-singbox_tuic5",
"1d2da142-VLESS_Reality_Vision5",
"e3ea3b30-singbox_hysteria_vultr",
"e3ea3b30-singbox_tuic_vultr",
"242af835-singbox_hysteria",
"hackrobot-singbox_tuic",
"VLESS_Reality_Vision",
"socks5",
"proxycheap",
)
SELECT_GROUPS = ("GLOBAL", "🚀 节点选择")
MANAGED_ROOTS: dict[str, tuple[str, str]] = {
"shellcrash-yamls": ("yamls", "YAML 配置"),
"shellcrash-configs": ("configs", "配置文件"),
"shellcrash-jsons": ("jsons", "JSON"),
}
def _run(cmd: list[str], *, timeout: float = 15.0) -> dict[str, Any]:
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
return {"ok": False, "code": 124, "stdout": "", "stderr": str(exc)}
return {
"ok": proc.returncode == 0,
"code": proc.returncode or 0,
"stdout": (proc.stdout or "").strip(),
"stderr": (proc.stderr or "").strip(),
}
def _priv(cmd: list[str], *, timeout: float = 20.0) -> dict[str, Any]:
if hasattr(os, "geteuid") and os.geteuid() == 0:
return _run(cmd, timeout=timeout)
if shutil.which("sudo"):
return _run(["sudo", "-n", *cmd], timeout=timeout)
return _run(cmd, timeout=timeout)
def shellcrash_dir() -> Path:
return Path(os.environ.get("SHELLCRASH_DIR", "/etc/ShellCrash"))
def default_node() -> str:
return DEFAULT_NODE
def default_profile() -> str:
return DEFAULT_PROFILE
def _read_cfg() -> dict[str, str]:
cfg = shellcrash_dir() / "configs" / "ShellCrash.cfg"
out: dict[str, str] = {}
if not cfg.is_file():
return out
try:
lines = cfg.read_text(encoding="utf-8", errors="ignore").splitlines()
except OSError:
return out
for raw in lines:
if "=" not in raw or raw.lstrip().startswith("#"):
continue
key, _, value = raw.partition("=")
out[key.strip()] = value.strip()
return out
def _config_yaml() -> dict[str, Any]:
base = shellcrash_dir()
for path in (base / "yamls" / "config.yaml", Path("/tmp/ShellCrash/config.yaml"), base / "config.yaml"):
try:
if path.is_file() and path.stat().st_size > 0:
return {"available": True, "path": str(path), "bytes": path.stat().st_size}
except OSError:
continue
return {"available": False, "path": "", "bytes": 0}
def _unit_exists(unit: str) -> bool:
r = _run(["systemctl", "list-unit-files", unit, "--no-legend"], timeout=3.0)
return r["ok"] and unit in (r["stdout"] + r["stderr"])
def _stage_runtime_config(config_path: str) -> None:
src = Path(config_path)
if not src.is_file():
return
dst = Path("/tmp/ShellCrash/config.yaml")
try:
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dst)
dst.chmod(0o644)
except OSError:
return
def _http_json(url: str, *, method: str = "GET", body: dict[str, Any] | None = None, timeout: float = 6.0) -> dict[str, Any]:
data = None if body is None else json.dumps(body).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
method=method,
headers={"Content-Type": "application/json"} if body is not None else {},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8", "replace")
return {"ok": True, "status": getattr(resp, "status", 200), "data": json.loads(raw) if raw.strip() else {}}
except urllib.error.HTTPError as exc:
return {"ok": False, "status": int(exc.code), "error": str(exc)}
except Exception as exc: # noqa: BLE001
return {"ok": False, "status": 0, "error": str(exc)}
def _safe_rel(root: Path, rel: str) -> Path:
rel = (rel or "").replace("\\", "/").lstrip("/")
if not rel or ".." in rel.split("/"):
raise ValueError("非法路径")
target = (root / rel).resolve()
root_res = root.resolve()
if root_res not in target.parents and target != root_res:
raise ValueError("路径越界")
return target
def managed_roots() -> list[dict[str, Any]]:
base = shellcrash_dir()
out: list[dict[str, Any]] = []
for root_id, (subdir, label) in MANAGED_ROOTS.items():
path = base / subdir
path.mkdir(parents=True, exist_ok=True)
files = []
try:
for p in sorted(path.rglob("*")):
if p.is_file():
rel = p.relative_to(path).as_posix()
files.append({"path": rel, "size": p.stat().st_size})
except OSError:
files = []
out.append({"root_id": root_id, "label": label, "file_count": len(files), "files": files})
return out
def list_files(root_id: str) -> dict[str, Any]:
if root_id not in MANAGED_ROOTS:
raise ValueError(f"unknown root: {root_id}")
subdir, label = MANAGED_ROOTS[root_id]
path = shellcrash_dir() / subdir
path.mkdir(parents=True, exist_ok=True)
files: list[dict[str, Any]] = []
for p in sorted(path.rglob("*")):
if p.is_file():
files.append({"path": p.relative_to(path).as_posix(), "size": p.stat().st_size})
return {"ok": True, "root_id": root_id, "label": label, "files": files}
def read_file(root_id: str, rel_path: str) -> dict[str, Any]:
if root_id not in MANAGED_ROOTS:
raise ValueError(f"unknown root: {root_id}")
subdir, _ = MANAGED_ROOTS[root_id]
target = _safe_rel(shellcrash_dir() / subdir, rel_path)
if not target.is_file():
raise FileNotFoundError(rel_path)
text = target.read_text(encoding="utf-8", errors="replace")
return {"ok": True, "root_id": root_id, "path": rel_path, "content": text, "bytes": len(text.encode("utf-8"))}
def write_file(root_id: str, rel_path: str, content: str) -> dict[str, Any]:
if root_id not in MANAGED_ROOTS:
raise ValueError(f"unknown root: {root_id}")
subdir, _ = MANAGED_ROOTS[root_id]
target = _safe_rel(shellcrash_dir() / subdir, rel_path)
target.parent.mkdir(parents=True, exist_ok=True)
# Write via temp then install with sudo if needed
tmp = Path("/tmp") / f"_sc_write_{os.getpid()}_{target.name}"
tmp.write_text(content if content.endswith("\n") else content + "\n", encoding="utf-8")
r = _priv(["install", "-m", "644", str(tmp), str(target)], timeout=10.0)
try:
tmp.unlink(missing_ok=True)
except OSError:
pass
if not r.get("ok") and not target.is_file():
raise RuntimeError(r.get("stderr") or "写入失败(需要 sudo 权限)")
if not r.get("ok"):
# fallback direct write
try:
target.write_text(content if content.endswith("\n") else content + "\n", encoding="utf-8")
except OSError as exc:
raise RuntimeError(str(exc)) from exc
return {"ok": True, "root_id": root_id, "path": rel_path, "bytes": target.stat().st_size}
def delete_file(root_id: str, rel_path: str) -> dict[str, Any]:
if root_id not in MANAGED_ROOTS:
raise ValueError(f"unknown root: {root_id}")
subdir, _ = MANAGED_ROOTS[root_id]
target = _safe_rel(shellcrash_dir() / subdir, rel_path)
if not target.is_file():
raise FileNotFoundError(rel_path)
r = _priv(["rm", "-f", str(target)], timeout=10.0)
if target.exists():
try:
target.unlink()
except OSError as exc:
if not r.get("ok"):
raise RuntimeError(str(exc)) from exc
return {"ok": True, "root_id": root_id, "path": rel_path}
def _patch_yaml_listeners(text: str) -> str:
lines: list[str] = []
found_ec = found_mp = False
for line in text.splitlines():
if line.startswith("global-client-fingerprint:"):
continue
if line.startswith("external-controller:"):
lines.append("external-controller: 0.0.0.0:9999")
found_ec = True
continue
if line.startswith("mixed-port:"):
lines.append("mixed-port: 7890")
found_mp = True
continue
lines.append(line)
if not found_ec:
lines.append("external-controller: 0.0.0.0:9999")
if not found_mp:
lines.append("mixed-port: 7890")
return _ensure_douyin_direct_rules("\n".join(lines).rstrip() + "\n")
# Hard requirement: Douyin must never go through overseas proxy nodes.
_DOUYIN_DIRECT_RULES = (
" - DOMAIN-SUFFIX,douyin.com,DIRECT",
" - DOMAIN-SUFFIX,douyincdn.com,DIRECT",
" - DOMAIN-SUFFIX,douyinpic.com,DIRECT",
" - DOMAIN-SUFFIX,douyinvod.com,DIRECT",
" - DOMAIN-SUFFIX,douyinstatic.com,DIRECT",
" - DOMAIN-SUFFIX,iesdouyin.com,DIRECT",
" - DOMAIN-KEYWORD,douyin,DIRECT",
)
def _ensure_douyin_direct_rules(text: str) -> str:
"""Prepend explicit Douyin DIRECT rules under `rules:` (idempotent)."""
if "DOMAIN-SUFFIX,douyin.com,DIRECT" in text:
return text
block = "\n".join(_DOUYIN_DIRECT_RULES) + "\n"
if re.search(r"(?m)^rules:\s*$", text):
return re.sub(r"(?m)^(rules:\s*\n)", r"\1" + block, text, count=1)
# No rules section — append one.
return text.rstrip() + "\n\nrules:\n" + block + " - MATCH,DIRECT\n"
def _select_node_in_groups(node: str) -> list[dict[str, Any]]:
listed = _http_json(f"{CONTROLLER}/proxies", timeout=5.0)
proxies = (listed.get("data") or {}).get("proxies") or {} if listed.get("ok") else {}
applied: list[dict[str, Any]] = []
for group in SELECT_GROUPS:
if group != "GLOBAL" and group not in proxies:
continue
enc = urllib.parse.quote(group, safe="")
put = _http_json(f"{CONTROLLER}/proxies/{enc}", method="PUT", body={"name": node}, timeout=5.0)
applied.append({"group": group, "ok": bool(put.get("ok")), "status": put.get("status")})
return applied
def apply_profile(rel_path: str | None = None, target_node: str | None = None) -> dict[str, Any]:
"""SH2-compatible: stage YAML → config.yaml → restart → select node."""
rel = (rel_path or DEFAULT_PROFILE).strip() or DEFAULT_PROFILE
node = (target_node or DEFAULT_NODE).strip() or DEFAULT_NODE
yamls = shellcrash_dir() / "yamls"
yamls.mkdir(parents=True, exist_ok=True)
source = _safe_rel(yamls, rel)
if not source.is_file():
# allow reading from staged clash assets copy
assets = Path(__file__).resolve().parent / "clash_assets" / "clash.yaml"
if assets.is_file() and rel in {"config.yaml", "clash.yaml", DEFAULT_PROFILE}:
text = assets.read_text(encoding="utf-8", errors="replace")
else:
raise FileNotFoundError(rel)
else:
text = source.read_text(encoding="utf-8", errors="replace")
text = _patch_yaml_listeners(text)
# Prefer target node first in select groups when present as a name token
if node and re.search(rf"(?m)^\s*-\s*{re.escape(node)}\s*$", text):
# light-touch: no full YAML reorder required; runtime select via API after restart
pass
write_file("shellcrash-yamls", rel if rel.endswith((".yaml", ".yml")) else "config.yaml", text)
write_file("shellcrash-yamls", "config.yaml", text)
_stage_runtime_config(str(yamls / "config.yaml"))
unit = "shellcrash.service"
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
run = _priv(["systemctl", "restart", unit], timeout=40.0)
time.sleep(3.0)
applied = _select_node_in_groups(node)
st = status()
return {
"ok": bool(st.get("running")),
"message": "ShellCrash 配置已应用",
"path": rel,
"target_node": node,
"selected": st.get("selected_node") or node,
"applied_groups": applied,
"command_ok": bool(run.get("ok")),
"shellcrash": st,
}
def apply_residential_chain(profile: dict[str, Any], *, dialer: str = "dialer") -> dict[str, Any]:
"""Upsert socks5 landing with dialer-proxy, restart ShellCrash, select it.
Path: local → ShellCrash → [dialer group/node] → residential SOCKS → target
See: https://wiki.metacubex.one/config/proxies/dialer-proxy/
"""
name = "dy-residential"
dialer = (dialer or "dialer").strip() or "dialer"
server = str(profile.get("server") or "").strip()
try:
port = int(profile.get("port") or 0)
except Exception:
port = 0
user = str(profile.get("username") or "")
pwd = str(profile.get("password") or "")
if not server or port <= 0:
raise ValueError("住宅 SOCKS 服务器/端口无效")
block_lines = [
f" - name: {name}",
f" dialer-proxy: {dialer}",
" type: socks5",
f" server: {server}",
f" port: {port}",
]
if user:
block_lines.append(f" username: {user}")
if pwd:
block_lines.append(f" password: {pwd}")
block = "\n".join(block_lines) + "\n"
yamls = shellcrash_dir() / "yamls"
yamls.mkdir(parents=True, exist_ok=True)
cfg_path = yamls / "config.yaml"
if cfg_path.is_file():
text = cfg_path.read_text(encoding="utf-8", errors="replace")
else:
assets = Path(__file__).resolve().parent / "clash_assets" / "clash.yaml"
text = assets.read_text(encoding="utf-8", errors="replace") if assets.is_file() else "proxies:\n"
text = _upsert_proxy_block(text, name, block)
text = _ensure_proxy_in_select_groups(text, name)
text = _patch_yaml_listeners(text)
write_file("shellcrash-yamls", "config.yaml", text)
_stage_runtime_config(str(yamls / "config.yaml"))
unit = "shellcrash.service"
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
run = _priv(["systemctl", "restart", unit], timeout=40.0)
time.sleep(3.0)
applied = _select_node_in_groups(name)
st = status()
return {
"ok": bool(st.get("running")),
"message": "已启用住宅链式落地(dialer-proxy)",
"proxy_name": name,
"dialer": dialer,
"selected": st.get("selected_node") or name,
"applied_groups": applied,
"command_ok": bool(run.get("ok")),
"shellcrash": st,
"docs": "https://wiki.metacubex.one/config/proxies/dialer-proxy/",
}
def _upsert_proxy_block(text: str, name: str, block: str) -> str:
"""Replace existing `- name: {name}` proxy entry or insert under proxies:."""
# Remove existing block for this name (from its "- name:" until next top-level proxy or section).
pattern = re.compile(
rf"(?ms)^ - name:\s*{re.escape(name)}\s*\n(?: .*\n)*",
)
text2, n = pattern.subn("", text)
if "proxies:" not in text2:
return "proxies:\n" + block + text2
# Insert right after `proxies:` line
return re.sub(r"(?m)^(proxies:\s*\n)", r"\1" + block, text2, count=1)
def _ensure_proxy_in_select_groups(text: str, name: str) -> str:
"""Append proxy name into main select groups if missing (best-effort)."""
if re.search(rf"(?m)^\s*-\s*{re.escape(name)}\s*$", text):
return text
# Insert into first proxy-groups select list after `proxies:` under that group — skip if hard.
# Prefer injecting near proxycheap if present.
if re.search(r"(?m)^\s*-\s*proxycheap\s*$", text):
return re.sub(r"(?m)^(\s*-\s*proxycheap\s*)$", rf"\1\n - {name}", text, count=1)
return text
def _wg_overlay_ip() -> str:
"""Best-effort WireGuard overlay address (e.g. 10.8.0.2) for direct :9999 access."""
r = _run(["bash", "-lc", "ip -4 -o addr show wg-dy 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1"])
ip = (r.get("stdout") or "").strip().splitlines()
if ip and ip[0]:
return ip[0].strip()
env_ip = (os.environ.get("DY_NEKO_EDGE_UPSTREAM") or os.environ.get("DY_WG_OVERLAY_IP") or "").strip()
return env_ip
def _controller_secret() -> str:
yml = shellcrash_dir() / "yamls" / "config.yaml"
try:
text = yml.read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
m = re.search(r"(?m)^\s*secret:\s*[\"']?([^\"'\n#]+)", text)
return (m.group(1).strip() if m else "")
def web_panel() -> dict[str, Any]:
"""Ensure service up; return dashboard URL on our public domain.
Physical edge Caddy proxies ``/ui`` + Clash API → WG ``:9999``.
Open ``/ui/#/setup?...`` with HTTPS backend prefilled so Zashboard does not
default to ``http://127.0.0.1:9090`` (mixed-content / unreachable).
"""
st = status()
if not st.get("running"):
action("start")
time.sleep(2.0)
st = status()
public = (os.environ.get("DY_PUBLIC_BASE_URL") or "").rstrip("/")
secret = _controller_secret()
secret_q = f"&secret={urllib.parse.quote(secret)}" if secret else ""
wg_ip = _wg_overlay_ip()
direct_url = f"http://{wg_ip}:9999/ui/#/proxies" if wg_ip else "http://127.0.0.1:9999/ui/#/proxies"
if public:
host = urllib.parse.urlparse(public).hostname or ""
# Must stay under /ui/; prefill HTTPS controller (same origin, port 443).
url = (
f"{public}/ui/#/setup?hostname={urllib.parse.quote(host)}"
f"&port=443&protocol=https{secret_q}"
)
proxies_url = f"{public}/ui/#/proxies"
else:
url = direct_url
proxies_url = direct_url
ui_dir = shellcrash_dir() / "ui"
ui_ok = ui_dir.is_dir() and (ui_dir / "index.html").is_file()
return {
"ok": True,
"message": "ShellCrash web 面板已就绪" if st.get("running") else "服务未就绪,仍返回面板地址",
"url": url,
"proxies_url": proxies_url,
"direct_url": direct_url,
"port": "9999",
"ui_installed": ui_ok,
"shellcrash": status(),
}
def probe_mixed(*, timeout: float = 10.0) -> dict[str, Any]:
cfg = _read_cfg()
port = cfg.get("mix_port") or "7890"
cmd = [
"curl", "-sS", "-m", str(int(timeout)), "-o", "/dev/null", "-w", "%{http_code}",
"-x", f"http://127.0.0.1:{port}", "https://www.google.com/generate_204",
]
r = _run(cmd, timeout=timeout + 2)
code = (r.get("stdout") or "").strip()
return {"ok": code in {"204", "200", "301", "302"}, "http_code": code, "mixed_port": port, "detail": r.get("stderr") or ""}
def pick_best_node(*, timeout_ms: int = 5000) -> dict[str, Any]:
listed = _http_json(f"{CONTROLLER}/proxies", timeout=5.0)
if not listed.get("ok"):
return {"ok": False, "error": listed.get("error") or "controller unreachable", "picked": None}
proxies = (listed.get("data") or {}).get("proxies") or {}
delays: list[dict[str, Any]] = []
best_name: str | None = None
best_delay = 10**9
for name in CANDIDATE_NODES:
if name not in proxies:
continue
enc = urllib.parse.quote(name, safe="")
url = f"{CONTROLLER}/proxies/{enc}/delay?timeout={timeout_ms}&url=http://www.gstatic.com/generate_204"
res = _http_json(url, timeout=(timeout_ms / 1000.0) + 3.0)
delay = int((res.get("data") or {}).get("delay") or 0) if res.get("ok") else 0
delays.append({"name": name, "delay": delay, "ok": delay > 0})
if delay > 0 and delay < best_delay:
best_name, best_delay = name, delay
applied: list[dict[str, Any]] = []
if best_name:
applied = _select_node_in_groups(best_name)
egress = probe_mixed() if best_name else {"ok": False, "http_code": ""}
return {
"ok": bool(best_name) and bool(egress.get("ok")),
"picked": best_name,
"delay_ms": best_delay if best_name else None,
"delays": delays,
"applied": applied,
"egress": egress,
}
def status() -> dict[str, Any]:
cfg_vals = _read_cfg()
yaml = _config_yaml()
unit_name = "shellcrash.service"
active = _run(["systemctl", "is-active", unit_name], timeout=3.0) if shutil.which("systemctl") else {"ok": False, "stdout": "unknown"}
enabled = _run(["systemctl", "is-enabled", unit_name], timeout=3.0) if shutil.which("systemctl") else {"ok": False, "stdout": "unknown"}
pgrep = _run(["pgrep", "-fa", "CrashCore|mihomo"], timeout=2.0) if shutil.which("pgrep") else {"ok": False, "stdout": ""}
unit_active = (active.get("stdout") or "").splitlines()[0] if active.get("stdout") else ("active" if active.get("ok") else "inactive")
running = unit_active == "active" or bool((pgrep.get("stdout") or "").strip())
start_sh = shellcrash_dir() / "start.sh"
mixed = cfg_vals.get("mix_port") or "7890"
selected = None
if running:
prox = _http_json(f"{CONTROLLER}/proxies", timeout=3.0)
if prox.get("ok"):
pdata = (prox.get("data") or {}).get("proxies") or {}
selected = (pdata.get("🚀 节点选择") or {}).get("now") or (pdata.get("GLOBAL") or {}).get("now")
return {
"ok": True,
"available": yaml.get("available") or start_sh.is_file() or unit_active == "active",
"installed": start_sh.is_file() or _unit_exists(unit_name),
"running": running,
"unit": unit_active,
"enabled": (enabled.get("stdout") or "").splitlines()[0] if enabled.get("stdout") else "unknown",
"label": "ShellCrash",
"description": "代理上网 / 规则分流",
"detail": f"mixed :{mixed}" + (f" · 节点 {selected}" if selected else ""),
"status": "online" if running else ("configured" if start_sh.is_file() or _unit_exists(unit_name) else "missing"),
"mixed_port": mixed,
"selected_node": selected,
"default_node": DEFAULT_NODE,
"default_profile": DEFAULT_PROFILE,
"config": yaml,
"roots": managed_roots(),
"hint": "应用配置会写入 config.yaml 并重启;web 面板打开 mihomo UI。",
}
def action(act: str) -> dict[str, Any]:
act = str(act or "").strip().lower()
if act not in {"start", "stop", "restart", "status", "pick"}:
raise ValueError(f"unsupported shellcrash action: {act}")
if act == "status":
return {"ok": True, "action": "status", **status()}
if act == "pick":
picked = pick_best_node()
return {"ok": bool(picked.get("ok")), "action": "pick", "pick": picked, "shellcrash": status()}
unit = "shellcrash.service"
cfg = _config_yaml()
if cfg.get("available") and act in {"start", "restart"}:
_stage_runtime_config(str(cfg.get("path") or ""))
if _unit_exists(unit) or shutil.which("systemctl"):
if act == "start":
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
run = _priv(["systemctl", "enable", "--now", unit], timeout=25.0)
elif act == "stop":
run = _priv(["systemctl", "stop", unit], timeout=20.0)
else:
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
run = _priv(["systemctl", "restart", unit], timeout=25.0)
else:
start = shellcrash_dir() / "start.sh"
if not start.is_file():
raise RuntimeError("未安装 ShellCrash(无 systemd 单元且无 start.sh)")
run = _priv(["bash", str(start), act if act != "restart" else "restart"], timeout=25.0)
time.sleep(2.0)
picked = None
if act in {"start", "restart"}:
time.sleep(1.0)
# Prefer configured default node first, then pick if needed
_select_node_in_groups(DEFAULT_NODE)
egress = probe_mixed(timeout=6.0)
if not egress.get("ok"):
picked = pick_best_node()
st = status()
ok = bool(st.get("running")) if act in {"start", "restart"} else (not st.get("running") if act == "stop" else True)
return {
"ok": bool(run.get("ok")) or ok,
"action": act,
"command_ok": bool(run.get("ok")),
"detail": run.get("stderr") or run.get("stdout") or "",
"pick": picked,
"shellcrash": st,
}

View File

@ -40,6 +40,99 @@ DEFAULT_OAUTH_PROFILES: list[dict[str, str]] = [
# state -> (channel_pk, expires_at, client_id, client_secret, return_to?)
_oauth_states: dict[str, tuple[str, float, str, str] | tuple[str, float, str, str, str]] = {}
_OAUTH_STATE_KEY = "shorts_oauth_pending_states"
def _persist_oauth_states() -> None:
"""Survive API restarts between Google consent and callback."""
now = time.time()
payload: dict[str, list[Any]] = {}
for k, packed in list(_oauth_states.items()):
if len(packed) < 2 or float(packed[1]) < now:
_oauth_states.pop(k, None)
continue
payload[k] = list(packed)
try:
db.update_settings_map({_OAUTH_STATE_KEY: payload})
except Exception:
pass
def _hydrate_oauth_states() -> None:
if _oauth_states:
return
try:
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
except Exception:
raw = {}
if not isinstance(raw, dict):
return
now = time.time()
for k, packed in raw.items():
if not isinstance(packed, (list, tuple)) or len(packed) < 4:
continue
try:
exp = float(packed[1])
except Exception:
continue
if exp < now:
continue
if len(packed) >= 5:
_oauth_states[str(k)] = (
str(packed[0]),
exp,
str(packed[2]),
str(packed[3]),
str(packed[4] or ""),
)
else:
_oauth_states[str(k)] = (str(packed[0]), exp, str(packed[2]), str(packed[3]))
def _stamp_oauth_error(channel_pk: str, err: str) -> None:
pk = str(channel_pk or "").strip()
if not pk:
return
try:
db.update_shorts_channel(
pk,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error=str(err or "授权失败")[:500],
)
except Exception:
pass
def _oauth_log(msg: str) -> None:
try:
with open("/tmp/shorts_oauth.log", "a", encoding="utf-8") as f:
f.write(f"{time.strftime('%F %T')} {msg}\n")
except Exception:
pass
def _google_http_proxy() -> str:
"""Google APIs must egress via ShellCrash on China physical hosts."""
try:
from . import egress_hub
return egress_hub.google_http_proxy()
except Exception:
return "http://127.0.0.1:7890"
def _google_client_kwargs(*, timeout: float = 45.0) -> dict[str, Any]:
try:
from . import egress_hub
return egress_hub.google_httpx_kwargs(timeout=timeout)
except Exception:
proxy = _google_http_proxy()
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
if proxy:
kw["proxy"] = proxy
return kw
def _cfg() -> dict[str, Any]:
@ -187,7 +280,7 @@ async def fetch_google_account_email(access_token: str) -> str:
if not token:
return ""
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
resp = await client.get(
"https://openidconnect.googleapis.com/v1/userinfo",
headers={"Authorization": f"Bearer {token}"},
@ -276,6 +369,7 @@ def channel_can_authorize(channel: dict[str, Any] | None, cfg: dict[str, Any] |
def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: str = "") -> str:
_hydrate_oauth_states()
cfg = _cfg()
channel = db.get_shorts_channel(channel_pk)
if not channel:
@ -291,22 +385,25 @@ def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: s
if ret and (not ret.startswith("/") or ret.startswith("//")):
ret = ""
now = time.time()
# Drop expired + any prior pending state for this same card (double-click / double-fetch).
for k, packed in list(_oauth_states.items()):
if len(packed) < 2 or packed[1] < now:
if len(packed) < 2 or packed[1] < now or str(packed[0]) == str(channel_pk):
_oauth_states.pop(k, None)
state = secrets.token_urlsafe(24)
if ret:
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret, ret)
else:
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret)
_persist_oauth_states()
params = {
"client_id": client_id,
"redirect_uri": resolve_redirect_uri(request_base),
"response_type": "code",
"scope": authorize_scopes(),
"access_type": "offline",
# Must force consent to obtain refresh_token. Do NOT set include_granted_scopes —
# Google often omits refresh_token when the app "already has some access".
"prompt": "consent select_account",
"include_granted_scopes": "true",
"state": state,
}
return "https://accounts.google.com/o/oauth2/v2/auth?" + urlencode(params)
@ -330,7 +427,7 @@ async def token_scopes(access_token: str) -> set[str]:
if not access_token:
return set()
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
resp = await client.get(
"https://oauth2.googleapis.com/tokeninfo",
params={"access_token": access_token},
@ -353,7 +450,7 @@ async def revoke_refresh_token(*, refresh_token: str, client_id: str = "", clien
if not rt:
return False
try:
async with httpx.AsyncClient(timeout=20.0, trust_env=False) as client:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
resp = await client.post(
"https://oauth2.googleapis.com/revoke",
data={"token": rt},
@ -377,8 +474,11 @@ async def prepare_reauthorize(channel_pk: str) -> None:
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
_hydrate_oauth_states()
packed = _oauth_states.pop(state, None)
_persist_oauth_states()
if not packed:
_oauth_log(f"state_miss state={state[:12]} mem={len(_oauth_states)}")
raise ValueError("授权 state 无效或已过期,请重新点击授权")
# Always bind OAuth result to the card the operator clicked.
channel_pk = packed[0]
@ -387,9 +487,12 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
if return_to and (not return_to.startswith("/") or return_to.startswith("//")):
return_to = ""
if exp < time.time():
_stamp_oauth_error(channel_pk, "授权已过期,请重新点击授权")
raise ValueError("授权已过期,请重新点击授权")
cfg = _cfg()
channel = db.get_shorts_channel(channel_pk) or {}
if not channel:
raise ValueError("授权对应的频道已被删除,请新建频道后再授权")
if len(packed) >= 4 and packed[2] and packed[3]:
client_id, client_secret = packed[2], packed[3]
else:
@ -400,120 +503,212 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
source = str(source_meta.get("source") or "none")
profile_id = str(source_meta.get("profile_id") or channel.get("oauth_profile_id") or "").strip().upper()
if not client_id or not client_secret:
raise ValueError("缺少 OAuth Client 配置")
err = "缺少 OAuth Client 配置"
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
redirect_uri = resolve_redirect_uri(request_base)
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client:
token_resp = await client.post(
"https://oauth2.googleapis.com/token",
data={
"code": code,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code",
},
)
token = token_resp.json() if token_resp.content else {}
if token_resp.status_code >= 400 or not token.get("access_token"):
raise ValueError(f"换取 token 失败: {token.get('error_description') or token or token_resp.text}")
access = str(token["access_token"])
refresh = str(token.get("refresh_token") or "").strip()
granted = await token_scopes(access)
missing = missing_required_scopes(granted)
if missing:
scope_hint = "、".join(s.rsplit("/", 1)[-1] for s in missing)
raise ValueError(
f"授权权限不完整(缺 {scope_hint})。"
f"请再点「重授权」;若仍失败,到 Google 账号 → 第三方应用访问权限,移除本应用后再授权。"
)
ch_resp = await client.get(
"https://www.googleapis.com/youtube/v3/channels",
params={"part": "snippet,contentDetails", "mine": "true"},
headers={"Authorization": f"Bearer {access}"},
)
ch_data = ch_resp.json() if ch_resp.content else {}
if ch_resp.status_code >= 400:
err = (ch_data.get("error") or {}).get("message") or ch_resp.text
if "has not been used in project" in str(err) or "youtube.googleapis.com" in str(err):
raise ValueError(
f"OAuth 配置档 {profile_id or '?'} 的 Google 项目未启用 YouTube Data API v3。"
"请到 Google Cloud Console → API 和服务 → 启用「YouTube Data API v3」后,再点「重授权」。"
)
raise ValueError(f"读取 YouTube 频道失败: {err}")
items = ch_data.get("items") or []
yt_id = ""
yt_title = ""
yt_handle = ""
if items:
sn = items[0].get("snippet") or {}
yt_id = str(items[0].get("id") or "")
yt_title = str(sn.get("title") or "")
yt_handle = str(sn.get("customUrl") or "").strip()
google_email = await fetch_google_account_email(access)
# Clicked card wins: accept whatever brand Google returned; never reject / never rewrite siblings.
had_old = bool(str(channel.get("refresh_token") or "").strip())
if not refresh:
if had_old:
refresh = str(channel.get("refresh_token") or "").strip()
else:
raise ValueError("未拿到 refresh_token,请在 Google 账号权限里撤销本应用后重试")
patch: dict[str, Any] = {
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh,
}
if yt_id:
patch["youtube_channel_id"] = yt_id
if google_email:
patch["oauth_email"] = google_email
# Refresh display name/handle from Google — brand label may differ from old card title.
if yt_title:
patch["name"] = yt_title
if profile_id and not str(channel.get("oauth_profile_id") or "").strip():
patch["oauth_profile_id"] = profile_id
updated = db.update_shorts_channel(
channel_pk,
**patch,
oauth_ok=1,
oauth_checked_at=time.time(),
oauth_error="",
proxy = _google_http_proxy()
_oauth_log(
f"exchange pk={channel_pk} redirect={redirect_uri} "
f"secret_tail={client_secret[-4:]} proxy={proxy or 'direct'}"
)
if google_email and profile_id:
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=60.0)) as client:
token_resp = await client.post(
"https://oauth2.googleapis.com/token",
data={
"code": code,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code",
},
)
token = token_resp.json() if token_resp.content else {}
if token_resp.status_code >= 400 or not token.get("access_token"):
err = f"换取 token 失败: {token.get('error_description') or token.get('error') or token or token_resp.text}"
_oauth_log(err)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
access = str(token["access_token"])
refresh = str(token.get("refresh_token") or "").strip()
_oauth_log(
f"token_ok has_refresh={bool(refresh)} keys={sorted(token.keys())} "
f"scope={token.get('scope') or ''}"
)
granted = await token_scopes(access)
missing = missing_required_scopes(granted)
if missing:
scope_hint = "、".join(s.rsplit("/", 1)[-1] for s in missing)
err = (
f"授权权限不完整(缺 {scope_hint})。"
f"请到 https://myaccount.google.com/connections 移除 dylive 后再授权。"
)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
ch_resp = await client.get(
"https://www.googleapis.com/youtube/v3/channels",
params={"part": "snippet,contentDetails", "mine": "true"},
headers={"Authorization": f"Bearer {access}"},
)
ch_data = ch_resp.json() if ch_resp.content else {}
if ch_resp.status_code >= 400:
err_msg = (ch_data.get("error") or {}).get("message") or ch_resp.text
if "has not been used in project" in str(err_msg) or "youtube.googleapis.com" in str(err_msg):
err = (
f"OAuth 配置档 {profile_id or '?'} 的 Google 项目未启用 YouTube Data API v3。"
"请到 Google Cloud Console → API 和服务 → 启用「YouTube Data API v3」后,再点「重授权」。"
)
else:
err = f"读取 YouTube 频道失败: {err_msg}"
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
items = ch_data.get("items") or []
yt_id = ""
yt_title = ""
yt_handle = ""
if items:
sn = items[0].get("snippet") or {}
yt_id = str(items[0].get("id") or "")
yt_title = str(sn.get("title") or "")
yt_handle = str(sn.get("customUrl") or "").strip()
if not items:
err = (
"Google 账号下没有可用的 YouTube 频道(mine=true 为空)。"
"请确认授权时选的是有频道的品牌账号,不是空的 Google 登录号。"
)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
google_email = await fetch_google_account_email(access)
# Clicked card wins: accept whatever brand Google returned; never rewrite siblings.
# Soft-warn if the same YouTube channel is already bound to another Shorts card.
dup_warn = ""
if yt_id:
try:
for other in db.list_shorts_channels(enabled=None):
oid = str(other.get("id") or "")
if oid == channel_pk:
continue
if str(other.get("youtube_channel_id") or "").strip() == yt_id:
dup_warn = (
f"注意:YouTube 频道 {yt_id} 已挂在另一张卡 "
f"「{other.get('name') or oid}」。两张卡会共用同一频道身份,建议删掉重复卡。"
)
try:
db.add_event(
kind="ops",
level="warn",
message=dup_warn,
meta={"channel_pk": channel_pk, "dup_channel_pk": oid, "youtube_channel_id": yt_id},
)
except Exception:
pass
break
except Exception:
pass
had_old = bool(str(channel.get("refresh_token") or "").strip())
if not refresh:
if had_old:
refresh = str(channel.get("refresh_token") or "").strip()
else:
# Revoke this access so the next consent can mint a refresh_token.
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
await client.post(
"https://oauth2.googleapis.com/revoke",
data={"token": access},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
except Exception:
pass
err = (
"未拿到 refresh_token(Google 未下发长期凭证)。"
"已尝试撤销本次临时授权。请打开 https://myaccount.google.com/connections "
"移除 dylive,再回到本页点一次「授权」。"
)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
patch: dict[str, Any] = {
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh,
}
if yt_id:
patch["youtube_channel_id"] = yt_id
if google_email:
patch["oauth_email"] = google_email
# Refresh display name/handle from Google — brand label may differ from old card title.
if yt_title:
patch["name"] = yt_title
if profile_id and not str(channel.get("oauth_profile_id") or "").strip():
patch["oauth_profile_id"] = profile_id
updated = db.update_shorts_channel(
channel_pk,
**patch,
oauth_ok=1,
oauth_checked_at=time.time(),
oauth_error="",
)
if google_email and profile_id:
try:
set_oauth_profile_email(profile_id, google_email)
except Exception:
pass
try:
set_oauth_profile_email(profile_id, google_email)
from . import yt_long_db
yt_long_db.sync_channels_from_shorts()
except Exception:
pass
try:
from . import yt_long_db
profile_err = ""
ypp_err = ""
try:
from . import youtube_manage as ytm
yt_long_db.sync_channels_from_shorts()
except Exception:
pass
try:
from . import youtube_manage as ytm
from .yt_long_monetize import refresh_ypp_for_shorts_channel
await ytm.fetch_channel_profile(channel_pk)
except Exception as exc:
profile_err = str(exc).strip() or "拉取频道资料失败"
try:
from .yt_long_monetize import refresh_ypp_for_shorts_channel
await ytm.fetch_channel_profile(channel_pk)
await refresh_ypp_for_shorts_channel(channel_pk)
ypp_r = await refresh_ypp_for_shorts_channel(channel_pk)
if not ypp_r.get("ok"):
ypp_err = str(ypp_r.get("error") or "YPP 探测失败")[:200]
except Exception as exc:
ypp_err = str(exc).strip() or "YPP 探测失败"
note = " · ".join(x for x in (profile_err, ypp_err) if x)
if note:
db.update_shorts_channel(channel_pk, oauth_error=note)
updated = db.get_shorts_channel(channel_pk) or updated
_oauth_log(f"exchange_ok pk={channel_pk} yt={yt_id} title={yt_title} profile_err={profile_err!r} ypp_err={ypp_err!r}")
return {
"ok": True,
"channel": updated,
"youtube_channel_id": yt_id,
"youtube_title": yt_title or str((updated or {}).get("name") or ""),
"youtube_handle": yt_handle,
"oauth_email": google_email,
"oauth_scopes_ok": True,
"oauth_client_source": source,
"oauth_profile_id": profile_id,
"profile_ok": not bool(profile_err),
"ypp_ok": not bool(ypp_err),
"profile_error": profile_err,
"ypp_error": ypp_err,
"duplicate_channel_warning": dup_warn,
"return_to": return_to,
}
except ValueError:
raise
except Exception as exc:
err = str(exc).strip() or "拉取频道资料失败"
db.update_shorts_channel(channel_pk, oauth_error=err)
return {
"ok": True,
"channel": updated,
"youtube_channel_id": yt_id,
"youtube_title": yt_title or str((updated or {}).get("name") or ""),
"youtube_handle": yt_handle,
"oauth_email": google_email,
"oauth_scopes_ok": True,
"oauth_client_source": source,
"oauth_profile_id": profile_id,
"return_to": return_to,
}
err = f"授权处理异常: {type(exc).__name__}: {exc}"
_oauth_log(err)
_stamp_oauth_error(channel_pk, err)
raise ValueError(err) from exc
def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, str]:

View File

@ -260,7 +260,11 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
"oauth_error": meta.get("oauth_error", str(c.get("oauth_error") or "")),
"brand_hint": meta.get("brand_hint") or "",
"note": str(c.get("note") or ""),
"ypp_ok": ypp_by_shorts.get(cid, -1),
"ypp_ok": (
int(c.get("ypp_ok"))
if c.get("ypp_ok") is not None and int(c.get("ypp_ok")) in (0, 1)
else ypp_by_shorts.get(cid, -1)
),
**stats,
}
)

View File

@ -8,17 +8,8 @@ from urllib.parse import quote
DEFAULT_SOCKS_PROFILE_ID = "residential-1"
DEFAULT_SOCKS_PROFILES: list[dict[str, Any]] = [
{
"id": DEFAULT_SOCKS_PROFILE_ID,
"label": "静态住宅 IP",
"type": "socks5",
"server": "185.124.61.35",
"port": 43676,
"username": "V0sI3BsI1bxgKRx",
"password": "QGwGeRTAa9YcVhM",
}
]
DEFAULT_SOCKS_PROFILES: list[dict[str, Any]] = []
# Fresh installs: no baked-in residential credentials.
def _norm_profile(raw: Any) -> dict[str, Any] | None:
@ -99,12 +90,27 @@ def socks_proxy_url(profile: dict[str, Any] | None) -> str:
def resolve_upload_socks_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Return proxy URL when Shorts SOCKS upload is enabled; else empty (direct)."""
"""Return proxy URL when business egress uploads cover is on; else empty (direct)."""
try:
from . import egress_hub
url = egress_hub.resolve_upload_proxy(cfg)
if url:
return url
# Fall through if egress off — keep legacy shorts toggle for older DBs.
except Exception:
pass
from . import db
settings = dict(cfg if cfg is not None else db.get_settings_map())
if not settings.get("shorts_upload_socks_enabled"):
if not settings.get("shorts_upload_socks_enabled") and not settings.get("global_socks_enabled"):
return ""
try:
from . import global_socks
return global_socks.resolve_app_proxy(settings) or ""
except Exception:
pass
pid = str(settings.get("shorts_upload_socks_profile_id") or "").strip() or DEFAULT_SOCKS_PROFILE_ID
prof = get_socks_profile(pid, settings)
if not prof:

View File

@ -36,9 +36,25 @@ def quota_error_message(profile_id: str = "") -> str:
)
def _sanitize_yt_title(title: str) -> str:
"""YouTube rejects empty titles and angle brackets (invalidTitle)."""
import re
t = re.sub(r"[<>]+", " ", str(title or ""))
t = re.sub(r"\s+", " ", t).strip()
return (t or "Shorts")[:100]
def _client_kwargs(*, timeout: float, proxy_url: str = "") -> dict[str, Any]:
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
proxy = str(proxy_url or "").strip()
if not proxy:
try:
from . import egress_hub
proxy = egress_hub.google_http_proxy()
except Exception:
proxy = ""
if proxy:
kw["proxy"] = proxy
return kw
@ -96,7 +112,7 @@ async def upload_shorts_mp4(
raise ValueError("成片文件不存在,已重新排队录制") from exc
meta = {
"snippet": {
"title": (title or "Shorts")[:100],
"title": _sanitize_yt_title(title),
"description": description or "",
"categoryId": "22",
},

View File

@ -0,0 +1,210 @@
# -*- coding: utf-8 -*-
"""sing-box local mixed inbound → remote SOCKS5 upstream."""
from __future__ import annotations
import json
import os
import shutil
import signal
import subprocess
import time
from pathlib import Path
from typing import Any
from .config import BACKEND
from .global_socks import (
CONFIG_DIR,
LOCAL_MIXED_HOST,
LOCAL_MIXED_PORT,
SINGBOX_CONFIG_PATH,
active_profile,
is_global_socks_enabled,
)
_PID_FILE = CONFIG_DIR / "sing-box.pid"
_LOG_PATH = CONFIG_DIR / "sing-box.log"
def _find_binary() -> str:
for name in ("sing-box", "/usr/bin/sing-box", "/usr/local/bin/sing-box"):
p = shutil.which(name) if not name.startswith("/") else (name if Path(name).is_file() else None)
if p and Path(p).is_file():
return str(p)
return ""
def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
if not profile:
raise ValueError("SOCKS 配置无效")
server = str(profile.get("server") or "").strip()
port = int(profile.get("port") or 0)
if not server or port <= 0:
raise ValueError("SOCKS 服务器或端口无效")
outbound: dict[str, Any] = {
"type": "socks",
"tag": "upstream",
"server": server,
"server_port": port,
"version": "5",
}
user = str(profile.get("username") or "").strip()
pwd = str(profile.get("password") or "")
if user:
outbound["username"] = user
if pwd:
outbound["password"] = pwd
return {
"log": {"level": "warn", "timestamp": True},
"inbounds": [
{
"type": "mixed",
"tag": "mixed-in",
"listen": LOCAL_MIXED_HOST,
"listen_port": LOCAL_MIXED_PORT,
"sniff": True,
}
],
"outbounds": [
outbound,
{"type": "direct", "tag": "direct"},
],
"route": {
"rules": [],
"final": "upstream",
},
}
def write_config(cfg_dict: dict[str, Any]) -> Path:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
SINGBOX_CONFIG_PATH.write_text(json.dumps(cfg_dict, ensure_ascii=False, indent=2), encoding="utf-8")
return SINGBOX_CONFIG_PATH
def _read_pid() -> int:
try:
return int(_PID_FILE.read_text(encoding="utf-8").strip())
except Exception:
return 0
def _pid_alive(pid: int) -> bool:
if pid <= 0:
return False
try:
os.kill(pid, 0)
return True
except OSError:
return False
def is_running() -> bool:
pid = _read_pid()
if _pid_alive(pid):
return True
# systemd fallback
try:
r = subprocess.run(
["systemctl", "is-active", "douyinweb-singbox"],
capture_output=True,
text=True,
timeout=5,
)
return r.returncode == 0 and "active" in (r.stdout or "")
except Exception:
return False
def stop() -> dict[str, Any]:
pid = _read_pid()
if _pid_alive(pid):
try:
os.kill(pid, signal.SIGTERM)
time.sleep(0.8)
except Exception:
pass
try:
subprocess.run(["systemctl", "stop", "douyinweb-singbox"], capture_output=True, timeout=15)
except Exception:
pass
_PID_FILE.unlink(missing_ok=True)
return {"ok": True, "running": False}
def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]:
binary = _find_binary()
if not binary:
return {"ok": False, "running": False, "error": "未安装 sing-box(apt install sing-box 或官方脚本)"}
write_config(cfg_dict)
stop()
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
log_f = open(_LOG_PATH, "a", encoding="utf-8") # noqa: SIM115
try:
proc = subprocess.Popen(
[binary, "run", "-c", str(SINGBOX_CONFIG_PATH)],
stdin=subprocess.DEVNULL,
stdout=log_f,
stderr=subprocess.STDOUT,
cwd=str(BACKEND),
start_new_session=True,
)
except Exception as exc:
log_f.close()
return {"ok": False, "running": False, "error": str(exc)}
_PID_FILE.write_text(str(proc.pid), encoding="utf-8")
time.sleep(0.6)
if proc.poll() is not None:
tail = ""
try:
tail = _LOG_PATH.read_text(encoding="utf-8", errors="replace")[-800:]
except Exception:
pass
return {"ok": False, "running": False, "error": f"sing-box 启动失败: {tail}"}
return {"ok": True, "running": True, "pid": proc.pid, "binary": binary}
def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
from .global_socks import _settings_dict
settings = _settings_dict(cfg)
if not is_global_socks_enabled(settings):
stop()
return {"ok": True, "running": False, "enabled": False}
prof = active_profile(settings)
if not prof:
stop()
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置"}
try:
cfg_dict = build_config(prof)
except ValueError as exc:
stop()
return {"ok": False, "running": False, "enabled": True, "error": str(exc)}
# Prefer systemd unit when present.
write_config(cfg_dict)
try:
r = subprocess.run(
["systemctl", "restart", "douyinweb-singbox"],
capture_output=True,
text=True,
timeout=20,
)
if r.returncode == 0:
time.sleep(0.5)
if is_running():
return {"ok": True, "running": True, "enabled": True, "via": "systemd"}
except Exception:
pass
return {**start_with_config(cfg_dict), "enabled": True, "via": "subprocess"}
def status() -> dict[str, Any]:
binary = _find_binary()
pid = _read_pid()
return {
"running": is_running(),
"pid": pid if _pid_alive(pid) else 0,
"binary": binary,
"config": str(SINGBOX_CONFIG_PATH),
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"error": "",
}

View File

@ -21,6 +21,15 @@ def _cfg() -> dict[str, Any]:
return db.get_settings_map()
def _overseas_kwargs(*, timeout: float = 30.0) -> dict[str, Any]:
try:
from . import egress_hub
return egress_hub.overseas_httpx_kwargs(timeout=timeout)
except Exception:
return {"timeout": timeout, "trust_env": False}
def resolve_client_key_secret(cfg: dict[str, Any] | None = None) -> tuple[str, str]:
settings = cfg or _cfg()
key = str(settings.get("tiktok_oauth_client_key") or "").strip()
@ -123,7 +132,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
if exp < time.time():
raise ValueError("授权已过期,请重新点击授权")
redirect_uri = resolve_redirect_uri(request_base)
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client:
async with httpx.AsyncClient(**_overseas_kwargs(timeout=45.0)) as client:
resp = await client.post(
"https://open.tiktokapis.com/v2/oauth/token/",
headers={"Content-Type": "application/x-www-form-urlencoded"},
@ -204,7 +213,7 @@ async def refresh_access_token(
) -> dict[str, str]:
if not (client_key and client_secret and refresh_token):
raise ValueError("缺少 TikTok OAuth 凭证")
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client:
async with httpx.AsyncClient(**_overseas_kwargs(timeout=45.0)) as client:
resp = await client.post(
"https://open.tiktokapis.com/v2/oauth/token/",
headers={"Content-Type": "application/x-www-form-urlencoded"},

View File

@ -0,0 +1,723 @@
# -*- coding: utf-8 -*-
"""WireGuard hub — adapted from sh2/d2ypp2 wireguard_config.py for douyinWEB.
Physical deploy rule: prefer overlay AllowedIPs (VPN subnet only), never 0.0.0.0/0,
so ShellCrash / soft-router default routes stay intact.
"""
from __future__ import annotations
import ipaddress
import json
import os
import platform
import re
import shutil
import subprocess
import time
from pathlib import Path
from typing import Any
from .config import settings
MAX_WIREGUARD_CONFIG_BYTES = 128 * 1024
_SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9_.-]+")
_BASE64_KEY_RE = re.compile(r"^[A-Za-z0-9+/]{43}=$")
_DEFAULT_ROUTES = {"0.0.0.0/0", "::/0"}
DEFAULT_OVERLAY_MTU = 1360
DEFAULT_KEEPALIVE_SECONDS = 25
PREFERRED_IFACE = "wg-dy"
class WireGuardConfigError(ValueError):
pass
def _imports_dir() -> Path:
p = settings.data_dir / "wireguard" / "imports"
p.mkdir(parents=True, exist_ok=True)
return p
def _run(cmd: list[str], *, timeout: float = 12.0) -> dict[str, Any]:
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
return {"ok": False, "code": 124, "stdout": "", "stderr": str(exc)}
out = (proc.stdout or "").strip()
err = (proc.stderr or "").strip()
return {"ok": proc.returncode == 0, "code": proc.returncode or 0, "stdout": out, "stderr": err}
def _priv(cmd: list[str], *, timeout: float = 20.0) -> dict[str, Any]:
"""Run as root when needed (API may be non-root with passwordless sudo)."""
if hasattr(os, "geteuid") and os.geteuid() == 0:
return _run(cmd, timeout=timeout)
if shutil.which("sudo"):
return _run(["sudo", "-n", *cmd], timeout=timeout)
return _run(cmd, timeout=timeout)
def _unit_state(unit: str) -> dict[str, str]:
if not shutil.which("systemctl"):
return {"active": "unknown", "enabled": "unknown"}
active = _run(["systemctl", "is-active", unit], timeout=3.0)
enabled = _run(["systemctl", "is-enabled", unit], timeout=3.0)
return {
"active": (active["stdout"] or ("active" if active["ok"] else "inactive")).splitlines()[0],
"enabled": (enabled["stdout"] or ("enabled" if enabled["ok"] else "disabled")).splitlines()[0],
}
def _strip_inline_comment(line: str) -> str:
in_quote = False
quote = ""
for idx, ch in enumerate(line):
if ch in {"'", '"'}:
if in_quote and ch == quote:
in_quote = False
quote = ""
elif not in_quote:
in_quote = True
quote = ch
if not in_quote and ch in {"#", ";"}:
return line[:idx]
return line
def _normalized_config_text(content: str) -> str:
return content.replace("\r\n", "\n").replace("\r", "\n")
def safe_wireguard_name(name: str | None) -> str:
raw = (name or PREFERRED_IFACE).strip()
raw = raw[:-5] if raw.lower().endswith(".conf") else raw
safe = _SAFE_NAME_RE.sub("-", raw).strip(".-")
return (safe or PREFERRED_IFACE)[:64]
def _split_csv(value: str) -> list[str]:
return [p.strip() for p in value.split(",") if p.strip()]
def _validate_ip_networks(values: list[str], label: str) -> list[str]:
out: list[str] = []
for raw in values:
try:
out.append(str(ipaddress.ip_network(raw, strict=False)))
except ValueError as exc:
raise WireGuardConfigError(f"Invalid {label}: {raw}") from exc
return out
def _validate_ip_interfaces(values: list[str], label: str) -> list[str]:
out: list[str] = []
for raw in values:
try:
out.append(str(ipaddress.ip_interface(raw)))
except ValueError as exc:
raise WireGuardConfigError(f"Invalid {label}: {raw}") from exc
return out
def _parse_endpoint(value: str) -> tuple[str, int]:
raw = value.strip()
if raw.startswith("["):
end = raw.find("]")
if end < 0 or end + 2 > len(raw) or raw[end + 1] != ":":
raise WireGuardConfigError(f"Invalid Endpoint: {raw}")
host, port_raw = raw[1:end], raw[end + 2 :]
else:
host, sep, port_raw = raw.rpartition(":")
if not sep:
raise WireGuardConfigError(f"Invalid Endpoint: {raw}")
try:
port = int(port_raw)
except ValueError as exc:
raise WireGuardConfigError(f"Invalid Endpoint port: {raw}") from exc
if not host or port < 1 or port > 65535:
raise WireGuardConfigError(f"Invalid Endpoint: {raw}")
return host.strip(), port
def _redact_key(value: str) -> str:
v = value.strip()
if len(v) < 12:
return "***"
return v[:8] + "…" + v[-4:]
def redact_wireguard_config(content: str) -> str:
lines: list[str] = []
for raw in _normalized_config_text(content).splitlines():
stripped = _strip_inline_comment(raw)
if "=" in stripped:
key, _, _val = stripped.partition("=")
if key.strip().lower() in {"privatekey", "presharedkey"}:
lines.append(f"{key.strip()} = ***REDACTED***")
continue
lines.append(raw)
return "\n".join(lines).rstrip() + "\n"
def parse_wireguard_config(content: str, *, name: str | None = None) -> dict[str, Any]:
if "\x00" in content:
raise WireGuardConfigError("config contains NUL")
if len(content.encode("utf-8")) > MAX_WIREGUARD_CONFIG_BYTES:
raise WireGuardConfigError("config too large")
sections: list[dict[str, Any]] = []
current: dict[str, Any] | None = None
warnings: list[str] = []
for lineno, raw in enumerate(_normalized_config_text(content).splitlines(), start=1):
line = _strip_inline_comment(raw).strip()
if not line:
continue
if line.startswith("[") and line.endswith("]"):
section_name = line[1:-1].strip()
if section_name not in {"Interface", "Peer"}:
warnings.append(f"Line {lineno}: ignored [{section_name}]")
current = {"name": section_name, "items": {}}
sections.append(current)
continue
if current is None:
raise WireGuardConfigError(f"Line {lineno}: value before section")
if "=" not in line:
raise WireGuardConfigError(f"Line {lineno}: expected key=value")
key, _, value = line.partition("=")
current["items"].setdefault(key.strip(), []).append(value.strip().strip('"').strip("'"))
interfaces = [s for s in sections if s["name"] == "Interface"]
peers = [s for s in sections if s["name"] == "Peer"]
if not interfaces:
raise WireGuardConfigError("missing [Interface]")
if not peers:
raise WireGuardConfigError("missing [Peer]")
iface_items = interfaces[0]["items"]
addresses = _validate_ip_interfaces(_split_csv(",".join(iface_items.get("Address", []))), "Address")
peer_summaries: list[dict[str, Any]] = []
for idx, peer in enumerate(peers, start=1):
items = peer["items"]
allowed = _validate_ip_networks(_split_csv(",".join(items.get("AllowedIPs", []))), "AllowedIPs")
routes_default = any(a in _DEFAULT_ROUTES for a in allowed)
if routes_default:
warnings.append(
f"Peer {idx}: AllowedIPs has default route — overlay mode strips this so ShellCrash keeps working"
)
endpoint_raw = (items.get("Endpoint") or [""])[-1]
endpoint_host, endpoint_port = ("", None)
if endpoint_raw:
endpoint_host, endpoint_port = _parse_endpoint(endpoint_raw)
keepalive = None
if items.get("PersistentKeepalive"):
try:
keepalive = int(items["PersistentKeepalive"][-1])
except ValueError as exc:
raise WireGuardConfigError("Invalid PersistentKeepalive") from exc
if endpoint_raw and keepalive is None:
warnings.append(f"Peer {idx}: add PersistentKeepalive=25 for NAT/VPS links")
pub = (items.get("PublicKey") or [""])[-1]
peer_summaries.append(
{
"id": idx,
"public_key": _redact_key(pub) if pub else "",
"endpoint": endpoint_raw,
"endpoint_host": endpoint_host,
"endpoint_port": endpoint_port,
"allowed_ips": allowed,
"routes_default": routes_default,
"persistent_keepalive": keepalive,
}
)
return {
"name": safe_wireguard_name(name),
"interface": {
"addresses": addresses,
"listen_port": (iface_items.get("ListenPort") or [None])[-1],
"dns": _split_csv(",".join(iface_items.get("DNS", []))),
"mtu": int(iface_items["MTU"][-1]) if iface_items.get("MTU") else None,
"has_private_key": bool((iface_items.get("PrivateKey") or [""])[-1]),
},
"peers": peer_summaries,
"peer_count": len(peer_summaries),
"warnings": warnings,
"routes_default": any(p.get("routes_default") for p in peer_summaries),
}
def _infer_overlay_allowed_ips(summary: dict[str, Any]) -> list[str]:
out: list[str] = []
for raw in (summary.get("interface") or {}).get("addresses") or []:
try:
iface = ipaddress.ip_interface(str(raw))
except ValueError:
continue
if not iface.ip.is_private:
continue
network = iface.network if iface.network.prefixlen < 32 else ipaddress.ip_network(f"{iface.ip}/24", strict=False)
value = str(network)
if value not in out:
out.append(value)
return out
def normalize_wireguard_keepalive_config(content: str) -> tuple[str, dict[str, Any]]:
lines = _normalized_config_text(content).splitlines()
next_lines: list[str] = []
section = ""
peer_has_keepalive = False
peer_seen_endpoint = False
changed = False
added = 0
def flush() -> None:
nonlocal added, changed, peer_has_keepalive, peer_seen_endpoint
if section == "Peer" and peer_seen_endpoint and not peer_has_keepalive:
next_lines.append(f"PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS}")
added += 1
changed = True
peer_has_keepalive = False
peer_seen_endpoint = False
for raw in lines:
stripped = _strip_inline_comment(raw).strip()
if stripped.startswith("[") and stripped.endswith("]"):
flush()
section = stripped[1:-1].strip()
next_lines.append(raw)
continue
if "=" in stripped and section == "Peer":
key = stripped.partition("=")[0].strip().lower()
if key == "endpoint":
peer_seen_endpoint = True
elif key == "persistentkeepalive":
peer_has_keepalive = True
next_lines.append(raw)
flush()
warnings = []
if added:
warnings.append(f"Added PersistentKeepalive={DEFAULT_KEEPALIVE_SECONDS} to {added} peer(s)")
return "\n".join(next_lines).strip() + "\n", {"changed": changed, "added_keepalive": added, "warnings": warnings}
def normalize_wireguard_overlay_config(content: str, *, name: str | None = None) -> tuple[str, dict[str, Any]]:
"""Strip default routes → VPN subnet only (SH2 overlay)."""
summary = parse_wireguard_config(content, name=name)
overlay_allowed = _infer_overlay_allowed_ips(summary)
warnings: list[str] = []
if not overlay_allowed:
warnings.append("No private Interface Address; kept AllowedIPs")
normalized, keepalive = normalize_wireguard_keepalive_config(content)
warnings.extend(keepalive.get("warnings") or [])
return normalized, {
"changed": bool(keepalive.get("changed")),
"allowed_ips": [],
"warnings": warnings,
"keepalive": keepalive,
}
lines = _normalized_config_text(content).splitlines()
next_lines: list[str] = []
section = ""
peer_has_keepalive = False
peer_seen_endpoint = False
changed = False
added_keepalive = 0
added_mtu = False
interface_has_mtu = False
interface_seen_address = False
def maybe_keepalive() -> None:
nonlocal added_keepalive, changed, peer_has_keepalive, peer_seen_endpoint
if section == "Peer" and peer_seen_endpoint and not peer_has_keepalive:
next_lines.append(f"PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS}")
added_keepalive += 1
changed = True
peer_has_keepalive = False
peer_seen_endpoint = False
for raw in lines:
stripped = _strip_inline_comment(raw).strip()
if stripped.startswith("[") and stripped.endswith("]"):
if section == "Interface" and interface_seen_address and not interface_has_mtu:
next_lines.append(f"MTU = {DEFAULT_OVERLAY_MTU}")
added_mtu = True
changed = True
maybe_keepalive()
section = stripped[1:-1].strip()
if section == "Interface":
interface_has_mtu = False
interface_seen_address = False
next_lines.append(raw)
continue
if "=" not in stripped:
next_lines.append(raw)
continue
key, _, value = stripped.partition("=")
key_l = key.strip().lower()
if section == "Interface":
if key_l == "address":
interface_seen_address = True
elif key_l == "mtu":
interface_has_mtu = True
elif section == "Peer":
if key_l == "endpoint":
peer_seen_endpoint = True
elif key_l == "persistentkeepalive":
peer_has_keepalive = True
elif key_l == "allowedips":
allowed = _validate_ip_networks(_split_csv(value), "AllowedIPs")
if any(item in _DEFAULT_ROUTES for item in allowed):
next_lines.append(f"AllowedIPs = {', '.join(overlay_allowed)}")
changed = True
continue
next_lines.append(raw)
if section == "Interface" and interface_seen_address and not interface_has_mtu:
next_lines.append(f"MTU = {DEFAULT_OVERLAY_MTU}")
added_mtu = True
changed = True
maybe_keepalive()
if changed:
warnings.append("Overlay removed 0.0.0.0/0 so WireGuard will not hijack ShellCrash egress")
if added_mtu:
warnings.append(f"Added MTU {DEFAULT_OVERLAY_MTU}")
if added_keepalive:
warnings.append(f"Added PersistentKeepalive={DEFAULT_KEEPALIVE_SECONDS} ×{added_keepalive}")
return "\n".join(next_lines).strip() + "\n", {
"changed": changed,
"allowed_ips": overlay_allowed,
"warnings": warnings,
}
def save_imported_wireguard_config(
content: str,
*,
name: str | None = None,
route_mode: str = "overlay",
) -> dict[str, Any]:
route_mode = (route_mode or "overlay").strip().lower()
overlay: dict[str, Any] = {"changed": False, "allowed_ips": [], "warnings": []}
if route_mode == "overlay":
normalized, overlay = normalize_wireguard_overlay_config(content, name=name)
elif route_mode == "preserve":
normalized, keepalive = normalize_wireguard_keepalive_config(content)
overlay = {"changed": bool(keepalive.get("changed")), "allowed_ips": [], "warnings": keepalive.get("warnings") or [], "keepalive": keepalive}
else:
raise WireGuardConfigError(f"unsupported route_mode: {route_mode}")
summary = parse_wireguard_config(normalized, name=name)
summary["warnings"] = [*summary.get("warnings", []), *(overlay.get("warnings") or [])]
summary["route_mode"] = route_mode
summary["overlay"] = overlay
safe_name = str(summary["name"])
target = _imports_dir() / f"{safe_name}.conf"
target.write_text(normalized, encoding="utf-8")
try:
os.chmod(target, 0o600)
except OSError:
pass
(target.with_suffix(".summary.json")).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return {
"name": safe_name,
"path": str(target),
"summary": summary,
"redacted_config": redact_wireguard_config(normalized),
"overlay": overlay,
"route_mode": route_mode,
}
def list_imported_configs() -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for path in sorted(_imports_dir().glob("*.conf")):
try:
content = path.read_text(encoding="utf-8", errors="replace")
summary = parse_wireguard_config(content, name=path.stem)
out.append({"name": path.stem, "path": str(path), "source": "import", "peer_count": summary.get("peer_count"), "summary": summary})
except Exception as exc:
out.append({"name": path.stem, "path": str(path), "source": "import", "error": str(exc)})
return out
def list_system_configs() -> list[dict[str, Any]]:
etc = Path("/etc/wireguard")
# Non-root API: list via sudo when directory not readable.
names: list[str] = []
if etc.is_dir():
try:
names = [p.stem for p in sorted(etc.glob("*.conf"))]
except OSError:
names = []
if not names:
ls = _priv(["bash", "-lc", "ls -1 /etc/wireguard/*.conf 2>/dev/null"], timeout=5.0)
for line in (ls.get("stdout") or "").splitlines():
p = Path(line.strip())
if p.suffix == ".conf":
names.append(p.stem)
out: list[dict[str, Any]] = []
for stem in names:
try:
content = _read_conf_text(stem, prefer_system=True)
summary = parse_wireguard_config(content, name=stem)
out.append(
{
"name": stem,
"path": f"/etc/wireguard/{stem}.conf",
"source": "system",
"peer_count": summary.get("peer_count"),
"routes_default": summary.get("routes_default"),
"summary": summary,
}
)
except Exception as exc:
out.append({"name": stem, "path": f"/etc/wireguard/{stem}.conf", "source": "system", "error": str(exc)})
return out
def _read_conf_text(name: str, *, prefer_system: bool = False) -> str:
safe = safe_wireguard_name(name)
bases = [Path("/etc/wireguard"), _imports_dir()] if prefer_system else [_imports_dir(), Path("/etc/wireguard")]
for base in bases:
path = base / f"{safe}.conf"
if path.is_file():
try:
return path.read_text(encoding="utf-8", errors="replace")
except OSError:
pass
# sudo cat for /etc/wireguard
if str(base) == "/etc/wireguard":
r = _priv(["cat", str(path)], timeout=5.0)
if r.get("ok") and r.get("stdout") is not None:
return str(r.get("stdout") or "")
raise WireGuardConfigError(f"config not found: {safe}")
def read_config(name: str) -> dict[str, Any]:
safe = safe_wireguard_name(name)
# Prefer live system conf when present — that is what wg-quick is running.
content = _read_conf_text(safe, prefer_system=True)
sys_path = Path("/etc/wireguard") / f"{safe}.conf"
imp_path = _imports_dir() / f"{safe}.conf"
if sys_path.is_file() or _priv(["test", "-f", str(sys_path)], timeout=3.0).get("ok"):
path_hint = str(sys_path)
source = "system"
else:
path_hint = str(imp_path)
source = "import"
return {
"name": safe,
"path": path_hint,
"source": source,
"content": content,
"redacted_config": redact_wireguard_config(content),
"summary": parse_wireguard_config(content, name=safe),
}
def delete_imported_config(name: str) -> dict[str, Any]:
safe = safe_wireguard_name(name)
path = _imports_dir() / f"{safe}.conf"
if not path.is_file():
raise WireGuardConfigError(f"导入配置不存在: {safe}")
path.unlink(missing_ok=True)
path.with_suffix(".summary.json").unlink(missing_ok=True)
return {"ok": True, "deleted": safe}
def apply_wireguard_config(
content: str,
*,
name: str | None = None,
route_mode: str = "overlay",
) -> dict[str, Any]:
"""Save (overlay by default) + install to /etc/wireguard + enable/restart unit."""
result = save_imported_wireguard_config(content, name=name, route_mode=route_mode)
safe_name = str(result["name"])
source = Path(str(result["path"]))
if platform.system().lower() != "linux":
result["applied"] = False
result["apply_error"] = "WireGuard apply only on Linux"
return result
if not shutil.which("wg-quick"):
raise WireGuardConfigError("wg-quick 未安装")
target = Path("/etc/wireguard") / f"{safe_name}.conf"
for cmd in (
["mkdir", "-p", "/etc/wireguard"],
["install", "-m", "600", str(source), str(target)],
):
run = _priv(cmd, timeout=10.0)
if not run["ok"]:
raise WireGuardConfigError(run["stderr"] or run["stdout"] or f"failed: {' '.join(cmd)}")
unit = f"wg-quick@{safe_name}.service"
st = _unit_state(unit)
if st.get("active") == "active":
run = _priv(["systemctl", "restart", unit], timeout=30.0)
else:
run = _priv(["systemctl", "enable", "--now", unit], timeout=30.0)
if not run["ok"]:
# iface may already be up outside systemd — try wg-quick
fallback = _priv(["wg-quick", "down", safe_name], timeout=15.0)
up = _priv(["wg-quick", "up", safe_name], timeout=20.0)
if not up["ok"]:
raise WireGuardConfigError(
(run["stderr"] or run["stdout"] or "")
+ " | "
+ (up["stderr"] or up["stdout"] or fallback.get("stderr") or "wg-quick failed")
)
result["applied"] = True
result["system_path"] = str(target)
result["status"] = runtime_status()
return result
def iface_action(name: str, action: str) -> dict[str, Any]:
action = str(action or "").strip().lower()
if action not in {"start", "stop", "restart", "status"}:
raise WireGuardConfigError(f"unsupported action: {action}")
safe = safe_wireguard_name(name)
unit = f"wg-quick@{safe}.service"
if action == "status":
return {"ok": True, "name": safe, "unit": _unit_state(unit), "runtime": runtime_status()}
if platform.system().lower() != "linux":
raise WireGuardConfigError("only Linux")
conf = Path("/etc/wireguard") / f"{safe}.conf"
if not conf.is_file() and action != "stop":
raise WireGuardConfigError(f"/etc/wireguard/{safe}.conf missing — import/apply first")
if action == "start":
run = _priv(["systemctl", "enable", "--now", unit], timeout=30.0)
if not run["ok"]:
run = _priv(["wg-quick", "up", safe], timeout=20.0)
elif action == "stop":
run = _priv(["systemctl", "stop", unit], timeout=20.0)
_priv(["wg-quick", "down", safe], timeout=15.0) # best-effort if unit failed
else: # restart
run = _priv(["systemctl", "restart", unit], timeout=30.0)
if not run["ok"]:
_priv(["wg-quick", "down", safe], timeout=15.0)
run = _priv(["wg-quick", "up", safe], timeout=20.0)
if action != "stop" and not run["ok"]:
# stop is ok even if already down
if action == "stop":
pass
else:
raise WireGuardConfigError(run["stderr"] or run["stdout"] or f"{action} failed")
return {"ok": True, "name": safe, "action": action, "unit": _unit_state(unit), "detail": run.get("stdout") or run.get("stderr") or "", "runtime": runtime_status()}
def _parse_wg_show(text: str) -> list[dict[str, Any]]:
ifaces: list[dict[str, Any]] = []
current: dict[str, Any] | None = None
for line in (text or "").splitlines():
if line.startswith("interface:"):
if current:
ifaces.append(current)
current = {"name": line.split(":", 1)[1].strip(), "peers": [], "listening_port": None, "public_key": ""}
elif current is None:
continue
elif "listening port:" in line:
try:
current["listening_port"] = int(line.split(":")[-1].strip())
except Exception:
pass
elif "public key:" in line:
current["public_key"] = _redact_key(line.split(":", 1)[1].strip())
elif line.strip().startswith("peer:"):
current["peers"].append(
{
"public_key": _redact_key(line.split(":", 1)[1].strip()),
"endpoint": "",
"allowed_ips": "",
"latest_handshake": "",
"transfer": "",
}
)
elif current["peers"] and "endpoint:" in line:
current["peers"][-1]["endpoint"] = line.split(":", 1)[1].strip()
elif current["peers"] and "allowed ips:" in line:
current["peers"][-1]["allowed_ips"] = line.split(":", 1)[1].strip()
current["peers"][-1]["routes_default"] = any(
x.strip() in _DEFAULT_ROUTES for x in current["peers"][-1]["allowed_ips"].split(",")
)
elif current["peers"] and "latest handshake:" in line:
current["peers"][-1]["latest_handshake"] = line.split(":", 1)[1].strip()
elif current["peers"] and "transfer:" in line:
current["peers"][-1]["transfer"] = line.split(":", 1)[1].strip()
if current:
ifaces.append(current)
for item in ifaces:
item["systemd"] = _unit_state(f"wg-quick@{item['name']}.service")
# iface up counts as healthy even if systemd unit failed (common with manual wg)
item["link_up"] = True
return ifaces
def runtime_status() -> dict[str, Any]:
from . import shellcrash_hub
commands = {n: bool(shutil.which(n)) for n in ("wg", "wg-quick", "ip", "systemctl")}
show = _priv(["wg", "show"], timeout=5.0) if commands["wg"] else {"ok": False, "stdout": "", "stderr": "no wg"}
# wg show often needs root; try without if priv failed
if not show["ok"] and commands["wg"]:
show = _run(["wg", "show"], timeout=5.0)
interfaces = _parse_wg_show(show["stdout"]) if show.get("ok") or show.get("stdout") else []
if not interfaces and commands["ip"]:
# detect wg-* links
ip_out = _run(["ip", "-br", "link", "show", "type", "wireguard"], timeout=4.0)
for line in (ip_out.get("stdout") or "").splitlines():
name = line.split()[0].rstrip(":") if line.split() else ""
if name:
interfaces.append({"name": name, "peers": [], "link_up": True, "systemd": _unit_state(f"wg-quick@{name}.service")})
system_configs = list_system_configs()
repo_configs = list_imported_configs()
recommendations: list[str] = []
if not interfaces:
names = [c["name"] for c in system_configs + repo_configs]
if names:
recommendations.append(f"配置存在但接口未激活 — 启动 wg-quick@{names[0]}")
else:
recommendations.append("未检测到 WireGuard 接口;导入 conf 后 Apply(overlay)")
for iface in interfaces:
for peer in iface.get("peers") or []:
if peer.get("routes_default"):
recommendations.append(f"{iface.get('name')}: peer 含 0.0.0.0/0 — 建议 overlay 重导入,避免劫持 ShellCrash")
unit = (iface.get("systemd") or {}).get("active")
if unit == "failed" and iface.get("link_up"):
recommendations.append(f"{iface.get('name')}: 接口已 up 但 systemd 为 failed(可忽略或 systemctl reset-failed)")
preferred = next((i for i in interfaces if i.get("name") == PREFERRED_IFACE), interfaces[0] if interfaces else None)
active_names = {str(i.get("name") or "") for i in interfaces if i.get("name")}
for row in system_configs:
row["active"] = str(row.get("name") or "") in active_names
row["role"] = "current" if row.get("name") == (preferred or {}).get("name") else "system"
for row in repo_configs:
row["active"] = str(row.get("name") or "") in active_names
row["role"] = "import"
shell = shellcrash_hub.status()
return {
"ok": True,
"available": bool(commands.get("wg") and commands.get("wg-quick")),
"commands": commands,
"active": bool(interfaces),
"interfaces": interfaces,
"primary": preferred,
"active_config_name": str((preferred or {}).get("name") or PREFERRED_IFACE),
"unit_wg_dy": _unit_state(f"wg-quick@{PREFERRED_IFACE}.service").get("active"),
"system_configs": system_configs,
"repo_configs": repo_configs,
"shellcrash": shell,
"recommendations": recommendations,
"hint": "物理机 AllowedIPs 仅 VPN 网段(如 10.8.0.0/24);导入默认 overlay,勿写 0.0.0.0/0",
"last_checked_at": int(time.time()),
"wg_error": "" if (show.get("ok") or interfaces) else (show.get("stderr") or show.get("stdout") or ""),
}

View File

@ -233,9 +233,16 @@ async def build_live_map(*, force: bool = False) -> dict[str, Any]:
now = time.time()
cached = _CACHE.get("payload")
fresh = bool(cached) and now - float(_CACHE.get("at") or 0) < _CACHE_TTL_SEC
if cached and (fresh or not force):
if force or not fresh:
_schedule_live_map_refresh()
# force=True must actually rebuild (homepage/ops probes rely on this).
if force:
async with _refresh_lock():
return await _build_live_map_unlocked(now=time.time())
if cached and fresh:
return cached
if cached:
_schedule_live_map_refresh()
return cached
# No cache yet: return empty immediately and refresh in background
@ -383,7 +390,158 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
if cid:
entries[f"channel:{cid}"] = dict(old)
live_count = sum(1 for k, v in entries.items() if k.startswith(("group:", "shorts:")) and v.get("is_live"))
# Mirror live Shorts → Live 分配;FFmpeg 转推 / Studio 遥测补洞
try:
from . import yt_assign_db
from . import youtube_neko
from .youtube_relay_pipeline import youtube_relay_pipeline
assign_groups = await asyncio.to_thread(
lambda: yt_assign_db.list_groups(include_urls=False)
)
relay_payload = await asyncio.to_thread(youtube_relay_pipeline.status)
relay_rows = {
str(r.get("group_id") or ""): r for r in (relay_payload.get("groups") or [])
}
pk_to_gid: dict[str, str] = {}
gid_to_name: dict[str, str] = {}
for g in assign_groups:
pk = str(g.get("channel_pk") or "").strip()
gid = str(g.get("id") or "").strip()
if pk and gid:
pk_to_gid[pk] = gid
gid_to_name[gid] = str(g.get("name") or "").strip()
for ref, ent in list(entries.items()):
if not str(ref).startswith("shorts:"):
continue
if not isinstance(ent, dict) or not ent.get("is_live"):
continue
pk = str(ref).split(":", 1)[1]
gid = pk_to_gid.get(pk)
if not gid:
continue
ent["assign_group_id"] = gid
assign_ent = dict(ent)
assign_ent["source"] = "assign"
assign_ent["assign_group_id"] = gid
assign_ent["channel_pk"] = pk
if gid_to_name.get(gid):
assign_ent["title"] = gid_to_name[gid]
entries[f"assign:{gid}"] = assign_ent
for g in assign_groups:
gid = str(g.get("id") or "").strip()
if not gid:
continue
pk = str(g.get("channel_pk") or "").strip()
row = relay_rows.get(gid) or {}
nid = 0
try:
nid = int(g.get("neko_instance_id") or 0)
except (TypeError, ValueError):
nid = 0
studio_snap: dict[str, Any] = {}
if nid > 0:
try:
studio_snap = await asyncio.to_thread(
lambda n=nid: youtube_neko.studio_on_air_lookup(n, max_age_sec=120.0)
)
except Exception:
studio_snap = {}
# Fallback: match telemetry by group's saved studio URL (no CDP / no instance tag).
if not studio_snap.get("on_air"):
studio_url = str(g.get("neko_studio_url") or "")
vid = ""
if "/video/" in studio_url:
try:
vid = studio_url.split("/video/", 1)[1].split("/", 1)[0]
except Exception:
vid = ""
if vid:
for ev in youtube_neko.latest_studio_telemetry(limit=40):
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
url = str(payload.get("url") or "")
if vid not in url:
continue
if str(payload.get("live_status") or "").lower() in {"live", "streaming"} or str(
payload.get("health") or ""
).lower() in {"excellent", "good"}:
studio_snap = {
"on_air": True,
"live_page_open": True,
"live_status": str(payload.get("live_status") or "live"),
"health": str(payload.get("health") or ""),
"viewer_count": payload.get("viewer_count"),
"url": url[:200],
"received_at": float(ev.get("received_at") or 0),
"detect_source": "telemetry_url_match",
"neko_instance_id": nid,
}
break
mark_live = bool(row.get("is_pushing") or studio_snap.get("on_air"))
if not mark_live:
# Keep studio snapshot on assign entry for UI even when offline.
if studio_snap.get("live_page_open") and f"assign:{gid}" in entries:
entries[f"assign:{gid}"]["studio"] = studio_snap
continue
prev = entries.get(f"assign:{gid}") or {}
source = "relay" if row.get("is_pushing") else "studio_telemetry"
if prev.get("is_live") and prev.get("source") not in {"relay", "studio_telemetry"}:
source = str(prev.get("source") or source)
entries[f"assign:{gid}"] = {
**prev,
"is_live": True,
"source": source,
"assign_group_id": gid,
"channel_pk": pk,
"title": gid_to_name.get(gid) or prev.get("title") or str(g.get("name") or ""),
"live_url": str(studio_snap.get("url") or prev.get("live_url") or ""),
"studio": studio_snap or prev.get("studio") or {},
}
if pk:
shorts_ref = f"shorts:{pk}"
shorts_prev = entries.get(shorts_ref) or {}
if not shorts_prev.get("is_live"):
entries[shorts_ref] = {
**shorts_prev,
"is_live": True,
"source": source,
"assign_group_id": gid,
"title": shorts_prev.get("title") or gid_to_name.get(gid) or "",
"live_url": str(studio_snap.get("url") or shorts_prev.get("live_url") or ""),
}
else:
entries[shorts_ref]["assign_group_id"] = gid
cid = str(shorts_prev.get("channel_id") or g.get("youtube_channel_id") or "").strip()
if cid:
entries[f"channel:{cid}"] = dict(entries[shorts_ref])
except Exception as exc:
import logging
logging.getLogger(__name__).warning("live-map assign/studio mirror failed: %s", exc)
live_count = 0
seen_assign: set[str] = set()
for k, v in entries.items():
if not k.startswith("assign:") or not v.get("is_live"):
continue
live_count += 1
seen_assign.add(k.split(":", 1)[1])
for k, v in entries.items():
if not v.get("is_live"):
continue
if k.startswith("shorts:"):
gid = str(v.get("assign_group_id") or "")
if gid and gid in seen_assign:
continue
live_count += 1
elif k.startswith("group:"):
live_count += 1
sources = {str(v.get("source") or "") for v in entries.values() if v.get("is_live")}
primary_source = "youtubei" if "youtubei" in sources else (next(iter(sources)) if sources else "none")

View File

@ -15,6 +15,19 @@ from . import s3_storage
from .shorts_oauth import channel_oauth_creds
from .shorts_upload import refresh_access_token
def _httpx_kwargs(*, timeout: float = 45.0, follow_redirects: bool = False) -> dict[str, Any]:
try:
from . import egress_hub
kw = egress_hub.google_httpx_kwargs(timeout=timeout)
except Exception:
kw = {"timeout": timeout, "trust_env": False}
if follow_redirects:
kw["follow_redirects"] = True
return kw
API = "https://www.googleapis.com/youtube/v3"
log = logging.getLogger("youtube_manage")
@ -67,7 +80,7 @@ async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]:
async def _get(path: str, *, token: str, params: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
async with httpx.AsyncClient(**_httpx_kwargs(timeout=45.0)) as client:
resp = await client.get(
f"{API}/{path}",
params=params,
@ -81,7 +94,7 @@ async def _get(path: str, *, token: str, params: dict[str, Any]) -> dict[str, An
async def _post(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
async with httpx.AsyncClient(**_httpx_kwargs(timeout=45.0)) as client:
resp = await client.post(
f"{API}/{path}",
params=params,
@ -96,7 +109,7 @@ async def _post(path: str, *, token: str, params: dict[str, Any], json_body: dic
async def _put(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
async with httpx.AsyncClient(**_httpx_kwargs(timeout=45.0)) as client:
resp = await client.put(
f"{API}/{path}",
params=params,
@ -111,7 +124,7 @@ async def _put(path: str, *, token: str, params: dict[str, Any], json_body: dict
async def _delete(path: str, *, token: str, params: dict[str, Any]) -> None:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
async with httpx.AsyncClient(**_httpx_kwargs(timeout=45.0)) as client:
resp = await client.delete(
f"{API}/{path}",
params=params,
@ -143,6 +156,11 @@ def list_managed_channels() -> list[dict[str, Any]]:
meta = oauth_meta_from_channel(ch)
except Exception:
meta = {}
try:
sc_ypp = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1)
except Exception:
sc_ypp = -1
ypp_ok = sc_ypp if sc_ypp in (0, 1) else ypp_by_shorts.get(cid, -1)
out.append(
{
"id": ch.get("id"),
@ -158,7 +176,7 @@ def list_managed_channels() -> list[dict[str, Any]]:
"last_status": str(ch.get("last_status") or "offline"),
"last_title": str(ch.get("last_title") or ""),
"last_live_url": str(ch.get("last_live_url") or ""),
"ypp_ok": ypp_by_shorts.get(cid, -1),
"ypp_ok": ypp_ok,
"daily_min": ch.get("daily_min"),
"daily_max": ch.get("daily_max"),
"privacy": ch.get("privacy"),
@ -181,7 +199,7 @@ async def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str:
if not s3_storage.s3_enabled():
return url
try:
async with httpx.AsyncClient(timeout=30.0, trust_env=False, follow_redirects=True) as client:
async with httpx.AsyncClient(**_httpx_kwargs(timeout=30.0, follow_redirects=True)) as client:
resp = await client.get(url, headers={"User-Agent": "Mozilla/5.0"})
resp.raise_for_status()
data = resp.content
@ -204,7 +222,8 @@ async def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str:
async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
token, ch = await _access_for_channel(channel_pk)
yt_id = str(ch.get("youtube_channel_id") or "").strip()
params: dict[str, Any] = {"part": "snippet,contentDetails,statistics,brandingSettings"}
# Include status → isChannelMonetizationEnabled so YPP is written with the same call.
params: dict[str, Any] = {"part": "snippet,contentDetails,statistics,brandingSettings,status"}
if yt_id:
params["id"] = yt_id
else:
@ -216,7 +235,7 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
data = await _get(
"channels",
token=token,
params={"part": "snippet,contentDetails,statistics,brandingSettings", "mine": "true"},
params={"part": "snippet,contentDetails,statistics,brandingSettings,status", "mine": "true"},
)
items = data.get("items") or []
if not items:
@ -232,6 +251,8 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads") or ""
sn = item.get("snippet") or {}
st = item.get("statistics") or {}
ch_status = item.get("status") or {}
ypp = bool(ch_status.get("isChannelMonetizationEnabled"))
thumbs = sn.get("thumbnails") or {}
thumb_cdn = (
((thumbs.get("medium") or {}).get("url"))
@ -240,6 +261,12 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
or ""
)
thumb_url = await _mirror_avatar_to_s3(channel_pk, thumb_cdn) if thumb_cdn else ""
try:
from .yt_long_monetize import _persist_ypp_for_shorts
_persist_ypp_for_shorts(shorts_pk=channel_pk, ypp=ypp, youtube_channel_id=yt_id)
except Exception:
log.exception("persist ypp_ok failed for %s", channel_pk)
profile = {
"ok": True,
"channel_pk": channel_pk,
@ -260,6 +287,7 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
"videoCount": st.get("videoCount"),
"hiddenSubscriberCount": st.get("hiddenSubscriberCount"),
},
"ypp_ok": 1 if ypp else 0,
"raw": item,
}
try:
@ -613,7 +641,7 @@ async def set_thumbnail_from_path(channel_pk: str, video_id: str, file_path: str
ctype = "image/jpeg"
if path.suffix.lower() == ".png":
ctype = "image/png"
async with httpx.AsyncClient(timeout=60.0, trust_env=False) as client:
async with httpx.AsyncClient(**_httpx_kwargs(timeout=60.0)) as client:
resp = await client.post(
"https://www.googleapis.com/upload/youtube/v3/thumbnails/set",
params={"videoId": video_id},

File diff suppressed because it is too large Load Diff

View File

@ -346,6 +346,17 @@ class RelayPushSession:
q.put(None)
try:
try:
from . import egress_hub
wrapped = egress_hub.wrap_ffmpeg_cmd(cmd)
if wrapped != cmd:
self.stats.recent_log.append(
f"[ffmpeg] egress proxychains mode={egress_hub.get_mode()}"
)
cmd = wrapped
except Exception as exc:
self.stats.recent_log.append(f"[ffmpeg] egress wrap skipped: {exc}")
self._proc = subprocess.Popen(
cmd,
stdin=subprocess.DEVNULL,

View File

@ -40,14 +40,7 @@ def _time_slot_mode(cfg: dict[str, Any] | None = None) -> bool:
def _group_in_active_slot(group_id: str, *, keyed_only: bool = False) -> bool:
sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=keyed_only)
for c in sched.get("channels") or []:
if str(c.get("group_id") or "") == str(group_id):
return bool(c.get("active"))
# No schedule rows → treat as not active when keyed_only (nothing to rotate).
if keyed_only:
return False
return True
return yt_assign_db.group_in_rotation_slot(group_id, keyed_only=keyed_only)
def pick_source_for_group(
@ -89,13 +82,8 @@ def pick_source_for_group(
for row in rooms:
if str(row.get("room_id") or "").strip() == prefer_rid:
return _row_to_src(row)
# Monitor may briefly mark room offline while FFmpeg still has a valid pull.
if prefer_url:
return {
"source_url": prefer_url,
"room_id": prefer_rid,
"anchor_name": str(group.get("name") or prefer_rid).strip(),
}
# Slot mode: never reuse stale featured URL when monitor says offline.
# FFmpeg keep-alive on probe flake is handled in _ensure_group_relay_locked.
for row in rooms:
url = str(row.get("url") or "").strip()
rid = str(row.get("room_id") or "").strip()
@ -202,8 +190,51 @@ class YoutubeRelayPipeline:
lane_armed=gid in self._manual_hold or pipeline_enabled,
time_slot_mode=_time_slot_mode(cfg),
)
receiving = bool(monitor.get("is_pushing"))
if monitor.get("is_pushing"):
pushing += 1
# Drop stale DB rows that claim pushing while FFmpeg is gone.
raw_st = str(st.get("status") or "").lower()
armed = gid in self._manual_hold or pipeline_enabled
if not receiving and not running and raw_st in {"pushing", "streaming", "starting"}:
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
ffmpeg_pid=0,
speed=0,
frame=0,
error="",
recent_log=st.get("recent_log") or [],
)
elif not receiving:
err = str(st.get("error") or "")
raw_st2 = str(st.get("status") or "").lower()
if (
err.startswith("非当前时段")
or err.startswith("时段外")
or raw_st2 == "outside_slot"
or "outside_slot" in str(
(st.get("recent_log") or [""])[-1] if isinstance(st.get("recent_log"), list) else ""
)
):
youtube_relay_db.upsert_relay_state(
gid,
status="outside_slot",
ffmpeg_pid=0,
error="",
recent_log=st.get("recent_log") or [],
)
elif not armed:
if err.startswith("同频道备用 KEY") or "outside_slot" in str(
(st.get("recent_log") or [""])[-1] if isinstance(st.get("recent_log"), list) else ""
):
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
ffmpeg_pid=0,
error="",
recent_log=st.get("recent_log") or [],
)
neko_id = int(g.get("neko_instance_id") or 0)
raw_neko = neko_by_id.get(neko_id) if neko_id > 0 else None
neko_state = None
@ -216,6 +247,27 @@ class YoutubeRelayPipeline:
"studio_url": raw_neko.get("studio_url"),
"exists": bool(raw_neko.get("exists")),
}
try:
snap = youtube_neko.studio_on_air_lookup(neko_id, max_age_sec=120.0)
neko_state["studio"] = {
"live_page_open": bool(snap.get("live_page_open")),
"on_air": bool(snap.get("on_air")),
"live_status": snap.get("live_status") or "",
"health": snap.get("health") or "",
"viewer_count": snap.get("viewer_count"),
"like_count": snap.get("like_count"),
"total_views": snap.get("total_views"),
"live_duration": snap.get("live_duration") or "",
"live_duration_sec": snap.get("live_duration_sec"),
"stream_title": snap.get("stream_title") or "",
"url": snap.get("url") or "",
"received_at": snap.get("received_at") or 0,
"age_sec": snap.get("age_sec"),
"detect_source": snap.get("detect_source") or "",
"minute_reports": snap.get("minute_reports") or [],
}
except Exception:
neko_state["studio"] = None
# Trim log text for poll JSON (selected card still has enough to read).
rl = monitor.get("recent_log")
if isinstance(rl, str) and len(rl) > 3500:
@ -230,7 +282,15 @@ class YoutubeRelayPipeline:
"name": g.get("name"),
"channel_pk": g.get("channel_pk"),
"enabled": bool(g.get("enabled")),
"status": "pushing" if running else str(st.get("status") or "idle"),
"status": (
"pushing"
if receiving
else (
"idle"
if raw_st in {"pushing", "streaming", "starting"}
else str(st.get("status") or "idle")
)
),
"error": st.get("error") or "",
"manual_hold": gid in self._manual_hold,
"neko_instance_id": neko_id,
@ -444,20 +504,25 @@ class YoutubeRelayPipeline:
if auto_on:
from . import youtube_neko
# Time-slot: identify current winner once per tick.
# Time-slot: identify current winner once per tick (one group per YouTube channel).
slot_winner_gid = ""
slot_winner_g: dict[str, Any] | None = None
if slot_mode and respect:
for g in groups:
gid0 = str(g.get("id") or "")
if not gid0 or not g.get("enabled"):
continue
if not (str(g.get("stream_key") or "").strip() or g.get("has_stream_key")):
continue
if _group_in_active_slot(gid0, keyed_only=True):
slot_winner_gid = gid0
slot_winner_g = g
break
sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True)
active_ch = next((c for c in sched.get("channels") or [] if c.get("active")), None)
if active_ch:
candidate_ids = [str(active_ch.get("group_id") or "")]
candidate_ids.extend(str(x) for x in (active_ch.get("alias_group_ids") or []) if x)
candidate_ids = [g for g in candidate_ids if g and by_id.get(g)]
for gid0 in candidate_ids:
sess = self._sessions.get(gid0)
if sess and sess.stats.running:
slot_winner_gid = gid0
slot_winner_g = by_id.get(gid0)
break
if not slot_winner_gid and candidate_ids:
slot_winner_gid = candidate_ids[0]
slot_winner_g = by_id.get(slot_winner_gid)
for g in groups:
gid = str(g.get("id") or "")
@ -467,19 +532,39 @@ class YoutubeRelayPipeline:
continue
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
continue
# 时间段模式:非当前时段 → 停推流 + 停 Neko。
# 时间段模式:非当前时段 → 停推流;仅在「单频道独占」时顺带停 Neko(物理机可常驻预热)。
if slot_mode and respect and gid != slot_winner_gid:
if gid in self._sessions:
await self._halt_session(gid, reason="outside_slot")
neko_id = int(g.get("neko_instance_id") or 0)
if neko_id > 0:
await asyncio.to_thread(youtube_neko.stop_instance, neko_id)
youtube_relay_db.upsert_relay_state(
gid,
status="idle",
error="非当前时段:已停推流并关闭 Neko",
recent_log=["[relay] outside_slot — ffmpeg+neko stopped"],
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
same_channel_as_winner = bool(
slot_winner_g and yt_assign_db.same_yt_channel(g, slot_winner_g)
)
in_active_slot = _group_in_active_slot(gid, keyed_only=True)
if same_channel_as_winner and in_active_slot:
if gid in self._sessions:
await self._halt_session(gid, reason="duplicate_channel_key")
neko_id = int(g.get("neko_instance_id") or 0)
if exclusive_on and neko_id > 0:
await asyncio.to_thread(youtube_neko.stop_instance, neko_id)
youtube_relay_db.upsert_relay_state(
gid,
status="paused_exclusive",
error=f"同频道备用 KEY:当前由 {slot_winner_g.get('name') if slot_winner_g else slot_winner_gid} 推流",
recent_log=["[relay] duplicate_yt_channel — paused"],
)
continue
if not in_active_slot:
if gid in self._sessions:
await self._halt_session(gid, reason="outside_slot")
neko_id = int(g.get("neko_instance_id") or 0)
if exclusive_on and neko_id > 0:
await asyncio.to_thread(youtube_neko.stop_instance, neko_id)
youtube_relay_db.upsert_relay_state(
gid,
status="outside_slot",
error="",
recent_log=["[relay] outside_slot — waiting schedule window"],
)
continue
continue
src = pick_source_for_group(
g,
@ -530,26 +615,21 @@ class YoutubeRelayPipeline:
await self.stop_group(gid)
async def set_exclusive_live(self, enabled: bool) -> dict[str, Any]:
"""Toggle hard exclusive (one FFmpeg + stop sibling Nekos). Independent of time-slot schedule."""
db.update_settings_map({"youtube_relay_exclusive_live": bool(enabled)})
if not enabled and (self._exclusive_winner or self._neko_paused_instances):
# 时间段模式强制独占,不允许关掉独占。
if _time_slot_mode():
db.update_settings_map({"youtube_relay_exclusive_live": True})
st = await asyncio.to_thread(self.status)
st["note"] = "时间段模式已开启,单频道独占保持开启"
return st
await self._release_exclusive_live()
return await asyncio.to_thread(self.status)
async def set_time_slot_mode(self, enabled: bool) -> dict[str, Any]:
"""Enable 24/N keyed-channel slots + live Douyin sources + exclusive Neko/FFmpeg.
"""Enable 24/N keyed-channel slots + live Douyin sources.
Does NOT turn on 自动推流 — operator must enable youtube_relay_enabled separately.
Does NOT force exclusive Neko/FFmpeg — operators on physical hosts may
keep multiple Studios warm. Does NOT turn on 自动推流.
"""
on = bool(enabled)
patch: dict[str, Any] = {"youtube_relay_time_slot_mode": on}
if on:
patch["youtube_relay_exclusive_live"] = True
patch["youtube_relay_respect_schedule"] = True
db.update_settings_map(patch)
self._status_cache = None
@ -559,8 +639,7 @@ class YoutubeRelayPipeline:
async def _enforce_exclusive_live(self, winner_gid: str, winner_group: dict[str, Any]) -> None:
"""When one channel actually pushes: stop other FFmpeg + Neko; keep winner Neko up."""
cfg = db.get_settings_map()
# 时间段模式始终独占;否则看开关。
if not (_time_slot_mode(cfg) or bool(cfg.get("youtube_relay_exclusive_live", True))):
if not bool(cfg.get("youtube_relay_exclusive_live", True)):
return
winner_gid = str(winner_gid or "").strip()
if not winner_gid:
@ -864,10 +943,11 @@ class YoutubeRelayPipeline:
await self._enforce_exclusive_live(gid, group)
# Exclusive / time-slot: NEVER start FFmpeg until Studio Live Control Room is
# freshly open and settled. Skipping on stale telemetry causes YouTube green-loading.
# Exclusive: wait for Studio Live before FFmpeg. Without exclusive, only wait if this group's Neko is enabled.
neko_id = int(group.get("neko_instance_id") or 0)
if neko_id > 0 and (_time_slot_mode(cfg) or bool(cfg.get("youtube_relay_exclusive_live", True))):
exclusive_on = bool(cfg.get("youtube_relay_exclusive_live", True))
neko_gate = exclusive_on or bool(group.get("neko_enabled"))
if neko_id > 0 and neko_gate:
from . import youtube_neko
boot_log.append(

View File

@ -191,10 +191,10 @@ def summarize_relay_group(
business_note = "推流速度低于实时"
elif session_running and (has_progress or healthy_speed) and (log_recent or healthy_speed):
business_status = "streaming"
business_note = "正在推流到 YouTube"
business_note = "YouTube 正在接收推流"
elif session_running and has_worker and log_recent and _has_any(tail, ("opening input", "opening output", "rtmps://", "starting ffmpeg", "quality=")):
business_status = "relay_starting"
business_note = "FFmpeg 已启动,等待进度上报"
business_note = "FFmpeg 已连接,等待 YouTube 确认收流"
elif session_running:
business_status = "relay_starting"
business_note = "推流进程运行中"
@ -218,6 +218,11 @@ def summarize_relay_group(
else:
business_status = "monitoring"
business_note = "监听中,等待开播后自动推流"
elif raw_status == "outside_slot" or _has_any(
str(st.get("error") or "").lower(), ("非当前时段", "outside_slot", "时段外")
):
business_status = "outside_slot"
business_note = str(st.get("error") or "时段外:等待本频道轮播窗口").strip() or "时段外:等待本频道轮播窗口"
elif has_key and featured_urls and pipeline_enabled:
business_status = "ready"
business_note = "已配置,等待自动推流"
@ -225,8 +230,11 @@ def summarize_relay_group(
business_status = "ready"
business_note = "已配置(未推流)"
is_pushing = business_status in {"streaming", "relay_slow"} or (
business_status == "source_stalled" and has_progress and has_worker
# YouTube 推流 = KEY 对应频道真正在收流;仅 FFmpeg 进程/DB 状态不算。
is_pushing = bool(
session_running
and business_status in {"streaming", "relay_slow"}
and not _looks_like_youtube_key_rejected(tail)
)
speed = latest.get("speed")

View File

@ -498,12 +498,37 @@ def create_group(
conn = _connect()
try:
ensure_yt_assign_tables(conn)
if ch_pk:
hit = conn.execute(
"SELECT id, name FROM yt_assign_groups WHERE channel_pk = ? LIMIT 1",
(ch_pk,),
).fetchone()
if hit:
raise ValueError(f"该 Shorts 卡已分配给分组「{hit['name'] or hit['id']}」")
if yt_id:
hit = conn.execute(
"SELECT id, name FROM yt_assign_groups WHERE youtube_channel_id = ? LIMIT 1",
(yt_id,),
).fetchone()
if hit:
raise ValueError(
f"YouTube 频道 {yt_id} 已分配给分组「{hit['name'] or hit['id']}」"
)
max_ord = conn.execute("SELECT COALESCE(MAX(sort_order), 0) AS m FROM yt_assign_groups").fetchone()
sort_order = int(max_ord["m"] if max_ord else 0) + 1
max_neko = conn.execute(
"SELECT COALESCE(MAX(neko_instance_id), 0) AS m FROM yt_assign_groups"
).fetchone()
neko_instance_id = int(max_neko["m"] if max_neko else 0) + 1
from . import youtube_neko as _yn
next_id = int(max_neko["m"] if max_neko else 0) + 1
cap = int(_yn._max_instances())
if next_id > cap:
raise ValueError(
f"Neko 实例已达上限 {cap}(DY_NEKO_MAX_INSTANCES / 边缘反代容量)。"
"请删除闲置分组或提高上限并同步边缘 /neko 路由。"
)
neko_instance_id = next_id
conn.execute(
"""
INSERT INTO yt_assign_groups(
@ -535,7 +560,11 @@ def create_group(
try:
from . import youtube_neko
neko_sync = youtube_neko.sync_for_groups(list_groups(include_urls=False))
# Never reconcile_running here — would stop exclusive-live Studio browsers.
neko_sync = youtube_neko.sync_for_groups(
list_groups(include_urls=False),
reconcile_running=False,
)
if not neko_sync.get("ok"):
db.add_event(
kind="ops",
@ -606,10 +635,11 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
if "channel_pk" in patch and patch["channel_pk"]:
ch = db.get_shorts_channel(str(patch["channel_pk"]))
if ch:
yt_from_ch = str(ch.get("youtube_channel_id") or "").strip()
if yt_from_ch:
patch["youtube_channel_id"] = yt_from_ch[:64]
if "name" not in patch or not patch.get("name"):
patch["name"] = str(ch.get("name") or patch.get("name") or "")[:120]
if "youtube_channel_id" not in patch or not patch.get("youtube_channel_id"):
patch["youtube_channel_id"] = str(ch.get("youtube_channel_id") or "")[:64]
if not patch:
g = get_group(group_id)
@ -640,7 +670,12 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
try:
from . import youtube_neko
youtube_neko.sync_for_groups(list_groups(include_urls=False))
# Never reconcile_running — exclusive-live / time-slot may leave
# winner running with neko_enabled=0 and siblings flagged enabled.
youtube_neko.sync_for_groups(
list_groups(include_urls=False),
reconcile_running=False,
)
except Exception:
pass
return group
@ -662,7 +697,8 @@ def delete_group(group_id: str) -> dict[str, Any]:
try:
from . import youtube_neko
youtube_neko.sync_for_groups(list_groups(include_urls=False))
# Do not stop siblings — deleted group's container can linger until manual stop.
youtube_neko.sync_for_groups(list_groups(include_urls=False), reconcile_running=False)
except Exception:
pass
return result
@ -1468,6 +1504,109 @@ def _group_has_stream_key(g: dict[str, Any]) -> bool:
return bool(str(g.get("stream_key") or "").strip())
def _group_yt_channel_key(g: dict[str, Any]) -> str:
"""Stable YouTube channel identity for time-slot dedupe (not per stream key / assign group)."""
meta = _group_yt_channel_meta(g)
if meta.get("youtube_channel_id"):
return f"yt:{meta['youtube_channel_id']}"
pk = str(g.get("channel_pk") or "").strip()
if pk:
return f"pk:{pk}"
return f"gid:{str(g.get('id') or '').strip()}"
def _group_yt_channel_meta(g: dict[str, Any]) -> dict[str, str]:
"""Resolve YouTube channel id + display name from linked Shorts channel (source of truth)."""
pk = str(g.get("channel_pk") or "").strip()
yt = ""
name = str(g.get("name") or "").strip()
if pk:
try:
from . import db as _db
ch = _db.get_shorts_channel(pk)
if ch:
yt = str(ch.get("youtube_channel_id") or "").strip()
name = str(ch.get("name") or name).strip()
except Exception:
pass
if not yt:
yt = str(g.get("youtube_channel_id") or "").strip()
return {"youtube_channel_id": yt, "display_name": name or str(g.get("name") or "")}
def same_yt_channel(a: dict[str, Any], b: dict[str, Any]) -> bool:
ka = _group_yt_channel_key(a)
kb = _group_yt_channel_key(b)
return bool(ka and kb and ka == kb)
def _pick_canonical_group(groups: list[dict[str, Any]]) -> dict[str, Any]:
"""When multiple assign rows share one YouTube channel, pick one schedule row."""
return min(
groups,
key=lambda g: (
int(g.get("sort_order") or 0),
0 if g.get("neko_enabled") else 1,
str(g.get("id") or ""),
),
)
def _dedupe_groups_by_yt_channel(groups: list[dict[str, Any]]) -> list[tuple[dict[str, Any], list[str]]]:
buckets: dict[str, list[dict[str, Any]]] = {}
order: list[str] = []
for g in groups:
key = _group_yt_channel_key(g)
if key not in buckets:
buckets[key] = []
order.append(key)
buckets[key].append(g)
out: list[tuple[dict[str, Any], list[str]]] = []
for key in order:
gs = buckets[key]
canonical = _pick_canonical_group(gs)
cid = str(canonical.get("id") or "")
aliases = [str(g.get("id") or "") for g in gs if str(g.get("id") or "") and str(g.get("id") or "") != cid]
out.append((canonical, aliases))
out.sort(key=lambda pair: (int(pair[0].get("sort_order") or 0), str(pair[0].get("name") or "")))
return out
def group_in_rotation_slot(group_id: str, *, keyed_only: bool | None = None) -> bool:
"""True when this assign group's YouTube channel is in the active 24/N window."""
gid = str(group_id or "").strip()
if not gid:
return False
g = get_group(gid)
if not g or not g.get("enabled"):
return False
if keyed_only is None:
try:
from . import db as _db
keyed_only = bool(_db.get_settings_map().get("youtube_relay_time_slot_mode"))
except Exception:
keyed_only = False
if keyed_only and not _group_has_stream_key(g):
return False
ch_key = _group_yt_channel_key(g)
sched = build_rotation_schedule(include_urls=False, keyed_only=keyed_only)
for c in sched.get("channels") or []:
if str(c.get("group_id") or "") == gid or gid in [str(x) for x in (c.get("alias_group_ids") or [])]:
return bool(c.get("active"))
slot_key = _group_yt_channel_key(
{
"youtube_channel_id": c.get("youtube_channel_id"),
"channel_pk": c.get("channel_pk"),
"id": c.get("group_id"),
}
)
if slot_key == ch_key:
return bool(c.get("active"))
return False if keyed_only else True
def build_rotation_schedule(
*,
include_urls: bool = True,
@ -1476,7 +1615,8 @@ def build_rotation_schedule(
) -> dict[str, Any]:
"""24h Beijing rotation: N channels → 24/N hours each, no overlap.
keyed_only=True (时间段模式): only enabled groups that have a YouTube stream key.
keyed_only=True (时间段模式): enabled groups with a stream key, deduped by YouTube channel
(same channel + different keys still counts as one slot; keys may be wrong/backups).
"""
if groups is None:
raw = list_groups(include_urls=include_urls)
@ -1491,8 +1631,11 @@ def build_rotation_schedule(
keyed_only = False
enabled = [g for g in raw if g.get("enabled")]
if keyed_only:
enabled = [g for g in enabled if _group_has_stream_key(g)]
n = len(enabled)
keyed = [g for g in enabled if _group_has_stream_key(g)]
rotation_rows = _dedupe_groups_by_yt_channel(keyed)
else:
rotation_rows = [(g, []) for g in enabled]
n = len(rotation_rows)
now_h = _beijing_hour_fraction()
if n == 0:
return {
@ -1507,7 +1650,7 @@ def build_rotation_schedule(
}
slot_h = 24.0 / n
channels: list[dict[str, Any]] = []
for i, g in enumerate(enabled):
for i, (g, alias_ids) in enumerate(rotation_rows):
start_h = i * slot_h
end_h = (i + 1) * slot_h
active = start_h <= now_h < end_h if end_h <= 24 else (now_h >= start_h or now_h < (end_h % 24))
@ -1528,13 +1671,16 @@ def build_rotation_schedule(
"window_hours": round(sub_h, 2),
}
)
meta = _group_yt_channel_meta(g)
channels.append(
{
"group_id": g.get("id"),
"name": g.get("name"),
"name": meta.get("display_name") or g.get("name"),
"channel_pk": g.get("channel_pk"),
"youtube_channel_id": g.get("youtube_channel_id"),
"youtube_channel_id": meta.get("youtube_channel_id") or g.get("youtube_channel_id"),
"yt_channel_key": _group_yt_channel_key(g),
"has_stream_key": _group_has_stream_key(g),
"alias_group_ids": alias_ids,
"start_hour": round(start_h, 3),
"end_hour": round(end_h, 3),
"start_label": _fmt_hour(start_h),

View File

@ -122,12 +122,23 @@ async def fetch_channel_ypp_status(
*,
access_token: str,
proxy_url: str = "",
youtube_channel_id: str = "",
) -> dict[str, Any]:
"""Return {ypp: bool, channel_id, raw_status} for the authorized account."""
"""Return {ypp: bool, channel_id, raw_status} for the authorized account.
Prefer explicit youtube_channel_id (multi-brand accounts); fall back to mine=true.
"""
yt_id = str(youtube_channel_id or "").strip()
params: dict[str, Any] = {"part": "id,status,snippet"}
if yt_id:
params["id"] = yt_id
else:
params["mine"] = "true"
async with httpx.AsyncClient(**_client_kwargs(timeout=45.0, proxy_url=proxy_url)) as client:
resp = await client.get(
"https://www.googleapis.com/youtube/v3/channels",
params={"part": "id,status,snippet", "mine": "true"},
params=params,
headers={"Authorization": f"Bearer {access_token}"},
)
data = resp.json() if resp.content else {}
@ -135,10 +146,22 @@ async def fetch_channel_ypp_status(
err = ((data.get("error") or {}).get("message") if isinstance(data, dict) else None) or resp.text[:200]
return {"ok": False, "ypp": False, "error": str(err)[:300]}
items = data.get("items") or []
if not items and yt_id:
resp2 = await client.get(
"https://www.googleapis.com/youtube/v3/channels",
params={"part": "id,status,snippet", "mine": "true"},
headers={"Authorization": f"Bearer {access_token}"},
)
data = resp2.json() if resp2.content else {}
if resp2.status_code >= 400:
err = ((data.get("error") or {}).get("message") if isinstance(data, dict) else None) or resp2.text[:200]
return {"ok": False, "ypp": False, "error": str(err)[:300]}
items = data.get("items") or []
if not items:
return {"ok": False, "ypp": False, "error": "no_channel"}
item = items[0]
st = item.get("status") or {}
# Field only present for owners; missing → treat as not monetized (not "unknown").
ypp = bool(st.get("isChannelMonetizationEnabled"))
return {
"ok": True,
@ -415,18 +438,54 @@ async def ensure_ypp_and_monetize(
return out
def _persist_ypp_for_shorts(*, shorts_pk: str, ypp: bool, youtube_channel_id: str = "") -> str:
"""Write ypp_ok onto Shorts row + linked yt_long (sync from Shorts if missing)."""
from . import db as appdb
from . import yt_long_db as yldb
pk = str(shorts_pk or "").strip()
if not pk:
return ""
now = time.time()
yt_id = str(youtube_channel_id or "").strip()
# Source of truth for UI badges: shorts_channels (always present after OAuth).
try:
sc_patch: dict[str, Any] = {"ypp_ok": 1 if ypp else 0, "ypp_checked_at": now}
if yt_id:
sc_patch["youtube_channel_id"] = yt_id
appdb.update_shorts_channel(pk, **sc_patch)
except Exception:
pass
row = yldb.get_yt_long_by_shorts_pk(pk)
if not row:
try:
yldb.sync_channels_from_shorts()
except Exception:
pass
row = yldb.get_yt_long_by_shorts_pk(pk)
long_id = str((row or {}).get("id") or "").strip()
if not long_id:
return ""
patch: dict[str, Any] = {
"ypp_ok": 1 if ypp else 0,
"ypp_checked_at": now,
}
if yt_id:
patch["youtube_channel_id"] = yt_id
yldb.update_yt_long_channel(long_id, **patch)
return long_id
async def refresh_ypp_for_shorts_channel(shorts_pk: str) -> dict[str, Any]:
"""Probe YPP via OAuth and update linked yt_long_channels row."""
from . import db as appdb
from . import yt_long_db as yldb
from .shorts_oauth import channel_oauth_creds
pk = str(shorts_pk or "").strip()
if not pk:
return {"ok": False, "error": "no_pk"}
row = yldb.get_yt_long_by_shorts_pk(pk)
ch = appdb.get_shorts_channel(pk) or {}
creds = channel_oauth_creds(ch if ch else (row or {}))
creds = channel_oauth_creds(ch)
if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")):
return {"ok": False, "error": "no_oauth", "shorts_pk": pk}
try:
@ -437,25 +496,23 @@ async def refresh_ypp_for_shorts_channel(shorts_pk: str) -> dict[str, Any]:
)
except Exception as exc:
return {"ok": False, "error": f"token:{exc}"[:200], "shorts_pk": pk}
info = await fetch_channel_ypp_status(access_token=access)
known_yt = str(ch.get("youtube_channel_id") or "").strip()
try:
info = await fetch_channel_ypp_status(access_token=access, youtube_channel_id=known_yt)
except Exception as exc:
return {"ok": False, "error": f"probe:{exc}"[:200], "shorts_pk": pk}
ypp = bool(info.get("ypp"))
yt_id = str(info.get("channel_id") or ch.get("youtube_channel_id") or "").strip()
long_id = str((row or {}).get("id") or "").strip()
if long_id and info.get("ok"):
patch: dict[str, Any] = {
"ypp_ok": 1 if ypp else 0,
"ypp_checked_at": time.time(),
}
if yt_id:
patch["youtube_channel_id"] = yt_id
yldb.update_yt_long_channel(long_id, **patch)
yt_id = str(info.get("channel_id") or known_yt).strip()
long_id = ""
if info.get("ok"):
long_id = _persist_ypp_for_shorts(shorts_pk=pk, ypp=ypp, youtube_channel_id=yt_id)
return {
"ok": bool(info.get("ok")),
"ypp": ypp,
"shorts_pk": pk,
"yt_long_pk": long_id,
"youtube_channel_id": yt_id,
"error": info.get("error"),
"error": info.get("error") if not info.get("ok") else ("" if long_id else "no_yt_long_row"),
}
@ -469,9 +526,14 @@ async def refresh_all_ypp_from_shorts(*, limit: int = 50) -> dict[str, Any]:
for ch in rows[: max(1, min(limit, 200))]:
if not str(ch.get("refresh_token") or "").strip():
continue
if not yldb.get_yt_long_by_shorts_pk(str(ch.get("id") or "")):
continue
r = await refresh_ypp_for_shorts_channel(str(ch.get("id") or ""))
# Ensure yt_long mirror exists; persist still writes shorts.ypp_ok even if missing.
pk = str(ch.get("id") or "")
if not yldb.get_yt_long_by_shorts_pk(pk):
try:
yldb.sync_channels_from_shorts()
except Exception:
pass
r = await refresh_ypp_for_shorts_channel(pk)
results.append(r)
if r.get("ypp"):
ypp_count += 1

View File

@ -42,7 +42,12 @@ async def upload_youtube_long_mp4(
raise ValueError("成片文件不存在") from exc
# No #Shorts — this is a normal YouTube watch video (9:16 vertical by default).
clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()[:100]
# Strip <> — YouTube API rejects them (invalidTitle); caption pool may contain ">".
import re
clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()
clean_title = re.sub(r"[<>]+", " ", clean_title)
clean_title = re.sub(r"\s+", " ", clean_title).strip()[:100]
meta = {
"snippet": {
"title": clean_title or "Live clip",

View File

@ -0,0 +1,504 @@
#!/bin/sh
set -eu
family="${1:-chromium}"
start_url="${NEKO_START_URL:-about:blank}"
arch="$(uname -m 2>/dev/null || echo unknown)"
DISPLAY="${DISPLAY:-${ENV_DISPLAY:-:99.0}}"
export DISPLAY
prune_path() {
target="${1:-}"
[ -n "$target" ] || return 0
[ -e "$target" ] || [ -L "$target" ] || return 0
rm -rf "$target" 2>/dev/null || true
}
ensure_writable_dir() {
target="${1:-}"
[ -n "$target" ] || return 0
mkdir -p "$target" 2>/dev/null || true
chmod u+rwX "$target" 2>/dev/null || true
}
repair_profile_runtime() {
mkdir -p "$profile_dir" 2>/dev/null || true
prune_path "$profile_dir/SingletonCookie"
prune_path "$profile_dir/SingletonLock"
prune_path "$profile_dir/SingletonSocket"
prune_path "$profile_dir/SingletonStartupLock"
prune_path "$profile_dir/lockfile"
prune_path "$profile_dir/DevToolsActivePort"
prune_path "$profile_dir/BrowserMetrics"
prune_path "$profile_dir/Crash Reports"
prune_path "$profile_dir/Crashpad"
prune_path "$profile_dir/ShaderCache"
prune_path "$profile_dir/GrShaderCache"
prune_path "$profile_dir/GraphiteDawnCache"
prune_path "$profile_dir/Default/Cache"
prune_path "$profile_dir/Default/Code Cache"
prune_path "$profile_dir/Default/GPUCache"
prune_path "$profile_dir/Default/DawnGraphiteCache"
prune_path "$profile_dir/Default/DawnWebGPUCache"
ensure_writable_dir "$profile_dir"
ensure_writable_dir "$profile_dir/Default"
ensure_writable_dir "$profile_dir/Crash Reports/pending"
ensure_writable_dir "$profile_dir/Default/WebStorage/3/IndexedDB"
ensure_writable_dir "$profile_dir/Default/IndexedDB"
ensure_writable_dir "$profile_dir/Default/Service Worker"
ensure_writable_dir "$profile_dir/Default/Service Worker/CacheStorage"
ensure_writable_dir "$profile_dir/Default/Local Extension Settings"
ensure_writable_dir "$profile_dir/Default/Managed Extension Settings"
chmod -R u+rwX "$profile_dir" 2>/dev/null || true
}
ensure_profile_preferences() {
if ! command -v python3 >/dev/null 2>&1; then
return 0
fi
mkdir -p "$profile_dir/Default"
PROFILE_DIR="$profile_dir" python3 - <<'PY'
import json
import os
from pathlib import Path
profile_dir = Path(os.environ["PROFILE_DIR"])
def load_json(path: Path) -> dict:
if path.exists():
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
return {}
def save_json(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(data, ensure_ascii=False, separators=(",", ":")),
encoding="utf-8",
)
for relative_path in ("Default/Preferences", "Local State"):
path = profile_dir / relative_path
data = load_json(path)
extensions = data.setdefault("extensions", {})
ui = extensions.setdefault("ui", {})
ui["developer_mode"] = True
profile = data.setdefault("profile", {})
profile["exit_type"] = "Normal"
save_json(path, data)
PY
}
managed_policies_enabled() {
case "${NEKO_MANAGED_POLICIES:-1}" in
1|true|TRUE|yes|YES|on|ON|enable|enabled)
return 0
;;
*)
return 1
;;
esac
}
copy_seed_dir_if_missing() {
src="${1:-}"
dst="${2:-}"
marker="${3:-}"
[ -d "$src" ] || return 0
if [ -e "$dst" ]; then
if [ -z "$marker" ] || grep -R -a -q "$marker" "$dst" 2>/dev/null; then
return 0
fi
rm -rf "$dst" 2>/dev/null || true
fi
mkdir -p "$(dirname "$dst")"
cp -a "$src" "$dst" 2>/dev/null || true
rm -f "$dst/LOCK" 2>/dev/null || true
chmod -R u+rwX "$dst" 2>/dev/null || true
}
seed_tampermonkey_storage_if_missing() {
src="${1:-}"
dst="${2:-}"
[ -d "$src" ] || return 0
grep -R -a -q "YouTube Studio Auto Dismiss" "$src" 2>/dev/null || return 0
if [ -d "$dst" ]; then
if grep -R -a -q "YouTube Studio Auto Dismiss" "$dst" 2>/dev/null; then
chmod -R u+rwX "$dst" 2>/dev/null || true
return 0
fi
case "${NEKO_TAMPERMONKEY_REPAIR:-1}" in
1|true|TRUE|yes|YES|on|ON|enable|enabled)
rm -rf "$dst" 2>/dev/null || true
;;
*)
return 0
;;
esac
fi
mkdir -p "$(dirname "$dst")"
cp -a "$src" "$dst" 2>/dev/null || true
rm -f "$dst/LOCK" 2>/dev/null || true
chmod -R u+rwX "$dst" 2>/dev/null || true
}
sync_tampermonkey_preferences() {
seed_preferences="${seed_dir}/Default/Preferences"
[ -f "$seed_preferences" ] || return 0
command -v python3 >/dev/null 2>&1 || return 0
SEED_PREFERENCES="$seed_preferences" PROFILE_DIR="$profile_dir" python3 - <<'PY'
import json
import os
from pathlib import Path
ext_id = "dhdgffkkebhmkfjojejmpbldmpobfkfo"
seed_preferences = Path(os.environ["SEED_PREFERENCES"])
profile_dir = Path(os.environ["PROFILE_DIR"])
target_preferences = profile_dir / "Default" / "Preferences"
ext_root = profile_dir / "Default" / "Extensions" / ext_id
def load(path: Path) -> dict:
if not path.exists():
return {}
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
def installed_versions(root: Path) -> list[str]:
if not root.is_dir():
return []
out = []
for child in root.iterdir():
if child.is_dir() and (child / "manifest.json").is_file():
out.append(child.name)
return sorted(out)
def version_from_path(path_value: str) -> str:
path_value = (path_value or "").strip()
if not path_value:
return ""
return path_value.split("/")[-1]
seed = load(seed_preferences)
source = seed.get("extensions", {}).get("settings", {}).get(ext_id)
if not isinstance(source, dict):
raise SystemExit(0)
target = load(target_preferences)
settings = target.setdefault("extensions", {}).setdefault("settings", {})
current = settings.get(ext_id)
installed = installed_versions(ext_root)
def should_replace_current(value: object) -> bool:
if not isinstance(value, dict):
return True
if value.get("state") != 1:
return True
registered = version_from_path(str(value.get("path") or ""))
if registered and registered in installed:
return False
if installed:
return False
return True
if should_replace_current(current):
settings[ext_id] = source
current = settings[ext_id]
if isinstance(current, dict) and installed:
registered = version_from_path(str(current.get("path") or ""))
chosen = registered if registered in installed else installed[-1]
current["path"] = f"{ext_id}/{chosen}"
current["state"] = 1
target_preferences.parent.mkdir(parents=True, exist_ok=True)
target_preferences.write_text(json.dumps(target, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
PY
}
ensure_tampermonkey_seed() {
seed_dir="${NEKO_TAMPERMONKEY_SEED_DIR:-/etc/neko/tampermonkey-seed}"
ext_id="dhdgffkkebhmkfjojejmpbldmpobfkfo"
[ -d "$seed_dir/Default" ] || return 0
mkdir -p "$profile_dir/Default"
copy_seed_dir_if_missing \
"$seed_dir/Default/Extensions/$ext_id" \
"$profile_dir/Default/Extensions/$ext_id" \
"Tampermonkey"
seed_tampermonkey_storage_if_missing \
"$seed_dir/Default/Local Extension Settings/$ext_id" \
"$profile_dir/Default/Local Extension Settings/$ext_id"
chown -R neko:neko "$profile_dir/Default/Local Extension Settings" "$profile_dir/Default/Managed Extension Settings" 2>/dev/null || true
sync_tampermonkey_preferences
}
find_bin() {
if [ "$family" = "google-chrome" ]; then
command -v google-chrome 2>/dev/null || command -v google-chrome-stable 2>/dev/null || true
else
command -v chromium 2>/dev/null || command -v chromium-browser 2>/dev/null || true
fi
}
browser_bin="$(find_bin)"
if [ -z "$browser_bin" ]; then
exit 0
fi
profile_dir="/home/neko/.config/chromium"
if [ "$family" = "google-chrome" ]; then
profile_dir="/home/neko/.config/google-chrome"
fi
render_mode="${NEKO_BROWSER_RENDER_MODE:-auto}"
render_flags="--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --disable-features=UseSkiaRenderer,Vulkan,VizDisplayCompositor,CanvasOopRasterization --disable-vulkan"
case "$render_mode" in
auto)
render_flags="--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --disable-features=UseSkiaRenderer,Vulkan,VizDisplayCompositor,CanvasOopRasterization --disable-vulkan --disable-zero-copy --disable-accelerated-2d-canvas --disable-accelerated-video-decode --disable-accelerated-video-encode"
;;
gpu)
render_flags=""
;;
legacy|x11|disable-gpu)
render_flags="--disable-gpu --disable-gpu-compositing --disable-software-rasterizer --disable-features=UseSkiaRenderer,VizDisplayCompositor,CanvasOopRasterization"
;;
software|swiftshader)
render_flags="--disable-gpu --use-gl=swiftshader --enable-unsafe-swiftshader --disable-features=UseSkiaRenderer,Vulkan,VizDisplayCompositor --disable-vulkan"
;;
esac
sandbox_flags=""
if [ "$(id -u 2>/dev/null || echo 0)" = "0" ]; then
sandbox_flags="--no-sandbox --disable-setuid-sandbox"
fi
proxy_flags=""
quic_flags=""
case "${NEKO_BROWSER_PROXY:-}" in
""|0|false|FALSE|off|OFF|none|NONE|direct|DIRECT)
;;
*invalid*|*invalid\ IP*|*host-gateway*)
;;
http://*|https://*)
proxy_bypass="${NEKO_BROWSER_PROXY_BYPASS:-<-loopback>;localhost;127.0.0.1;::1;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;*.local;host.docker.internal}"
proxy_flags="--proxy-server=${NEKO_BROWSER_PROXY} --proxy-bypass-list=${proxy_bypass}"
# Avoid Google login cancel when HTTP goes via proxy but WebRTC STUN leaks LAN/Docker IP.
quic_flags="--disable-quic --force-webrtc-ip-handling-policy=disable_non_proxied_udp --disable-features=WebRtcAllowInputVolumeAdjustment"
;;
esac
extension_flags=""
case "${NEKO_LIVE_OPS_EXTENSION:-1}" in
0|false|FALSE|off|OFF|disable|disabled)
;;
*)
live_ops_extension_dir="${NEKO_LIVE_OPS_EXTENSION_DIR:-/etc/neko/live-ops-extension}"
if [ -f "$live_ops_extension_dir/manifest.json" ]; then
extension_flags="--load-extension=${live_ops_extension_dir}"
fi
;;
esac
mkdir -p "${HOME:-/home/neko}/.local/share/icons/hicolor" 2>/dev/null || true
browser_class="google-chrome"
if [ "$family" != "google-chrome" ]; then
browser_class="chromium"
fi
profile_has_session() {
for candidate in \
"$profile_dir/Default/Last Session" \
"$profile_dir/Default/Current Session" \
"$profile_dir/Default/Last Tabs"
do
if [ -f "$candidate" ]; then
return 0
fi
done
if [ -d "$profile_dir/Default/Sessions" ] && [ -n "$(ls -A "$profile_dir/Default/Sessions" 2>/dev/null || true)" ]; then
return 0
fi
return 1
}
launch_browser() {
launch_url=""
launch_window_flag="--new-window"
if profile_has_session; then
launch_url=""
launch_window_flag=""
elif [ -n "$start_url" ] && [ "$start_url" != "about:blank" ]; then
launch_url="$start_url"
fi
set -- "$browser_bin" \
${render_flags} \
${proxy_flags} \
${quic_flags} \
${extension_flags} \
${sandbox_flags} \
--window-position=0,0 \
--display="${DISPLAY}" \
--remote-debugging-address=127.0.0.1 \
--remote-debugging-port=9222 \
--user-data-dir="$profile_dir" \
--password-store=basic \
--no-first-run \
--start-maximized \
--disable-background-mode \
--disable-dev-shm-usage \
--disable-breakpad \
--disable-default-apps \
--disable-translate \
--metrics-recording-only \
--no-default-browser-check
if [ -n "$launch_window_flag" ]; then
set -- "$@" "$launch_window_flag"
fi
if [ -n "$launch_url" ]; then
set -- "$@" "$launch_url"
fi
"$@" &
browser_pid=$!
}
visible_window_count() {
if ! command -v xdotool >/dev/null 2>&1; then
return 1
fi
DISPLAY="${DISPLAY:?DISPLAY is required}" xdotool search --onlyvisible --class "$browser_class" 2>/dev/null | wc -l | tr -d ' '
}
devtools_ready() {
if command -v curl >/dev/null 2>&1; then
curl -fsS --max-time 1 http://127.0.0.1:9222/json/version >/dev/null 2>&1 && return 0
fi
if command -v wget >/dev/null 2>&1; then
wget -q -T 1 -O /dev/null http://127.0.0.1:9222/json/version >/dev/null 2>&1 && return 0
fi
return 1
}
browser_healthy() {
window_count="$(visible_window_count || true)"
if [ -n "${window_count:-}" ] && [ "$window_count" -gt 0 ] 2>/dev/null; then
return 0
fi
devtools_ready
}
focus_live_studio_tab_once() {
case "${NEKO_FOCUS_LIVE_TAB:-1}" in
0|false|FALSE|off|OFF|disable|disabled)
return 0
;;
esac
command -v python3 >/dev/null 2>&1 || return 0
python3 - <<'PY'
import json
import time
import urllib.request
def fetch_tabs():
with urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3) as resp:
return json.loads(resp.read().decode("utf-8", "replace"))
for _ in range(40):
try:
tabs = fetch_tabs()
break
except Exception:
time.sleep(1)
else:
raise SystemExit(0)
def is_live(url: str) -> bool:
return "studio.youtube.com" in url and "livestreaming" in url
def is_junk(url: str) -> bool:
return any(
x in url
for x in (
"tampermonkey.net/changelog",
"tampermonkey.net/installed",
"accounts.google.com/ServiceLogin",
"accounts.google.com/v3/signin",
"accounts.google.com/accountchooser",
"accounts.google.com/RotateCookiesPage",
)
)
live = [t for t in tabs if is_live(t.get("url") or "")]
for tab in tabs:
if not is_junk(tab.get("url") or ""):
continue
tid = tab.get("id")
if not tid:
continue
try:
urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=2)
except Exception:
pass
if not live:
raise SystemExit(0)
target = live[0]
tid = target.get("id")
if not tid:
raise SystemExit(0)
try:
urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}", timeout=2)
except Exception:
pass
PY
}
restart_delay="${NEKO_BROWSER_RESTART_DELAY:-2}"
while :; do
repair_profile_runtime
ensure_tampermonkey_seed
ensure_profile_preferences
launch_browser
seen_window=0
focused_live_tab=0
startup_misses=0
closed_misses=0
while kill -0 "$browser_pid" 2>/dev/null; do
if browser_healthy; then
if [ "$focused_live_tab" -eq 0 ]; then
focus_live_studio_tab_once || true
focused_live_tab=1
fi
seen_window=1
startup_misses=0
closed_misses=0
else
if [ "$seen_window" -eq 0 ]; then
startup_misses=$((startup_misses + 1))
if [ "$startup_misses" -ge 15 ]; then
echo "Chromium did not expose a visible window or DevTools endpoint; restarting"
kill -TERM "$browser_pid" 2>/dev/null || true
break
fi
else
closed_misses=$((closed_misses + 1))
if [ "$closed_misses" -ge 3 ]; then
echo "Chromium health check failed after startup; restarting"
kill -TERM "$browser_pid" 2>/dev/null || true
break
fi
fi
fi
sleep 2
done
browser_rc=0
wait "$browser_pid" 2>/dev/null || browser_rc=$?
echo "Chromium exited with status ${browser_rc}; restarting in ${restart_delay}s"
sleep "$restart_delay"
done

View File

@ -0,0 +1,260 @@
# -*- coding: utf-8 -*-
"""Read-only CDP scrape of YouTube Studio livestreaming page (inside Neko)."""
from __future__ import annotations
import base64
import json
import os
import re
import socket
import struct
import time
import urllib.request
def ws_connect(url: str) -> socket.socket:
assert url.startswith("ws://"), url
hostport, path = url[5:].split("/", 1)
path = "/" + path
host, port_s = hostport.split(":")
port = int(port_s)
key = base64.b64encode(os.urandom(16)).decode()
sock = socket.create_connection((host, port), timeout=6)
req = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {hostport}\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n"
).encode()
sock.sendall(req)
buf = b""
while b"\r\n\r\n" not in buf:
chunk = sock.recv(4096)
if not chunk:
raise RuntimeError("ws handshake closed")
buf += chunk
return sock
def ws_send(sock: socket.socket, payload: dict) -> None:
data = json.dumps(payload).encode()
mask = os.urandom(4)
header = bytearray([0x81])
n = len(data)
if n < 126:
header.append(0x80 | n)
elif n < 65536:
header.append(0x80 | 126)
header.extend(struct.pack("!H", n))
else:
header.append(0x80 | 127)
header.extend(struct.pack("!Q", n))
header.extend(mask)
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
sock.sendall(bytes(header) + masked)
def ws_recv(sock: socket.socket):
def readexact(n: int) -> bytes:
out = b""
while len(out) < n:
chunk = sock.recv(n - len(out))
if not chunk:
raise RuntimeError("ws closed")
out += chunk
return out
hdr = readexact(2)
b1, b2 = hdr[0], hdr[1]
opcode = b1 & 0x0F
masked = (b2 & 0x80) != 0
ln = b2 & 0x7F
if ln == 126:
ln = struct.unpack("!H", readexact(2))[0]
elif ln == 127:
ln = struct.unpack("!Q", readexact(8))[0]
mask = readexact(4) if masked else b""
data = readexact(ln)
if masked:
data = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
if opcode == 0x8:
return None
if opcode != 0x1:
# ignore non-text frames
return {"id": None}
return json.loads(data.decode())
def main() -> None:
tabs = json.loads(
urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode()
)
live = []
chooser = None
for t in tabs:
u = t.get("url") or ""
try:
from urllib.parse import urlparse
p = urlparse(u)
host = (p.netloc or "").lower()
path = (p.path or "").lower()
except Exception:
continue
if host.endswith("studio.youtube.com") and "livestreaming" in path:
live.append(t)
if "accounts.google.com" in host and chooser is None:
chooser = t
if not live:
if chooser:
print(
json.dumps(
{
"ok": True,
"url": (chooser.get("url") or "")[:200],
"live_status": "signed_out",
"health": "",
"viewer_count": None,
"on_air": False,
"text": "Google accountchooser / signed out",
},
ensure_ascii=False,
)
)
return
print(json.dumps({"ok": False, "error": "no_live_tab"}))
return
tab = live[0]
ws_url = tab.get("webSocketDebuggerUrl") or ""
url = tab.get("url") or ""
if not ws_url:
print(json.dumps({"ok": False, "error": "no_ws", "url": url[:120]}))
return
sock = ws_connect(ws_url)
ws_send(
sock,
{
"id": 1,
"method": "Runtime.evaluate",
"params": {
"expression": "(document.body && (document.body.innerText||'')).slice(0,12000)",
"returnByValue": True,
},
},
)
deadline = time.time() + 5
text = ""
while time.time() < deadline:
msg = ws_recv(sock)
if not msg:
break
if msg.get("id") == 1:
text = str(((msg.get("result") or {}).get("result") or {}).get("value") or "")
break
try:
sock.close()
except Exception:
pass
lower = text.lower()
status = ""
if re.search(r"stream ended|not live|offline|直播已结束|未在直播", lower):
status = "ended"
elif re.search(
r"you.?re live|you are live|stream is healthy|excellent connection|"
r"concurrent viewers|watching now|stop streaming|end stream|"
r"直播中|正在直播|人正在观看|结束直播",
lower,
):
status = "live"
elif re.search(r"\blive\b.{0,40}\d+:\d{2}:\d{2}", lower):
# e.g. "LIVE 1:19:36" on Studio control room
status = "live"
elif re.search(r"waiting|preview|scheduled|等待|预定|未开始", lower):
status = "waiting"
health = ""
if re.search(r"excellent connection|stream is healthy|状况良好|连接状况极佳", lower):
health = "excellent"
elif re.search(r"good connection|healthy|良好", lower):
health = "good"
elif re.search(r"unstable|poor|buffer|warning|不稳定|卡顿", lower):
health = "warning"
# Concurrent viewers (not cumulative Views)
viewers = None
m = re.search(
r"([\d,.]+)\s*(?:watching|concurrent viewers|人正在观看|正在观看)",
text,
re.I,
)
if not m:
m = re.search(
r"(?:concurrent viewers|watching now|同时观看人数)\s*[::]?\s*([\d,.]+)",
text,
re.I,
)
if m:
try:
viewers = int(float(m.group(1).replace(",", "")))
except Exception:
viewers = None
# Analytics cumulative Views (Studio Analytics tab)
total_views = None
m = re.search(r"(?:^|\n)\s*Views\s*\n\s*([\d,.]+)", text, re.I)
if not m:
m = re.search(r"\bViews\b(?!\s*per)(?![^\n]{0,12}concurrent)\s*[::]?\s*([\d,.]+)", text, re.I)
if not m:
m = re.search(r"(?:总观看|观看次数|观看量)\s*[::]?\s*([\d,.]+)", text)
if m:
try:
total_views = int(float(m.group(1).replace(",", "")))
except Exception:
total_views = None
# LIVE pill duration e.g. "LIVE 37:06" / "LIVE 1:19:36"
live_duration = ""
live_duration_sec = None
m = re.search(r"\bLIVE\b\s*(\d{1,2}:\d{2}(?::\d{2})?)", text, re.I)
if not m:
m = re.search(r"(?:直播时长|已直播)\s*[::]?\s*(\d{1,2}:\d{2}(?::\d{2})?)", text)
if m:
live_duration = m.group(1)
try:
parts = [int(x) for x in live_duration.split(":")]
if len(parts) == 3:
live_duration_sec = parts[0] * 3600 + parts[1] * 60 + parts[2]
elif len(parts) == 2:
live_duration_sec = parts[0] * 60 + parts[1]
except Exception:
live_duration_sec = None
on_air = status == "live" or health in {"excellent", "good"} or (
viewers is not None and status != "ended" and status != "waiting"
) or bool(live_duration and status != "ended" and status != "waiting")
print(
json.dumps(
{
"ok": True,
"url": url[:200],
"live_status": status,
"health": health,
"viewer_count": viewers,
"total_views": total_views,
"live_duration": live_duration,
"live_duration_sec": live_duration_sec,
"on_air": on_air,
"text": text[:500],
},
ensure_ascii=False,
)
)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,32 @@
[program:chromium]
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
command=/etc/neko/browser-launch.sh chromium
stopsignal=INT
autorestart=true
priority=800
user=%(ENV_USER)s
stdout_logfile=/var/log/neko/chromium.log
stdout_logfile_maxbytes=100MB
stdout_logfile_backups=10
redirect_stderr=true
[program:tampermonkey-provisioning]
command=/bin/sh -c 'cd /var/www/provisioning && if command -v python3 >/dev/null 2>&1; then exec python3 -m http.server 18080 --bind 127.0.0.1; fi; if command -v busybox >/dev/null 2>&1; then exec busybox httpd -f -p 127.0.0.1:18080 -h /var/www/provisioning; fi; echo "no static file server for Tampermonkey provisioning"; sleep 3600'
autorestart=true
priority=250
user=%(ENV_USER)s
stdout_logfile=/var/log/neko/tampermonkey-provisioning.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3
redirect_stderr=true
[program:openbox]
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
command=/usr/bin/openbox --config-file /etc/neko/openbox.xml
autorestart=true
priority=300
user=%(ENV_USER)s
stdout_logfile=/var/log/neko/openbox.log
stdout_logfile_maxbytes=100MB
stdout_logfile_backups=10
redirect_stderr=true

View File

@ -0,0 +1,32 @@
[program:google-chrome]
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
command=/etc/neko/browser-launch.sh google-chrome
stopsignal=INT
autorestart=true
priority=800
user=%(ENV_USER)s
stdout_logfile=/var/log/neko/google-chrome.log
stdout_logfile_maxbytes=100MB
stdout_logfile_backups=10
redirect_stderr=true
[program:tampermonkey-provisioning]
command=/bin/sh -c 'cd /var/www/provisioning && if command -v python3 >/dev/null 2>&1; then exec python3 -m http.server 18080 --bind 127.0.0.1; fi; if command -v busybox >/dev/null 2>&1; then exec busybox httpd -f -p 127.0.0.1:18080 -h /var/www/provisioning; fi; echo "no static file server for Tampermonkey provisioning"; sleep 3600'
autorestart=true
priority=250
user=%(ENV_USER)s
stdout_logfile=/var/log/neko/tampermonkey-provisioning.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3
redirect_stderr=true
[program:openbox]
environment=HOME="/home/%(ENV_USER)s",USER="%(ENV_USER)s",DISPLAY="%(ENV_DISPLAY)s"
command=/usr/bin/openbox --config-file /etc/neko/openbox.xml
autorestart=true
priority=300
user=%(ENV_USER)s
stdout_logfile=/var/log/neko/openbox.log
stdout_logfile_maxbytes=100MB
stdout_logfile_backups=10
redirect_stderr=true

View File

@ -0,0 +1,186 @@
const API_BASES = [
// Physical / Docker: hit host API first — public HTTPS often hangs and blocks all telemetry.
"http://host.docker.internal:8014",
"http://172.17.0.1:8014",
"https://dy.nomadro.com",
"https://dy.nomadro.cn",
"https://dy.nomadro.live",
"http://127.0.0.1:8014",
];
const JUNK_TAB_RE = /tampermonkey\.net\/(changelog|installed)\.php/i;
const LIVE_STUDIO_RE = /studio\.youtube\.com\/.*\/livestreaming/i;
const AUTH_JUNK_RE =
/accounts\.google\.com\/(?:ServiceLogin|signin|v3\/signin|accountchooser|RotateCookiesPage)/i;
const YOUTUBE_HOME_RE = /^https:\/\/www\.youtube\.com\/?(?:\?|$)/;
let cachedNekoInstanceId = 0;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function tabUrl(tab) {
return tab?.pendingUrl || tab?.url || "";
}
async function loadNekoInstanceId() {
if (cachedNekoInstanceId > 0) return cachedNekoInstanceId;
try {
const stored = await chrome.storage.local.get(["nekoInstanceId"]);
const fromStore = Number(stored.nekoInstanceId || 0);
if (fromStore > 0) {
cachedNekoInstanceId = fromStore;
return cachedNekoInstanceId;
}
} catch {}
try {
const res = await fetch(chrome.runtime.getURL("instance_id.txt"), { cache: "no-store" });
if (res.ok) {
const text = (await res.text()).trim();
const nid = Number(text);
if (Number.isFinite(nid) && nid > 0) {
cachedNekoInstanceId = nid;
await chrome.storage.local.set({ nekoInstanceId: nid });
return nid;
}
}
} catch {}
return 0;
}
loadNekoInstanceId().catch(() => {});
async function focusYoutubeLiveTab(tabs) {
const liveTabs = tabs.filter((tab) => LIVE_STUDIO_RE.test(tabUrl(tab)) && tab.id);
if (liveTabs.length) {
const target = liveTabs.find((tab) => tab.active) || liveTabs[0];
await chrome.tabs.update(target.id, { active: true });
await chrome.tabs.reload(target.id);
if (LIVE_STUDIO_RE.test(tabUrl(target))) {
await chrome.storage.local.set({ lastLiveStudioUrl: tabUrl(target) });
}
return target.id;
}
const stored = await chrome.storage.local.get(["lastLiveStudioUrl"]);
const saved = (stored.lastLiveStudioUrl || "").trim();
if (saved && LIVE_STUDIO_RE.test(saved)) {
const created = await chrome.tabs.create({ url: saved, active: true });
return created?.id || null;
}
return null;
}
async function normalizeTabsAfterRestore(attempt = 0) {
const delayMs = attempt === 0 ? 5000 : 2500;
if (attempt > 12) return;
await sleep(delayMs);
let tabs = [];
try {
tabs = await chrome.tabs.query({});
} catch {
return;
}
for (const tab of tabs) {
const url = tabUrl(tab);
if (!tab.id) continue;
if (JUNK_TAB_RE.test(url)) {
try {
await chrome.tabs.remove(tab.id);
} catch {}
}
}
tabs = await chrome.tabs.query({});
const liveTabId = await focusYoutubeLiveTab(tabs);
if (liveTabId) {
const refreshed = await chrome.tabs.query({});
for (const tab of refreshed) {
const url = tabUrl(tab);
if (!tab.id || tab.id === liveTabId) continue;
if (JUNK_TAB_RE.test(url) || AUTH_JUNK_RE.test(url) || YOUTUBE_HOME_RE.test(url)) {
try {
await chrome.tabs.remove(tab.id);
} catch {}
}
}
}
const remainingJunk = (await chrome.tabs.query({})).some((tab) => JUNK_TAB_RE.test(tabUrl(tab)));
if (remainingJunk) {
normalizeTabsAfterRestore(attempt + 1);
}
}
function scheduleTabHygiene() {
normalizeTabsAfterRestore(0).catch(() => {});
}
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
const url = changeInfo.url || tabUrl(tab);
if (!url || !JUNK_TAB_RE.test(url)) return;
chrome.tabs.remove(tabId).catch(() => {});
});
chrome.tabs.onCreated.addListener((tab) => {
const url = tabUrl(tab);
if (!url || !JUNK_TAB_RE.test(url)) return;
if (tab.id) chrome.tabs.remove(tab.id).catch(() => {});
});
chrome.runtime.onStartup.addListener(scheduleTabHygiene);
chrome.runtime.onInstalled.addListener(scheduleTabHygiene);
scheduleTabHygiene();
async function postTelemetry(payload) {
const stored = await chrome.storage.local.get(["liveHubIngestToken"]);
const ingestToken = (stored.liveHubIngestToken || "").trim();
const nekoInstanceId = (await loadNekoInstanceId()) || Number(payload?.neko_instance_id || 0) || 0;
const body = JSON.stringify({
...payload,
source: payload.source || "chrome_extension",
received_at: Date.now() / 1000,
...(nekoInstanceId > 0 ? { neko_instance_id: nekoInstanceId } : {}),
...(ingestToken ? { ingest_token: ingestToken } : {}),
});
let lastError = "";
for (const base of API_BASES) {
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 3500);
const res = await fetch(`${base}/hub/youtube/live/ingest`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
cache: "no-store",
signal: ctrl.signal,
});
clearTimeout(timer);
if (res.ok) {
const data = await res.json().catch(() => ({}));
await chrome.storage.local.set({
liveHubLastOk: Date.now(),
liveHubLastBase: base,
liveHubLastEvent: data?.event?.id || null,
liveHubLastNekoId: data?.event?.neko_instance_id || nekoInstanceId || null,
});
return { ok: true, base, eventId: data?.event?.id || null };
}
lastError = `${base} HTTP ${res.status}`;
} catch (err) {
lastError = `${base} ${err?.message || String(err)}`;
}
}
await chrome.storage.local.set({ liveHubLastError: lastError, liveHubLastErrorAt: Date.now() });
return { ok: false, error: lastError };
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!message || message.type !== "live-hub-youtube-telemetry") return false;
postTelemetry(message.payload || {}).then(sendResponse);
return true;
});

View File

@ -0,0 +1,220 @@
const LIVE_HUB_MIN_INTERVAL_MS = 1800;
let lastSentAt = 0;
let lastSignature = "";
function cleanText(value, max = 260) {
return String(value || "")
.replace(/\s+/g, " ")
.trim()
.slice(0, max);
}
function pageText() {
return cleanText(document.body?.innerText || "", 6000);
}
function parseCompactNumber(raw) {
const text = cleanText(raw, 40).replace(/,/g, "");
const match = text.match(/(\d+(?:\.\d+)?)([kKmMwW万]*)/);
if (!match) return null;
let value = Number(match[1]);
const unit = match[2].toLowerCase();
if (unit === "k") value *= 1000;
if (unit === "m") value *= 1000000;
if (unit === "w" || unit === "万") value *= 10000;
return Number.isFinite(value) ? Math.round(value) : null;
}
function firstNumberByPatterns(text, patterns) {
for (const pattern of patterns) {
const match = text.match(pattern);
if (match) {
const parsed = parseCompactNumber(match[1]);
if (parsed != null) return parsed;
}
}
return null;
}
function detectLiveStatus(text) {
const lower = text.toLowerCase();
if (/stream ended|not live|offline|直播已结束|未在直播/.test(lower)) return "ended";
if (/connect your encoder|no data|stream offline|not streaming|waiting for you to start/.test(lower)) {
return "waiting";
}
if (
/you'?re live|you are live|excellent connection|stream is healthy|end stream|stop streaming|concurrent viewers|watching now|直播中|正在直播|已开始直播|结束直播/.test(
lower
)
) {
return "live";
}
// Studio shows a LIVE pill + duration while on-air
if (/\blive\b[\s\S]{0,40}\d+:\d{2}(?::\d{2})?/.test(lower) && /end stream|stop streaming/.test(lower)) {
return "live";
}
if (/waiting|preview|scheduled|等待|预定|未开始/.test(lower)) return "waiting";
if (/error|failed|copyright|policy|异常|错误|受限|违规/.test(lower)) return "attention";
return "";
}
function detectHealth(text) {
const lower = text.toLowerCase();
if (/excellent connection|stream is healthy|health excellent|连接状况极佳|状况良好/.test(lower)) return "excellent";
if (/good connection|healthy|良好/.test(lower)) return "good";
if (/unstable|poor|buffer|warning|警告|不稳定|不佳|卡顿/.test(lower)) return "warning";
if (/error|failed|disconnect|异常|错误|断开/.test(lower)) return "error";
return "";
}
/** LIVE pill duration e.g. "37:06" or "1:19:36" → seconds */
function parseLiveDuration(text) {
const match =
text.match(/\bLIVE\b\s*(\d{1,2}:\d{2}(?::\d{2})?)/i) ||
text.match(/(?:直播时长|已直播)\s*[::]?\s*(\d{1,2}:\d{2}(?::\d{2})?)/i);
if (!match) return { live_duration: "", live_duration_sec: null };
const raw = match[1];
const parts = raw.split(":").map((x) => Number(x));
let sec = null;
if (parts.length === 3 && parts.every((n) => Number.isFinite(n))) {
sec = parts[0] * 3600 + parts[1] * 60 + parts[2];
} else if (parts.length === 2 && parts.every((n) => Number.isFinite(n))) {
sec = parts[0] * 60 + parts[1];
}
return { live_duration: raw, live_duration_sec: sec };
}
/** Analytics tab cumulative Views (not concurrent). */
function parseTotalViews(text) {
// Prefer labeled "Views" / 观看次数, avoid "Concurrent viewers"
const patterns = [
/(?:^|\n)\s*Views\s*\n\s*([\d,.]+[kKmMwW万]?)/i,
/\bViews\b(?!\s*per)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/i,
/(?:总观看|观看次数|观看量)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/,
];
for (const pattern of patterns) {
const match = text.match(pattern);
if (!match) continue;
// Reject if this is clearly the concurrent line
const around = text.slice(Math.max(0, (match.index || 0) - 24), (match.index || 0) + 40).toLowerCase();
if (/concurrent/.test(around)) continue;
const parsed = parseCompactNumber(match[1]);
if (parsed != null) return parsed;
}
return null;
}
function collectPopupTexts() {
const selectors = [
"[role='dialog']",
"[aria-live='assertive']",
"[aria-live='polite']",
"ytcp-toast",
"tp-yt-paper-toast",
"paper-dialog",
"ytcp-alert",
"ytcp-ve",
];
const out = [];
for (const node of document.querySelectorAll(selectors.join(","))) {
const rect = node.getBoundingClientRect?.();
if (rect && rect.width === 0 && rect.height === 0) continue;
const text = cleanText(node.innerText || node.textContent || "", 500);
if (text && !out.includes(text)) out.push(text);
if (out.length >= 8) break;
}
return out;
}
function collectStreamTitle() {
const selectors = [
"input[aria-label*='Title']",
"textarea[aria-label*='Title']",
"ytcp-social-suggestions-textbox",
"ytcp-video-title",
"h1",
];
for (const selector of selectors) {
const node = document.querySelector(selector);
const value = node?.value || node?.innerText || node?.textContent;
const text = cleanText(value, 180);
if (text) return text;
}
return cleanText(document.title, 180);
}
function collectTelemetry() {
const text = pageText();
const viewerCount = firstNumberByPatterns(text, [
/([\d,.]+[kKmMwW万]?)\s*(?:watching|concurrent viewers)/i,
/(?:concurrent viewers|watching now|同时观看)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/i,
/([\d,.]+[kKmMwW万]?)\s*(?:人正在观看|正在观看)/,
]);
const likeCount = firstNumberByPatterns(text, [
/([\d,.]+[kKmMwW万]?)\s*(?:likes|like count)/i,
/([\d,.]+[kKmMwW万]?)\s*(?:点赞|赞)/,
]);
const dur = parseLiveDuration(text);
const totalViews = parseTotalViews(text);
const popups = collectPopupTexts();
const payload = {
captured_at: Date.now() / 1000,
source: "chrome_extension",
url: location.href,
page_title: document.title,
stream_title: collectStreamTitle(),
live_status: detectLiveStatus(text),
health: detectHealth(text),
viewer_count: viewerCount,
like_count: likeCount,
total_views: totalViews,
live_duration: dur.live_duration,
live_duration_sec: dur.live_duration_sec,
popups,
text: text.slice(0, 2200),
signals: {
has_dialog: popups.length > 0,
visibility: document.visibilityState,
focused: document.hasFocus(),
path: location.pathname,
},
};
return payload;
}
function signatureOf(payload) {
return JSON.stringify([
payload.url,
payload.live_status,
payload.health,
payload.viewer_count,
payload.like_count,
payload.total_views,
payload.live_duration,
payload.popups,
payload.stream_title,
]);
}
function sendTelemetry(force = false) {
const now = Date.now();
if (!force && now - lastSentAt < LIVE_HUB_MIN_INTERVAL_MS) return;
const payload = collectTelemetry();
const sig = signatureOf(payload);
if (!force && sig === lastSignature && now - lastSentAt < 10000) return;
lastSentAt = now;
lastSignature = sig;
if (/studio\.youtube\.com\/.*\/livestreaming/.test(location.href)) {
chrome.storage.local.set({ lastLiveStudioUrl: location.href });
}
chrome.runtime.sendMessage({ type: "live-hub-youtube-telemetry", payload }, () => {
void chrome.runtime.lastError;
});
}
const observer = new MutationObserver(() => sendTelemetry(false));
observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
window.addEventListener("focus", () => sendTelemetry(true));
document.addEventListener("visibilitychange", () => sendTelemetry(true));
setInterval(() => sendTelemetry(false), 3000);
sendTelemetry(true);

View File

@ -0,0 +1 @@
0

View File

@ -0,0 +1,31 @@
{
"manifest_version": 3,
"name": "Live Hub YouTube Studio Telemetry",
"version": "1.3.0",
"description": "Captures YouTube Studio live status, viewer signals, stream health, and popups for the LAN Live Hub.",
"permissions": ["storage", "tabs"],
"host_permissions": [
"https://studio.youtube.com/*",
"https://www.youtube.com/*",
"https://dy.nomadro.live/*",
"https://dy.nomadro.com/*",
"https://dy.nomadro.cn/*",
"http://host.docker.internal:8014/*",
"http://172.17.0.1:8014/*",
"http://127.0.0.1:8014/*"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"https://studio.youtube.com/*",
"https://www.youtube.com/live_dashboard*",
"https://www.youtube.com/watch*"
],
"js": ["content.js"],
"run_at": "document_idle"
}
]
}

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,42 @@
{
"ExtensionInstallForcelist": [
"dhdgffkkebhmkfjojejmpbldmpobfkfo;https://clients2.google.com/service/update2/crx"
],
"ExtensionInstallBlocklist": [],
"DownloadRestrictions": 0,
"AllowFileSelectionDialogs": true,
"URLAllowlist": [
"file:///home/neko/Downloads/*"
],
"DefaultCookiesSetting": 1,
"RestoreOnStartup": 1,
"AutoplayAllowed": true,
"DefaultPopupsSetting": 1,
"DefaultNotificationsSetting": 1,
"VideoCaptureAllowed": true,
"AudioCaptureAllowed": true,
"VideoCaptureAllowedUrls": [
"https://*.google.com/*",
"https://*.youtube.com/*"
],
"AudioCaptureAllowedUrls": [
"https://*.google.com/*",
"https://*.youtube.com/*"
],
"DeveloperToolsAvailability": 1,
"DefaultGeolocationSetting": 1,
"3rdparty": {
"extensions": {
"dhdgffkkebhmkfjojejmpbldmpobfkfo": {
"jsonImport": [
{
"hash": "1:b75c2df29e515233fce1ca146ab62fff6bcbbaa20f5d5a8c16aa8f8993b77b15",
"url": "http://127.0.0.1:18080/tampermonkey-provisioning.json",
"haltOnError": false,
"installAsSystemScripts": false
}
]
}
}
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,231 @@
// ==UserScript==
// @name YouTube Studio Auto Dismiss
// @namespace http://tampermonkey.net/
// @version 2.2.0
// @description 直播结束 endscreen 自动离开:读 a#dismiss-link 并 location.assign,避免 MouseEvent 风控
// @author You
// @match https://studio.youtube.com/*
// @run-at document-idle
// @license MIT
// @grant none
// @downloadURL https://update.greasyfork.org/scripts/557378/YouTube%20Studio%20Auto%20Dismiss.user.js
// @updateURL https://update.greasyfork.org/scripts/557378/YouTube%20Studio%20Auto%20Dismiss.meta.js
// ==/UserScript==
(function () {
"use strict";
// 不要用 <script> 注入:Studio CSP 常会静默拦截,导致“脚本装了但不跑”。
// @grant none 下直接跑即可操作 DOM / location。
if (window.__ytStudioAutoDismissV22__) return;
window.__ytStudioAutoDismissV22__ = true;
const COOLDOWN_MS = 8000;
const HUMAN_DELAY_MIN = 400;
const HUMAN_DELAY_MAX = 1200;
const POLL_MS = 1500;
let busy = false;
let lastAt = 0;
let lastHrefTried = "";
function log() {
try {
console.log.apply(console, ["[YT Auto Dismiss]"].concat([].slice.call(arguments)));
} catch (_) {}
}
function rand(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}
function sleep(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}
function visible(el) {
if (!el || !el.getBoundingClientRect) return false;
var s = window.getComputedStyle(el);
if (s.display === "none" || s.visibility === "hidden" || Number(s.opacity) === 0) return false;
var r = el.getBoundingClientRect();
return r.width > 1 && r.height > 1;
}
function queryDeep(selector, root) {
root = root || document;
try {
var hit = root.querySelector(selector);
if (hit) return hit;
} catch (_) {}
var nodes = [];
try {
nodes = root.querySelectorAll("*");
} catch (_) {
return null;
}
for (var i = 0; i < nodes.length; i++) {
var el = nodes[i];
if (!el.shadowRoot) continue;
var nested = queryDeep(selector, el.shadowRoot);
if (nested) return nested;
}
return null;
}
function findEndscreen() {
return (
queryDeep("ytls-stream-endscreen-renderer") ||
(function () {
var box = queryDeep("#endscreen-container");
return box && box.closest ? box.closest("ytls-stream-endscreen-renderer") : null;
})()
);
}
function findDismissTarget() {
var host = findEndscreen();
if (!host || !visible(host)) return null;
var link =
host.querySelector("a#dismiss-link") ||
host.querySelector("#dismiss-link") ||
host.querySelector("#completion-buttons a[href]") ||
null;
var btn =
host.querySelector("#dismiss-button button") ||
host.querySelector("ytcp-button#dismiss-button") ||
host.querySelector("#dismiss-button") ||
null;
if (!link && !btn) return null;
if (link && !visible(link) && btn && !visible(btn)) return null;
return { host: host, link: link, btn: btn };
}
function resolveHref(link) {
if (!link) return "";
var raw = link.href || link.getAttribute("href") || "";
if (!raw) return "";
try {
return new URL(raw, location.origin).href;
} catch (_) {
return raw;
}
}
function hideEndscreen(host) {
try {
host.setAttribute("hidden", "");
host.style.setProperty("display", "none", "important");
if (host.remove) host.remove();
return true;
} catch (_) {
return false;
}
}
async function dismissOnce(reason) {
if (busy) return false;
if (Date.now() - lastAt < COOLDOWN_MS) return false;
var target = findDismissTarget();
if (!target) return false;
var href = resolveHref(target.link);
if (href && href === lastHrefTried && Date.now() - lastAt < COOLDOWN_MS) return false;
busy = true;
lastAt = Date.now();
lastHrefTried = href || lastHrefTried;
try {
log(reason || "found endscreen", {
href: href,
path: location.pathname,
});
await sleep(rand(HUMAN_DELAY_MIN, HUMAN_DELAY_MAX));
if (!findDismissTarget()) {
log("endscreen disappeared before action");
return false;
}
// 1) 首选:按原生 <a id="dismiss-link"> 导航(无合成 click)
if (href) {
try {
var url = new URL(href);
if (url.origin === location.origin) {
log("location.assign", url.href);
location.assign(url.href);
return true;
}
} catch (err) {
log("assign failed", String(err));
}
}
// 2) 摘掉 endscreen
if (hideEndscreen(target.host)) {
await sleep(300);
if (!findDismissTarget()) {
log("removed endscreen node");
return true;
}
}
// 3) 兜底原生 click(仅限 endscreen 内按钮)
var clickEl =
(target.btn && target.btn.querySelector && target.btn.querySelector("button")) ||
target.btn ||
target.link;
if (clickEl && clickEl.click) {
log("native click fallback");
HTMLElement.prototype.click.call(clickEl);
return true;
}
return false;
} finally {
busy = false;
}
}
function tick(reason) {
dismissOnce(reason).catch(function (err) {
log("error", String(err));
});
}
var observer = new MutationObserver(function () {
clearTimeout(tick._t);
tick._t = setTimeout(function () {
tick("mutation");
}, 200);
});
try {
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["style", "class", "hidden", "href"],
});
} catch (_) {}
// SPA:从 dashboard 进直播页时 userscript 不一定重跑,靠轮询兜底
setInterval(function () {
tick("poll");
}, POLL_MS);
window.addEventListener("yt-navigate-finish", function () {
tick("yt-navigate-finish");
});
window.addEventListener("popstate", function () {
tick("popstate");
});
log("installed", location.href);
tick("boot");
})();

View File

@ -0,0 +1,94 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import base64
import hashlib
import json
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent
DEFAULT_SCRIPT = ROOT / "provisioning" / "youtube-studio-auto-dismiss.user.js"
DEFAULT_OUTPUT = ROOT / "provisioning" / "tampermonkey-provisioning.json"
GREASYFORK_URL = "https://greasyfork.org/scripts/557378-youtube-studio-auto-dismiss/code/YouTube%20Studio%20Auto%20Dismiss.user.js"
def tm_sha256(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def tm_hash(value: Any, seen: list[int] | None = None) -> str:
if seen is None:
seen = []
if value is None:
return tm_sha256("object:null")
if isinstance(value, dict):
ident = id(value)
if ident in seen:
raise ValueError("Found circular structure")
seen.append(ident)
try:
parts = [tm_hash(value[key], seen) for key in sorted(value)]
finally:
seen.pop()
return tm_sha256("".join(parts))
if isinstance(value, list):
ident = id(value)
if ident in seen:
raise ValueError("Found circular structure")
seen.append(ident)
try:
parts = [tm_hash(item, seen) for item in value]
finally:
seen.pop()
return tm_sha256("".join(parts))
if isinstance(value, bool):
return tm_sha256(f"boolean:{str(value).lower()}")
if isinstance(value, (int, float)) and not isinstance(value, bool):
return tm_sha256(f"number:{value}")
if isinstance(value, str):
return tm_sha256(f"string:{value}")
raise TypeError(f"Unsupported provisioning value: {type(value)!r}")
def build_payload(script_text: str) -> dict[str, Any]:
encoded_source = base64.b64encode(script_text.encode("utf-8")).decode("ascii")
return {
"version": "1",
"scripts": [
{
"name": "YouTube Studio Auto Dismiss",
"file_url": GREASYFORK_URL,
"source": encoded_source,
"enabled": True,
"position": 1,
"options": {},
}
],
"settings": {
"runtime_content_mode": "userscripts",
},
}
def main() -> int:
parser = argparse.ArgumentParser(description="Render Tampermonkey provisioning JSON and hash.")
parser.add_argument("--script", type=Path, default=DEFAULT_SCRIPT)
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
parser.add_argument("--write", action="store_true", help="Write the rendered JSON to --output.")
args = parser.parse_args()
script_text = args.script.read_text(encoding="utf-8").strip() + "\n"
payload = build_payload(script_text)
rendered = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
if args.write:
args.output.write_text(rendered, encoding="utf-8")
print(rendered, end="")
print(f"hash=1:{tm_hash(payload)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,2 @@
Copyright 2018 Jan Biniok. All rights reserved.

View File

@ -0,0 +1,848 @@
{
"0name0_0version0_is_available__Please_re_start_your_browser_to_update_": {
"message": "$name$ $version$ tersedia.\nSilakan mulai ulang peramban untuk memperbarui!",
"placeholders": {
"name": {
"content": "$1"
},
"version": {
"content": "$2"
}
}
},
"A_recheck_of_the_GreaseMonkey_FF_compatibility_options_may_be_required_in_order_to_run_this_script_": {
"message": "Sebuah pemeriksaan ulang opsi kompatibilitas GreaseMonkeFF mungkin diperlukan untuk menjalankan skrip ini."
},
"A_request_to_a_cross_origin_resource_is_nothing_unusual__You_just_have_to_check_whether_this_script_has_a_good_reason_to_access_this_domain__For_example_there_are_only_a_very_few_reasons_for_a_userscript_to_contact_your_bank__Please_note_that_userscript_authors_can_avoid_this_dialog_by_adding_@connect_tags_to_their_scripts__You_can_change_your_opinion_at_any_time_at_the_scripts_settings_tab_": {
"message": "Permintaan untuk sumber daya lintas tidak aneh\nAnda hanya perlu memeriksa apakah skrip ini memiliki alasan yang bagus untuk mengakses domain ini. Contohnya hanya ada sangat sedikit alasan untuk uskrip pengguna untuk menghubungi bank Anda.\n\nMohon dicatat bahwa penulis skrip pengguna dapat menghindari dialog ini dengan menambahkan [url=$connect$]@connect tag [/url] pada skrip mereka.\n\nTidak peduli bagaimana Anda akan memutuskan, Anda dapat mengubah pendapat Anda setiap saat di skrip [url=$settings$]tab pengaturan[/url].",
"placeholders": {
"connect": {
"content": "$1"
},
"settings": {
"content": "$2"
}
}
},
"A_userscript_wants_to_access_a_cross_origin_resource_": {
"message": "Sebah skrip pengguna ingin mengakses sumber daya lintas asal."
},
"Action": {
"message": "Tindakan"
},
"Action_Menu": {
"message": "Menu Tindakan"
},
"Actions": {
"message": "Tindakan"
},
"Add": {
"message": "Tambah"
},
"Add_TM_to_CSP": {
"message": "Tambahkan Tampermonkey dengan kebijakan keamanan konten situs (CSP) jika ada"
},
"Add_Tag": {
"message": "Tambah Tag"
},
"Add_Tag_to_System": {
"message": "Tambahkan tag ke daftar sistem"
},
"Add_new_script___": {
"message": "Buat sebuah skrip..."
},
"Advanced": {
"message": "Lanjutan"
},
"All_but_HttpOnly": {
"message": "Semua kecuali HttpOnly"
},
"All_modifications_are_only_kept_a_few_moments_Reconfigure_the_0name0_option_to_save_them_permanently_": {
"message": "Modifikasi hanya disimpan beberapa saat. Konfigurasikan opsi '$name$' untuk menyimpannya secara permanen.",
"placeholders": {
"name": {
"content": "$1"
}
}
},
"All_script_settings_will_be_reset_": {
"message": "Semua pengaturan skrip akan diatur ulang!"
},
"Allow_once": {
"message": "Izinkan sekali"
},
"Always": {
"message": "Selalu"
},
"Always_allow": {
"message": "Selalu izinkan"
},
"Always_allow_all_domains": {
"message": "Selalu izinkan semua domain"
},
"Always_allow_domain": {
"message": "Selalu izinkan domain"
},
"Always_ask": {
"message": "Selalu tanya"
},
"Always_forbid": {
"message": "Selalu tolak"
},
"Always_forbid_domain": {
"message": "Selalu tolak domain"
},
"An_error_occured_during_import_": {
"message": "Terjadi kesalahan selama impor."
},
"Appearance": {
"message": "Tampilan"
},
"Apply_compatibility_options_to_required_script_too": {
"message": "Terapkan juga opsi kompatibilitas untuk @require script"
},
"Apply_this_action_to_the_selected_scripts": {
"message": "Terapkan ini ke semua skrip yang dipilih"
},
"Apply_update": {
"message": "Terapkan pembaruan"
},
"Are_you_sure_that_you_don_t_want_to_be_notified_of_updates_": {
"message": "Ketika Tampermonkey diperbarui oleh peramban Anda itu juga dimulai ulang. Sayangnya ini mungkin dapat menganggu skrip! \n\nJadi, apakah Anda yakin bahwa Anda tidak ingin mendapat notifikasi pembaruan?"
},
"Ask_if_unknown": {
"message": "Tanya jika tak diketahui"
},
"Attention_Can_not_display_all_excludes_": {
"message": "Perhatian: Daftar exclude telah disingkat.\nSilakan periksa secara manual!"
},
"Attention_Can_not_display_all_includes_": {
"message": "Perhatian: Daftar include telah disingkat.\nSilakan periksa secara manual!"
},
"Author": {
"message": "Penulis"
},
"Auto": {
"message": "Otomatis"
},
"Auto_syntax_check_on_typing": {
"message": "Cek otomatis sintaks saat mengetik"
},
"Beginner": {
"message": "Pemula"
},
"Browser_API": {
"message": "API Peramban"
},
"Browser_API_Downloads": {
"message": "Unduhan API Peramban"
},
"CONFLICT__This_script_was_modified_0t0_seconds_ago_": {
"message": "KONFLIK:\nSkrip ini dimodifikasi oleh tab lain $t$ detik yang lalu!",
"placeholders": {
"t": {
"content": "$1"
}
}
},
"Cancel": {
"message": "Batal"
},
"Casual": {
"message": "Kasual"
},
"Changelog": {
"message": "Daftar pembaruan"
},
"Changes_the_number_of_visible_config_options": {
"message": "Mengubah jumlah yang terlihat pada konfigurasi pilihan"
},
"Check_disabled_scripts": {
"message": "Periksa Skrip yang dimatikan"
},
"Check_for_Updates": {
"message": "Memeriksa pembaruan"
},
"Check_for_userscripts_updates": {
"message": "Periksa pembaruan skrip pengguna"
},
"Check_interval": {
"message": "Interval Pemeriksaan"
},
"Click_here_to_allow_TM_to_make_use_of_a_proxy": {
"message": "Klik OKE untuk mengizinkan Tampermonkey menggunakan proxy."
},
"Click_here_to_allow_TM_to_start_downloads": {
"message": "Klik OKE untuk mengizinkan Tampermonkey memulai unduh instan."
},
"Click_here_to_see_the_recent_changes": {
"message": "Klik di sini untuk melihat perubahan terbaru"
},
"Close": {
"message": "Tutup"
},
"Columns": {
"message": "Kolom"
},
"Comment": {
"message": "Komentar"
},
"Config_Mode": {
"message": "Mode Konfig"
},
"Convert_CDATA_sections_into_a_chrome_compatible_format": {
"message": "Mengkonversi bagian CDATA ke dalam format yang kompatibel peramban"
},
"Custom_CSS": {
"message": "CSS Pengguna"
},
"Debug_scripts": {
"message": "Pengawakutu Skrip"
},
"Delete": {
"message": "Hapus"
},
"Description": {
"message": "Deskripsi"
},
"Details": {
"message": "Detail"
},
"Disable_Updates": {
"message": "Nonaktifkan Pembaruan"
},
"Disable_all_remaining_scripts_of_this_tag": {
"message": "Klik untuk menonaktifkan semua skrip yang tersisa dari tag ini"
},
"Disable_all_scripts_of_this_tag": {
"message": "Klik untuk menonaktifkan semua skrip dari tag ini"
},
"Disabled": {
"message": "Nonaktif"
},
"Do_you_really_want_to_store_fixed_code_": {
"message": "Opsi '$option$' telah terbuka!\n\nApakah Anda benar-benar ingin menyimpan sumber tetap?",
"placeholders": {
"option": {
"content": "$1"
}
}
},
"Does_not_run_in_incognito_tabs": {
"message": "Tak berjalan di tab penyamaran"
},
"Does_not_run_in_normal_tabs": {
"message": "Tak berjalan di tab normal"
},
"Dont_ask_again": {
"message": "Jangan tanya lagi"
},
"Download_Mode": {
"message": "Mode Unduhan"
},
"Downloaded_from_0url0": {
"message": "Diunduh dari: $url$",
"placeholders": {
"url": {
"content": "$1"
}
}
},
"Downloads": {
"message": "Unduhan"
},
"Edit": {
"message": "Sunting"
},
"Enable_Tags": {
"message": "Aktifkan Tag"
},
"Enable_all_scripts_of_this_tag": {
"message": "Klik untuk mengaktifkan semua skrip dari tag ini"
},
"Enable_autoSave": {
"message": "Menyimpan konten ketika Editor kehilangan fokus"
},
"Enable_easySave": {
"message": "Jangan tampilkan dialog konfirmasi saat menyimpan"
},
"Enabled": {
"message": "Diaktifkan"
},
"Enter_the_new_rule": {
"message": "Masukkan aturan baru"
},
"Every_12_Hour": {
"message": "Setiap 12 jam"
},
"Every_6_Hours": {
"message": "Setiap 6 jam"
},
"Every_Day": {
"message": "Setiap hari"
},
"Every_Hour": {
"message": "Setiap jam"
},
"Every_Month": {
"message": "Setiap bulan"
},
"Every_Week": {
"message": "Setiap pekan"
},
"Export": {
"message": "Ekspor"
},
"Externals": {
"message": "Eksternal"
},
"Factory_Reset": {
"message": "Reset ke Pengaturan Pabrik"
},
"Features": {
"message": "Fitur"
},
"Filter_by": {
"message": "Filter dengan"
},
"Fix_wrappedJSObject_property_access": {
"message": "Perbaiki akses properti wrappedJSObject"
},
"Focus_tab": {
"message": "Fokus tab sumber"
},
"Font_Size": {
"message": "Ukuran Fonta"
},
"Forbid_once": {
"message": "Tolak sekali"
},
"GM_compat_options_": {
"message": "Opsi kompatibilitas GM/FF "
},
"General": {
"message": "Umum"
},
"Get_new_scripts___": {
"message": "Temukan skrip baru..."
},
"Get_some_scripts___": {
"message": "Dapatkan skrip..."
},
"Global_Settings": {
"message": "Pengaturan Global"
},
"Global_settings_import": {
"message": "Impor Pengaturan Global"
},
"Help": {
"message": "Bantuan"
},
"Hide_disabled_scripts": {
"message": "Sembunyikan script nonaktif"
},
"Highlight_trailing_whitespace": {
"message": "Otomatis cek ukuran maksimal sintaks"
},
"Homepage": {
"message": "Laman utama"
},
"I_contributed_already": {
"message": "Saya sudah menyumbang."
},
"I_dont_want_to_contribute": {
"message": "Saya tak mau menyumbang."
},
"Icon_badge_color": {
"message": "Warna Ikon Lencana"
},
"Import": {
"message": "Impor"
},
"Import_from_file": {
"message": "Impor"
},
"Include_TM_settings": {
"message": "Termasuk pengaturan Tampermonkey"
},
"Include_script_storage": {
"message": "Termasuk penyimpanan skrip"
},
"Info": {
"message": "Informasi"
},
"Install": {
"message": "Pasang"
},
"Installed_Version_": {
"message": "Versi terpasang"
},
"Installed_userscripts": {
"message": "Skrip pengguna terpasang"
},
"Invalid_UserScript__Sry_": {
"message": "Skrip pengguna tak sah. Maaf!"
},
"Invalid_UserScript_name__Sry_": {
"message": "Nama skrip pengguna tak sah. Maaf!"
},
"Jump_to_line": {
"message": "Lompat ke baris"
},
"Just_another_service_provided_by_your_friendly_script_updater_": {
"message": "Hanya layanan lain yang disediakan oleh pembaru skrip ramah Anda"
},
"Last_updated": {
"message": "Terakhir diperbarui"
},
"Learn_more": {
"message": "Pelajari lebih lanjut"
},
"Line_break": {
"message": "Baris Jeda"
},
"LogLevel": {
"message": "Tingkat Log"
},
"Malicious_scripts_can_violate_your_privacy_": {
"message": "script berbahaya dapat melanggar privasi Anda dan bertindak atas nama Anda!\nAnda hanya harus menginstal script dari sumber yang dipercaya."
},
"Matching_URL": {
"message": "Menemukan URL"
},
"Modify": {
"message": "Modifikasi"
},
"Name": {
"message": "Nama"
},
"Never": {
"message": "Tak pernah"
},
"New_Tag": {
"message": "Tag Baru"
},
"No": {
"message": "Tidak"
},
"No_backups_found": {
"message": "Tak ada cadangan ditemukan"
},
"No_script_is_installed": {
"message": "Tak ada skrip yang terpasang"
},
"No_script_is_running": {
"message": "Tak ada skrip yang berjalan"
},
"No_text": {
"message": "Tidak ada teks"
},
"No_update_found__sry_": {
"message": "Pembaruan tak ditemukan, maaf!"
},
"Note": {
"message": "Catatan"
},
"Novice": {
"message": "Simpel"
},
"One_or_more_compatibility_options_are_set": {
"message": "Satu atau beberapa opsi kompatibilitas ditetapkan. Anda mungkin ingin/harus tinjau mereka."
},
"Only_Manual": {
"message": "Hanya Manual"
},
"Only_files_with_these_extensions_can_be_saved_to_the_harddisk_Be_careful_to_not_allow_file_extensions_that_represent_executables_at_your_operating_system_": {
"message": "Hanya berkas dengan ekstensi ini dapat disimpan ke hard disk.\nHati-hati untuk tidak mengizinkan ekstensi file yang mewakili executable di sistem operasi Anda!"
},
"Open": {
"message": "Terbuka"
},
"Operation_completed_successfully": {
"message": "Operasi berhasil diselesaikan"
},
"Permanent": {
"message": "Permanen"
},
"Please_check_the_0editor0_documentation_for_more_details_": {
"message": "Silakan cek $editor$ documentation untuk lebih detailnya.",
"placeholders": {
"editor": {
"content": "$1"
}
}
},
"Please_consider_a_contribution": {
"message": "Pertimbangkan memberi sumbangan."
},
"Please_enable_anonymous_statistics_and_help_to_improve_this_extension_": {
"message": "Silakan aktifkan statistik anonim dan bantu optimalkan ekstensi ini. Hanya data teknis dan interaksi ekstensi yang dikumpulkan. Klik di sini untuk info lebih lanjut tentang data tersebut."
},
"Please_enable_the_allow_userscripts_extension_setting_": {
"message": "Silakan aktifkan pengaturan ekstensi `Izinkan User Scripts`. Klik di sini untuk info lebih lanjut bagaimana melakukannya."
},
"Please_select_a_file": {
"message": "Silakan pilih berkas"
},
"Please_wait___": {
"message": "Silakan tunggu..."
},
"Position_": {
"message": "Posisi"
},
"Really_delete_0name0__": {
"message": "Apa Anda benar-benar ingin hapus '$name$'?",
"placeholders": {
"name": {
"content": "$1"
}
}
},
"Really_delete_the_selected_items_": {
"message": "Anda yakin menghapus butir terpilih?"
},
"Really_factory_reset_the_selected_items_": {
"message": "Anda yakin untuk reset pabrik butir terpilih?"
},
"Really_factory_reset_this_script_": {
"message": "Anda yakin untuk atur ulang pabrikan skrip ini?"
},
"Really_reset_all_changes_": {
"message": "Anda yakin untuk atur ulang semua perubahan?"
},
"Reindent_on_typing": {
"message": "Inden ulang pada saat mengetik"
},
"Reinstall": {
"message": "Pasang ulang"
},
"Remind_me_later": {
"message": "Ingatkan saya nanti"
},
"Remove": {
"message": "Hapus"
},
"Remove_Tag": {
"message": "Hapus Tag"
},
"Replace": {
"message": "Ganti"
},
"Replace_": {
"message": "Ganti?"
},
"Replace_all_with": {
"message": "Ganti semua"
},
"Replace_with": {
"message": "Ganti dengan"
},
"Report_a_bug": {
"message": "Laporkan kutu"
},
"Report_an_issue_to_the_script_hoster_": {
"message": "Melaporkan masalah ke pengehos skrip. \n(Sebuah akun pengguna mungkin diperlukan)"
},
"Requires": {
"message": "Membutuhkan"
},
"Restart_Tampermonkey": {
"message": "Jalankan ulang Tampermonkey"
},
"Run_at": {
"message": "Jalankan pada"
},
"Run_in": {
"message": "Jalankan di"
},
"Save": {
"message": "Simpan"
},
"Scan_the_QR_code_to_use_Tampermonkey_on_your_phone_or_tablet_": {
"message": "Pindai kode QR untuk menggunakan Tampermonkey di ponsel atau tablet Anda."
},
"Script_Blacklist_Source": {
"message": "Sumber Daftar-Hitam skrip"
},
"Script_Tags": {
"message": "Tag Skrip"
},
"Script_Update": {
"message": "Pembaruan skrip"
},
"Script_cookies_access": {
"message": "Akses cookie skrip"
},
"Script_name_0name0": {
"message": "Nama skrip: $name$",
"placeholders": {
"name": {
"content": "$1"
}
}
},
"Script_order": {
"message": "Urutan Skrip"
},
"Search": {
"message": "Cari"
},
"Security": {
"message": "Keamanan"
},
"Settings": {
"message": "Pengaturan"
},
"Show_backups": {
"message": "Buka cadangan"
},
"Show_fixed_source": {
"message": "Tampilkan sumber tetap"
},
"Sites": {
"message": "Laman"
},
"Size": {
"message": "Ukuran"
},
"Skip_timeout__0seconds0_seconds_": {
"message": "Lewati batas waktu ($seconds$ detik)",
"placeholders": {
"seconds": {
"content": "$1"
}
}
},
"Some_URLs_are_restricted_by_your_browser_or_a_setting_": {
"message": "Beberapa URL dibatasi oleh peramban atau pengaturannya!"
},
"Source": {
"message": "Sumber"
},
"Start": {
"message": "Mulai"
},
"Sync_Type": {
"message": "Tipe"
},
"System_Tags": {
"message": "Tag Sistem"
},
"Tag_Already_Exists": {
"message": "Tag ini sudah ada"
},
"Tags": {
"message": "Tag"
},
"Tampermonkey_is_available_on_mobile_platforms": {
"message": "Tampermonkey tersedia di platform seluler"
},
"Tampermonkey_needs_to_be_restarted_to_make_this_change_apply_Do_you_want_to_continue_": {
"message": "Tampermonkey perlu mulai kembali untuk menyimpan perubahan.\n\nLanjutkan?"
},
"Tampermonkey_won_t_inject_into_other_tab_types_anymore_": {
"message": "Tampermonkey tidak akan menyuntikkan lagi pada jenis tab lain!"
},
"Temporarily_allow": {
"message": "Izinkan sementara"
},
"Temporary": {
"message": "Sementara"
},
"Thank_you_very_much_": {
"message": "Terima kasih banyak!"
},
"The_Browser_API_mode_requires_a_special_permission_": {
"message": "Mode Browser API memerlukan izin khusus."
},
"The_downgraded_script_might_have_problems_to_read_its_stored_data_": {
"message": "Penurunan versi skrip dapat membuat masalah pada saat memuat data yang tersimpan!"
},
"The_update_url_has_changed_from_0oldurl0_to__0newurl0": {
"message": "Pembaruan telah berubah dari:\n '$oldurl$'\n ke:\n '$newurl$'\n",
"placeholders": {
"newurl": {
"content": "$2"
},
"oldurl": {
"content": "$1"
}
}
},
"Theme": {
"message": "Tema"
},
"There_are_unsaved_changed_": {
"message": "Ada perubahan yang belum disimpan.\nApakah Anda yakin ingin menutup editor?"
},
"This_editor_is_tracking_the_changes_of_0name0_": {
"message": "Editor ini melacak perubahan dari $name$.",
"placeholders": {
"name": {
"content": "$1"
}
}
},
"This_gives_this_script_the_permission_to_retrieve_and_send_data_from_and_to_every_webpage__This_is_potentially_unsafe__Are_you_sure_you_want_to_continue_": {
"message": "Hal ini memberikan skrip ini izin untuk mengambil dan mengirim data dari dan ke setiap halaman web. Hal ini berpotensi tidak aman!\n\nApakah Anda yakin ingin melanjutkan?"
},
"This_is_a_system_script": {
"message": "Ini adalah skrip sistem."
},
"This_is_a_userscript": {
"message": "Ini adalah skrip pengguna yang ditulis menggunakan Javascript"
},
"This_script_does_not_provide_any__include_information_": {
"message": "Skrip ini tidak memberikan informasi @include apapun."
},
"This_script_has_access_to_https_pages": {
"message": "Skrip ini memiliki akses ke laman https."
},
"This_script_has_full_web_access": {
"message": "Skrip ini memiliki akses internet penuh."
},
"This_script_stores_data": {
"message": "Skrip ini menyimpan data ke Tampermonkey."
},
"This_tag_is_not_part_of_the_system_tag_list_": {
"message": "Tag ini tidak ada dalam daftar tag sistem"
},
"This_will_overwrite_the_current_script_with_the_content_of_0name0__Are_you_sure_": {
"message": "Ini akan menimpa skrip saat ini dengan konten dari $name$. Apakah Anda yakin?",
"placeholders": {
"name": {
"content": "$1"
}
}
},
"This_will_overwrite_your_global_settings_": {
"message": "Ini akan menimpa Pengaturan Global Anda!"
},
"This_will_remove_all_remote_data_from_sync_Ok_": {
"message": "Yakin hapus semua data remot from sinkron?"
},
"This_will_remove_all_scripts_and_reset_all_settings_Ok_": {
"message": "Anda yakin hapus semua skrip dan reset semua pengaturan?"
},
"Track_from_disk": {
"message": "Melacak dari cakram keras"
},
"Trigger_Update": {
"message": "Picu pembaruan"
},
"Type": {
"message": "Tipe"
},
"Unable_to_parse_this_": {
"message": "Tidak dapat mengurai ini! :("
},
"Unknown_method_0name0": {
"message": "Metode yang tidak diketahui $name$",
"placeholders": {
"name": {
"content": "$1"
}
}
},
"Update": {
"message": "Perbarui"
},
"Update_Notification": {
"message": "Tampilkan pembaruan TM pemberitahuan"
},
"Updated_to__0version0": {
"message": "Diperbaharui ke: $version$",
"placeholders": {
"version": {
"content": "$1"
}
}
},
"Updates": {
"message": "Pembaruan"
},
"Utilities": {
"message": "Utilitas"
},
"Verbose": {
"message": "Jejak"
},
"Version": {
"message": "Versi"
},
"Waiting_for_sync_to_finish": {
"message": "Menunggu sinkron untuk menyelesaikan"
},
"Yes": {
"message": "Ya"
},
"You_are_about_to_downgrade_a_UserScript": {
"message": "Perhatian! Penurunan versi skrip pengguna"
},
"You_are_about_to_install_a_UserScript_": {
"message": "Pemasangan skrip pengguna"
},
"You_are_about_to_modify_a_UserScript_": {
"message": "Ubah skrip pengguna"
},
"You_are_about_to_reinstall_a_UserScript_": {
"message": "Pemasangan ulang skrip pengguna"
},
"You_are_about_to_update_a_UserScript_": {
"message": "Pembaruan skrip pengguna"
},
"You_can_add_your_custom_CSS_rules_here_": {
"message": "Anda dapat menambahkan aturan CSS Anda sendiri untuk Tampermonkey UI di sini. Dalam hal ini Anda dapat memecahkan sesuatu dengan menambahkan ?layout=reset ke halaman pilihan URL."
},
"Your_language_is_not_supported__Click_here_to_get_intructions_how_to_translate_TM_": {
"message": "Bahasamu tidak didukung?\nCoba klik disini untuk mendapat instruksi cara menerjemahkan Tampermonkey?\n\nYour language is not supported?\nClick here to get instructions how to translate Tampermonkey?"
},
"Your_whitelist_seems_to_include_executable_files_This_means_your_userscripts_may_download_malware_or_spyware_to_your_harddisk_": {
"message": "Daftar putih Anda tampaknya menyertakan berkas executable!\nIni berarti skrip pengguna Anda dapat mengunduh perangkat berbahaya atu merusak ke cakram keras Anda!!"
},
"__Please_choose__": {
"message": "-- Silakan pilih --"
},
"connect_mode": {
"message": "@connect mode"
},
"extDescription": {
"message": "Change the web at will with userscripts"
},
"extName": {
"message": "Tampermonkey"
},
"extNameBeta": {
"message": "Tampermonkey BETA"
},
"extNameClassic": {
"message": "Tampermonkey Classic"
},
"extNameLegacy": {
"message": "Tampermonkey Legacy"
},
"extShortName": {
"message": "Tampermonkey"
},
"extShortNameBeta": {
"message": "TM BETA"
},
"extShortNameClassic": {
"message": "TM Classic"
},
"extShortNameLegacy": {
"message": "TM Legacy"
},
"fatal_error": {
"message": "kesalahan fatal"
},
"severity_1": {
"message": "1 (lebih aman)"
},
"severity_10": {
"message": "10 (paling tidak aman)"
},
"some_secs": {
"message": "beberapa"
}
}

View File

@ -0,0 +1,11 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="extension.js"></script>
</head>
<body></body>
</html>

View File

@ -0,0 +1,14 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="editor.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="editor.js"></script>
<script src="extension.js"></script>
</head>
<body>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="test.js"></script>
<script src="background.js"></script>
</head>
<body>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
(()=>{"use strict";const{AbortController:e,FileReader:t,TextDecoder:s,atob:n,btoa:o,clearInterval:r,clearTimeout:a,crypto:c,decodeURIComponent:i,encodeURIComponent:l,escape:u,location:h,setInterval:d,setTimeout:p,unescape:f}=self;let{fetch:w}=self;h.origin,h.host;const{addEventListener:g,removeEventListener:m}=self,{DOMParser:W,Notification:v,Image:y,Worker:x,alert:S,confirm:T,document:b,screen:k,webkitNotifications:R,navigation:D,showOpenFilePicker:I}=self;let L;try{L=self.localStorage
}catch(e){}let{XMLHttpRequest:q}=self;const{clients:E}=self;self.addEventListener("install",(()=>{console.log("SW: started"),self.skipWaiting().catch((e=>console.warn(e)))}));const $="x-sw-cache-timestamp";self.addEventListener("fetch",(e=>{const t=e.request.url,s=caches.match(t).then((async s=>{let n;if(s&&(!(n=s.headers.get($))||Date.now()<Number(n)+6048e5))return console.log(`SW: delivering cached response for ${t}`),s
;if(!t.startsWith("http")||!(t.startsWith("https://www.google.com/s2/favicons")||t.startsWith("https://icons.duckduckgo.com/ip2/")||t.endsWith("favicon.ico")))return w(e.request);try{const s=await w(e.request);return(async(e,t)=>{console.log(`SW: caching ${e}`);const s=await caches.open("dynamic"),n=await(async(e,t)=>{const s=t?t((()=>{const t=new Headers;for(const[s,n]of e.headers.entries())t.append(s,n);return t})()):e.headers,n=await e.blob();return new Response(n,{status:e.status,
statusText:e.statusText,headers:s})})(t,(e=>(e.set($,Date.now().toString()),e)));return s.put(e,n.clone()).catch((e=>console.warn(e))),n})(t,s)}catch(e){return(async(e,t)=>{console.log(`SW: caching error response for ${e}`);const s=await caches.open("dynamic"),n=new Response(null,{status:500,statusText:t||"internal error",headers:{[$]:Date.now().toString()}});return s.put(e,n.clone()).catch((e=>console.warn(e))),n})(t,e.message)}})).catch((e=>{const t=e.message||e.statusText||"unknown error"
;return console.log(`SW: unexpected error ${t}`),new Response(null,{status:500,statusText:t})}));e.respondWith(s)}))})();

View File

@ -0,0 +1,92 @@
((twod, k) => { if(window[k]) return; window[k] = true;(()=>{"use strict";function e(e,t,n,o,s,r,i){try{var c=r(e,i),a=kt(c,"value")}catch(e){return void n(e)}kt(c,"done")?t(a):an(new dn((e=>e(a))),o,s)}function t(t){const n=function(){var n=this,o=arguments;return new dn((function(s,r){function i(t){e(a,s,r,i,c,ln,t)}function c(t){e(a,s,r,i,c,un,t)}var a=$t(t,n,o);i(void 0)}))};return Tt(n,"apply",(function(e,t){return $t(n,e,t)})),n}function n(e,t){let n,o=!0;return"boolean"==typeof e?(o=e,n=t):n=e,Xn((e=>{const t=_n(_t.document)
;"interactive"==t||"complete"==t?(n&&n(),e()):Fn.addEventListener("DOMContentLoaded",(()=>{n&&n(),e()}),At({capture:o,once:!0}))}))}const o=["chrome"],s=e=>{const t=Object.call,n=t.bind(t),o=Object.assign,s=Object.getOwnPropertyDescriptor,r=Object.getPrototypeOf,i=e=>o({__proto__:null},e),c=r(function*(){}()),a=r(Uint8Array.prototype);return i({sourceWindow:e,cSO:i,F_c:n,F_a:Object.apply,F_b:Object.bind,F_tS:Function.toString,A_fE:[].forEach,A_so:[].some,A_sh:[].shift,A_j:[].join,
A_iO:[].indexOf,A_iA:Array.isArray,O_a:o,O_k:Object.keys,O_v:Object.values,O_dP:Object.defineProperties,O_dPy:Object.defineProperty,O_hOP:Object.hasOwnProperty,O_gOPN:Object.getOwnPropertyNames,O_gOPD:s,O_gOPDs:Object.getOwnPropertyDescriptors,O_gPO:r,O_tS:{}.toString,J_p:JSON.parse,J_s:JSON.stringify,M_f:Math.floor,M_r:Math.random,M_m:Math.max,M_mi:Math.min,N_tS:(0).toString,N_MSI:Number.MAX_SAFE_INTEGER,P_t:Promise.prototype.then,P_c:Promise.prototype.catch,P_co:Promise.prototype.constructor,
G_n:c.next,G_t:c.throw,R_rABS:FileReader.prototype.readAsBinaryString,R_rAT:FileReader.prototype.readAsText,R_r:s(FileReader.prototype,"result").get,R_enq:e.ReadableStreamDefaultController?e.ReadableStreamDefaultController.prototype.enqueue:null,R_cl:e.ReadableStreamDefaultController?e.ReadableStreamDefaultController.prototype.close:null,S_fCC:String.fromCharCode,S_sl:"".slice,S_su:"".substr,S_sp_nr:"".split,S_iO:"".indexOf,S_tr:"".trim,S_r_nr:"".replace,S_rA_nr:"".replaceAll,
S_cCA:"".charCodeAt,S_tLC:"".toLowerCase,S_tUC:"".toUpperCase,Y_tST:Symbol.toStringTag,Y_unsc:Symbol.unscopables,USP_tS:URLSearchParams.prototype.toString,D_pFS:DOMParser.prototype.parseFromString,U_cOU:URL.createObjectURL,U_rOU:URL.revokeObjectURL,X_o:XMLHttpRequest.prototype.open,X_pSD:XMLHttpRequest.prototype.DONE,X_pSH:XMLHttpRequest.prototype.HEADERS_RECEIVED,X_pSL:XMLHttpRequest.prototype.LOADING,X_pSO:XMLHttpRequest.prototype.OPENED,X_pSU:XMLHttpRequest.prototype.UNSENT,
X_s:XMLHttpRequest.prototype.send,D_n:Date.now,I_tS:e=>""+e,E_r:Element.prototype.remove,E_s:Element.prototype.setAttribute,E_rA:Element.prototype.removeAttribute,D_cS:s(Document.prototype,"currentScript").get,D_gRS:s(Document.prototype,"readyState").get,D_cE:Document.prototype.createElementNS,D_gEBT:Document.prototype.getElementsByTagName,M_rT:s(MouseEvent.prototype,"relatedTarget").get,C_d:s(CustomEvent.prototype,"detail").get,P_p:s(PageTransitionEvent.prototype,"persisted").get,
C_pA:CustomEvent.prototype.AT_TARGET,M_d:MutationObserver.prototype.disconnect,W_aEL:addEventListener,W_rEL:removeEventListener,FD_e:FormData.prototype.entries,TA_b:s(a,"buffer").get,TA_sa:Uint8Array.prototype.subarray,parseInt,parseFloat,CustomEvent,CompositionEvent,KeyboardEvent,MouseEvent,MutationObserver,console:Object.assign({},console),Error,Uint8Array,Blob,ReadableStream,Number,String,Proxy,Window,FileReader,DOMParser,XMLHttpRequest,Function,RegExp,Promise,encodeURIComponent,
decodeURIComponent,encodeURI,decodeURI,escape,unescape,atob,btoa,setTimeout,clearTimeout,setInterval,clearInterval,postMessage,dispatchEvent,alert,prompt,confirm,close,getElementById:e.Document.prototype.getElementById,createEvent:e.Document.prototype.createEvent,createElement:e.Document.prototype.createElement})},r="vault"in twod;if(r&&void 0===twod.vault)throw"Invalid vault"
;const i=twod.vault=twod.vault||s(twod.unsafeWindow),{cSO:c,F_c:a,F_a:d,F_b:l,F_tS:u,A_fE:p,A_so:g,A_sh:m,A_j:f,A_iO:h,A_iA:v,O_a:b,O_k:_,O_v:w,O_dP:y,O_dPy:M,O_hOP:L,O_gOPN:E,O_gOPD:I,O_gOPDs:S,O_gPO:O,O_tS:x,J_p:D,J_s:j,M_f:R,M_r:P,M_m:C,M_mi:$,N_tS:A,N_MSI:T,P_t:U,P_c:k,P_co:B,G_n:F,G_t:X,R_rABS:N,R_rAT:q,R_r:W,R_enq:H,R_cl:G,S_fCC:J,S_sl:K,S_su:z,S_iO:Y,S_sp_nr:V,S_tr:Z,S_rA_nr:Q,S_cCA:ee,S_tLC:te,S_tUC:ne,Y_tST:oe,Y_unsc:se,D_pFS:re,D_cS:ie,D_gRS:ce,D_cE:ae,D_gEBT:de,E_r:le,E_s:ue,E_rA:pe,C_pA:ge,M_d:me,C_d:fe,P_p:he,M_rT:ve,U_cOU:be,U_rOU:_e,USP_tS:we,X_o:ye,X_s:Me,X_pSD:Le,X_pSH:Ee,X_pSL:Ie,X_pSO:Se,X_pSU:Oe,D_n:xe,I_tS:De,W_aEL:je,W_rEL:Re,FD_e:Pe,TA_b:Ce,TA_sa:$e,parseInt:Ae,parseFloat:Te,console:Ue,encodeURIComponent:ke,decodeURIComponent:Be,encodeURI:Fe,decodeURI:Xe,escape:Ne,unescape:qe,atob:We,btoa:He,postMessage:Ge,dispatchEvent:Je,alert:Ke,prompt:ze,confirm:Ye,close:Ve,getElementById:Ze,createEvent:Qe,createElement:et,CustomEvent:tt,CompositionEvent:nt,KeyboardEvent:ot,MouseEvent:st,MutationObserver:rt,Uint8Array:it,FileReader:ct,DOMParser:at,XMLHttpRequest:dt,Function:lt,RegExp:ut,Blob:pt,ReadableStream:gt,Number:mt,String:ft,Proxy:ht,Window:vt}=i,bt=twod,{unsafeWindow:_t,unsafeThis:wt}=bt,yt=a,Mt=d,Lt=_,Et=w,It=b,St=M,Ot=E,xt=I,Dt=O,jt=v,Rt=P,Pt=C,Ct=$,$t=(e,t,n)=>yt(Mt,e,t,n),At=c,Tt=(e,t,n)=>(St(e,t,At({
value:n,configurable:!0,enumerable:!0,writable:!0})),e),Ut=(e,t)=>Zt(e,t)?e[t]:void 0,kt=(e,t)=>{const n=xt(e,t);return n?At(n).value:void 0},Bt=(e,t)=>{const n=(e,t,o)=>{const s=xt(e,t),r=s?At(s):void 0;let i;return r?r.enumerable?r.value:void 0:--o>=0&&(i=Dt(e))?n(i,t,o):void 0};return n(e,t,5)},Ft=e=>{const t=(t,...n)=>$t(e,t,n);return Tt(t,"wrappedJSObject",e),t},Xt=()=>e=>Ft(e),Nt=Ft(l),qt=D,Wt=Xt()(g),Ht=Xt()(m),Gt=(e,t)=>{const n=[];return Vt(e,(e=>{t(e)&&zt(n,e)})),n},Jt=(e,t,n)=>{
const o=e.length;let s=t||0;if(s>=o)return[];s<0&&(s=Pt(0,o+s));let r=void 0===n?o:n;r<0&&(r=Pt(0,o+r)),r>o&&(r=o);const i=At({});for(let t=s;t<r;t++)i[t]=kt(e,t);return Et(i)},Kt=Xt()(f),zt=(e,t)=>{let n=e.length||0;return Tt(e,n,t),n++,e.length=n},Yt=Xt()(h),Vt=Xt()(p),Zt=Xt()(L),Qt=Xt()(V),en=Xt()(K),tn=Ft(x),nn=Dt({}),on=e=>{const t=At(e),n=Ot(t);for(let e=0;e<n.length;e++){const o=n[e],s=t[o];null!==s&&"object"==typeof s&&Dt(s)===nn&&(t[o]=on(s))}return t},sn=e=>{const t=Qt(tn(e)," ")
;return en(Kt(Jt(t,1)," "),0,-1)},rn=Xt()(u),cn=Xt()(A),an=Xt()(U),dn=(Xt()(k),Nt(B,Dt((async()=>{})()))),ln=Xt()(F),un=Xt()(X),pn=Xt()(N),gn=(Xt()(q),Xt()(W)),mn=(H&&Xt()(H),G&&Xt()(G),J),fn=Xt()(z),hn=Xt()(Y),vn=(Xt()(Z),Xt()(Q||function(e,t){return Kt(Qt(this,e),t)}),Xt()(ee)),bn=Xt()(te),_n=(Xt()(ne),Ft(re),Ft(ie),Ft(ce)),wn=Ft(ae),yn=Ft(de),Mn=(Ft(le),Ft(ue),Ft(pe),Ft(ve)),Ln=Ft(fe),En=Ft(he),In=me?Xt()(me):me,Sn=be,On=_e,xn=(Ft(we),Ft(Pe),Ft(Ce)),Dn=(Xt()($e),Xt()(ye),Xt()(Me),
xe),jn=tt,Rn=st,Pn=it,Cn=rt,$n=pt,An=ut,Tn=function(e,t){return kt(e,t)},Un=At({addEventListener:!1,Array:!0,Blob:!0,close:!1,CustomEvent:!0,Date:!0,DOMParser:!0,Error:!0,Event:!0,FileReader:!0,KeyboardEvent:!0,location:!0,Math:!0,MouseEvent:!0,Number:!0,Object:!0,ReadableStream:!0,removeEventListener:!1,Uint8Array:!0,XMLHttpRequest:!0}),kn=((()=>{const e=At({getElementById:Ze,createEvent:Qe,createElement:et,dispatchEvent:Je,addEventListener,removeEventListener}),t=At({});Vt(Lt(e),(n=>{try{
const o=e[n];t[n]=function(...e){return $t(o,_t.document,e)}}catch(e){t[n]=((e,t)=>{if(Bn.error(`Tampermonkey sandbox preparation ${t?"("+t+") ":""}failed. This usually is caused by a third-party extension.`,e),t)return()=>{}})(e,`document.${n}`)}}))})(),At({top:!0,location:!0}));twod.bridges=twod.bridges||At({});const Bn=twod.console=twod.console||At({}),Fn=At({addEventListener:Nt(je,_t),removeEventListener:Nt(Re,_t)});Vt(Lt(kn),(async e=>{if(!Fn[e])try{const t=_t[e];if(null==t)return;Fn[e]=t
}catch(e){}})),Vt(Lt(Un),(async e=>{if(!Fn[e])try{let t=kt(_t,e);if(void 0===t&&(wt===_t||void 0===(t=kt(wt,e))))return;const n=Un[e];Fn[e]=!1===n&&"function"==typeof t?Nt(t,wt):t}catch(e){}}));const Xn=e=>{let t,n=[],o=!1;e((e=>{if(!o){if(n.length){const t=n;n=[],Vt(t,(t=>t(e)))}else t=e;o=!0}}));const s=At({then:e=>(o?e(t):zt(n,e),s)});return s},Nn=()=>cn(Dn()+19831206*Rt()+1,36),qn=function(){var e=t((function*(e){yield null,e()}));return function(t){return e.apply(this,arguments)}
}(),Wn=(()=>{const{console:e,bridges:t}=twod,n=At({});let o;const s=(t,o,s,i)=>{let c,a=[],d=[],l=[],u=[];const p=()=>{d=[],l=[],u=[],h(),y=null,delete n[o]},g=e=>{t.send("port.message",At({response_id:o,value:e}))},m=e=>{i&&"messageId"in e&&zt(a,e),g(e)},f=(e,t=!0)=>{c=e,t&&g(e)},h=()=>{c=void 0},v=At({addListener:e=>{zt(d,e)}}),b=At({addListener:e=>{zt(l,e)}}),_=At({addListener:e=>{zt(u,e)}}),w=()=>{p(),t.send("port.message",At({response_id:o,disconnect:!0}))};let y=At(s?{postMessage:m,
connectMessage:f,stopReconnecting:h,onMessage:v,onDisconnect:b,onReconnect:_,disconnect:w}:{postMessage:m,onMessage:v,onDisconnect:b,disconnect:w});return n[o]=At({message:t=>{if(i&&(e=>"ack"in e)(t)){const{messageId:n,refreshId:o}=t;((t,n)=>{if(n)return;if(!t)return void e.warn("PortMessaging: no message id in ack message");if(c&&c.messageId===t)return;let o=-1;Wt(a,((e,n)=>e.messageId===t&&(o=n,!0))),-1!==o?(Vt(Jt(a,0,o),(t=>e.warn(`PortMessaging: message ${t.messageId} was not ack'ed!`,t))),
a=Jt(a,o+1)):e.warn(`PortMessaging: no one is waiting for ${t}`)})(n,o)}d&&Vt(d,(e=>e(t)))},disconnect:()=>{if(c&&s)return r(s,o),f(c),i&&Vt(a,(e=>g(e))),void(u.length&&Vt(u,(e=>e())));l.length&&Vt(l,(e=>e())),p()}}),y},r=(e,n)=>{t.first.send("port.message",At({response_id:n,connect:!0,destination:e}))};return At({message:(t,r)=>{let i;if(t.connect){if(!t.destination||!t.response_id)throw"invalid message";o&&o(t.destination,s(r,t.response_id))}else{if(!t.response_id)throw"invalid message"
;if(!(i=n[t.response_id]))return void e.warn("ports: unknown id",t.response_id,t);t.disconnect?i.disconnect():i.message(t.value)}},connect:function(e,n,o){const i=Nn();return r(e,i),s(t.first,i,n?e:void 0,o)},onConnect:At({addListener:e=>{o=e}})})})(),{setInterval:Hn,setTimeout:Gn,clearInterval:Jn,clearTimeout:Kn,console:zn,cloneInto:Yn,exportFunction:Vn,createObjectIn:Zn,btoa:Qn}=_t,eo=Object.assign({},zn),to=Hn.bind(_t),no=Gn.bind(_t),oo=Jn.bind(_t),so=(Kn.bind(_t),
wt==_t.top),{arrayBuffer:ro,blob:io}=_t.Response.prototype,{arrayBuffer:co}=_t.Blob.prototype,{then:ao}=_t.Promise.prototype,{fetch:lo,location:uo,document:po,Response:go}=_t,mo=Ft(ro),fo=Ft(io),ho=Ft(co),vo=Yn,bo=(At({encode:e=>qe(ke(e)),decode:e=>Be(Ne(e))}),At({encode:e=>{let t="";for(let n=0;n<e.length;n++)t+=mn(255&vn(e,n));return He(t)},decode:e=>We(e)})),_o=e=>{const t=new Pn(e.length);for(let n=0;n<e.length;n++)t[n]=vn(e,n);return xn(t)},wo=e=>{let t;const n=Qt(e,","),o=Tn(n,0),s=Tn(n,1)
;t=-1!=hn(o,"base64")?We(s):qe(s);const r=Tn(Qt(o,":"),1),i=Tn(Qt(r,";"),0);return new $n([_o(t)],At({type:i}))},yo=(e,t)=>{const n=wn(_t.document,"http://www.w3.org/1999/xhtml",e);return"string"==typeof t?n.append(t):t&&Vt(Lt(t),(e=>{"textContent"==e?n.textContent=t[e]:n.setAttribute(e,t[e])})),n},Mo=e=>{const t=_t.document;if(t.body||"text/xml"==t.contentType)e();else{let t=!1;const o=new Cn((()=>{t=!0,Mo(e),(In||(e=>e.disconnect()))(o)}));o.observe(_t.document,At({childList:!0})),n((()=>{
t||((In||(e=>e.disconnect()))(o),e())}))}},Lo=e=>{n((()=>{no((()=>e()),1)}))};let Eo,Io;const So=uo.host,Oo=e=>{"n:"==fn(e,0,2)?Eo=fn(e,2):e&&(Io=fn(e,2))},xo=()=>Eo||(Io?(Eo=(e=>{const t=(e,t)=>e<<t|e>>>32-t,n=(e,t)=>{const n=2147483648&e,o=2147483648&t,s=1073741824&e,r=1073741824&t,i=(1073741823&e)+(1073741823&t);return s&r?2147483648^i^n^o:s|r?1073741824&i?3221225472^i^n^o:1073741824^i^n^o:i^n^o},o=(e,o,s,r,i,c,a)=>(e=n(e,n(n(((e,t,n)=>e&t|~e&n)(o,s,r),i),a)),
n(t(e,c),o)),s=(e,o,s,r,i,c,a)=>(e=n(e,n(n(((e,t,n)=>e&n|t&~n)(o,s,r),i),a)),n(t(e,c),o)),r=(e,o,s,r,i,c,a)=>(e=n(e,n(n(((e,t,n)=>e^t^n)(o,s,r),i),a)),n(t(e,c),o)),i=(e,o,s,r,i,c,a)=>(e=n(e,n(n(((e,t,n)=>t^(e|~n))(o,s,r),i),a)),n(t(e,c),o)),c=e=>{let t,n,o="",s="";for(n=0;n<=3;n++)t=e>>>8*n&255,s="0"+cn(t,16),o+=fn(s,s.length-2,2);return o};let a,d,l,u,p,g,m,f;const h=(e=>{let t;const n=e.length,o=n+8,s=16*((o-o%64)/64+1),r=[];for(let e=0;e<=s-1;e++)zt(r,0);let i=0,c=0;for(;c<n;)t=(c-c%4)/4,
i=c%4*8,r[t]=r[t]|vn(e,c)<<i,c++;return t=(c-c%4)/4,i=c%4*8,r[t]=r[t]|128<<i,r[s-2]=n<<3,r[s-1]=n>>>29,r})(e);p=1732584193,g=4023233417,m=2562383102,f=271733878;for(let e=0;e<h.length;e+=16)a=p,d=g,l=m,u=f,p=o(p,g,m,f,h[e+0],7,3614090360),f=o(f,p,g,m,h[e+1],12,3905402710),m=o(m,f,p,g,h[e+2],17,606105819),g=o(g,m,f,p,h[e+3],22,3250441966),p=o(p,g,m,f,h[e+4],7,4118548399),f=o(f,p,g,m,h[e+5],12,1200080426),m=o(m,f,p,g,h[e+6],17,2821735955),g=o(g,m,f,p,h[e+7],22,4249261313),
p=o(p,g,m,f,h[e+8],7,1770035416),f=o(f,p,g,m,h[e+9],12,2336552879),m=o(m,f,p,g,h[e+10],17,4294925233),g=o(g,m,f,p,h[e+11],22,2304563134),p=o(p,g,m,f,h[e+12],7,1804603682),f=o(f,p,g,m,h[e+13],12,4254626195),m=o(m,f,p,g,h[e+14],17,2792965006),g=o(g,m,f,p,h[e+15],22,1236535329),p=s(p,g,m,f,h[e+1],5,4129170786),f=s(f,p,g,m,h[e+6],9,3225465664),m=s(m,f,p,g,h[e+11],14,643717713),g=s(g,m,f,p,h[e+0],20,3921069994),p=s(p,g,m,f,h[e+5],5,3593408605),f=s(f,p,g,m,h[e+10],9,38016083),
m=s(m,f,p,g,h[e+15],14,3634488961),g=s(g,m,f,p,h[e+4],20,3889429448),p=s(p,g,m,f,h[e+9],5,568446438),f=s(f,p,g,m,h[e+14],9,3275163606),m=s(m,f,p,g,h[e+3],14,4107603335),g=s(g,m,f,p,h[e+8],20,1163531501),p=s(p,g,m,f,h[e+13],5,2850285829),f=s(f,p,g,m,h[e+2],9,4243563512),m=s(m,f,p,g,h[e+7],14,1735328473),g=s(g,m,f,p,h[e+12],20,2368359562),p=r(p,g,m,f,h[e+5],4,4294588738),f=r(f,p,g,m,h[e+8],11,2272392833),m=r(m,f,p,g,h[e+11],16,1839030562),g=r(g,m,f,p,h[e+14],23,4259657740),
p=r(p,g,m,f,h[e+1],4,2763975236),f=r(f,p,g,m,h[e+4],11,1272893353),m=r(m,f,p,g,h[e+7],16,4139469664),g=r(g,m,f,p,h[e+10],23,3200236656),p=r(p,g,m,f,h[e+13],4,681279174),f=r(f,p,g,m,h[e+0],11,3936430074),m=r(m,f,p,g,h[e+3],16,3572445317),g=r(g,m,f,p,h[e+6],23,76029189),p=r(p,g,m,f,h[e+9],4,3654602809),f=r(f,p,g,m,h[e+12],11,3873151461),m=r(m,f,p,g,h[e+15],16,530742520),g=r(g,m,f,p,h[e+2],23,3299628645),p=i(p,g,m,f,h[e+0],6,4096336452),f=i(f,p,g,m,h[e+7],10,1126891415),
m=i(m,f,p,g,h[e+14],15,2878612391),g=i(g,m,f,p,h[e+5],21,4237533241),p=i(p,g,m,f,h[e+12],6,1700485571),f=i(f,p,g,m,h[e+3],10,2399980690),m=i(m,f,p,g,h[e+10],15,4293915773),g=i(g,m,f,p,h[e+1],21,2240044497),p=i(p,g,m,f,h[e+8],6,1873313359),f=i(f,p,g,m,h[e+15],10,4264355552),m=i(m,f,p,g,h[e+6],15,2734768916),g=i(g,m,f,p,h[e+13],21,1309151649),p=i(p,g,m,f,h[e+4],6,4149444226),f=i(f,p,g,m,h[e+11],10,3174756917),m=i(m,f,p,g,h[e+2],15,718787259),g=i(g,m,f,p,h[e+9],21,3951481745),p=n(p,a),g=n(g,d),
m=n(m,l),f=n(f,u);const v=c(p)+c(g)+c(m)+c(f);return bn(v)})(`${So}#${Io}`),Eo):void 0),Do=e=>void 0!==kt(e,"objUrl"),jo=e=>void 0!==kt(e,"blob"),Ro=e=>void 0!==kt(e,"dataUri"),Po=e=>void 0!==e.binary,Co=globalThis;let $o,Ao,To,Uo,{chrome:ko,browser:Bo}=Co;To=()=>{if(void 0!==$o)return $o;try{const e=navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);e&&($o=parseInt(e[2]))}catch(e){}return $o},Uo=()=>{if(void 0!==Ao)return Ao;try{Ao=-1!=navigator.userAgent.search(/Android|Mobile/)}catch(e){}
return Ao},To();const Fo=["chrome-extension:"];[].concat(["chrome"]);const Xo=(()=>{const e={getInternalPathRegexp:function(e,t){const n=new RegExp("(\\"+["/",".","+","?","|","(",")","[","]","{","}","\\"].join("|\\")+")","g"),o=Fo[0]+"//"+Xo.id+"/";return new RegExp(o.replace(n,"\\$1")+"([a-zA-Z"+(e?"\\/":"")+"]*)"+(t||"").replace(n,"\\$1"))},getInternalPageRegexp:function(){return Xo.getInternalPathRegexp(!1,".html")},getPlatformInfo:e=>ko.runtime.getPlatformInfo(e),getBrowserInfo:e=>{e({
name:"Chrome",version:`${To()}`,vendor:"unknown"})}};return Object.defineProperty(e,"lastError",{get:()=>ko.runtime.lastError,enumerable:!0}),Object.defineProperty(e,"id",{get:()=>ko.runtime.id,enumerable:!0}),Object.defineProperty(e,"short_id",{get:()=>e.id.replace(/[^0-9a-zA-Z]/g,"").substr(0,4),enumerable:!0}),e})(),No=(()=>{let e;return Object.defineProperties({},{inIncognitoContext:{get:()=>(void 0===e&&(e=ko.extension.inIncognitoContext),e),set:t=>{e=t},enumerable:!0},
...Object.getOwnPropertyDescriptors({getURL:function(e){return ko.runtime.getURL(e)},sendMessage:(e,t)=>ko.runtime.sendMessage(e,t),onMessage:{addListener:e=>ko.runtime.onMessage.addListener(e)},connect:e=>ko.runtime.connect({name:e}),urls:{prepareForReport:function(e){return e}}})})})();t((function*(e,t){yield ko.offscreen.createDocument({url:"offscreen.html",...e}),t&&t()})),t((function*(e){yield ko.offscreen.closeDocument(),e&&e()}))
;const qo=ko&&ko.userScripts&&ko.userScripts.onBeforeScript?{supported:!0,onBeforeScript:{addListener:e=>ko.userScripts.onBeforeScript.addListener(e)}}:{supported:!1},Wo=({sendPrefix:e,listenPrefix:n,send:o,onMessage:s})=>{if(void 0===o||void 0===s)throw"invalid args";let r,i,c=1;const a=At({}),d=At({}),l=e=>{e&&(r=e)},u=e=>{const t=++c;return d[c]=e,t};s(((t,s)=>t==`${n}_${r}`?(t=>{const{m:n,r:s,a:c,n:l}=t;if(a[n]&&(Vt(a[n],(e=>e(c))),delete a[n]),"message.response"==n){
if(null==s)throw"Invalid Message";((e,t,n)=>{let o;e&&(o=d[e])&&(o(t,n),delete d[e])})(s,c,l)}else if(i){const t=s?(t,n)=>{o(`${e}_${r}`,At({m:"message.response",a:t,r:s,n}))}:()=>{};i(At({method:n,args:c,node:l}),t)}})(s):null));const p=At({init:(g=t((function*(e){r?l():l(e)})),function(e){return g.apply(this,arguments)}),refresh:()=>null,switchId:e=>{r&&p.cleanup(),l(e)},send:(t,n,s,i)=>Xn((c=>{let a,d;"function"!=typeof s&&null!==s?(a=s,d=i):d=s,o(`${e}_${r}`,At({m:t,a:n,r:d?u(d):null,n:a})),
c()})),sendToId:(t,n,s)=>{o(`${e}_${t}`,At({m:n,a:s,r:null}))},once:(e,t)=>{a[e]||(a[e]=[]),zt(a[e],t)},setMessageListener:e=>{i=e},cleanup:()=>null});var g;return p},Ho=qo,Go=qo.supported&&!_t.pagejs;let Jo;const Ko=(e,t)=>{try{Jo(e),t&&t()}catch(e){t&&t(e.message||e)}},zo="u"+Nn(),{bridges:Yo}=twod;let Vo=[];const Zo=e=>{Ho.onBeforeScript.addListener((o=>{const s=(e,n)=>{Vt(t,(t=>t(e,n)))},r=e=>zt(n,At({listener:e,clone:o.export}));St(o.global,"pagejs",At({set:o.export((t=>{
delete o.global.pagejs;const n=o.metadata,{modes:i,nonce:c}=n;if(c&&Oo(c),Vt(Vo,(e=>e(t,n))),Vo=[],i.js){const n=At({unsafeWindow:o.global,unsafeThis:o.global.window,pageWindow:void 0,contextId:zo,fSend:s,fOnMessage:r,cloneInto:void 0,exportFunction:void 0});t(o.export(n)),Yo.js.sendToId(zo,"commid",At({id:e}))}})),configurable:!0})),Jo=o.global.eval}));const t=[],n=[],o=(e,t)=>{Vt(n,(({listener:n,clone:o})=>n(e,o(t))))},s=e=>zt(t,e);return At({createBridge:()=>{const t=Wo(At({sendPrefix:"2S",
listenPrefix:"2U",cloneInto:vo,send:o,onMessage:s}));return t.init(e),t}})},Qo=At({});let es,ts;const ns=function(){var e=t((function*(){if(es)return;const{contextId:e}=twod,{location:t,document:n}=_t;ts=n,es=()=>{try{No.sendMessage(At({method:"contextmenu",url:t.href,id:e}),(()=>{}))}catch(e){}},ts.addEventListener("mouseenter",es,!1)}));return function(){return e.apply(this,arguments)}}(),os=function(){var e=t((function*(e){es||(yield ns()),ts.addEventListener("mousemove",es,At({once:!0})),
Qo[e]=!0}));return function(t){return e.apply(this,arguments)}}(),ss=function(){var e=t((function*(e){delete Qo[e],!Lt(Qo).length&&es&&(ts.removeEventListener("mouseenter",es,!1),es=void 0)}));return function(t){return e.apply(this,arguments)}}();let rs=[],is=[];const cs=At({}),as=e=>{const t=No.connect(e);if(Xo.lastError)return;let n=[],o=[];const s=Nn(),r=At({postMessage:e=>{try{return t.postMessage(e)}catch(e){const t="message"in e?e.message:"unknown error"
;eo.warn("port: background communication error - this context might have missed important events!",t),c(t)}},onMessage:At({addListener:e=>t.onMessage.addListener(e)}),onError:At({addListener:e=>{zt(o,e)}}),onDisconnect:At({addListener:e=>{zt(n,e)}}),disconnect:()=>(i(!1),t.disconnect())});cs[s]=r;const i=e=>{e&&Vt(n,(e=>e())),n=[],o=[],rs=Gt(rs,(e=>e!==a)),is=Gt(is,(e=>e!==d)),delete cs[s]};t.onDisconnect.addListener((()=>i(!0)));const c=e=>{Vt(o,(t=>t(e))),delete cs[s],Vt(Lt(cs),(e=>{
const t=cs[e];t&&t.postMessage(At({refreshId:Nn()}))}))},a=()=>{t.disconnect(),Xo.lastError,i(!0)};zt(rs,a);const d=()=>{t.disconnect(),Xo.lastError};return zt(is,d),r};let ds,ls,us;Fn.addEventListener("pagehide",(e=>{En(e)&&Vt(is,(e=>e()))})),Fn.addEventListener("pageshow",(e=>{En(e)&&Vt(rs,(e=>e()))}));const{console:ps}=twod,gs=e=>Xn(function(){var n=t((function*(t){const n=e.url;let o,s,r,i;if(!n)return t(At({t:e,c:o}));const c=sn(n);if("string"==typeof n){const e=fn(n,0,5)
;if("blob:"===e)if(us)s=At({objUrl:At({url:n})});else{const e=yield lo(n);i=yield fo(e)}else(us||ls)&&"data:"===e?i=wo(n):r=n}else"Blob"==c||"File"==c?i=n:"ArrayBuffer"==c&&(i=new $n([n]));if(i)if(ls)s=At({blob:i});else if(us){const e=Sn(i);o=()=>On(e),s=At({objUrl:At({url:e})})}else{const e=yield(a=i,Xn((e=>{const t=new Fn.FileReader;t.onload=()=>{e(gn(t))},t.onerror=t=>{Bn.warn(`unable to decode data ${t}`),e("")},pn(t,a)}))),t=i.type||"application/octet-stream";try{s=At({
dataUri:`data:${t};base64,${bo.encode(e)}`})}catch(e){ps.warn(`content: failed to get blob data from ${n}`,e)}}var a;t(At({t:At({url:r,tfd:s}),c:o}))}));return function(e){return n.apply(this,arguments)}}()),ms=At({setInterval:e=>{let t;e.onMessage.addListener((n=>{"setInterval"==n.method&&(t=to(e.postMessage,n.t))})),e.onDisconnect.addListener((()=>{t&&oo(t),t=null}))},registerMenuCommand:e=>{const t=as("registerMenuCommand");if(!t)return void no((()=>e.disconnect()),1);let n
;t.onMessage.addListener((t=>{if("ack"in t)e.postMessage(t);else{const{method:n,event:o}=t;e.postMessage(At({method:n,event:o}))}})),t.onDisconnect.addListener((()=>e.disconnect())),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{const{messageId:o,name:s,uuid:r,accessKey:i,autoClose:c,title:a,id:d}=e,l=n=Kt([d,ds,r],"#");os(n),t.postMessage(At({messageId:o,method:"registerMenuCommand",name:s,title:a,uuid:r,menuId:l,accessKey:i,autoClose:c}))})),
e.onDisconnect.addListener((()=>{n&&ss(n),t.disconnect()}))},notification:e=>{const t=as("notification");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),t.onDisconnect.addListener((()=>e.disconnect())),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{t.postMessage(e)})),e.onDisconnect.addListener((()=>{t.disconnect()}))):no((()=>e.disconnect()),1)},openInTab:e=>{const t=as("openInTab");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),
t.onDisconnect.addListener((()=>e.disconnect())),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{const{messageId:n}=e;if("method"in e){const{method:o}=e;if("openInTab"==o)if("url"in e){let o=e.url;const{active:s,loadInBackground:r,insert:i,incognito:c,setParent:a,cookieStoreId:d}="boolean"==typeof e.options||void 0===e.options?At({loadInBackground:e.options}):e.options,l=void 0===s?void 0!==r&&!r:s,u=void 0===i||i;o&&"//"==fn(o,0,2)&&(o=uo.protocol+o),t.postMessage(At({
messageId:n,method:"openInTab",details:At({url:o,options:At({active:!!l,insert:!!u,incognito:!!c,setParent:!c&&!!a,cookieStoreId:d})}),uuid:e.uuid}))}else t.postMessage(e);else ps.warn(`content: unknown method ${o}`)}else"name"in e?t.postMessage(At({messageId:n,name:e.name})):"focus"in e?t.postMessage(At({messageId:n,focus:!0})):"close"in e&&t.postMessage(At({messageId:n,close:!0}))})),e.onDisconnect.addListener((()=>{t.disconnect()}))):no((()=>e.disconnect()),1)},download:e=>{let t
;const n=as("download");if(!n)return void no((()=>e.disconnect()),1);let o;n.onMessage.addListener((t=>{e.postMessage(t)})),n.onDisconnect.addListener((()=>{e.disconnect(),t=!0})),n.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{if("cancel"in e)t=!0,n.postMessage(At({cancel:!0,id:ds,uuid:e.uuid}));else if("details"in e){const{details:s,messageId:r,uuid:i}=e;gs(s).then((({t:e,c})=>{if(t)return void(c&&c());o=c;const{url:a,...d}=s;n.postMessage(At({messageId:r,
method:"download",details:At({...d,from:e}),id:ds,uuid:i,location:uo.href}))}))}else n.postMessage(At({messageId:e.messageId,method:"download",uuid:e.uuid,id:e.id}))})),e.onDisconnect.addListener((()=>{o&&o(),o=void 0,n.disconnect()}))},webRequest:e=>{const t=as("webRequest");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),t.onDisconnect.addListener((()=>{e.disconnect()})),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{const{messageId:n,rules:o,uuid:s}=e
;t.postMessage(At({messageId:n,method:"webRequest",rules:o,uuid:s}))})),e.onDisconnect.addListener((()=>{t.disconnect()}))):no((()=>e.disconnect()),1)},xhr:e=>{let n,o;const s=[];let r;const i=function(){var e=t((function*(e){if(e&&zt(s,e),o)yield o,i();else{const e=Ht(s);e&&e()}}));return function(t){return e.apply(this,arguments)}}(),c=as("xhr");c?(c.onMessage.addListener((n=>{"ack"in n?e.postMessage(n):i((()=>{const{onpartial:s,data:r,...i}=n;let c;if(s&&r){const{tfd:n}=r;if(n){
const r=(e=>e&&(jo(e)||Do(e)||Ro(e)||Po(e))?((e,t)=>{let n,o,s,r,i;if(Do(e))n=e.objUrl.url;else if(jo(e))o=e.blob;else if(Ro(e))s=e.dataUri;else{if(!Po(e))throw"incompatible TransferableData";r=e.binary,i=e.type}return At({toBlob:()=>Xn((e=>{if(o)e(o);else if(n)try{an(lo(n),(t=>{an(fo(t),(t=>{e(t)}))}))}catch(t){e(void 0)}else if(s)e(wo(s));else{if(void 0===r)throw"incompatible Transferable";{const t=_o(r);e(new $n([t],i?At({type:i}):void 0))}}})),get tryObjectUrl(){return n},dispose:()=>{
t?t():n&&On(n),n=o=s=r=void 0}})})(e,(()=>{const e=r&&r.tryObjectUrl;e&&fs.revoke(At({args:At({method:"revoke",urls:[e]})}))})):void 0)(n);if(!r)return;return void(o=Xn(function(){var n=t((function*(t){const n=()=>{o=null,t(),r&&r.dispose()};try{const t=yield r.toBlob();if(!t)return void n();const o=t.type;let a;if(a="arrayBuffer"in t?yield ho(t):yield mo(new go(t)),!a)return void n();c=At({nada:At({buffer:a,type:o})}),e.postMessage(At({...i,onpartial:s,data:c})),n()}catch(e){ps.warn(e),n()}}))
;return function(e){return n.apply(this,arguments)}}()))}c=r}else c=r;e.postMessage(At({...i,onpartial:s,data:c}))}))})),c.onDisconnect.addListener((()=>{i(function(){var o=t((function*(){e.disconnect(),n=!0}));return function(){return o.apply(this,arguments)}}())})),c.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{Go&&(e=((e,t=[])=>{const n=(e,o)=>{if(null===e)return null;if("object"==typeof e){const s=sn(e);if(-1!=Yt(t,s))return e;if(o){
if(-1!==Yt(o,e))throw"Converting circular structure to clone";Tt(o,o.length,e)}else o=[e];if(jt(e)){const t=[];for(let s=0;s<e.length;s++){let r;r=Zt(e,s)?Ut(e,s):Bt(e,s);const i=n(r,o);zt(t,i)}return o.length-=1,t}if("Object"===s){const t=At({});return Vt(Lt(e),(s=>{const r=n(e[s],o);void 0!==r&&(t[s]=r)})),o.length-=1,t}throw`Unsupported type in clone: ${s}`}return e};return n(e)})(e,["Blob","File","ArrayBuffer"]));const{details:t}=e;(t?gs(t):Xn((e=>e()))).then((o=>{const{t:s,c:i}=o||At({})
;if(n)return void(i&&i());let a,d;r=i,s&&t?(a=At({...t,...s}),d=At({...e,details:a,location:uo.href})):d=e,c.postMessage(d)}))})),e.onDisconnect.addListener((()=>{r&&r(),r=void 0,c.disconnect()}))):no((()=>e.disconnect()),1)},onurlchange:e=>{const t=as("onurlchange");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),t.onDisconnect.addListener((()=>{e.disconnect()})),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{t.postMessage(e)})),e.onDisconnect.addListener((()=>{
t.disconnect()}))):no((()=>e.disconnect()),1)},onaudiostatechange:e=>{const t=as("onaudiostatechange");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),t.onDisconnect.addListener((()=>e.disconnect())),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{t.postMessage(e)})),e.onDisconnect.addListener((()=>{t.disconnect()}))):no((()=>e.disconnect()),1)},values:e=>{const t=as("values");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),
t.onDisconnect.addListener((()=>e.disconnect())),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{t.postMessage(e)})),e.onDisconnect.addListener((()=>{t.disconnect()}))):no((()=>e.disconnect()),1)},backgroundControl:e=>{const t=as("backgroundControl");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),t.onDisconnect.addListener((()=>e.disconnect())),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{t.postMessage(e)})),
e.onDisconnect.addListener((()=>{t.disconnect()}))):no((()=>e.disconnect()),1)},keepAlive:e=>{const t=as("keepAlive");t?(t.onMessage.addListener((t=>{e.postMessage(t)})),t.onDisconnect.addListener((()=>e.disconnect())),t.onError.addListener((()=>e.disconnect())),e.onMessage.addListener((e=>{t.postMessage(e),Xo.lastError})),e.onDisconnect.addListener((()=>{t.disconnect()}))):no((()=>e.disconnect()),1)}}),fs=At({setTimeout:({args:e,cb:t})=>{no(t,e.t)},setClipboard:({args:e,cb:t})=>{
const{content:n,info:o,uuid:s}=e;let r,i;"object"==typeof o?(o.type&&(r=o.type),o.mimetype&&(i=o.mimetype)):"string"==typeof o&&(r=o);const c=i||("html"==r?"text/html":"text/plain");_t.document.addEventListener("copy",(e=>{e.stopImmediatePropagation(),e.preventDefault(),e.clipboardData&&e.clipboardData.setData(c,n)}),At({capture:!0,once:!0})),_t.document.execCommand("copy"),t()},closeTab:({args:{uuid:e},cb:t})=>{No.sendMessage(At({method:"closeTab",uuid:e,id:ds}),(e=>{
e&&e.error&&ps.warn(e.error),t(e)}))},focusTab:({args:{uuid:e},cb:t})=>{No.sendMessage(At({method:"focusTab",uuid:e,id:ds}),(e=>{e&&e.error&&ps.warn(e.error),t(e)}))},navigateTab:({args:{uuid:e,url:t,location:n},cb:o})=>{No.sendMessage(At({method:"navigateTab",uuid:e,url:t,location:n,id:ds}),(e=>{e&&e.error&&ps.warn(e.error),o(e)}))},addElement:(hs=t((function*({args:e,node:t,cb:o}){try{const s=yo(e.tag,At({...e.properties||At({}),...e.id?At({id:e.id}):At({})}));let r,i
;if("script"===e.tag&&(r=xo())&&s.setAttribute("nonce",r),t)i=t;else{const e=_t.document;if(i=e.head||e.body||e.documentElement,!i){const e=_t.document;i=yield Xn((t=>n((()=>t(e.head||e.body)))))}}i.appendChild(s),r&&s.removeAttribute("nonce"),o(void 0,s)}catch(e){ps.warn("content: error adding script",e)}})),function(){return hs.apply(this,arguments)}),tabs:({args:e,cb:t})=>{e.method="tabs",No.sendMessage(e,(e=>e&&t(e.data)))},cookie:({args:e,cb:t})=>{e.method="cookie",
No.sendMessage(e,(e=>e&&t(e.data)))},audio:({args:e,cb:t})=>{e.method="audio",No.sendMessage(e,(e=>e&&t(e.data)))},revoke:({args:e})=>{e.method="revoke",No.sendMessage(e,(e=>{e&&e.error&&ps.warn("content: revoke error:"+e.error)}))}});var hs;const vs=At({init:()=>{ds=twod.contextId},setup:(e,t)=>{ls=e,us=t},processMessage:({method:e,args:t,node:n},o)=>{let s;if(s=fs[e])return s(At({args:t,node:n,cb:o}));ps.warn(`content: unknown method ${e}`),o()},processConnect:(e,t)=>{let n
;if(n=ms[e])return n(t)}}),bs=["GM_info","GM.info"],_s=["unsafeWindow","navigate",...bs],ws=e=>e.replace(new RegExp("[\"']","g"),"\\$1");let ys=!1;const Ms=(e,n,o,s,r)=>{const{console:i}=twod;ys=ys||e.logLevel>=60;const{version:c,injectMode:a,inIncognitoContext:d,isFirstPartyIsolation:l,downloadMode:u,relaxedCsp:p,userAgent:g,container:m,logLevel:f}=e,h=At({version:c,injectMode:a,inIncognitoContext:d,isFirstPartyIsolation:l,downloadMode:u,relaxedCsp:p,container:m});Vt(n,function(){
var n=t((function*(t){const{script:n,storage:c}=t,{name:a,uuid:d,options:{run_at:l}}=n,{requires:u,...p}=n,m=u.length,v=!n.options.unwrap,b=At({...h,userAgent:g,logLevel:f,sandboxMode:r}),_="context-menu"===l;let w,y;const M=((e,t)=>{const{measure_scripts:n,top_level_await:o,enforce_strict_mode:s}=e,{source_url:r,script:i,code:c}=t,{name:a,grant:d}=i,{requires:l}=i,u=!i.options.unwrap,p=l.map((e=>e.textContent||"")).join("\n");if(u){let e=""
;const t=["define","module","exports"],l=t.map((()=>"undefined")),u=-1!==i.grant.indexOf("none");let g;return g=u?bs:d.concat(_s),g.forEach((e=>{const n=e.split(".")[0];"window"!==n&&-1===t.indexOf(n)&&(t.push(n),l.push(`p.${n}`))})),
[`with (${u?"this.s":"this"}) {`,"(async (u, { p, r, s }) => {","try {",n?`console.time("${e=`SCRIPT RUN TIME[${ws(a)}]`}");\n`:"","r(u, s, [",l.join(","),"]);",n?`console.timeEnd("${e}");\n`:"","} catch (e) {","if (e.message && e.stack) {","console.error(\"ERROR: Execution of script '",ws(a),"' failed! \" + e.message);","console.log(e.stack);","} else {","console.error(e);","}","}","})","(",(o?"async ":"")+"function(",t.join(","),") {",s?'"use strict";\n':"\n",p,c,"\n",`}, ${u?"this":"seed"})`,"}","\n",r?`//# sourceURL=${r}\n`:""].join("")
}return[p,c,"\n",r?`//# sourceURL=${r}\n`:""].join("")})(e,t);return v?(w=()=>{ys&&i.debug(`env: inject "${a}" now`);const e=`__f__${Nn()}`,t=At({storage:c,script:p}),n=`window["${e}"] = function(){${M}}`;let r=!0;s.once(`scriptack-${e}`,(()=>{ys&&!r&&i.log(`env: execution of "${a}" was delayed`),o(n,(e=>{e&&i.error(`Uncaught SyntaxError: ${e}`)}))})),s.send("script",At({id:e,unwrap:!1,bundle:t,flags:b})),r=!1},y=_||"document-start"==l?void 0:()=>{
ys&&i.debug(`env: run "${a}" now (${m} requires)`),s.send("run",At({uuid:d}))}):y=()=>{ys&&i.debug(`env: inject @unwrap "${a}" now`),o(M,(e=>{e&&i.error(`Uncaught SyntaxError: ${e}`)}))},_&&ss(d),Ls(a,l,w,y,ys)}));return function(e){return n.apply(this,arguments)}}())},Ls=(e,t,o,s,r)=>{const{console:i}=twod;let c;"document-start"==t?(r&&i.debug(`env: run "${e}" ASAP -> document-start`),c=e=>e()):"document-body"==t?(r&&i.debug(`env: schedule "${e}" for document-body`),
c=Mo):"context-menu"==t?r&&i.debug(`env: run "${e}" ASAP -> context-menu`):"document-end"==t?(r&&i.debug(`env: schedule "${e}" for document-end`),c=e=>n(!1,e)):(r&&i.debug(`env: schedule "${e}" for document-idle`),c=Lo),o&&o(),s&&c&&c((()=>{s()}))},Es=(e,t)=>{let n,o;try{o=(0,eval)(e)}catch(e){n=e.message||e}return t&&t(n),o},Is=({sendPrefix:e,listenPrefix:n,cloneInto:o})=>{const s=e=>o?o(e,_t.document):e,i=At({});let c,a,d=1;const l=At({});let u=!1,p=[];const g=()=>{
_=_t.document.documentElement,u=!1;const e=p;p=[],Vt(e,(e=>{u||y()?zt(p,e):e()}))};let m;const f=e=>{const t=++d;return l[d]=e,t},h=(e,t)=>{const{m:n,a:o,r,n:i}=t,{m:c,c:a}=((e,t,n)=>{let o,r;return n?(r=new Rn(e,At({relatedTarget:n})),o=new jn(e,At({detail:s(t)}))):o=new jn(e,At({detail:s(t)})),At({m:r,c:o})})(e,At({m:n,a:o,r}),i);c&&$t(Je,_t,[c]),$t(Je,_t,[a])},v=t=>{const n=(e=>{if("MouseEvent"===sn(e)){const t=Mn(e);if(!t)throw"Invalid MouseEvent";return void(m=t)}const t=on(Ln(e))
;return m&&(t.n=m,m=void 0),t})(t);if(!n)return;const{m:o,r:s,a:r,n:d}=n;if(i[o]&&(Vt(i[o],(e=>e(r))),delete i[o]),"unlock"==o)h(`${e}_${a}`,At({m:"unlocked",a:void 0,r:null})),g();else if("unlocked"==o)g();else if("message.response"==o){if(null==s)throw"Invalid Message";((e,t,n)=>{let o;e&&(o=l[e])&&(o(t,n),delete l[e])})(s,r,d)}else if(c){const t=s?(t,n)=>{h(`${e}_${a}`,At({m:"message.response",a:t,r:s,n}))}:()=>{};c(At({method:o,args:r,node:d}),t)}},b=e=>{e&&(a=e),
a&&Fn.addEventListener(`${n}_${a}`,v,!0)};let _,w;const y=()=>{if((()=>{const e=_t.document.documentElement;return _||(_=e),_!==e})()){if(w){const e=w;w=void 0,e(_t.document)}return!0}},M=e=>(_=_t.document.documentElement,Xn(function(){var n=t((function*(t){if(w=t,r&&!e&&(yield null,y()))return;const n=new Cn((()=>{y()&&n.disconnect()}));n.observe(_t.document,At({childList:!0}))}));return function(e){return n.apply(this,arguments)}}())),L=At({init:(E=t((function*(t,n){a?b():b(t),M(n).then((()=>{
u=!0,L.refresh(),h(`${e}_${a}`,At({m:"unlock",a:void 0,r:null}))}))})),function(e,t){return E.apply(this,arguments)}),refresh:()=>{const e=a;e&&(L.cleanup(),L.init(e,!0))},switchId:e=>{a&&L.cleanup(),b(e)},send:(t,n,o,s)=>Xn((r=>{let i,c;"function"!=typeof o&&null!==o?(i=o,c=s):c=o,y();const d=()=>{h(`${e}_${a}`,At({m:t,a:n,r:c?f(c):null,n:i})),r()};u?zt(p,d):d()})),sendToId:(t,n,o)=>{h(`${e}_${t}`,At({m:n,a:o,r:null}))},setMessageListener:e=>{c=e},once:(e,t)=>{i[e]||(i[e]=[]),zt(i[e],t)},
cleanup:()=>{a&&(Fn.removeEventListener(`${n}_${a}`,v,!0),a=void 0)}});var E;return L},Ss=function(e,t,n,o,s){let r;const i=xo(),c=yo("script");i&&c.setAttribute("nonce",i);try{c.textContent=t,e.appendChild(c)}catch(e){r=e.message||e}if(i&&c.removeAttribute("nonce"),!s){const e=c.parentNode;e&&e.removeChild(c)}return o&&o(r),!r},Os=(e,t)=>{try{Ss(po.head||po.body||po.documentElement||po,e,0,t)}catch(e){t&&t(e.message||e)}};let xs,Ds;const js=e=>{const t=as("tabInfo")
;t?(t.onMessage.addListener((e=>{if("ack"in e);else{const{info:t}=e;t?xs=on(t):eo.warn("tabInfo: unexpected message",e)}})),t.onDisconnect.addListener((()=>{Rs()})),t.onError.addListener((()=>{try{t.disconnect()}catch(e){}Rs()})),e(t)):no((()=>js(e)),100)},Rs=()=>{js((e=>{xs=Ds||xs,Ds=void 0,e.postMessage(At({method:"tabInfo",messageId:Nn(),info:xs}))}))},Ps=e=>{e=e||Fn.location.href;const t=as("tabInfo");t?(t.onMessage.addListener((e=>{"ack"in e||eo.warn("tabInfo.frame: unexpected message",e)
})),t.onDisconnect.addListener((()=>{Ps(e)})),t.onError.addListener((()=>{try{t.disconnect()}catch(e){}Ps(e)})),t.postMessage(At({method:"tabInfo",messageId:Nn(),url:e}))):no((()=>Ps(e)),100)};let Cs=!1;const $s=location.pathname+location.search;Xo.short_id,window.btoa($s.length+$s).substr(0,255).replace(/[#=/]/g,"_");let As=!1;const Ts=(e,t,o)=>{const{contextId:s,bridges:r,console:i}=twod;let c;Xn((n=>{const o=e=>{let t=1;const o=()=>{Cs&&i.log('content: send "prepare" message'),
No.sendMessage({method:"prepare",id:s,topframe:so,url:window.location.href},(s=>{if(!As){if(!s)return Cs&&i.log("content: _early_ execution, connection to bg failed -> retry!"),window.setTimeout(o,t),void(t=Ct(2*t,3e3));As=!0,s.nonce&&Oo(s.nonce),Lt(s.contexters).length||Lt(s.scripts).length||s.external_connect?(e&&e(s),n({info:s,type:"complete"==_n(_t.document)?"late":"normal"})):n({info:s})}}))};!function(e){const t=()=>"prerender"!==document.webkitVisibilityState,n=()=>{
t()&&(document.removeEventListener("webkitvisibilitychange",n,!1),e())};t()?e():document.addEventListener("webkitvisibilitychange",n,!1)}(o)},r=()=>{let r;if(Cs&&i.log("content: Started ("+s+", "+window.location.origin+window.location.pathname+")",wt.tm_info),r=wt.tm_info){delete wt.tm_info,r.nonce&&Oo(r.nonce);const{contexters:o,scripts:i}=r;if(Lt(o).length||Lt(i).length){if(r.contexters.raw||r.scripts.raw)if(e.raw)void 0===c&&(c=e.raw());else if(!t)throw"raw inject missing";n({info:r,
type:"sync"})}else n({info:r});{let e;if("userscripts-dynamic"===r.contentMode){const t=e={};Vt(Lt(i),(e=>{const n=i[e];n&&Vt(n,(({script:{uuid:e,name:n}})=>t[e]=n))}))}No.sendMessage({method:"prepare",id:s,topframe:so,url:window.location.href,scripts:e,cleanup:!0},(()=>null))}}else t?o((({scripts:t,contexters:n})=>{e.raw&&void 0===c&&(t.raw||n.raw)&&(c=e.raw())})):(e.raw&&void 0===c&&(c=e.raw()),o())};t?window.setTimeout((()=>r()),1):r()})).then((({info:a,type:d})=>{const{external_connect:l}=a
;if(!t&&(e=>{if(e){const t=location.href.split("#")[0];return e.some((({source:e,flags:n})=>{const o=new An(e,n);if(""===t.replace(o,""))return!0}))}return!1})(l)&&(void 0===c&&e.raw&&(c=e.raw()),c||i.warn("content: external connectability detected, but unable to initialize raw mode!"),qn((()=>r.first.send("external.connect")))),d){Cs=Cs||a.logLevel>=60;const{scripts:c,sharedBlobs:l,sharedObjectUrls:p}=a;if(vs.setup(l,p),c.raw){let n;t&&!e.raw&&(n=!0),n&&(e.js?(c.js=(c.js||[]).concat(c.raw||[]),
delete c.raw):e.dom&&(c.dom=(c.dom||[]).concat(c.raw||[]),delete c.raw))}if(c.js){if(!e.js)throw"js inject missing";e.js()}if(c.dom){if(!e.dom)throw"dom inject missing";e.dom()}n(!1,(()=>{Cs&&i.log("content: DOMContentLoaded"),Vt(Lt(r),(e=>r[e].send("DOMContentLoaded")))})),u=()=>{Cs&&i.log("content: load"),Vt(Lt(r),(e=>r[e].send("load")))},"complete"==_n(_t.document)?u():Fn.addEventListener("load",(()=>u()),At({capture:!0,once:!0}))
;const g=(c.dom||[]).length+(c.js||[]).length+(c.raw||[]).length;Cs&&i.log("content: "+(d||"normal")+" start event processing for "+s+" ("+g+" to run)"),Us(a,"sync"===d),!so&&g&&Ps(location.href),o()}else o();var u}))},Us=e=>{const{bridges:n,contextId:s}=twod,{scripts:r,contexters:i,...c}=e;r.js&&Ms(c,r.js,Ko,n.js,"js"),r.dom&&(Vt(o,(e=>wt[e]=void 0)),Ms(c,r.dom,Es,n.dom,"dom")),r.raw&&Ms(c,r.raw,Os,n.raw,"raw"),Vt(Et(i),(e=>{e&&Vt(e,function(){var e=t((function*({uuid:e,name:t}){os(e);let n=!1
;const o=()=>{const r=as("registerCtxer");r&&(r.onMessage.addListener((e=>{"ack"in e||e.done&&(n=!0,r.disconnect())})),r.onDisconnect.addListener((()=>{console.log(`content: context-menu ${t} disconnect`),n||o()})),r.onError.addListener((e=>{console.warn(`content: context-menu ${t} error`,e)})),r.postMessage(At({messageId:Nn(),contextId:s,uuid:e,method:"registerCtxer"})))};o()}));return function(t){return e.apply(this,arguments)}}())}))};let ks;t((function*(){
const{unsafeWindow:e,bridges:t}=twod,{location:n,document:o}=e,r=o instanceof XMLDocument;if(!At({"http:":!0,"https:":!0,"file:":!0})[e.location.protocol])return;so&&(Rs(),Fn.addEventListener("pagehide",(e=>{En(e)&&(Ds=xs)})));const i=twod.contextId?twod.contextId:twod.contextId=Nn();let c;const a=At({});It(twod.console,eo),Xn((n=>{if(Go){const{createBridge:e}=Zo(i);zt(Vo,((o,s)=>{ks=c=o;const{modes:i}=s;i.js&&(t.js=e(),a.js=()=>!1,r&&(i.raw=!1)),n(s)}))}else Xn((t=>{ks=c=e.pagejs,
delete e.pagejs,ks?t():(()=>{let e=n=>{delete _t.pagejs,e=void 0,(e=>{if(!e)throw"Error: pagejs missing. Please see http://tmnk.net/faq#Q208 for more information.";ks=c=e,t()})(n)};St(_t,"pagejs",At({set:e,configurable:!0})),no((()=>{e&&e()}),1)})()})).then((()=>{n(At({modes:At({js:!1,raw:!0,dom:!0})}))}))})).then((({modes:{dom:o,raw:d},answer:l})=>{var u;if(l&&(u=l).scripts&&u.contexters&&(wt.tm_info=l),o){const e=Go?Es(`() => ${c};`)():c,{createBridge:n,inject:o}=((e,t)=>{const n=(e,t)=>{
Vt(s,(n=>n(e,t)))},o=e=>zt(r,At({listener:e,clone:e=>e})),s=[],r=[],i=(e,t)=>{Vt(r,(({listener:n,clone:o})=>n(e,o(t))))},c=e=>zt(s,e),a="c"+Nn();let d;return At({createBridge:()=>(d=Wo(At({sendPrefix:"2S",listenPrefix:"2U",send:i,onMessage:c})),d.init(e),d),inject:()=>(t(At({unsafeWindow:_t,unsafeThis:wt,pageWindow:void 0,contextId:a,fSend:n,fOnMessage:o})),d.sendToId(a,"commid",At({id:e})),!0)})})(i,e);a.dom=o,t.dom=n()}if(d){const{createBridge:e,inject:n}=((e,t)=>{let n;return At({
createBridge:()=>(n=Is(At({sendPrefix:"2P",listenPrefix:"2C",cloneInto:vo})),n),inject:()=>{n.init(e);let o=!1;const r=Nn(),i="("+rn(((e,t)=>{const n=window,o=t(n),s=n.parent,{O_dPy:r,cSO:i}=o;r(s,e,i({value:o,enumerable:!1,writable:!1,configurable:!0}))}))+')("'+r+'", '+rn(s)+")";return n.once("ack",(()=>{o=!0})),(o=>{((e,t)=>{const n=Tn(yn(_t.document,"*"),0)||_t.document,o=yo("div"),s=o.attachShadow(At({mode:"closed"}));s.appendChild(yo("style",":host { display: none }"))
;const r=yo("iframe",At({sandbox:"allow-scripts allow-same-origin",style:"display: none",src:"javascript:void 0"}));let i=()=>{if(null===i)return;i=null;let n=!1;try{const t=r.contentDocument,o=r.contentWindow;t&&o&&(n=Ss(Tn(t.getElementsByTagName("*"),0),e))}catch(e){}t(o,n),r.remove(),o.remove()};r.addEventListener("load",i,At({once:!0,capture:!0})),s.appendChild(r),n.appendChild(o),i&&i()})(o,((o,s)=>{
Ss(o,`((w, g) => {(${t})({ unsafeWindow: typeof g === "undefined" ? w : g, unsafeThis: w, vault: ${s?`w["${r}"]`:"null"}, contextId: "${r}", __proto__: null }); delete w["${r}"]; })(window, globalThis)\n`,0,(()=>{n.sendToId(r,"commid",At({id:e}))}),!0)}))})(i),o}})})(i,c);a.raw=n,t.raw=e()}const p=t.first=t.js||t.raw||t.dom;No.onMessage.addListener(((t,o,s)=>{"executeScript"==t.method?(t.url&&0!==hn(n.href,t.url)||void 0!==t.topframe&&t.topframe!=so||Us(t.info,!1),
s(At({}))):so&&("loadUrl"==t.method?(e.location=t.url,s(At({}))):"reload"==t.method?(n.reload(),s(At({}))):"setForeignAttr"==t.method?(p.send(t.method,t),s(At({}))):eo.log("content: unknown method "+(e=>{const t=(e,n)=>{let o;if(null===e)o="null";else{const s=typeof e;if("object"===s){if(n){if(-1!=Yt(n,e))throw"Converting circular structure to JSON";Tt(n,n.length,e)}else n=[e];if(jt(e)){let s="";for(let o=0;o<e.length;o++){let r;r=Zt(e,o)?Ut(e,o):Bt(e,o);const i=t(r,n)
;s+=`${o?",":""}${void 0===i?"null":i}`}o=`[${s}]`}else{let s="";Vt(Lt(e),(o=>{const r=t(e[o],n);void 0!==r&&(s+=`${s?",":""}${j(o)}: ${r}`)})),o=`{${s}}`}n.length-=1}else{if("bigint"===s)throw"Do not know how to serialize a BigInt";o=j(e)}}return o};return t(e)})(t)))})),Wn.onConnect.addListener(((e,t)=>{vs.processConnect(e,t)})),vs.init(),Vt(Lt(t),(e=>{if("first"==e)return;const n=t[e];n.setMessageListener(((t,o)=>{const{method:s,args:r}=t
;if("port.message"==s)Wn.message(r,n);else if("csp"==s){let t;t="raw"==e?Os:"dom"==e?Es:Ko,t(r.src,(e=>{e&&eo.error(`Uncaught Error: ${e}`)}))}else if("external.message"==s)No.sendMessage(At({method:"externalMessage",request:r}),(e=>{o(e)}));else if("console"==s){const e=r,t=Tn(e,0),n=Tn(e,1),o=eo[t]||eo.log;o&&$t(o,eo,((e,...t)=>{let n=e.length;const o=At(e);for(let e=0;e<t.length;e++){const s=t[e],r=jt(s)?s:[s];for(let e=0;e<r.length;e++)o[n+e]=kt(r,e);n+=r.length}return Et(o)
})(["injected:"],(e=>{const t=[];return Vt(e,(e=>{zt(t,(e=>"string"==typeof e?qt(e):e)(e))})),t})(n)))}else"commid"==s||(e=>"ack"==e.method||"injectableack"==e.method||0===hn(e.method,"scriptack-"))(t)||vs.processMessage(t,o)}))})),Ts(a,r,(()=>ks=void 0))}))}))()})();})({ __proto__: null, unsafeWindow: typeof globalThis === "undefined" ? window : globalThis, unsafeThis: window, }, "tm_wwywqw")

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 749 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 454 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 474 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 632 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 800 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 972 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Some files were not shown because too many files have changed in this diff Show More