@zfadhli/tokrec 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -0
- package/dist/app/config.mjs.map +1 -1
- package/dist/app/job.mjs +39 -17
- package/dist/app/job.mjs.map +1 -1
- package/dist/app/logger.mjs +8 -16
- package/dist/app/logger.mjs.map +1 -1
- package/dist/app/loop.mjs +6 -3
- package/dist/app/loop.mjs.map +1 -1
- package/dist/app/recorder.d.mts.map +1 -1
- package/dist/app/recorder.mjs +25 -29
- package/dist/app/recorder.mjs.map +1 -1
- package/dist/core/plan.mjs.map +1 -1
- package/dist/core/verdict.d.mts +1 -1
- package/dist/core/verdict.mjs.map +1 -1
- package/dist/io/http.mjs +16 -24
- package/dist/io/http.mjs.map +1 -1
- package/dist/io/media/download.mjs +1 -1
- package/dist/io/media/ffmpeg.mjs +52 -6
- package/dist/io/media/ffmpeg.mjs.map +1 -1
- package/dist/io/tiktok/client.mjs +9 -12
- package/dist/io/tiktok/client.mjs.map +1 -1
- package/dist/io/tiktok/discovery/chain.mjs +14 -17
- package/dist/io/tiktok/discovery/chain.mjs.map +1 -1
- package/dist/io/tiktok/discovery/page.mjs +38 -52
- package/dist/io/tiktok/discovery/page.mjs.map +1 -1
- package/dist/io/tiktok/parse.mjs +24 -31
- package/dist/io/tiktok/parse.mjs.map +1 -1
- package/dist/io/tiktok/webcast.mjs +15 -29
- package/dist/io/tiktok/webcast.mjs.map +1 -1
- package/package.json +1 -1
- package/src/app/config.ts +5 -19
- package/src/app/job.ts +61 -27
- package/src/app/logger.ts +9 -23
- package/src/app/loop.ts +12 -11
- package/src/app/recorder.ts +44 -47
- package/src/core/plan.ts +1 -1
- package/src/core/verdict.ts +1 -1
- package/src/index.ts +1 -1
- package/src/io/http.ts +24 -49
- package/src/io/media/ffmpeg.ts +65 -7
- package/src/io/tiktok/client.ts +13 -24
- package/src/io/tiktok/discovery/chain.ts +15 -24
- package/src/io/tiktok/discovery/page.ts +51 -90
- package/src/io/tiktok/parse.ts +38 -48
- package/src/io/tiktok/webcast.ts +30 -41
- package/dist/app/abort.mjs +0 -14
- package/dist/app/abort.mjs.map +0 -1
- package/dist/app/events.mjs +0 -36
- package/dist/app/events.mjs.map +0 -1
- package/dist/io/media/convert.mjs +0 -60
- package/dist/io/media/convert.mjs.map +0 -1
- package/dist/io/media/normalize.mjs +0 -32
- package/dist/io/media/normalize.mjs.map +0 -1
- package/src/app/abort.ts +0 -18
- package/src/app/events.ts +0 -46
- package/src/io/media/convert.ts +0 -69
- package/src/io/media/normalize.ts +0 -64
package/src/app/recorder.ts
CHANGED
|
@@ -2,23 +2,27 @@
|
|
|
2
2
|
* Recorder orchestrator — wires the TikTok client, stream download, and
|
|
3
3
|
* RecordingJob into a single RecorderController.
|
|
4
4
|
*
|
|
5
|
-
* Policy lives in `
|
|
5
|
+
* Policy lives in `core/plan.ts`; this file maps a TickPlan to effects and
|
|
6
6
|
* owns the session state those effects mutate. Everything a tick needs is
|
|
7
7
|
* constructed as a `const` in `start()` and passed in, so no call site has to
|
|
8
8
|
* assert a non-null module-level `let` back into existence.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { EventEmitter } from "node:events"
|
|
11
12
|
import { planTick, type TickFacts } from "../core/plan"
|
|
12
13
|
import { verdictOf } from "../core/verdict"
|
|
13
14
|
import { createHttpClient, type HttpClient } from "../io/http"
|
|
14
|
-
import { type Converter, createConverter } from "../io/media/convert"
|
|
15
15
|
import { downloadStream } from "../io/media/download"
|
|
16
|
-
import { type
|
|
16
|
+
import { createMediaConverter, type MediaConverter } from "../io/media/ffmpeg"
|
|
17
17
|
import { createTikTokClient, type TikTokClient } from "../io/tiktok/client"
|
|
18
|
-
import
|
|
19
|
-
|
|
18
|
+
import type {
|
|
19
|
+
RecorderConfig,
|
|
20
|
+
RecorderController,
|
|
21
|
+
RecorderEvent,
|
|
22
|
+
RecorderEventHandler,
|
|
23
|
+
RecorderStatus,
|
|
24
|
+
} from "./config"
|
|
20
25
|
import { resolveConfig } from "./config"
|
|
21
|
-
import { createEventEmitter } from "./events"
|
|
22
26
|
import { createRecordingJob, type RecordingJob } from "./job"
|
|
23
27
|
import { createLogger } from "./logger"
|
|
24
28
|
import { createPollingMonitor, type PollingMonitor } from "./loop"
|
|
@@ -30,17 +34,16 @@ const POST_REMUX_GRACE_MS = 10 * 60 * 1000
|
|
|
30
34
|
interface TickDeps {
|
|
31
35
|
client: TikTokClient
|
|
32
36
|
monitor: PollingMonitor
|
|
33
|
-
scope:
|
|
34
|
-
post:
|
|
35
|
-
converter:
|
|
36
|
-
audioNormalizer: AudioNormalizer | null
|
|
37
|
+
scope: AbortController
|
|
38
|
+
post: AbortController
|
|
39
|
+
converter: MediaConverter
|
|
37
40
|
}
|
|
38
41
|
|
|
39
42
|
/** What `stop()` has to join and release. */
|
|
40
43
|
interface Running {
|
|
41
44
|
monitor: PollingMonitor
|
|
42
45
|
http: HttpClient
|
|
43
|
-
scope:
|
|
46
|
+
scope: AbortController
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
export function createRecorder(config: RecorderConfig): RecorderController {
|
|
@@ -51,12 +54,28 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
51
54
|
console: cfg.logConsole,
|
|
52
55
|
})
|
|
53
56
|
|
|
54
|
-
|
|
57
|
+
// Typed over `node:events`; a throwing subscriber must not kill a recording.
|
|
58
|
+
const bus = new EventEmitter()
|
|
59
|
+
const emitter = {
|
|
60
|
+
on: bus.on.bind(bus) as RecorderController["on"],
|
|
61
|
+
off: bus.off.bind(bus) as RecorderController["off"],
|
|
62
|
+
emit: <E extends RecorderEvent>(
|
|
63
|
+
event: E,
|
|
64
|
+
...args: Parameters<RecorderEventHandler[E]>
|
|
65
|
+
): void => {
|
|
66
|
+
try {
|
|
67
|
+
bus.emit(event, ...args)
|
|
68
|
+
} catch {
|
|
69
|
+
// ignore — a bad subscriber must never crash the recorder
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
clear: () => bus.removeAllListeners(),
|
|
73
|
+
}
|
|
55
74
|
|
|
56
75
|
// Session state — written by ticks and by the job lifecycle, read by getStatus().
|
|
57
76
|
const status: RecorderStatus = { state: "idle", user: cfg.user }
|
|
58
77
|
let running: Running | null = null
|
|
59
|
-
let postScope:
|
|
78
|
+
let postScope: AbortController | null = null
|
|
60
79
|
let currentJob: RecordingJob | null = null
|
|
61
80
|
let recordedSec = 0
|
|
62
81
|
let consecutiveErrors = 0
|
|
@@ -99,15 +118,11 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
99
118
|
return
|
|
100
119
|
}
|
|
101
120
|
case "hold": {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}
|
|
107
|
-
logger.warn(
|
|
108
|
-
`@${user} is live but no stream URL found (reason: no-stream-url, room: ${plan.room.id})`,
|
|
109
|
-
)
|
|
110
|
-
}
|
|
121
|
+
const why =
|
|
122
|
+
plan.reason === "restricted"
|
|
123
|
+
? "age-protected/restricted — stream unavailable (reason: restricted, status_code 4003110"
|
|
124
|
+
: "no stream URL found (reason: no-stream-url"
|
|
125
|
+
logger.warn(`@${user} is live but ${why}, room: ${plan.room.id})`)
|
|
111
126
|
return
|
|
112
127
|
}
|
|
113
128
|
case "stop": {
|
|
@@ -156,10 +171,9 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
156
171
|
|
|
157
172
|
const job = createRecordingJob({
|
|
158
173
|
result,
|
|
159
|
-
cfg
|
|
174
|
+
cfg,
|
|
160
175
|
logger,
|
|
161
176
|
converter: d.converter,
|
|
162
|
-
audioNormalizer: d.audioNormalizer,
|
|
163
177
|
signal: post.signal,
|
|
164
178
|
emitRecord: (event) => emitter.emit("record", event),
|
|
165
179
|
emitProgress: (event) => emitter.emit("progress", event),
|
|
@@ -199,10 +213,10 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
199
213
|
logger.warn(`start() ignored: already in state ${status.state}`)
|
|
200
214
|
return
|
|
201
215
|
}
|
|
202
|
-
const scope =
|
|
216
|
+
const scope = new AbortController()
|
|
203
217
|
// Post-processing outlives a user stop: Ctrl+C aborts the download, but the
|
|
204
218
|
// partial .ts is still remuxed to .mp4 before the process exits.
|
|
205
|
-
const post =
|
|
219
|
+
const post = new AbortController()
|
|
206
220
|
postScope = post
|
|
207
221
|
currentJob = null
|
|
208
222
|
recordedSec = 0
|
|
@@ -211,24 +225,7 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
211
225
|
logger.info(`Starting recorder for @${cfg.user}`)
|
|
212
226
|
const http = await createHttpClient(cfg)
|
|
213
227
|
const client = createTikTokClient(http, logger, cfg.debug, scope.signal)
|
|
214
|
-
const converter =
|
|
215
|
-
const audioNormalizer = cfg.normalizeAudio
|
|
216
|
-
? createAudioNormalizer(
|
|
217
|
-
{
|
|
218
|
-
loudness: cfg.normalizeLoudness,
|
|
219
|
-
audioCodec: cfg.normalizeCodec,
|
|
220
|
-
audioBitrate: cfg.normalizeBitrate,
|
|
221
|
-
onProgress: (file, percent, phase) =>
|
|
222
|
-
emitter.emit("progress", {
|
|
223
|
-
kind: "normalize",
|
|
224
|
-
file,
|
|
225
|
-
percent,
|
|
226
|
-
phase: phase as "analyzing" | "normalizing",
|
|
227
|
-
}),
|
|
228
|
-
},
|
|
229
|
-
logger,
|
|
230
|
-
)
|
|
231
|
-
: null
|
|
228
|
+
const converter = createMediaConverter(logger, post.signal)
|
|
232
229
|
|
|
233
230
|
// Self-reference inside `onTick` is safe: the monitor calls it from
|
|
234
231
|
// `start()`, never during construction.
|
|
@@ -237,7 +234,7 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
237
234
|
intervalMinutes: cfg.interval,
|
|
238
235
|
signal: scope.signal,
|
|
239
236
|
logger,
|
|
240
|
-
onTick: () => tick({ client, monitor, scope, post, converter
|
|
237
|
+
onTick: () => tick({ client, monitor, scope, post, converter }),
|
|
241
238
|
})
|
|
242
239
|
running = { monitor, http, scope }
|
|
243
240
|
|
|
@@ -251,9 +248,9 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
251
248
|
return
|
|
252
249
|
}
|
|
253
250
|
logger.info("Stopping recorder...")
|
|
254
|
-
running?.scope.
|
|
251
|
+
running?.scope.abort("user")
|
|
255
252
|
|
|
256
|
-
const grace = setTimeout(() => postScope?.
|
|
253
|
+
const grace = setTimeout(() => postScope?.abort("stop-timeout"), POST_REMUX_GRACE_MS)
|
|
257
254
|
try {
|
|
258
255
|
const job = currentJob
|
|
259
256
|
if (job) {
|
package/src/core/plan.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Tick policy — pure mapping from a `Verdict` plus facts to an action.
|
|
3
3
|
*
|
|
4
|
-
* No I/O, no clock, no promises. `
|
|
4
|
+
* No I/O, no clock, no promises. `app/recorder.ts` executes the returned plan.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import type { RoomRef, StreamRef, Verdict } from "./verdict"
|
package/src/core/verdict.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Verdict — the per-tick liveness result and its machine-readable reason.
|
|
3
3
|
*
|
|
4
|
-
* Pure domain type: no I/O, no imports outside `
|
|
4
|
+
* Pure domain type: no I/O, no imports outside `core/`. `reason` is derived
|
|
5
5
|
* by `verdictOf`, never passed by callers; discovery reports facts, one total
|
|
6
6
|
* function decides what they mean.
|
|
7
7
|
*/
|
package/src/index.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Library entry point — programmatic API for the TikTok Live Recorder.
|
|
3
3
|
*
|
|
4
4
|
* ```ts
|
|
5
|
-
* import { createRecorder } from '
|
|
5
|
+
* import { createRecorder } from '@zfadhli/tokrec'
|
|
6
6
|
*
|
|
7
7
|
* const recorder = createRecorder({ user: 'username', outputDir: './videos' })
|
|
8
8
|
* recorder.on('recording:end', (info) => console.log('Done:', info.file))
|
package/src/io/http.ts
CHANGED
|
@@ -61,7 +61,29 @@ export async function createHttpClient(config: RecorderConfig): Promise<HttpClie
|
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
|
|
64
|
+
// Token bucket: a minimum interval between requests. `0` or less is unlimited.
|
|
65
|
+
const minIntervalMs = config.ratePerSecond ? 1000 / config.ratePerSecond : 0
|
|
66
|
+
let lastTokenTime = 0
|
|
67
|
+
|
|
68
|
+
/** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */
|
|
69
|
+
async function waitForToken(signal: AbortSignal): Promise<void> {
|
|
70
|
+
if (minIntervalMs <= 0 || signal.aborted) return
|
|
71
|
+
const waitTime = Math.max(0, lastTokenTime + minIntervalMs - Date.now())
|
|
72
|
+
if (waitTime > 0) {
|
|
73
|
+
await new Promise<void>((resolve) => {
|
|
74
|
+
const timer = setTimeout(resolve, waitTime)
|
|
75
|
+
signal.addEventListener(
|
|
76
|
+
"abort",
|
|
77
|
+
() => {
|
|
78
|
+
clearTimeout(timer)
|
|
79
|
+
resolve()
|
|
80
|
+
},
|
|
81
|
+
{ once: true },
|
|
82
|
+
)
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
lastTokenTime = Date.now()
|
|
86
|
+
}
|
|
65
87
|
|
|
66
88
|
async function rateLimitedFetch(
|
|
67
89
|
url: string,
|
|
@@ -74,7 +96,7 @@ export async function createHttpClient(config: RecorderConfig): Promise<HttpClie
|
|
|
74
96
|
else external?.addEventListener("abort", onAbort, { once: true })
|
|
75
97
|
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
|
76
98
|
try {
|
|
77
|
-
await
|
|
99
|
+
await waitForToken(controller.signal)
|
|
78
100
|
const res = await session.fetch(url, {
|
|
79
101
|
method: options?.method,
|
|
80
102
|
body: options?.body as never,
|
|
@@ -118,50 +140,3 @@ export async function createHttpClient(config: RecorderConfig): Promise<HttpClie
|
|
|
118
140
|
},
|
|
119
141
|
}
|
|
120
142
|
}
|
|
121
|
-
|
|
122
|
-
// ─── rate limiting ─────────────────────────────────────────
|
|
123
|
-
|
|
124
|
-
interface RateLimiter {
|
|
125
|
-
/** Wait until a rate-limit token is available, then consume it. */
|
|
126
|
-
acquire(signal?: AbortSignal): Promise<void>
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* Token bucket: a minimum interval between requests. `0` or less is unlimited.
|
|
131
|
-
* Abort-aware, so a stop does not wait out a pending token.
|
|
132
|
-
*/
|
|
133
|
-
function createRateLimiter(tokensPerSecond: number): RateLimiter {
|
|
134
|
-
if (tokensPerSecond <= 0) {
|
|
135
|
-
return { acquire: async () => {} }
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const MIN_INTERVAL_MS = 1000 / tokensPerSecond
|
|
139
|
-
let lastTokenTime = 0
|
|
140
|
-
|
|
141
|
-
return {
|
|
142
|
-
async acquire(signal?: AbortSignal): Promise<void> {
|
|
143
|
-
if (signal?.aborted) return
|
|
144
|
-
|
|
145
|
-
const now = Date.now()
|
|
146
|
-
const waitTime = Math.max(0, lastTokenTime + MIN_INTERVAL_MS - now)
|
|
147
|
-
|
|
148
|
-
if (waitTime > 0) {
|
|
149
|
-
await new Promise<void>((resolve) => {
|
|
150
|
-
const timer = setTimeout(resolve, waitTime)
|
|
151
|
-
if (signal) {
|
|
152
|
-
signal.addEventListener(
|
|
153
|
-
"abort",
|
|
154
|
-
() => {
|
|
155
|
-
clearTimeout(timer)
|
|
156
|
-
resolve()
|
|
157
|
-
},
|
|
158
|
-
{ once: true },
|
|
159
|
-
)
|
|
160
|
-
}
|
|
161
|
-
})
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
lastTokenTime = Date.now()
|
|
165
|
-
},
|
|
166
|
-
}
|
|
167
|
-
}
|
package/src/io/media/ffmpeg.ts
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* FFmpeg — the single home for process invocation.
|
|
3
3
|
*
|
|
4
|
-
* Two
|
|
5
|
-
* capture)
|
|
6
|
-
*
|
|
7
|
-
* PATH lookup.
|
|
4
|
+
* Two entry points: `pipeFfmpegSegment` streams stdout into a `WriteStream`
|
|
5
|
+
* (live capture) and `createMediaConverter` builds the remux/segment capability
|
|
6
|
+
* the job consumes. Locating the binary lives here too, so no caller
|
|
7
|
+
* reimplements a PATH lookup.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { type ChildProcess, spawn } from "node:child_process"
|
|
11
11
|
import type { WriteStream } from "node:fs"
|
|
12
|
-
import { statSync } from "node:fs"
|
|
12
|
+
import { statSync, unlinkSync } from "node:fs"
|
|
13
13
|
import { execa } from "execa"
|
|
14
14
|
import { TikTokError } from "../../core/errors"
|
|
15
|
+
import type { Logger } from "../../core/log"
|
|
15
16
|
|
|
16
17
|
/** Kill FFmpeg if no output is received within this window after spawn. */
|
|
17
|
-
|
|
18
|
+
const FFMPEG_STARTUP_TIMEOUT = 30_000
|
|
18
19
|
|
|
19
20
|
/** Find the FFmpeg binary via `Bun.which()` or a PATH search. */
|
|
20
21
|
export function findFfmpegPath(): string | null {
|
|
@@ -39,7 +40,7 @@ export function findFfmpegPath(): string | null {
|
|
|
39
40
|
* Run FFmpeg to completion and return stdout — for output that is a file
|
|
40
41
|
* rather than a pipe (the segment muxer's `-segment_list pipe:1`).
|
|
41
42
|
*/
|
|
42
|
-
|
|
43
|
+
async function runFfmpeg(args: string[], signal?: AbortSignal): Promise<string> {
|
|
43
44
|
const ffmpegPath = findFfmpegPath()
|
|
44
45
|
if (!ffmpegPath) {
|
|
45
46
|
throw new TikTokError(
|
|
@@ -65,6 +66,63 @@ export async function runFfmpeg(args: string[], signal?: AbortSignal): Promise<s
|
|
|
65
66
|
}
|
|
66
67
|
}
|
|
67
68
|
|
|
69
|
+
/** The media-processing capability `RecordingJob` depends on. */
|
|
70
|
+
export interface MediaConverter {
|
|
71
|
+
/** Convert a TS file to MP4 (stream copy). Deletes the original on success. */
|
|
72
|
+
convert: (input: string) => Promise<string>
|
|
73
|
+
/** Split a file into `<name>_partN.mp4`; returns FFmpeg's CSV segment listing. */
|
|
74
|
+
segment: (input: string, segmentSeconds: number, outputPattern: string) => Promise<string>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function createMediaConverter(logger?: Logger, signal?: AbortSignal): MediaConverter {
|
|
78
|
+
async function convert(input: string): Promise<string> {
|
|
79
|
+
const output = input.replace(/\.(flv|ts)$/i, ".mp4")
|
|
80
|
+
logger?.info(`Converting: ${input} → ${output}`)
|
|
81
|
+
|
|
82
|
+
await runFfmpeg(["-i", input, "-c", "copy", "-y", output], signal)
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
unlinkSync(input)
|
|
86
|
+
logger?.info(`Deleted original: ${input}`)
|
|
87
|
+
} catch {
|
|
88
|
+
logger?.warn(`Could not delete original: ${input}`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return output
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function segment(
|
|
95
|
+
input: string,
|
|
96
|
+
segmentSeconds: number,
|
|
97
|
+
outputPattern: string,
|
|
98
|
+
): Promise<string> {
|
|
99
|
+
return runFfmpeg(
|
|
100
|
+
[
|
|
101
|
+
"-i",
|
|
102
|
+
input,
|
|
103
|
+
"-c",
|
|
104
|
+
"copy",
|
|
105
|
+
"-f",
|
|
106
|
+
"segment",
|
|
107
|
+
"-segment_time",
|
|
108
|
+
String(segmentSeconds),
|
|
109
|
+
"-reset_timestamps",
|
|
110
|
+
"1",
|
|
111
|
+
"-segment_start_number",
|
|
112
|
+
"1",
|
|
113
|
+
"-segment_list",
|
|
114
|
+
"pipe:1",
|
|
115
|
+
"-segment_list_type",
|
|
116
|
+
"csv",
|
|
117
|
+
outputPattern,
|
|
118
|
+
],
|
|
119
|
+
signal,
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return { convert, segment }
|
|
124
|
+
}
|
|
125
|
+
|
|
68
126
|
/**
|
|
69
127
|
* Build FFmpeg HTTP option arguments for cookies and headers.
|
|
70
128
|
* TikTok's CDN requires session cookies and a Referer to serve the stream.
|
package/src/io/tiktok/client.ts
CHANGED
|
@@ -1,19 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* TikTok API — resolves room IDs, live status, and stream URLs.
|
|
3
3
|
*
|
|
4
|
-
* `createTikTokClient` is a thin orchestrator: per-
|
|
5
|
-
* and `discover()` over sources returning `Candidate`s. The chain
|
|
6
|
-
* failures into evidence instead of aborting. `getVerdict` is the only
|
|
4
|
+
* `createTikTokClient` is a thin orchestrator: per-tick cache, cache
|
|
5
|
+
* invalidation, and `discover()` over sources returning `Candidate`s. The chain
|
|
6
|
+
* turns failures into evidence instead of aborting. `getVerdict` is the only
|
|
7
7
|
* public verdict surface.
|
|
8
8
|
*
|
|
9
|
-
* Architecture:
|
|
10
|
-
* createTikTokClient(httpClient) → { isRoomAlive, getLiveUrl, getVerdict }
|
|
11
|
-
*
|
|
12
9
|
* All public methods share a per-tick cache so the page is fetched at most once
|
|
13
10
|
* per poll cycle. The optional `signal` aborts in-flight HTTP requests.
|
|
14
|
-
*
|
|
15
|
-
* Note: The room/enter Webcast endpoint has been deprecated due to frequent
|
|
16
|
-
* 403 errors. All lookups go through room/info (reliable for live + offline).
|
|
17
11
|
*/
|
|
18
12
|
|
|
19
13
|
import type { Logger } from "../../core/log"
|
|
@@ -57,23 +51,18 @@ export function createTikTokClient(
|
|
|
57
51
|
createProfileSource(),
|
|
58
52
|
]
|
|
59
53
|
|
|
60
|
-
async function ensureCache(user: string): Promise<Verdict> {
|
|
61
|
-
if (cached && cachedUser === user) return cached
|
|
62
|
-
cached = await resolveVerdict(user)
|
|
63
|
-
cachedUser = user
|
|
64
|
-
return cached
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function invalidateCache(): void {
|
|
68
|
-
cached = null
|
|
69
|
-
cachedUser = ""
|
|
70
|
-
}
|
|
71
|
-
|
|
72
54
|
return {
|
|
73
|
-
invalidateCache
|
|
55
|
+
invalidateCache() {
|
|
56
|
+
cached = null
|
|
57
|
+
cachedUser = ""
|
|
58
|
+
},
|
|
74
59
|
|
|
75
60
|
async getVerdict(user: string): Promise<Verdict> {
|
|
76
|
-
|
|
61
|
+
if (!cached || cachedUser !== user) {
|
|
62
|
+
cached = await resolveVerdict(user)
|
|
63
|
+
cachedUser = user
|
|
64
|
+
}
|
|
65
|
+
return cached
|
|
77
66
|
},
|
|
78
67
|
|
|
79
68
|
async isRoomAlive(roomId: string): Promise<boolean> {
|
|
@@ -89,7 +78,7 @@ export function createTikTokClient(
|
|
|
89
78
|
if (cached?.room && String(cached.room.id) === String(roomId) && cached.stream) {
|
|
90
79
|
return cached.stream.url
|
|
91
80
|
}
|
|
92
|
-
// Room ID, not a username: never route this through
|
|
81
|
+
// Room ID, not a username: never route this through the user cache.
|
|
93
82
|
const res = await webcast.fetchStreamUrlFromApi(roomId)
|
|
94
83
|
return res.ok ? res.value : null
|
|
95
84
|
},
|
|
@@ -2,10 +2,6 @@
|
|
|
2
2
|
* Discovery chain — one idea in one file: a source reports facts, the chain
|
|
3
3
|
* turns every outcome (including a throw) into evidence, and the first room or
|
|
4
4
|
* gate refusal ends it.
|
|
5
|
-
*
|
|
6
|
-
* Types, candidate constructors, and the runner live together because they are
|
|
7
|
-
* a single contract; splitting them across `types.ts` and `candidates.ts` only
|
|
8
|
-
* added import edges.
|
|
9
5
|
*/
|
|
10
6
|
|
|
11
7
|
import type { Evidence, EvidenceOutcome, RoomRef, SourceId, StreamRef } from "../../../core/verdict"
|
|
@@ -96,18 +92,16 @@ export async function refused(
|
|
|
96
92
|
// ─── runner ────────────────────────────────────────────────
|
|
97
93
|
|
|
98
94
|
function outcomeOf(candidate: Candidate): EvidenceOutcome {
|
|
99
|
-
|
|
100
|
-
case "room":
|
|
101
|
-
return "hit"
|
|
102
|
-
case "denied":
|
|
103
|
-
return "denied"
|
|
104
|
-
case "failed":
|
|
105
|
-
return "error"
|
|
106
|
-
case "miss":
|
|
107
|
-
return "miss"
|
|
108
|
-
}
|
|
95
|
+
return OUTCOME[candidate.kind]
|
|
109
96
|
}
|
|
110
97
|
|
|
98
|
+
const OUTCOME = {
|
|
99
|
+
room: "hit",
|
|
100
|
+
denied: "denied",
|
|
101
|
+
failed: "error",
|
|
102
|
+
miss: "miss",
|
|
103
|
+
} satisfies Record<Candidate["kind"], EvidenceOutcome>
|
|
104
|
+
|
|
111
105
|
/**
|
|
112
106
|
* Run discovery sources in order. A throw — sync or async — becomes a
|
|
113
107
|
* `failed` candidate and the chain continues: the `probe.ts:154` dead end,
|
|
@@ -122,16 +116,13 @@ export async function discover(
|
|
|
122
116
|
let best: Candidate = { kind: "miss", note: "no sources configured" }
|
|
123
117
|
|
|
124
118
|
for (const source of sources) {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) }
|
|
133
|
-
}
|
|
134
|
-
})()
|
|
119
|
+
let candidate: Candidate
|
|
120
|
+
try {
|
|
121
|
+
candidate = await source.find(ctx)
|
|
122
|
+
} catch (error) {
|
|
123
|
+
ctx.debug(`discover: ${source.id} threw — ${error instanceof Error ? error.message : error}`)
|
|
124
|
+
candidate = failed(error)
|
|
125
|
+
}
|
|
135
126
|
evidence.push({
|
|
136
127
|
source:
|
|
137
128
|
candidate.kind === "room" || candidate.kind === "denied" ? candidate.source : source.id,
|