# saermart/douyinlivewebfetcher architecture

> Architecture diagram of the GitHub repository saermart/douyinlivewebfetcher, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-03). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/saermart/douyinlivewebfetcher
- Repository: https://github.com/saermart/douyinlivewebfetcher

## Overview

##### 项目类型与目的（先定“画什么”）
从 README 与文件树看，这是一个**桌面/脚本型抓取工具**（非 Web 服务、非传统前后端），目标是**抓取抖音网页版直播间弹幕/互动事件**（进场、聊天、点赞、礼物、粉丝团、统计等）。

核心特征（决定你图里一定要出现的元素）：
- **Python 作为主控/抓取器**：发起请求、建立连接、接收数据、解码、输出。
- **抖音侧接口是 Web 端风控/签名体系**：需要 `signature`、`a_bogus` 等参数（文件名已明确：`ac_signature.py`, `a_bogus.js`, `sign.js`, `sign_v0.js`, `webmssdk.js`）。
- **数据传输与编码**：直播消息通常走 **WSS(WebSocket over TLS)**，且消息体是 **protobuf**（目录 `protobuf/` 内有 `douyin.proto` / `douyin.py` / `protoc.exe`）。

因此你在系统设计图里要把它画成：
“本地抓取器（Python） + 本地签名生成（Node/JS） + protobuf 解码 + 外部 Douyin Web API/WSS + 输出终端/日志”的组合系统。

##### 文件结构映射到架构组件（把文件树“翻译成方块”）
结合文件名推断的组件划分（建议你直接按这个拆块画）：

##### 运行入口 / 编排层（Orchestration）
- `main.py`：大概率是主入口（参数解析、启动抓取、调用 liveMan 等）。
- `liveMan.py`：直播间抓取会话管理（连接、心跳、重连、消息路由）。
> 这层在图里通常是“DouyinLiveWebFetcher (Python App)”的核心容器。

##### 风控参数/签名生成层（Anti-bot / Signature）
- `ac_signature.py`：Python 侧的 signature 获取/计算适配（README 提到更新 signature 获取方式）。
- `sign.js`, `sign_v0.js`, `webmssdk.js`, `a_bogus.js`：JS 侧实现（很可能需要 Node 执行），提供：
- `signature` / `msToken` / `X-Bogus` / `a_bogus` 等风控参数计算
> 这在图上要明确画成“Python 调用 Node/JS 计算签名”（子进程或本地模块调用），否则系统交互链不完整。

##### 协议层 / 编码解码（Protocol / Protobuf）
- `protobuf/douyin.proto`：消息结构定义（来自抖音 live 协议）。
- `protobuf/douyin.py`：由 protoc 生成的 Python 解码代码（或封装）。
- `protobuf/protoc.exe`：Windows 环境下编译 proto 的工具（构建期依赖，而非运行时依赖）。
> 图里建议区分：**Build-time**（protoc 生成代码）与 **Runtime**（douyin.py 解码消息）。

##### 外部依赖与配置
- `requirements.txt`：Python 依赖（HTTP、WebSocket、protobuf、加密等常见库）。
- NodeJs v18：运行 JS 签名生成所需（README 指明）。
- `LICENSE` / `.gitignore`：可不画。

##### 外部系统（必须画清楚“你连的是谁”）
在架构图里把抖音侧至少拆成两个外部框（不要只写 “Douyin” 一个框）：

##### Douyin Web HTTP endpoints（HTTPS）
- 用于：获取直播间信息/roomId、拉取初始配置、下发 websocket 地址/参数、校验签名等
- 输入：带签名的 query/headers/cookies（signature/a_bogus 等）
- 输出：连接所需的 token、wss 参数、房间相关数据等

##### Douyin Live WebSocket Gateway（WSS）
- 用于：实时推送弹幕/礼物/点赞/进场/统计等事件
- 数据格式：protobuf 二进制帧（解码依赖 `douyin.proto`）

可选第三个外部框（视项目实现而定，但画上通常更完整）：
##### 风控/脚本运行环境（Local Node Runtime）
- 虽然在你机器上，但它是“独立运行时”，和 Python 进程边界不同，建议单独一个容器框表示。

##### 推荐你画的“最准确”图集（按 C4 + 时序补齐）
为了“最详细、最不漏”，建议你输出 **4 张图**（每张图的粒度不同）：

##### 图1：System Context（系统上下文图）
目标：让人一眼明白这是“本地工具抓取抖音直播”。

方块建议：
- Actor：`Operator/User`（运行脚本、输入直播间 URL/roomId）
- System：`DouyinLiveWebFetcher (Local Machine)`
- External Systems：
- `Douyin Web APIs (HTTPS)`
- `Douyin Live WS Gateway (WSS)`
- （可选）`Node.js Runtime (Local)`：若你想把它当作系统内部容器，则在下一张图体现即可

箭头建议：
- User → Fetcher：启动/配置
- Fetcher → Douyin Web APIs：请求（包含 signature/a_bogus）
- Fetcher ↔ Douyin Live WS：建立连接/接收事件
- Fetcher → User：输出日志/控制台/文件

目标：明确 Python 与 Node 的边界，及 protobuf 解码属于哪个容器。

容器建议（至少 4 个）：
##### `Python Fetcher Process`
- 组件：会话管理、HTTP client、WS client、事件处理、输出
##### `Node Signature Generator Process/Module`
- 资产：`sign.js` / `sign_v0.js` / `webmssdk.js` / `a_bogus.js`
- 职责：生成签名/风控参数
##### `Protobuf Decoder (Python module)`
- 资产：`protobuf/douyin.py`（运行时）
##### 外部：
- `Douyin Web HTTP`
- `Douyin WS Gateway`

关键连线（必须画清楚）：
- Python → Node：`spawn node ...` 或 `exec JS`（输入：url/params/cookies；输出：signature/a_bogus）
- Python → Douyin HTTP：HTTPS requests（带签名）
- Python ↔ Douyin WSS：WebSocket（收 binary frames）
- Python → Protobuf Decoder：decode(frame) → structured events
- Python → Output：stdout/file

目标：按文件/职责“尽量拆细”，契合你仓库结构。

在 `Python Fetcher Process` 内建议拆出：
- `Entry/CLI (main.py)`
- `Live Session Manager (liveMan.py)`
- `HTTP Client`（获取房间信息、握手参数）
- `WS Client`（connect/heartbeat/reconnect）
- `Signature Adapter (ac_signature.py)`
- 职责：封装“如何拿到 signature/a_bogus”（调用 Node 或内部算法）
- `Message Router/Handlers`
- handlers：Chat / Gift / Like / Enter / Stats（你 README 样例输出里已经体现出多类事件）
- `Output Sink`
- console logger / file logger（按实际实现）

在 `Node Signature Generator` 内建议拆出：
- `webmssdk.js`（核心算法/环境模拟）
- `sign.js` / `sign_v0.js`（对外入口/不同版本实现）
- `a_bogus.js`（专门生成 a_bogus）
> 组件图的价值是让人定位“改签名/改解码/改输出”分别改哪里。

目标：把“签名→HTTP→WSS→protobuf→输出”的链路串起来，最能体现真实运行逻辑。

建议时序（参与者）：
- User
- main.py
- liveMan.py (Session)
- Node(Signature)
- Douyin HTTP
- Douyin WSS
- Protobuf Decoder
- Output

典型流程（箭头顺序）：

##### 关系与交互：你在图上必须“标注具体数据/协议”
为了“最准确”，每条箭头不要只写“request/response”，而要写**关键协议与关键字段**：

- Python → Node：
- `input`: URL + query params + UA/cookies（若有）
- `output`: `signature`, `a_bogus`（以及可能的 msToken 等）
- 方式：`child_process` / `subprocess`（你画“subprocess call”即可）

- Python → Douyin HTTP：
- 协议：HTTPS
- 数据：signed query + headers

- Python ↔ Douyin WSS：
- 协议：WSS
- 数据：binary protobuf frames + heartbeat frames（如果实现了心跳）

- Python → Protobuf：
- `douyin.py`（generated）基于 `douyin.proto`
- 输出：结构化消息（ChatMessage/GiftMessage 等）

- Python → Output：
- 控制台文本（README 样例就是输出格式的证据）

##### 架构模式/设计原则（用于图例与分层）
这个项目本质上是：
- **Pipeline/Stream Processing**：WS 流式输入 → 解码 → 路由 → 输出
- **Adapter pattern**：签名算法变化频繁，因此 `ac_signature.py`/JS 脚本是可替换的适配层
- **Contract-first parsing**：protobuf proto 定义是消息契约，生成代码用于解码

你可以在图里用颜色/分区强调三层：

##### 元素与标注
- 每个组件框里写清：
- 名称（对应文件/模块名）
- 职责（1 行）
- 关键技术（Python/Node/protobuf/WSS）
- 每条箭头写清：
- 协议（HTTPS/WSS/Local subprocess）
- 关键数据（signature/a_bogus、protobuf frames）

##### 颜色/形状建议（快速可读）
- 外部系统（Douyin）用灰色云形/边框
- 本地进程容器：
- Python：蓝色
- Node：绿色
- 数据契约/构建产物：
- `douyin.proto`、`protoc.exe`：用“工厂/构建”图标或橙色框，标注 Build-time
- `douyin.py`：Runtime module

##### “尽量拆细但不乱”的技巧
- 拆到“可替换边界”为止：
- 签名模块（最常改）独立
- protobuf 解码独立
- WS 会话管理独立
- handlers 独立
- 把 `protoc.exe` 放在图的“build lane”，避免误解为运行时必须常驻。

##### 你最终应该交付的架构图长什么样（最低合格清单）
如果只允许你交付 1 张图：选 **Container + 关键组件** 的混合图，并确保包含：
- Python 主进程（main.py/liveMan.py）
- Node 签名生成（sign.js/webmssdk.js/a_bogus.js）
- Douyin HTTP + Douyin WSS（分开画）
- Protobuf 解码（douyin.proto → douyin.py）
- 数据流箭头（签名参数流 + WSS 二进制流 + 解码后事件流）

这样画出来的系统设计图，才会对这个仓库“最贴合、最准确、最不漏关键点”。

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================
    %% System Context + Container/Component Hybrid (Vertical)
    %% =========================

    User["Operator / User\n- Runs script\n- Inputs live URL/roomId"]:::actor

    subgraph "Local Machine: DouyinLiveWebFetcher (Desktop/Script Tool)"
        direction TB

        subgraph "Python Fetcher Process"
            direction TB
            Main["Entry / CLI (main.py)\n- Parse args\n- Bootstrap session"]:::py
            LiveMan["Live Session Manager (liveMan.py)\n- HTTP+WSS lifecycle\n- Heartbeat/reconnect\n- Route events"]:::py
            SigAdapter["Signature Adapter (ac_signature.py)\n- Adapter layer\n- Calls Node/JS or local logic"]:::py

            subgraph "Message Processing Pipeline (Python)"
                direction TB
                WSClient["WS Client\n- WSS connect\n- Receive binary frames"]:::py
                Decoder["Protobuf Decoder (protobuf/douyin.py)\n- Decode frames\n- Emit structured events"]:::protoRt
                Router["Message Router / Handlers\n- Chat/Gift/Like/Enter/Stats"]:::py
                Output["Output Sink\n- Console/log/file"]:::output
            end

            HTTPClient["HTTP Client\n- Fetch room info\n- Get WSS params/tokens"]:::py
        end

        subgraph "Node.js Runtime (Local)"
            direction TB
            NodeProc["Node Signature Generator\n- Computes anti-bot params"]:::node

            subgraph "JS Signature Assets"
                direction TB
                WebMSSDK["webmssdk.js\n- Core algorithm/env simulation"]:::node
                SignJS["sign.js\n- Signature entry"]:::node
                SignV0["sign_v0.js\n- Legacy/backup signature"]:::node
                ABogus["a_bogus.js\n- a_bogus generator"]:::node
            end
        end

        subgraph "Protobuf Contract & Build-time"
            direction TB
            ProtoFile["douyin.proto (protobuf/douyin.proto)\n- Message contract"]:::protoCt
            Protoc["protoc.exe (build-time)\n- Generates douyin.py"]:::build
            ProtoInit["protobuf/__init__.py\n- Package entry"]:::protoRt
            ProtoReadme["protobuf/readme.md\n- Protocol notes"]:::doc
        end

        Req["requirements.txt\n- Python deps"]:::doc
        Readme["README.MD\n- Usage & architecture notes"]:::doc
    end

    subgraph "External: Douyin Platform"
        direction TB
        DouyinHTTP["Douyin Web HTTP Endpoints (HTTPS)\n- Room info/handshake\n- WSS endpoint+tokens\n- Signature validation"]:::external
        DouyinWSS["Douyin Live WS Gateway (WSS)\n- Push real-time events\n- Binary protobuf frames"]:::external
    end

    %% =========================
    %% Relationships (Data flow / Protocol / Key fields)
    %% =========================

    User -->|"start&config (URL/roomId)"| Main
    Main -->|"startSession()"| LiveMan

    LiveMan -->|"needSignedParams()"| SigAdapter
    SigAdapter -->|"localSubprocessCall (url,params,cookies,UA)"| NodeProc
    NodeProc -->|"uses"| WebMSSDK
    NodeProc -->|"entry"| SignJS
    NodeProc -->|"fallback"| SignV0
    NodeProc -->|"compute"| ABogus
    NodeProc -->|"returns (signature,a_bogus,msToken...)"| SigAdapter

    LiveMan -->|"HTTPS(signedQuery+headers)"| HTTPClient
    HTTPClient -->|"requestRoomInfo()"| DouyinHTTP
    DouyinHTTP -->|"wssEndpoint+tokens+params"| HTTPClient
    HTTPClient -->|"handshakeData"| LiveMan

    LiveMan -->|"openWSS(endpoint,tokens)"| WSClient
    WSClient <-->|"WSS(heartbeat+binaryFrames)"| DouyinWSS

    WSClient -->|"binary protobuf frame"| Decoder
    Decoder -->|"structuredEvent(Chat/Gift/Like/Enter/Stats)"| Router
    Router -->|"print/log"| Output
    Output -->|"stdout/logs"| User

    %% Protobuf build/runtime linkage
    Protoc -->|"generate"| Decoder
    ProtoFile -->|"contractFor"| Decoder
    ProtoInit -->|"exports"| Decoder
    ProtoReadme -->|"docs"| ProtoFile

    %% =========================
    %% Click Events (from component_mapping)
    %% =========================
    click Main "https://github.com/saermart/douyinlivewebfetcher/blob/main/main.py"
    click LiveMan "https://github.com/saermart/douyinlivewebfetcher/blob/main/liveMan.py"
    click SigAdapter "https://github.com/saermart/douyinlivewebfetcher/blob/main/ac_signature.py"
    click SignJS "https://github.com/saermart/douyinlivewebfetcher/blob/main/sign.js"
    click SignV0 "https://github.com/saermart/douyinlivewebfetcher/blob/main/sign_v0.js"
    click ABogus "https://github.com/saermart/douyinlivewebfetcher/blob/main/a_bogus.js"
    click WebMSSDK "https://github.com/saermart/douyinlivewebfetcher/blob/main/webmssdk.js"
    click ProtoFile "https://github.com/saermart/douyinlivewebfetcher/blob/main/protobuf/douyin.proto"
    click Decoder "https://github.com/saermart/douyinlivewebfetcher/blob/main/protobuf/douyin.py"
    click ProtoInit "https://github.com/saermart/douyinlivewebfetcher/blob/main/protobuf/__init__.py"
    click Protoc "https://github.com/saermart/douyinlivewebfetcher/blob/main/protobuf/protoc.exe"
    click ProtoReadme "https://github.com/saermart/douyinlivewebfetcher/blob/main/protobuf/readme.md"
    click Req "https://github.com/saermart/douyinlivewebfetcher/blob/main/requirements.txt"
    click Readme "https://github.com/saermart/douyinlivewebfetcher/blob/main/README.MD"

    %% =========================
    %% Styles (Color is critical)
    %% =========================
    classDef actor fill:#FFF3CD,stroke:#B08900,color:#3B2F00,stroke-width:1px
    classDef py fill:#D6E9FF,stroke:#1E5AA8,color:#0B2A4A,stroke-width:1px
    classDef node fill:#D9FBE3,stroke:#1E7E34,color:#0D3B1A,stroke-width:1px
    classDef external fill:#ECEFF4,stroke:#4C566A,color:#2E3440,stroke-width:1px,stroke-dasharray: 4 3
    classDef protoCt fill:#FFE6CC,stroke:#B35C00,color:#4A2A00,stroke-width:1px
    classDef protoRt fill:#FFD9B3,stroke:#B35C00,color:#4A2A00,stroke-width:1px
    classDef build fill:#FFE0E0,stroke:#B00020,color:#4A0010,stroke-width:1px
    classDef output fill:#E8EAF6,stroke:#3949AB,color:#1A237E,stroke-width:1px
    classDef doc fill:#F5F5F5,stroke:#616161,color:#212121,stroke-width:1px
```
