00-字节preload免签名接口-参考.md


name: hongguo-douyin-video-api-tricks description: >- Comprehensive runbook, free API tricks, multi-provider rotation architecture, and CENC-AES-128-CTR (spade_a) MP4 decryption guide for Hongguo Short Drama (红果免费短剧 / Fanqie Novel / qznovelvod) and Douyin/TikTok video downloaders on Cloudflare Pages/Workers Free and Python Render.com. Activate this skill when building, debugging, or extending video parsers, short-drama scrapers, or ByteDance VOD decryptors.


Hongguo Short Drama & Douyin/TikTok Video API Tricks & Decryption Skill

1. Hongguo Short Drama (红果免费短剧 / Fanqie) Input Resolution

  1. Short Share Links (novelquickapp.com/s/..., changdunovel.com):
    • Send a GET request with redirect: "manual" and mobile User-Agent.
    • Parse the Location header query string for video_series_id, series_id, book_id, album_id, group_id, item_id, or vid (19-digit numeric IDs).
  2. Official Web Links (hongguoduanju.com):
    • Series page: https://hongguoduanju.com/detail?series_id={19_digit_id}
    • Episode player page: https://hongguoduanju.com/player/{series_id}/{vid}

2. Trick #1: Bypassing X-Gorgon via Official Fqnovel App Preload Mirrors

Standard Fqnovel/Hongguo mobile endpoints enforce ByteDance X-Gorgon / X-Argus signatures. However, the Preload v1 endpoints across 6 official mirrors accept unauthenticated POST requests when passed the standard Android preload query parameters and "dr_scene": "preload":


3. Trick #2: Hongguo Official Web SSR (window._ROUTER_DATA) & Direct H.264 Stream

  1. Extracting window._ROUTER_DATA:
    • Fetch https://hongguoduanju.com/ pages with standard Desktop Browser UA:
      • Trending/Home: https://hongguoduanju.com/ (loaderData.page.homeSections)
      • Category pages: https://hongguoduanju.com/category/{real-drama|comic-drama|ai-drama} (loaderData.category_page.recommendList)
      • Keyword Search: https://hongguoduanju.com/search/{encodeURIComponent(keyword)} (loaderData["search_(keyword)/page"].searchList)
      • Series Detail: https://hongguoduanju.com/detail?series_id={seriesId} (seriesDetail.vid_list)
    • Extract the JSON assigned to _ROUTER_DATA via brace-balanced parsing starting at the first { after _ROUTER_DATA.
  2. Unencrypted H.264 Stream (360p-h264):
    • Every episode vid has a direct unencrypted H.264/AAC MP4 endpoint: https://hongguoduanju.com/video/public/{vid}/360p.mp4
    • Must be fetched with header Referer: https://hongguoduanju.com/.
    • Use this stream for instant <video> preview in browsers (since browsers cannot natively play CENC-encrypted encv streams without EME/MSE).

4. Trick #3: spade_a Key Derivation & Fast WebCrypto CENC-AES-128-CTR Decryption

  1. spade_a to 16-Byte AES Key (key_hex — libttmplayer.so algorithm):
    • Base64-decode spade_a into buf (L = buf.length).
    • Compute key0 = buf[0] ^ buf[1] ^ buf[2], x27 = key0 - 0x30, w22 = L - key0 + 0x2f.
    • Slice x21 = buf.slice(1, 1 + w22). Initialize w11 = 0x55, w12 = 0xfa, w10 = 0xeb.
    • For each index i, compute popcount pc = popcount(i), w14 = (i & 1) === 0 ? w12 : w11, update w11/w12 with x21[i], and set x21[i] = ((w10 - pc) + (w14 ^ x21[i])) & 0xff.
    • Decode base36 digit hval from x21[0], compute w9 = w22 - hval, and extract ASCII hex string x21.slice(1, w9) (32 hex chars = 16-byte AES key).
  2. Decrypting ISO-BMFF cenc MP4 (encv -> hvc1, enca -> mp4a):
    • Locate moov box and iterate over each trak -> mdia -> minf -> stbl:
      • Parse stsz (sample sizes), stsc (sample-to-chunk), stco (chunk offsets), and senc (8-byte IV per sample at senc.off + 16 + i * 8).
      • Zero-pad each 8-byte IV into a 16-byte AES-CTR counter block (counter[0..7] = iv8, counter[8..15] = 0) and decrypt each sample with crypto.subtle.decrypt({ name: "AES-CTR", counter, length: 64 }, cryptoKey, sampleSlice).
    • Rebuild moov:
      • Rename encv -> hvc1, enca -> mp4a, remove sinf, senc, saio, saiz boxes, and subtract delta = oldMoovSize - newMoovSize from every offset in stco that follows moov (or overwrite sinf/senc/saio/saiz in-place with free boxes to keep moov size constant).

5. Trick #4: Cloudflare Free Tier 10ms CPU Bypass & Multi-Provider Douyin Rotation

  1. Hybrid Client + Server Decryption:
    • On Cloudflare Free Tier (10ms CPU limit), expose /api/download?url=...&raw=1 (streaming passthrough with Referer: https://novelquickapp.com/).
    • Perform CENC-AES-128-CTR decryption in the browser via window.HongguoClientDecryptor using hardware-accelerated WebCrypto (0ms Worker CPU cost), while keeping server-side decryption in /api/download and Python app.py (Render.com with pycryptodome) as fallback.
  2. Douyin / TikTok Multi-Provider Failover:
    • Primary: TikWM (https://www.tikwm.com/api/, POST url=...&hd=1) — no cooldown.
    • Fallback: Apihz 4 routes (https://cn.apihz.cn/api/fun/douyin.php + 3 HTTP IP mirrors proxied server-side via Cloudflare Worker to avoid browser HTTPS Mixed-Content blocking).
    • Note: api.cenguigui.cn/api/duanju.html is deprecated (HTTP 404); keep only as last-resort fallback.

6. Trick #5: Cloudflare Free "Max Ping" & Quota Optimization Runbook

To achieve <2ms Edge delivery, zero CPU overruns, and prevent burning the 100,000/day Cloudflare Free Worker invocation quota:

  1. Static Asset Quota Bypass (public/_routes.json):
    • Use "include": ["/api/*"] and "exclude": ["/", "/index.html", "/articles.js", "/ads.txt", "/robots.txt", "/sitemap.xml", "/favicon.svg"].
    • Result: Static files are served directly by Cloudflare CDN at Edge PoPs (~5ms ping) and consume zero Worker invocations.
  2. Singleflight Request Coalescing (INFLIGHT_MAP):
    • Coalesce concurrent incoming requests for the same series, episode, or category into a single Promise. Downstream requests await the existing inflight fetch, preventing duplicate upstream calls.
  3. Stale-While-Revalidate (SWR) in V8 Isolate RAM:
    • Cache parsed JSON in module-level MEM_CACHE. If a request arrives after soft TTL expires but within hard TTL (3x), return cached data instantly (0.0ms) and trigger an asynchronous background refresh via ctx.waitUntil.
  4. Adaptive Mirror Latency Scoreboard (EMA Tracker + Hedging):
    • Continually measure RTT across all 6 Fqnovel preload mirrors (sinfonlineb, sinfonlinea, sinfonlinec, lf, lq, hl).
    • Dynamically sort mirrors by lowest EMA latency and hedge upstream requests with a 650ms parallel timeout.
  5. 15-Episode Single-Request Batching:
    • Fqnovel's /novel/player/multi_video_model/preload/v1 accepts up to 15 VIDs in mixed_video_id_map: { "1004": [vid1, vid2, ... vid15] }.
    • Prefetch 15 episodes on the initial /api/parse call and during batch downloads via /api/episode?vids=...&indices=..., cutting 93% of API roundtrips.
  6. Smart Placement (wrangler.toml):
    • Specify [placement] mode = "smart" so Cloudflare executes Workers at Edge datacenters near ByteDance/Hongguo Asian upstreams, reducing multi-hop network latency by 40-70%.
  7. Edge Cache API (caches.default):
    • Cache cover images (/api/proxy) for 30 days (immutable) and small decrypted MP4s (<= 20MB) for 1-2 hours so repeated requests and range requests serve directly from Edge RAM.

7. Trick #6: Direct ByteDance CDN Offloading (Zero Bandwidth & 0ms CPU Cost)

  1. Upstream CORS Header Discovery:
    • Both *.qznovelvod.com (ByteDance VOD CDN for 1080p CENC MP4) and *.byteimg.com (cover image CDN) return HTTP 200 with header: Access-Control-Allow-Origin: * when requested without a Referer header (referrerPolicy: "no-referrer").
  2. Client-Side Direct Fetching:
    • In browser frontend, fetch raw MP4 bytes directly via: fetch(rawVideoUrl, { referrerPolicy: "no-referrer" }) and only fall back to /api/download?url=...&raw=1 if CORS fails.
    • For images, use <img src="direct_byteimg_url" referrerpolicy="no-referrer" onerror="this.src='/api/proxy?url=...'"/>.
    • Benefit: 100% of video bandwidth and 99% of image requests bypass Cloudflare Workers entirely, saving thousands of worker invocations and bandwidth limits on Cloudflare Free.

8. Trick #7: Hybrid 4.1x T-Table + WebCrypto AES-128-CTR Decryption Engine

  1. Sample Distribution in 1080p CENC MP4:
    • In ISO-BMFF CENC MP4 streams, 94.2% of samples are ≤2048\le 2048 bytes (audio frames and P/B video slices). Only ~5.8% (large I-frames) exceed 2048 bytes.
    • Calling crypto.subtle.decrypt for 12,000+ tiny samples creates 12,000+ Promise allocations, causing severe event-loop overhead and hitting Cloudflare Worker 10ms CPU limits (Error 1102).
  2. Hybrid Solution:
    • Precompute 32-bit AES T-tables (AES_TE0..TE3, AES_SBOX).
    • Decrypt all samples ≤2048\le 2048 bytes synchronously in-place (0 Promise allocation, 0 GC).
    • Dispatch only large I-frames (>2048> 2048 bytes) to hardware-accelerated crypto.subtle.decrypt.
    • Result: Decryption time drops from 395.6ms to 95.7ms (4.1x faster), Promise allocations drop by 94.2%.
  3. Browser Inline Web Worker:
    • Run the decryptor inside an inline Blob Web Worker with zero-copy Transferable ArrayBuffer (postMessage(..., [u8.buffer])).
    • Ensures 0ms UI freeze on the browser main thread during multi-episode batch downloading.

9. Trick #8: Douyin / TikTok Multi-Provider Rotation & Cooldown Bypass

  1. Apihz 30s Cooldown:
    • Free Apihz accounts enforce a strict 30s rate-limit (该接口免费用户限制30秒解析1次).
    • Primary Route: Must use HTTPS https://cn.apihz.cn/api/fun/douyin.php (raw IPs like 101.35.2.25 fail across firewalls).
    • Two-Tier Cache: Cache parsed Douyin responses for 30 minutes (getOrSetCache(cacheKey, 1800, ...)) using canonical aweme_id or resolved URL. Subsequent hits return in <1ms<1\text{ms} and bypass the 30s rate limit completely.
  2. TikWM & Native SSR Hedged Fallback:
    • Resolve v.douyin.com with redirect: "manual" in ~200ms to get canonical aweme_id.
    • Race Apihz (primary) with TikWM and Native SSR backups using raceWithHedge(primary, backups, 1200).
下载此文件