@bililive-tools/douyin-recorder 1.0.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/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # Intro
2
+
3
+ 原项目:https://github.com/WhiteMinds/DouYinRecorder
4
+
5
+ 这是 [biliLive-tools](https://github.com/renmu123/biliLive-tools) 的一个平台插件,为其支持了抖音平台录制
6
+
7
+ # 安装
8
+
9
+ `npm i @bililive-tools/douyin-recorder @bililive-tools/manager`
10
+
11
+ # 使用
12
+
13
+ ```ts
14
+ import { createRecorderManager } from "@bililive-tools/manager";
15
+ import { provider } from "@bililive-tools/douyin-recorder";
16
+
17
+ const manager = createRecorderManager({ providers: [provider] });
18
+ manager.addRecorder({
19
+ providerId: provider.id,
20
+ channelId: "203641303310",
21
+ quality: "origin",
22
+ streamPriorities: [],
23
+ sourcePriorities: [],
24
+ });
25
+
26
+ // 录制前请设置好ffmepg的环境变量,或手动指定,具体见`@bililive-tools/manager`文档
27
+ manager.startCheckLoop();
28
+ ```
29
+
30
+ ## 参数
31
+
32
+ ```ts
33
+ interface Options {
34
+ channelId: string; // 直播间ID,具体解析见文档,也可自行解析
35
+ quality: string; // 见画质参数
36
+ qualityRetry?: number; // 画质匹配重试次数, -1为强制匹配画质,0为自动配置,正整数为最大匹配次数
37
+ streamPriorities: []; // 废弃
38
+ sourcePriorities: []; // 废弃
39
+ disableAutoCheck?: boolean; // 为 true 时 manager 将跳过自动检查
40
+ segment?: number; // 分段参数,单位分钟
41
+ disableProvideCommentsWhenRecording?: boolean; // 禁用弹幕录制
42
+ saveGiftDanma?: boolean; // 保存礼物弹幕
43
+ saveCover?: boolean; // 保存封面
44
+ }
45
+ ```
46
+
47
+ ## 画质
48
+
49
+ 遗漏了部分画质,有了解的可以提PR
50
+
51
+ | 画质 | 值 |
52
+ | ------ | ------ |
53
+ | 原画 | origin |
54
+ | 蓝光 | uhd |
55
+ | 超清 | hd |
56
+ | 高清 | sd |
57
+ | 标清 | ld |
58
+ | 音频流 | ao |
59
+
60
+ ## 直播间ID解析
61
+
62
+ 解析出真实直播间ID
63
+
64
+ ```ts
65
+ import { provider } from "@bililive-tools/douyin-recorder";
66
+
67
+ const url = "https://live.douyin.com/203641303310";
68
+ const { id } = await provider.resolveChannelInfoFromURL(url);
69
+ ```
70
+
71
+ # 协议
72
+
73
+ 与原项目保存一致为 LGPL
@@ -0,0 +1,37 @@
1
+ export declare const getCookie: () => Promise<string>;
2
+ export declare function getRoomInfo(webRoomId: string, retryOnSpecialCode?: boolean): Promise<{
3
+ living: boolean;
4
+ roomId: string;
5
+ owner: string;
6
+ title: string;
7
+ streams: StreamProfile[];
8
+ sources: SourceProfile[];
9
+ avatar: string;
10
+ cover: string;
11
+ liveId: string;
12
+ }>;
13
+ export interface StreamProfile {
14
+ desc: string;
15
+ key: string;
16
+ bitRate: number;
17
+ }
18
+ export interface SourceProfile {
19
+ name: string;
20
+ streamMap: StreamData["data"];
21
+ }
22
+ interface StreamData {
23
+ common: unknown;
24
+ data: Record<string, {
25
+ main: {
26
+ flv: string;
27
+ hls: string;
28
+ cmaf: string;
29
+ dash: string;
30
+ lls: string;
31
+ tsl: string;
32
+ tile: string;
33
+ sdk_params: string;
34
+ };
35
+ }>;
36
+ }
37
+ export {};
@@ -0,0 +1,114 @@
1
+ import axios from "axios";
2
+ import { assert } from "./utils.js";
3
+ const requester = axios.create({
4
+ timeout: 10e3,
5
+ // axios 会自动读取环境变量中的 http_proxy 和 https_proxy 并应用,这会让请求发往代理的 host。
6
+ // 所以这里需要主动禁用代理功能。
7
+ proxy: false,
8
+ });
9
+ let cookieCache;
10
+ export const getCookie = async () => {
11
+ const now = new Date().getTime();
12
+ // 缓存24小时
13
+ if (cookieCache?.startTimestamp && now - cookieCache.startTimestamp < 24 * 60 * 60 * 1000) {
14
+ return cookieCache.cookies;
15
+ }
16
+ const res = await requester.get("https://live.douyin.com/");
17
+ if (!res.headers["set-cookie"]) {
18
+ throw new Error("No cookie in response");
19
+ }
20
+ const cookies = (res.headers["set-cookie"] ?? [])
21
+ .map((cookie) => {
22
+ return cookie.split(";")[0];
23
+ })
24
+ .join("; ");
25
+ cookieCache = {
26
+ startTimestamp: now,
27
+ cookies,
28
+ };
29
+ return cookies;
30
+ };
31
+ export async function getRoomInfo(webRoomId, retryOnSpecialCode = true) {
32
+ // 抖音的 'webcast/room/web/enter' api 会需要 ttwid 的 cookie,这个 cookie 是由这个请求的响应头设置的,
33
+ // 所以在这里请求一次自动设置。
34
+ const cookies = await getCookie();
35
+ const res = await requester.get("https://live.douyin.com/webcast/room/web/enter/", {
36
+ params: {
37
+ aid: 6383,
38
+ live_id: 1,
39
+ device_platform: "web",
40
+ language: "zh-CN",
41
+ enter_from: "web_live",
42
+ cookie_enabled: "true",
43
+ screen_width: 1920,
44
+ screen_height: 1080,
45
+ browser_language: "zh-CN",
46
+ browser_platform: "MacIntel",
47
+ browser_name: "Chrome",
48
+ browser_version: "108.0.0.0",
49
+ web_rid: webRoomId,
50
+ // enter_source:,
51
+ "Room-Enter-User-Login-Ab": 0,
52
+ is_need_double_stream: "false",
53
+ },
54
+ headers: {
55
+ cookie: cookies,
56
+ },
57
+ });
58
+ // console.log(JSON.stringify(res.data, null, 2));
59
+ // 无 cookie 时 code 为 10037
60
+ if (res.data.status_code === 10037 && retryOnSpecialCode) {
61
+ // resp 自动设置 cookie
62
+ // const cookieRes = await requester.get("https://live.douyin.com/favicon.ico");
63
+ // const cookies = cookieRes.headers["set-cookie"]
64
+ // .map((cookie) => {
65
+ // return cookie.split(";")[0];
66
+ // })
67
+ // .join("; ");
68
+ // console.log("cookies", cookies);
69
+ return getRoomInfo(webRoomId, false);
70
+ }
71
+ assert(res.data.status_code === 0, `Unexpected resp, code ${res.data.status_code}, msg ${res.data.data}, id ${webRoomId}`);
72
+ const data = res.data.data;
73
+ const room = data.data[0];
74
+ assert(room, `No room data, id ${webRoomId}`);
75
+ if (room?.stream_url == null) {
76
+ return {
77
+ living: false,
78
+ roomId: webRoomId,
79
+ owner: data.user.nickname,
80
+ title: room?.title ?? data.user.nickname,
81
+ streams: [],
82
+ sources: [],
83
+ avatar: data.user?.avatar_thumb?.url_list?.[0],
84
+ cover: room.cover?.url_list?.[0],
85
+ liveId: room.id_str,
86
+ };
87
+ }
88
+ const { options: { qualities }, stream_data, } = room.stream_url.live_core_sdk_data.pull_data;
89
+ const streamData = JSON.parse(stream_data).data;
90
+ const streams = qualities.map((info) => ({
91
+ desc: info.name,
92
+ key: info.sdk_key,
93
+ bitRate: info.v_bit_rate,
94
+ }));
95
+ // 看起来抖音是自动切换 cdn 的,所以这里固定返回一个默认的 source。
96
+ const sources = [
97
+ {
98
+ name: "自动",
99
+ streamMap: streamData,
100
+ },
101
+ ];
102
+ return {
103
+ living: data.room_status === 0,
104
+ // 接口里不会再返回 web room id,只能直接用入参原路返回了。
105
+ roomId: webRoomId,
106
+ owner: data.user.nickname,
107
+ title: room.title,
108
+ streams,
109
+ sources,
110
+ avatar: data.user.avatar_thumb.url_list[0],
111
+ cover: room.cover?.url_list?.[0],
112
+ liveId: room.id_str,
113
+ };
114
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { RecorderProvider } from "@bililive-tools/manager";
2
+ export declare const provider: RecorderProvider<{}>;
package/lib/index.js ADDED
@@ -0,0 +1,296 @@
1
+ import path from "node:path";
2
+ import mitt from "mitt";
3
+ import { defaultFromJSON, defaultToJSON, genRecorderUUID, genRecordUUID, FFMPEGRecorder, } from "@bililive-tools/manager";
4
+ import { getInfo, getStream } from "./stream.js";
5
+ import { ensureFolderExist, singleton } from "./utils.js";
6
+ import DouYinDanmaClient from "douyin-danma-listener";
7
+ function createRecorder(opts) {
8
+ // 内部实现时,应该只有 proxy 包裹的那一层会使用这个 recorder 标识符,不应该有直接通过
9
+ // 此标志来操作这个对象的地方,不然会跳过 proxy 的拦截。
10
+ const recorder = {
11
+ id: opts.id ?? genRecorderUUID(),
12
+ extra: opts.extra ?? {},
13
+ // @ts-ignore
14
+ ...mitt(),
15
+ ...opts,
16
+ availableStreams: [],
17
+ availableSources: [],
18
+ qualityMaxRetry: opts.qualityRetry ?? 0,
19
+ qualityRetry: opts.qualityRetry ?? 0,
20
+ state: "idle",
21
+ getChannelURL() {
22
+ return `https://live.douyin.com/${this.channelId}`;
23
+ },
24
+ checkLiveStatusAndRecord: singleton(checkLiveStatusAndRecord),
25
+ toJSON() {
26
+ return defaultToJSON(provider, this);
27
+ },
28
+ async getLiveInfo() {
29
+ const channelId = this.channelId;
30
+ const info = await getInfo(channelId);
31
+ return {
32
+ channelId,
33
+ ...info,
34
+ };
35
+ },
36
+ async getStream() {
37
+ const res = await getStream({
38
+ channelId: this.channelId,
39
+ quality: this.quality,
40
+ streamPriorities: this.streamPriorities,
41
+ sourcePriorities: this.sourcePriorities,
42
+ });
43
+ return res.currentStream;
44
+ },
45
+ };
46
+ const recorderWithSupportUpdatedEvent = new Proxy(recorder, {
47
+ set(obj, prop, value) {
48
+ Reflect.set(obj, prop, value);
49
+ if (typeof prop === "string") {
50
+ obj.emit("Updated", [prop]);
51
+ }
52
+ return true;
53
+ },
54
+ });
55
+ return recorderWithSupportUpdatedEvent;
56
+ }
57
+ const ffmpegOutputOptions = [
58
+ "-c",
59
+ "copy",
60
+ "-movflags",
61
+ "faststart+frag_keyframe+empty_moov",
62
+ "-min_frag_duration",
63
+ "60000000",
64
+ ];
65
+ const checkLiveStatusAndRecord = async function ({ getSavePath, banLiveId, isManualStart, }) {
66
+ if (this.recordHandle != null)
67
+ return this.recordHandle;
68
+ const liveInfo = await getInfo(this.channelId);
69
+ const { living, owner, title, liveId } = liveInfo;
70
+ this.liveInfo = liveInfo;
71
+ this.emit("LiveStart", { liveId });
72
+ if (liveInfo.liveId === banLiveId) {
73
+ this.tempStopIntervalCheck = true;
74
+ }
75
+ else {
76
+ this.tempStopIntervalCheck = false;
77
+ }
78
+ if (this.tempStopIntervalCheck)
79
+ return null;
80
+ if (!living)
81
+ return null;
82
+ let res;
83
+ try {
84
+ let strictQuality = false;
85
+ if (this.qualityRetry > 0) {
86
+ strictQuality = true;
87
+ }
88
+ if (this.qualityMaxRetry < 0) {
89
+ strictQuality = true;
90
+ }
91
+ if (isManualStart) {
92
+ strictQuality = false;
93
+ }
94
+ res = await getStream({
95
+ channelId: this.channelId,
96
+ quality: this.quality,
97
+ streamPriorities: this.streamPriorities,
98
+ sourcePriorities: this.sourcePriorities,
99
+ strictQuality: strictQuality,
100
+ });
101
+ }
102
+ catch (err) {
103
+ this.state = "idle";
104
+ throw err;
105
+ }
106
+ this.state = "recording";
107
+ const { currentStream: stream, sources: availableSources, streams: availableStreams } = res;
108
+ this.availableStreams = availableStreams.map((s) => s.desc);
109
+ this.availableSources = availableSources.map((s) => s.name);
110
+ this.usedStream = stream.name;
111
+ this.usedSource = stream.source;
112
+ // TODO: emit update event
113
+ let isEnded = false;
114
+ const onEnd = (...args) => {
115
+ if (isEnded)
116
+ return;
117
+ isEnded = true;
118
+ this.emit("DebugLog", {
119
+ type: "common",
120
+ text: `ffmpeg end, reason: ${JSON.stringify(args, (_, v) => (v instanceof Error ? v.stack : v))}`,
121
+ });
122
+ const reason = args[0] instanceof Error ? args[0].message : String(args[0]);
123
+ this.recordHandle?.stop(reason);
124
+ };
125
+ const recorder = new FFMPEGRecorder({
126
+ url: stream.url,
127
+ outputOptions: ffmpegOutputOptions,
128
+ segment: this.segment ?? 0,
129
+ getSavePath: (opts) => getSavePath({ owner, title, startTime: opts.startTime }),
130
+ disableDanma: this.disableProvideCommentsWhenRecording,
131
+ }, onEnd);
132
+ const savePath = getSavePath({
133
+ owner,
134
+ title,
135
+ });
136
+ try {
137
+ ensureFolderExist(savePath);
138
+ }
139
+ catch (err) {
140
+ this.state = "idle";
141
+ throw err;
142
+ }
143
+ const handleVideoCreated = async ({ filename }) => {
144
+ this.emit("videoFileCreated", { filename });
145
+ const extraDataController = recorder.getExtraDataController();
146
+ extraDataController?.setMeta({
147
+ room_id: this.channelId,
148
+ platform: provider?.id,
149
+ // liveStartTimestamp: liveInfo.startTime?.getTime(),
150
+ recordStopTimestamp: Date.now(),
151
+ title: title,
152
+ user_name: owner,
153
+ });
154
+ };
155
+ recorder.on("videoFileCreated", handleVideoCreated);
156
+ recorder.on("videoFileCompleted", ({ filename }) => {
157
+ this.emit("videoFileCompleted", { filename });
158
+ });
159
+ recorder.on("DebugLog", (data) => {
160
+ this.emit("DebugLog", data);
161
+ });
162
+ recorder.on("progress", (progress) => {
163
+ if (this.recordHandle) {
164
+ this.recordHandle.progress = progress;
165
+ }
166
+ this.emit("progress", progress);
167
+ });
168
+ const client = new DouYinDanmaClient(liveInfo.liveId);
169
+ client.on("chat", (msg) => {
170
+ const extraDataController = recorder.getExtraDataController();
171
+ if (!extraDataController)
172
+ return;
173
+ const comment = {
174
+ type: "comment",
175
+ timestamp: Date.now(),
176
+ text: msg.content,
177
+ color: "#ffffff",
178
+ sender: {
179
+ uid: msg.user.id,
180
+ name: msg.user.nickName,
181
+ // avatar: msg.user.AvatarThumb.urlListList[0],
182
+ // extra: {
183
+ // level: msg.level,
184
+ // },
185
+ },
186
+ };
187
+ // console.log("comment", comment);
188
+ this.emit("Message", comment);
189
+ extraDataController.addMessage(comment);
190
+ });
191
+ client.on("gift", (msg) => {
192
+ const extraDataController = recorder.getExtraDataController();
193
+ if (!extraDataController)
194
+ return;
195
+ if (this.saveGiftDanma === false)
196
+ return;
197
+ // console.log("gift", msg);
198
+ const gift = {
199
+ type: "give_gift",
200
+ timestamp: new Date(msg.sendTime).getTime(),
201
+ name: msg.gift.name,
202
+ price: 1,
203
+ count: Number(msg.totalCount),
204
+ color: "#ffffff",
205
+ sender: {
206
+ uid: msg.user.id,
207
+ name: msg.user.nickName,
208
+ // avatar: msg.ic,
209
+ // extra: {
210
+ // level: msg.level,
211
+ // },
212
+ },
213
+ };
214
+ // console.log("gift", gift);
215
+ this.emit("Message", gift);
216
+ extraDataController.addMessage(gift);
217
+ });
218
+ // client.on("open", () => {
219
+ // console.log("open");
220
+ // });
221
+ // client.on("close", () => {
222
+ // console.log("close");
223
+ // });
224
+ // client.on("error", (err) => {
225
+ // console.log("error", err);
226
+ // });
227
+ // client.on("heartbeat", () => {
228
+ // // console.log("heartbeat");
229
+ // });
230
+ if (!this.disableProvideCommentsWhenRecording) {
231
+ client.connect();
232
+ }
233
+ const ffmpegArgs = recorder.getArguments();
234
+ recorder.run();
235
+ const stop = singleton(async (reason) => {
236
+ if (!this.recordHandle)
237
+ return;
238
+ this.state = "stopping-record";
239
+ client.close();
240
+ try {
241
+ await recorder.stop();
242
+ }
243
+ catch (err) {
244
+ this.emit("DebugLog", {
245
+ type: "common",
246
+ text: `stop ffmpeg error: ${String(err)}`,
247
+ });
248
+ }
249
+ this.usedStream = undefined;
250
+ this.usedSource = undefined;
251
+ this.emit("RecordStop", { recordHandle: this.recordHandle, reason });
252
+ this.recordHandle = undefined;
253
+ this.liveInfo = undefined;
254
+ this.state = "idle";
255
+ });
256
+ this.recordHandle = {
257
+ id: genRecordUUID(),
258
+ stream: stream.name,
259
+ source: stream.source,
260
+ url: stream.url,
261
+ ffmpegArgs,
262
+ savePath: savePath,
263
+ stop,
264
+ };
265
+ this.emit("RecordStart", this.recordHandle);
266
+ return this.recordHandle;
267
+ };
268
+ export const provider = {
269
+ id: "DouYin",
270
+ name: "抖音",
271
+ siteURL: "https://live.douyin.com/",
272
+ matchURL(channelURL) {
273
+ // TODO: 暂时不支持 v.douyin.com
274
+ return /https?:\/\/live\.douyin\.com\//.test(channelURL);
275
+ },
276
+ async resolveChannelInfoFromURL(channelURL) {
277
+ if (!this.matchURL(channelURL))
278
+ return null;
279
+ const id = path.basename(new URL(channelURL).pathname);
280
+ const info = await getInfo(id);
281
+ return {
282
+ id: info.roomId,
283
+ title: info.title,
284
+ owner: info.owner,
285
+ };
286
+ },
287
+ createRecorder(opts) {
288
+ return createRecorder({ providerId: provider.id, ...opts });
289
+ },
290
+ fromJSON(recorder) {
291
+ return defaultFromJSON(this, recorder);
292
+ },
293
+ setFFMPEGOutputArgs(args) {
294
+ ffmpegOutputOptions.splice(0, ffmpegOutputOptions.length, ...args);
295
+ },
296
+ };
@@ -0,0 +1,30 @@
1
+ import type { Recorder } from "@bililive-tools/manager";
2
+ export declare function getInfo(channelId: string): Promise<{
3
+ living: boolean;
4
+ owner: string;
5
+ title: string;
6
+ roomId: string;
7
+ avatar: string;
8
+ cover: string;
9
+ startTime: Date;
10
+ liveId: string;
11
+ }>;
12
+ export declare function getStream(opts: Pick<Recorder, "channelId" | "quality" | "streamPriorities" | "sourcePriorities"> & {
13
+ rejectCache?: boolean;
14
+ strictQuality?: boolean;
15
+ }): Promise<{
16
+ currentStream: {
17
+ name: string;
18
+ source: string;
19
+ url: string;
20
+ };
21
+ living: boolean;
22
+ roomId: string;
23
+ owner: string;
24
+ title: string;
25
+ streams: import("./douyin_api.js").StreamProfile[];
26
+ sources: import("./douyin_api.js").SourceProfile[];
27
+ avatar: string;
28
+ cover: string;
29
+ liveId: string;
30
+ }>;
package/lib/stream.js ADDED
@@ -0,0 +1,69 @@
1
+ import { getRoomInfo } from "./douyin_api.js";
2
+ export async function getInfo(channelId) {
3
+ const info = await getRoomInfo(channelId);
4
+ return {
5
+ living: info.living,
6
+ owner: info.owner,
7
+ title: info.title,
8
+ roomId: info.roomId,
9
+ avatar: info.avatar,
10
+ cover: info.cover,
11
+ startTime: new Date(),
12
+ liveId: info.liveId,
13
+ };
14
+ }
15
+ export async function getStream(opts) {
16
+ const info = await getRoomInfo(opts.channelId);
17
+ if (!info.living) {
18
+ throw new Error("It must be called getStream when living");
19
+ }
20
+ const qualityMap = [
21
+ {
22
+ key: "origin",
23
+ desc: "原画",
24
+ },
25
+ {
26
+ key: "uhd",
27
+ desc: "蓝光",
28
+ },
29
+ {
30
+ key: "hd",
31
+ desc: "超清",
32
+ },
33
+ {
34
+ key: "sd",
35
+ desc: "高清",
36
+ },
37
+ {
38
+ key: "标清",
39
+ desc: "ld",
40
+ },
41
+ ];
42
+ const sources = info.sources[0];
43
+ let url = sources.streamMap[opts.quality]?.main?.flv;
44
+ let qualityName = qualityMap.find((q) => q.key === opts.quality)?.desc ?? "未知";
45
+ if (!url && opts.strictQuality) {
46
+ throw new Error("Can not get expect quality because of strictQuality");
47
+ }
48
+ // 如果url不存在,那么按照优先级选择
49
+ if (!url) {
50
+ for (const quality of qualityMap) {
51
+ url = sources.streamMap[quality.key]?.main?.flv;
52
+ if (url) {
53
+ qualityName = quality.desc;
54
+ break;
55
+ }
56
+ }
57
+ }
58
+ if (!url) {
59
+ throw new Error("未找到对应的流");
60
+ }
61
+ return {
62
+ ...info,
63
+ currentStream: {
64
+ name: qualityName,
65
+ source: "自动",
66
+ url: url,
67
+ },
68
+ };
69
+ }
package/lib/test.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/lib/test.js ADDED
@@ -0,0 +1,13 @@
1
+ // execute in shell `ts-node src/test.ts` to run test
2
+ // TODO: add to scripts
3
+ import { createRecorderManager } from "@bililive-tools/manager";
4
+ import { provider } from "./index.js";
5
+ const manager = createRecorderManager({ providers: [provider] });
6
+ manager.addRecorder({
7
+ providerId: provider.id,
8
+ channelId: "317590520822",
9
+ quality: "medium",
10
+ streamPriorities: [],
11
+ sourcePriorities: [],
12
+ });
13
+ manager.startCheckLoop();
package/lib/utils.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 接收 fn ,返回一个和 fn 签名一致的函数 fn'。当已经有一个 fn' 在运行时,再调用
3
+ * fn' 会直接返回运行中 fn' 的 Promise,直到 Promise 结束 pending 状态
4
+ */
5
+ export declare function singleton<Fn extends (...args: any) => Promise<any>>(fn: Fn): Fn;
6
+ export declare function ensureFolderExist(fileOrFolderPath: string): void;
7
+ export declare function assert(assertion: unknown, msg?: string): asserts assertion;
8
+ export declare function assertStringType(data: unknown, msg?: string): asserts data is string;
9
+ export declare function assertNumberType(data: unknown, msg?: string): asserts data is number;
10
+ export declare function assertObjectType(data: unknown, msg?: string): asserts data is object;
11
+ export declare function replaceExtName(filePath: string, newExtName: string): string;
package/lib/utils.js ADDED
@@ -0,0 +1,44 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ /**
4
+ * 接收 fn ,返回一个和 fn 签名一致的函数 fn'。当已经有一个 fn' 在运行时,再调用
5
+ * fn' 会直接返回运行中 fn' 的 Promise,直到 Promise 结束 pending 状态
6
+ */
7
+ export function singleton(fn) {
8
+ let latestPromise = null;
9
+ return function (...args) {
10
+ if (latestPromise)
11
+ return latestPromise;
12
+ // @ts-ignore
13
+ const promise = fn.apply(this, args).finally(() => {
14
+ if (promise === latestPromise) {
15
+ latestPromise = null;
16
+ }
17
+ });
18
+ latestPromise = promise;
19
+ return promise;
20
+ };
21
+ }
22
+ export function ensureFolderExist(fileOrFolderPath) {
23
+ const folder = path.dirname(fileOrFolderPath);
24
+ if (!fs.existsSync(folder)) {
25
+ fs.mkdirSync(folder, { recursive: true });
26
+ }
27
+ }
28
+ export function assert(assertion, msg) {
29
+ if (!assertion) {
30
+ throw new Error(msg);
31
+ }
32
+ }
33
+ export function assertStringType(data, msg) {
34
+ assert(typeof data === "string", msg);
35
+ }
36
+ export function assertNumberType(data, msg) {
37
+ assert(typeof data === "number", msg);
38
+ }
39
+ export function assertObjectType(data, msg) {
40
+ assert(typeof data === "object", msg);
41
+ }
42
+ export function replaceExtName(filePath, newExtName) {
43
+ return path.join(path.dirname(filePath), path.basename(filePath, path.extname(filePath)) + newExtName);
44
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@bililive-tools/douyin-recorder",
3
+ "version": "1.0.0",
4
+ "description": "@bililive-tools douyin recorder implemention",
5
+ "main": "./lib/index.js",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./src/index.ts",
13
+ "development": "./src/index.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./*.js": {
17
+ "types": "./src/*.ts",
18
+ "development": "./src/*.ts",
19
+ "default": "./lib/*.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "lib"
24
+ ],
25
+ "keywords": [
26
+ "douyin",
27
+ "recorder",
28
+ "bililive-tools",
29
+ "直播",
30
+ "录制",
31
+ "抖音"
32
+ ],
33
+ "repository": "https://github.com/renmu123/biliLive-tools/tree/master/packages/DouYinRecorder",
34
+ "author": "WhiteMind",
35
+ "license": "LGPL",
36
+ "dependencies": {
37
+ "axios": "^1.7.8",
38
+ "lodash-es": "^4.17.21",
39
+ "mitt": "^3.0.1",
40
+ "@bililive-tools/manager": "^1.1.0",
41
+ "douyin-danma-listener": "0.1.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "*"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc",
48
+ "watch": "tsc -w",
49
+ "gen:proto": "pbjs -t static-module -w es6 -o src/danma/proto.js src/danma/dy.proto"
50
+ }
51
+ }