@zfadhli/tokrec 0.15.2 → 0.17.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/dist/app/config.d.mts +5 -2
- package/dist/app/config.d.mts.map +1 -1
- package/dist/app/config.mjs +1 -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 +34 -31
- 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/index.d.mts +2 -1
- package/dist/index.mjs +4 -2
- package/dist/io/http.d.mts +13 -0
- package/dist/io/http.d.mts.map +1 -0
- package/dist/io/http.mjs +50 -30
- 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 +16 -21
- 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 +58 -48
- package/src/core/plan.ts +1 -1
- package/src/core/verdict.ts +1 -1
- package/src/index.ts +2 -1
- package/src/io/http.ts +54 -52
- 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/loop.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Polling monitor — calls a tick function on a configurable interval.
|
|
3
3
|
* Fires the first tick immediately, then every N minutes.
|
|
4
4
|
*
|
|
5
|
-
* One external `AbortSignal` (the
|
|
5
|
+
* One external `AbortSignal` (the recorder's scope) interrupts both the
|
|
6
6
|
* sleep and any in-flight tick; there is no private controller.
|
|
7
7
|
*/
|
|
8
8
|
|
|
@@ -15,17 +15,18 @@ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
|
15
15
|
resolve()
|
|
16
16
|
return
|
|
17
17
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
{ once: true },
|
|
27
|
-
)
|
|
18
|
+
|
|
19
|
+
let timer: ReturnType<typeof setTimeout>
|
|
20
|
+
// One exit path: clear the timer, drop the listener, resolve. Without the
|
|
21
|
+
// removal a long-lived signal accumulates one listener per poll interval.
|
|
22
|
+
const done = (): void => {
|
|
23
|
+
clearTimeout(timer)
|
|
24
|
+
signal?.removeEventListener("abort", done)
|
|
25
|
+
resolve()
|
|
28
26
|
}
|
|
27
|
+
|
|
28
|
+
timer = setTimeout(done, ms)
|
|
29
|
+
signal?.addEventListener("abort", done, { once: true })
|
|
29
30
|
})
|
|
30
31
|
}
|
|
31
32
|
|
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
|
-
import { createHttpClient, type HttpClient } from "../io/http"
|
|
14
|
-
import { type Converter, createConverter } from "../io/media/convert"
|
|
14
|
+
import { createHttpClient, type HttpClient, splitCookies } from "../io/http"
|
|
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,36 +213,20 @@ 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
|
|
209
223
|
consecutiveErrors = 0
|
|
210
224
|
|
|
211
225
|
logger.info(`Starting recorder for @${cfg.user}`)
|
|
226
|
+
warnStaleCookies(cfg.cookies, logger)
|
|
212
227
|
const http = await createHttpClient(cfg)
|
|
213
228
|
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
|
|
229
|
+
const converter = createMediaConverter(logger, post.signal)
|
|
232
230
|
|
|
233
231
|
// Self-reference inside `onTick` is safe: the monitor calls it from
|
|
234
232
|
// `start()`, never during construction.
|
|
@@ -237,7 +235,7 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
237
235
|
intervalMinutes: cfg.interval,
|
|
238
236
|
signal: scope.signal,
|
|
239
237
|
logger,
|
|
240
|
-
onTick: () => tick({ client, monitor, scope, post, converter
|
|
238
|
+
onTick: () => tick({ client, monitor, scope, post, converter }),
|
|
241
239
|
})
|
|
242
240
|
running = { monitor, http, scope }
|
|
243
241
|
|
|
@@ -251,9 +249,9 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
251
249
|
return
|
|
252
250
|
}
|
|
253
251
|
logger.info("Stopping recorder...")
|
|
254
|
-
running?.scope.
|
|
252
|
+
running?.scope.abort("user")
|
|
255
253
|
|
|
256
|
-
const grace = setTimeout(() => postScope?.
|
|
254
|
+
const grace = setTimeout(() => postScope?.abort("stop-timeout"), POST_REMUX_GRACE_MS)
|
|
257
255
|
try {
|
|
258
256
|
const job = currentJob
|
|
259
257
|
if (job) {
|
|
@@ -280,6 +278,18 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
280
278
|
}
|
|
281
279
|
}
|
|
282
280
|
|
|
281
|
+
/** Say once, up front, that a routing hint from the config is being ignored. */
|
|
282
|
+
function warnStaleCookies(
|
|
283
|
+
cookies: Record<string, string> | undefined,
|
|
284
|
+
logger: { warn: (msg: string) => void },
|
|
285
|
+
): void {
|
|
286
|
+
const { stale } = splitCookies(cookies ?? {})
|
|
287
|
+
if (stale.length === 0) return
|
|
288
|
+
logger.warn(
|
|
289
|
+
`Ignoring ${stale.join(" and ")}: TikTok computes those per session, and a stale value makes the room API look like a private room`,
|
|
290
|
+
)
|
|
291
|
+
}
|
|
292
|
+
|
|
283
293
|
function lastSource(verdict: ReturnType<typeof verdictOf>): string {
|
|
284
294
|
return (
|
|
285
295
|
[...verdict.evidence].reverse().find((e) => e.outcome === "hit" || e.outcome === "denied")
|
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))
|
|
@@ -23,6 +23,7 @@ export type {
|
|
|
23
23
|
RecorderEventHandler,
|
|
24
24
|
RecorderStatus,
|
|
25
25
|
} from "./app/config"
|
|
26
|
+
export { splitCookies } from "./app/config"
|
|
26
27
|
export { createRecorder } from "./app/recorder"
|
|
27
28
|
export type { TikTokErrorCode } from "./core/errors"
|
|
28
29
|
export { TikTokError } from "./core/errors"
|
package/src/io/http.ts
CHANGED
|
@@ -40,6 +40,34 @@ const BROWSER_HEADERS: Record<string, string> = {
|
|
|
40
40
|
"Sec-Fetch-User": "?1",
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Routing hints TikTok computes per session: the datacentre hint and its
|
|
45
|
+
* signature. Sent by hand a value from a config file is stale by definition,
|
|
46
|
+
* and `tt-target-idc=useast2a` makes `room/info` answer 4003110 — the same
|
|
47
|
+
* refusal an age-restricted room returns, so the failure reads as a private
|
|
48
|
+
* room. Measured against tokgo (`internal/tiktok/client.go`), which strips
|
|
49
|
+
* both names for the same reason.
|
|
50
|
+
*/
|
|
51
|
+
export const SERVER_COOKIES: readonly string[] = ["tt-target-idc", "tt-target-idc-sign"]
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Split configured cookies into the ones we may send and the ones TikTok owns.
|
|
55
|
+
* `stale` is non-empty whenever the config carries a hint we are ignoring, so
|
|
56
|
+
* the caller can say so instead of silently dropping it.
|
|
57
|
+
*/
|
|
58
|
+
export function splitCookies(cookies: Record<string, string>): {
|
|
59
|
+
seed: [string, string][]
|
|
60
|
+
stale: string[]
|
|
61
|
+
} {
|
|
62
|
+
const seed: [string, string][] = []
|
|
63
|
+
const stale: string[] = []
|
|
64
|
+
for (const entry of Object.entries(cookies)) {
|
|
65
|
+
if (SERVER_COOKIES.includes(entry[0])) stale.push(entry[0])
|
|
66
|
+
else seed.push(entry)
|
|
67
|
+
}
|
|
68
|
+
return { seed, stale }
|
|
69
|
+
}
|
|
70
|
+
|
|
43
71
|
export async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {
|
|
44
72
|
const session: Session = await createSession({
|
|
45
73
|
browser: "firefox_149",
|
|
@@ -54,14 +82,35 @@ export async function createHttpClient(config: RecorderConfig): Promise<HttpClie
|
|
|
54
82
|
// subdomains automatically in wreq-js's cookie jar.
|
|
55
83
|
if (config.cookies && "sessionid_ss" in config.cookies) {
|
|
56
84
|
const domains = ["https://www.tiktok.com", "https://webcast.tiktok.com", "https://m.tiktok.com"]
|
|
85
|
+
const { seed } = splitCookies(config.cookies)
|
|
57
86
|
for (const domain of domains) {
|
|
58
|
-
for (const [name, value] of
|
|
59
|
-
session.setCookie(name, value, domain)
|
|
60
|
-
}
|
|
87
|
+
for (const [name, value] of seed) session.setCookie(name, value, domain)
|
|
61
88
|
}
|
|
62
89
|
}
|
|
63
90
|
|
|
64
|
-
|
|
91
|
+
// Token bucket: a minimum interval between requests. `0` or less is unlimited.
|
|
92
|
+
const minIntervalMs = config.ratePerSecond ? 1000 / config.ratePerSecond : 0
|
|
93
|
+
let lastTokenTime = 0
|
|
94
|
+
|
|
95
|
+
/** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */
|
|
96
|
+
async function waitForToken(signal: AbortSignal): Promise<void> {
|
|
97
|
+
if (minIntervalMs <= 0 || signal.aborted) return
|
|
98
|
+
const waitTime = Math.max(0, lastTokenTime + minIntervalMs - Date.now())
|
|
99
|
+
if (waitTime > 0) {
|
|
100
|
+
await new Promise<void>((resolve) => {
|
|
101
|
+
const timer = setTimeout(resolve, waitTime)
|
|
102
|
+
signal.addEventListener(
|
|
103
|
+
"abort",
|
|
104
|
+
() => {
|
|
105
|
+
clearTimeout(timer)
|
|
106
|
+
resolve()
|
|
107
|
+
},
|
|
108
|
+
{ once: true },
|
|
109
|
+
)
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
lastTokenTime = Date.now()
|
|
113
|
+
}
|
|
65
114
|
|
|
66
115
|
async function rateLimitedFetch(
|
|
67
116
|
url: string,
|
|
@@ -74,7 +123,7 @@ export async function createHttpClient(config: RecorderConfig): Promise<HttpClie
|
|
|
74
123
|
else external?.addEventListener("abort", onAbort, { once: true })
|
|
75
124
|
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
|
76
125
|
try {
|
|
77
|
-
await
|
|
126
|
+
await waitForToken(controller.signal)
|
|
78
127
|
const res = await session.fetch(url, {
|
|
79
128
|
method: options?.method,
|
|
80
129
|
body: options?.body as never,
|
|
@@ -118,50 +167,3 @@ export async function createHttpClient(config: RecorderConfig): Promise<HttpClie
|
|
|
118
167
|
},
|
|
119
168
|
}
|
|
120
169
|
}
|
|
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,
|