@sdeck/youtube 0.0.0-stage → 1.0.1
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 +81 -2
- package/dist/actions.d.ts +4 -0
- package/dist/actions.d.ts.map +1 -0
- package/dist/api.d.ts +68 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/chat.d.ts +28 -0
- package/dist/chat.d.ts.map +1 -0
- package/dist/displays.d.ts +2 -0
- package/dist/displays.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1792 -0
- package/dist/index.js.map +19 -0
- package/dist/looks.d.ts +11 -0
- package/dist/looks.d.ts.map +1 -0
- package/dist/model.d.ts +175 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/plugin.d.ts +68 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/state.d.ts +19 -0
- package/dist/state.d.ts.map +1 -0
- package/dist/triggers.d.ts +2 -0
- package/dist/triggers.d.ts.map +1 -0
- package/package.json +67 -4
- package/src/actions.ts +471 -0
- package/src/api.ts +367 -0
- package/src/chat.ts +95 -0
- package/src/displays.ts +270 -0
- package/src/index.tsx +58 -0
- package/src/looks.ts +18 -0
- package/src/model.ts +378 -0
- package/src/plugin.ts +326 -0
- package/src/state.ts +99 -0
- package/src/triggers.ts +177 -0
package/src/api.ts
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* YouTube's Data API, signed in through sdeck's app, or with an app of the user's own that sends the
|
|
3
|
+
* browser back to this computer.
|
|
4
|
+
* https://developers.google.com/identity/protocols/oauth2/native-app
|
|
5
|
+
*/
|
|
6
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
7
|
+
import { OAuthError, type OAuthSignIn, type OAuthTokens } from "@sdeck/plugin";
|
|
8
|
+
|
|
9
|
+
/** Everything the plugin does, including chat. Google has none that allow less and still do it. */
|
|
10
|
+
export const SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"];
|
|
11
|
+
|
|
12
|
+
export interface Endpoints {
|
|
13
|
+
authorize: string;
|
|
14
|
+
/** Has `/token` and `/revoke`. */
|
|
15
|
+
oauth: string;
|
|
16
|
+
api: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const GOOGLE: Endpoints = {
|
|
20
|
+
authorize: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
21
|
+
oauth: "https://oauth2.googleapis.com",
|
|
22
|
+
api: "https://www.googleapis.com/youtube/v3",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export interface SignIn {
|
|
26
|
+
/** Where to send the user. */
|
|
27
|
+
url: string;
|
|
28
|
+
/** Resolves once they approved and the tokens are saved. */
|
|
29
|
+
done: Promise<void>;
|
|
30
|
+
cancel(): void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Signing in through sdeck's app. */
|
|
34
|
+
export interface Broker {
|
|
35
|
+
start(): Promise<OAuthSignIn>;
|
|
36
|
+
refresh(refreshToken: string): Promise<OAuthTokens>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface OwnApp {
|
|
40
|
+
clientId: string;
|
|
41
|
+
clientSecret: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ClientOptions {
|
|
45
|
+
/** The user's own app; without one, sdeck's is used. */
|
|
46
|
+
app(): OwnApp | undefined;
|
|
47
|
+
broker: Broker;
|
|
48
|
+
tokens: {
|
|
49
|
+
get(): string | undefined;
|
|
50
|
+
set(refresh: string | undefined): Promise<void>;
|
|
51
|
+
};
|
|
52
|
+
endpoints?: Endpoints;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type Method = "GET" | "POST" | "PUT" | "DELETE";
|
|
56
|
+
export type Json = Record<string, unknown>;
|
|
57
|
+
|
|
58
|
+
/** Not signed in: there is nothing to retry until the user signs in. */
|
|
59
|
+
export class SignedOut extends Error {
|
|
60
|
+
constructor(message = "Sign in to YouTube from the plugin's settings") {
|
|
61
|
+
super(message);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** YouTube refused a request. */
|
|
66
|
+
export class YouTubeError extends Error {
|
|
67
|
+
constructor(
|
|
68
|
+
readonly status: number,
|
|
69
|
+
/** Google's word for it, such as `liveChatEnded`. */
|
|
70
|
+
readonly reason: string,
|
|
71
|
+
message: string,
|
|
72
|
+
) {
|
|
73
|
+
super(message);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The app has made all the requests it may make today. It gets more at midnight in California. */
|
|
78
|
+
export class QuotaError extends YouTubeError {
|
|
79
|
+
constructor(ownApp: boolean) {
|
|
80
|
+
super(
|
|
81
|
+
403,
|
|
82
|
+
"quotaExceeded",
|
|
83
|
+
ownApp
|
|
84
|
+
? "your app has used up YouTube's limit for today"
|
|
85
|
+
: "sdeck has used up YouTube's limit for today; an app of your own has a limit of its own",
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const QUOTA = new Set(["quotaExceeded", "dailyLimitExceeded"]);
|
|
91
|
+
const MESSAGES: Record<string, string> = {
|
|
92
|
+
liveStreamingNotEnabled: "live streaming is not turned on for this channel (see YouTube Studio)",
|
|
93
|
+
redundantTransition: "YouTube is already doing that",
|
|
94
|
+
invalidTransition: "YouTube does not allow that at this point of the stream",
|
|
95
|
+
errorStreamInactive:
|
|
96
|
+
"YouTube receives no video yet: start streaming in OBS or your encoder first",
|
|
97
|
+
liveChatDisabled: "chat is turned off for this stream",
|
|
98
|
+
liveChatEnded: "the chat of this stream has ended",
|
|
99
|
+
insufficientPermissions: "Sign in to YouTube again, and allow everything it asks for",
|
|
100
|
+
ACCESS_TOKEN_SCOPE_INSUFFICIENT: "Sign in to YouTube again, and allow everything it asks for",
|
|
101
|
+
accessNotConfigured: "turn on the YouTube Data API v3 for your app in the Google Cloud console",
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
interface GoogleError {
|
|
105
|
+
message?: string;
|
|
106
|
+
errors?: { reason?: string }[];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
type Tokens = Pick<OAuthTokens, "accessToken" | "refreshToken" | "expiresAt">;
|
|
110
|
+
|
|
111
|
+
const page = (message: string) =>
|
|
112
|
+
new Response(`<!doctype html><meta charset="utf-8"><title>sdeck</title><p>${message}</p>`, {
|
|
113
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
export class YouTubeClient {
|
|
117
|
+
readonly #options: ClientOptions;
|
|
118
|
+
readonly #endpoints: Endpoints;
|
|
119
|
+
#access: { token: string; expires: number } | undefined;
|
|
120
|
+
#renewing: Promise<string> | undefined;
|
|
121
|
+
/** Changes when someone signs in or out, so that nothing from before is used after. */
|
|
122
|
+
#era = 0;
|
|
123
|
+
|
|
124
|
+
constructor(options: ClientOptions) {
|
|
125
|
+
this.#options = options;
|
|
126
|
+
this.#endpoints = options.endpoints ?? GOOGLE;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
get signedIn(): boolean {
|
|
130
|
+
return this.#options.tokens.get() !== undefined;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Starts signing in, and waits for the user to allow it in the browser. */
|
|
134
|
+
async signIn(): Promise<SignIn> {
|
|
135
|
+
const app = this.#options.app();
|
|
136
|
+
if (app) return this.#signInWithOwnApp(app);
|
|
137
|
+
const { url, tokens } = await this.#options.broker.start();
|
|
138
|
+
let cancelled = false;
|
|
139
|
+
const done = tokens.then(async (tokens) => {
|
|
140
|
+
if (cancelled) throw new Error("sign-in cancelled");
|
|
141
|
+
await this.#begin(tokens);
|
|
142
|
+
});
|
|
143
|
+
return {
|
|
144
|
+
url,
|
|
145
|
+
done,
|
|
146
|
+
cancel: () => {
|
|
147
|
+
cancelled = true;
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Listens on a free port of this computer until the user is done, or five minutes pass. */
|
|
153
|
+
#signInWithOwnApp(app: OwnApp, timeoutMs = 300_000): SignIn {
|
|
154
|
+
const verifier = randomBytes(64).toString("base64url");
|
|
155
|
+
const state = randomBytes(16).toString("base64url");
|
|
156
|
+
let closed = false;
|
|
157
|
+
let finish: (error?: Error) => void = () => {};
|
|
158
|
+
const done = new Promise<void>((resolve, reject) => {
|
|
159
|
+
finish = (error) => (error ? reject(error) : resolve());
|
|
160
|
+
});
|
|
161
|
+
const close = (error?: Error) => {
|
|
162
|
+
if (closed) return;
|
|
163
|
+
closed = true;
|
|
164
|
+
clearTimeout(timer);
|
|
165
|
+
// Let the answer to the browser go out first.
|
|
166
|
+
setTimeout(() => server.stop(), 100);
|
|
167
|
+
finish(error);
|
|
168
|
+
};
|
|
169
|
+
const server = Bun.serve({
|
|
170
|
+
hostname: "127.0.0.1",
|
|
171
|
+
port: 0,
|
|
172
|
+
fetch: async (request) => {
|
|
173
|
+
const { pathname, searchParams } = new URL(request.url);
|
|
174
|
+
if (pathname !== "/") return new Response("not found", { status: 404 });
|
|
175
|
+
// A page elsewhere cannot finish the sign-in: it does not know `state`.
|
|
176
|
+
if (closed || searchParams.get("state") !== state) {
|
|
177
|
+
return new Response("wrong state", { status: 400 });
|
|
178
|
+
}
|
|
179
|
+
const code = searchParams.get("code");
|
|
180
|
+
if (!code) {
|
|
181
|
+
const said = searchParams.get("error");
|
|
182
|
+
close(
|
|
183
|
+
new Error(said === "access_denied" ? "YouTube was not allowed" : `Google: ${said}`),
|
|
184
|
+
);
|
|
185
|
+
return page("sdeck was not given access. You can close this tab.");
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
await this.#begin(
|
|
189
|
+
await this.#ask(app, {
|
|
190
|
+
grant_type: "authorization_code",
|
|
191
|
+
code,
|
|
192
|
+
redirect_uri: redirect,
|
|
193
|
+
code_verifier: verifier,
|
|
194
|
+
}),
|
|
195
|
+
);
|
|
196
|
+
close();
|
|
197
|
+
return page("sdeck is connected to YouTube. You can close this tab.");
|
|
198
|
+
} catch (error) {
|
|
199
|
+
close(error as Error);
|
|
200
|
+
return page("Signing in failed. See the plugin's settings in sdeck.");
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
const redirect = `http://127.0.0.1:${server.port}`;
|
|
205
|
+
const timer = setTimeout(() => close(new Error("signing in took too long")), timeoutMs);
|
|
206
|
+
const url = new URL(this.#endpoints.authorize);
|
|
207
|
+
url.search = new URLSearchParams({
|
|
208
|
+
client_id: app.clientId,
|
|
209
|
+
response_type: "code",
|
|
210
|
+
redirect_uri: redirect,
|
|
211
|
+
scope: SCOPES.join(" "),
|
|
212
|
+
state,
|
|
213
|
+
code_challenge_method: "S256",
|
|
214
|
+
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
|
|
215
|
+
// Without these, signing in a second time gives nothing that lasts.
|
|
216
|
+
access_type: "offline",
|
|
217
|
+
prompt: "consent",
|
|
218
|
+
}).toString();
|
|
219
|
+
return { url: url.href, done, cancel: () => close(new Error("sign-in cancelled")) };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async signOut(): Promise<void> {
|
|
223
|
+
const token = this.#options.tokens.get();
|
|
224
|
+
this.#forget();
|
|
225
|
+
await this.#options.tokens.set(undefined);
|
|
226
|
+
if (!token) return;
|
|
227
|
+
// So that the access ends at Google's side too.
|
|
228
|
+
await fetch(`${this.#endpoints.oauth}/revoke`, {
|
|
229
|
+
method: "POST",
|
|
230
|
+
body: new URLSearchParams({ token }),
|
|
231
|
+
signal: AbortSignal.timeout(10_000),
|
|
232
|
+
}).catch(() => {});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Calls the API. Resolves with its answer, which is empty for some requests. */
|
|
236
|
+
async request(
|
|
237
|
+
method: Method,
|
|
238
|
+
path: string,
|
|
239
|
+
query: Record<string, string> = {},
|
|
240
|
+
body?: unknown,
|
|
241
|
+
): Promise<Json> {
|
|
242
|
+
const url = new URL(`${this.#endpoints.api}${path}`);
|
|
243
|
+
for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
|
|
244
|
+
for (let attempt = 0; ; attempt++) {
|
|
245
|
+
const token = await this.#token();
|
|
246
|
+
const response = await fetch(url, {
|
|
247
|
+
method,
|
|
248
|
+
headers: {
|
|
249
|
+
authorization: `Bearer ${token}`,
|
|
250
|
+
...(body !== undefined && { "content-type": "application/json" }),
|
|
251
|
+
},
|
|
252
|
+
...(body !== undefined && { body: JSON.stringify(body) }),
|
|
253
|
+
signal: AbortSignal.timeout(15_000),
|
|
254
|
+
});
|
|
255
|
+
const answer = ((await response.json().catch(() => undefined)) ?? {}) as Json;
|
|
256
|
+
if (response.ok) return answer;
|
|
257
|
+
// The token was withdrawn early. Another may work.
|
|
258
|
+
if (response.status === 401 && attempt === 0) {
|
|
259
|
+
if (this.#access?.token === token) this.#access = undefined;
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const error = (answer.error ?? {}) as GoogleError;
|
|
263
|
+
const reason = error.errors?.[0]?.reason ?? "";
|
|
264
|
+
if (QUOTA.has(reason)) throw new QuotaError(this.#options.app() !== undefined);
|
|
265
|
+
throw new YouTubeError(
|
|
266
|
+
response.status,
|
|
267
|
+
reason,
|
|
268
|
+
MESSAGES[reason] ??
|
|
269
|
+
// Some of Google's messages have links in them.
|
|
270
|
+
(error.message?.replace(/<[^>]*>/g, "") || `YouTube answered ${response.status}`),
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** As {@link request}, for the items of a list. */
|
|
276
|
+
async list(path: string, query: Record<string, string>): Promise<Json[]> {
|
|
277
|
+
const { items } = await this.request("GET", path, query);
|
|
278
|
+
return Array.isArray(items) ? items : [];
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
#forget() {
|
|
282
|
+
this.#era++;
|
|
283
|
+
this.#access = undefined;
|
|
284
|
+
this.#renewing = undefined;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async #begin(tokens: Tokens): Promise<void> {
|
|
288
|
+
if (!tokens.refreshToken) throw new Error("Google gave no lasting access; sign in again");
|
|
289
|
+
this.#forget();
|
|
290
|
+
await this.#keep(tokens);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async #keep(tokens: Tokens): Promise<string> {
|
|
294
|
+
if (tokens.refreshToken) await this.#options.tokens.set(tokens.refreshToken);
|
|
295
|
+
// A minute early, so a token never expires mid-request.
|
|
296
|
+
this.#access = { token: tokens.accessToken, expires: tokens.expiresAt - 60_000 };
|
|
297
|
+
return tokens.accessToken;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async #token(): Promise<string> {
|
|
301
|
+
if (this.#access && Date.now() < this.#access.expires) return this.#access.token;
|
|
302
|
+
if (!this.#renewing) {
|
|
303
|
+
const renewing = this.#renew().finally(() => {
|
|
304
|
+
if (this.#renewing === renewing) this.#renewing = undefined;
|
|
305
|
+
});
|
|
306
|
+
this.#renewing = renewing;
|
|
307
|
+
}
|
|
308
|
+
return this.#renewing;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async #renew(): Promise<string> {
|
|
312
|
+
const era = this.#era;
|
|
313
|
+
const refresh = this.#options.tokens.get();
|
|
314
|
+
if (!refresh) throw new SignedOut();
|
|
315
|
+
const app = this.#options.app();
|
|
316
|
+
let tokens: Tokens;
|
|
317
|
+
try {
|
|
318
|
+
tokens = app
|
|
319
|
+
? await this.#ask(app, { grant_type: "refresh_token", refresh_token: refresh })
|
|
320
|
+
: await this.#options.broker.refresh(refresh);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if (!(error instanceof OAuthError) || error.code !== "invalid_grant") throw error;
|
|
323
|
+
if (era === this.#era) {
|
|
324
|
+
this.#forget();
|
|
325
|
+
await this.#options.tokens.set(undefined);
|
|
326
|
+
}
|
|
327
|
+
throw new SignedOut("The YouTube sign-in expired: sign in again");
|
|
328
|
+
}
|
|
329
|
+
if (era !== this.#era) throw new SignedOut();
|
|
330
|
+
return this.#keep(tokens);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Asks Google for tokens, for the user's own app. */
|
|
334
|
+
async #ask(app: OwnApp, fields: Record<string, string>): Promise<Tokens> {
|
|
335
|
+
const response = await fetch(`${this.#endpoints.oauth}/token`, {
|
|
336
|
+
method: "POST",
|
|
337
|
+
body: new URLSearchParams({
|
|
338
|
+
...fields,
|
|
339
|
+
client_id: app.clientId,
|
|
340
|
+
...(app.clientSecret && { client_secret: app.clientSecret }),
|
|
341
|
+
}),
|
|
342
|
+
signal: AbortSignal.timeout(15_000),
|
|
343
|
+
});
|
|
344
|
+
const body = (await response.json().catch(() => ({}))) as {
|
|
345
|
+
access_token?: string;
|
|
346
|
+
refresh_token?: string;
|
|
347
|
+
expires_in?: number;
|
|
348
|
+
error?: string;
|
|
349
|
+
error_description?: string;
|
|
350
|
+
};
|
|
351
|
+
if (!response.ok || !body.access_token) {
|
|
352
|
+
// `unauthorized_client`: the sign-in was made with another app.
|
|
353
|
+
if (body.error === "invalid_grant" || body.error === "unauthorized_client") {
|
|
354
|
+
throw new OAuthError("Google no longer accepts this sign-in", "invalid_grant");
|
|
355
|
+
}
|
|
356
|
+
if (body.error === "invalid_client") {
|
|
357
|
+
throw new Error("Google does not accept the client ID and secret of your app; check them");
|
|
358
|
+
}
|
|
359
|
+
throw new Error(`Google: ${body.error_description ?? body.error ?? response.status}`);
|
|
360
|
+
}
|
|
361
|
+
return {
|
|
362
|
+
accessToken: body.access_token,
|
|
363
|
+
expiresAt: Date.now() + (body.expires_in ?? 3600) * 1000,
|
|
364
|
+
...(body.refresh_token && { refreshToken: body.refresh_token }),
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
}
|
package/src/chat.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a live chat, by asking again and again: YouTube's way to be told of new messages is gRPC,
|
|
3
|
+
* closes every ten seconds, and costs as much.
|
|
4
|
+
* https://developers.google.com/youtube/v3/live/docs/liveChatMessages/list
|
|
5
|
+
*/
|
|
6
|
+
import { type Json, QuotaError, SignedOut, type YouTubeClient, YouTubeError } from "./api.ts";
|
|
7
|
+
import { CHAT, type ChatType } from "./model.ts";
|
|
8
|
+
|
|
9
|
+
export interface ChatEvent {
|
|
10
|
+
type: ChatType;
|
|
11
|
+
item: Json;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ChatOptions {
|
|
15
|
+
client: YouTubeClient;
|
|
16
|
+
chatId: string;
|
|
17
|
+
/** At least this long between two requests. */
|
|
18
|
+
everyMs: () => number;
|
|
19
|
+
onEvent(event: ChatEvent): void;
|
|
20
|
+
onError(error: Error): void;
|
|
21
|
+
signal: AbortSignal;
|
|
22
|
+
/** The first pause after something went wrong (default 5 seconds). */
|
|
23
|
+
retryMs?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const REMEMBERED = 5000;
|
|
27
|
+
/** The chat is over, or never was. */
|
|
28
|
+
const OVER = new Set(["liveChatEnded", "liveChatDisabled", "liveChatNotFound"]);
|
|
29
|
+
/** How long to wait once the day's requests are used up. */
|
|
30
|
+
export const QUOTA_PAUSE_MS = 15 * 60_000;
|
|
31
|
+
|
|
32
|
+
export const pause = (ms: number, signal: AbortSignal) =>
|
|
33
|
+
new Promise<void>((resolve) => {
|
|
34
|
+
if (signal.aborted) return resolve();
|
|
35
|
+
const done = () => {
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
signal.removeEventListener("abort", done);
|
|
38
|
+
resolve();
|
|
39
|
+
};
|
|
40
|
+
const timer = setTimeout(done, ms);
|
|
41
|
+
signal.addEventListener("abort", done, { once: true });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/** Tells what happens from now on. Resolves when the chat ends, or on `signal`. */
|
|
45
|
+
export async function readChat(options: ChatOptions): Promise<void> {
|
|
46
|
+
const { client, chatId, everyMs, onEvent, onError, signal, retryMs = 5000 } = options;
|
|
47
|
+
const seen = new Set<string>();
|
|
48
|
+
let pageToken = "";
|
|
49
|
+
/** The first answer has what was written before, which did not happen now. */
|
|
50
|
+
let first = true;
|
|
51
|
+
let failures = 0;
|
|
52
|
+
|
|
53
|
+
while (!signal.aborted) {
|
|
54
|
+
let waitMs: number;
|
|
55
|
+
try {
|
|
56
|
+
const answer = await client.request("GET", "/liveChat/messages", {
|
|
57
|
+
liveChatId: chatId,
|
|
58
|
+
part: "id,snippet,authorDetails",
|
|
59
|
+
maxResults: "2000",
|
|
60
|
+
...(pageToken && { pageToken }),
|
|
61
|
+
});
|
|
62
|
+
if (signal.aborted) return;
|
|
63
|
+
failures = 0;
|
|
64
|
+
for (const item of (Array.isArray(answer.items) ? answer.items : []) as Json[]) {
|
|
65
|
+
const snippet = item.snippet as Json | undefined;
|
|
66
|
+
const type = String(snippet?.type);
|
|
67
|
+
if (!Object.hasOwn(CHAT, type)) continue;
|
|
68
|
+
// The same gift again, and the end of a poll, may come under the same id.
|
|
69
|
+
const gift = (snippet?.giftDetails as Json | undefined)?.comboCount ?? "";
|
|
70
|
+
const poll = (snippet?.pollDetails as Json | undefined)?.status ?? "";
|
|
71
|
+
const key = `${item.id}:${gift}:${poll}`;
|
|
72
|
+
if (seen.has(key)) continue;
|
|
73
|
+
seen.add(key);
|
|
74
|
+
if (seen.size > REMEMBERED) seen.delete(seen.values().next().value as string);
|
|
75
|
+
if (!first) onEvent({ type: type as ChatType, item });
|
|
76
|
+
}
|
|
77
|
+
first = false;
|
|
78
|
+
if (typeof answer.nextPageToken === "string") pageToken = answer.nextPageToken;
|
|
79
|
+
if (answer.offlineAt) return;
|
|
80
|
+
waitMs = Math.max(everyMs(), Number(answer.pollingIntervalMillis) || 0);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (signal.aborted) return;
|
|
83
|
+
if (error instanceof YouTubeError && OVER.has(error.reason)) return;
|
|
84
|
+
onError(error as Error);
|
|
85
|
+
if (error instanceof SignedOut) return;
|
|
86
|
+
if (error instanceof YouTubeError && error.reason === "pageTokenInvalid") {
|
|
87
|
+
pageToken = "";
|
|
88
|
+
first = true;
|
|
89
|
+
}
|
|
90
|
+
waitMs =
|
|
91
|
+
error instanceof QuotaError ? QUOTA_PAUSE_MS : Math.min(retryMs * 2 ** failures++, 60_000);
|
|
92
|
+
}
|
|
93
|
+
await pause(waitMs, signal);
|
|
94
|
+
}
|
|
95
|
+
}
|