@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/model.ts
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/** What the API says, in the form the plugin uses. */
|
|
2
|
+
|
|
3
|
+
type Raw = Record<string, unknown> | undefined;
|
|
4
|
+
|
|
5
|
+
const text = (value: unknown) => (typeof value === "string" ? value : "");
|
|
6
|
+
const part = (value: unknown, name: string) => (value as Raw)?.[name] as Raw;
|
|
7
|
+
/** The API writes most numbers as text. Nothing when there is none, as for a hidden count. */
|
|
8
|
+
const maybe = (value: unknown): number | undefined =>
|
|
9
|
+
value === undefined || value === null || value === "" || !Number.isFinite(Number(value))
|
|
10
|
+
? undefined
|
|
11
|
+
: Number(value);
|
|
12
|
+
const count = (value: unknown) => maybe(value) ?? 0;
|
|
13
|
+
|
|
14
|
+
// -- The stream ---------------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
export interface Stream {
|
|
17
|
+
live: boolean;
|
|
18
|
+
/** Of the video, which is also the broadcast. */
|
|
19
|
+
id: string;
|
|
20
|
+
title: string;
|
|
21
|
+
/** Empty when chat is off. */
|
|
22
|
+
chatId: string;
|
|
23
|
+
/** When it went live (ms since 1970), or 0. */
|
|
24
|
+
startedAt: number;
|
|
25
|
+
/** 0 also when the channel hides it. */
|
|
26
|
+
viewers: number;
|
|
27
|
+
/** Nothing when the channel hides them. */
|
|
28
|
+
likes: number | undefined;
|
|
29
|
+
views: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const OFFLINE: Stream = {
|
|
33
|
+
live: false,
|
|
34
|
+
id: "",
|
|
35
|
+
title: "",
|
|
36
|
+
chatId: "",
|
|
37
|
+
startedAt: 0,
|
|
38
|
+
viewers: 0,
|
|
39
|
+
likes: undefined,
|
|
40
|
+
views: 0,
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** Reads the video of a broadcast that was live. */
|
|
44
|
+
export function parseStream(video: Raw): Stream {
|
|
45
|
+
const details = part(video, "liveStreamingDetails");
|
|
46
|
+
if (!video || details?.actualEndTime) return OFFLINE;
|
|
47
|
+
const statistics = part(video, "statistics");
|
|
48
|
+
return {
|
|
49
|
+
live: true,
|
|
50
|
+
id: text(video.id),
|
|
51
|
+
title: text(part(video, "snippet")?.title),
|
|
52
|
+
chatId: text(details?.activeLiveChatId),
|
|
53
|
+
startedAt: Date.parse(text(details?.actualStartTime)) || 0,
|
|
54
|
+
viewers: count(details?.concurrentViewers),
|
|
55
|
+
likes: maybe(statistics?.likeCount),
|
|
56
|
+
views: count(statistics?.viewCount),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface Broadcast {
|
|
61
|
+
id: string;
|
|
62
|
+
title: string;
|
|
63
|
+
status: string;
|
|
64
|
+
/** When it went live, or is to (ms since 1970). */
|
|
65
|
+
at: number;
|
|
66
|
+
/** The video it gets: see `GET /liveStreams`. */
|
|
67
|
+
streamId: string;
|
|
68
|
+
/** It has to be in preview before it can go live. */
|
|
69
|
+
preview: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function parseBroadcast(raw: Raw): Broadcast {
|
|
73
|
+
const snippet = part(raw, "snippet");
|
|
74
|
+
const details = part(raw, "contentDetails");
|
|
75
|
+
return {
|
|
76
|
+
id: text(raw?.id),
|
|
77
|
+
title: text(snippet?.title),
|
|
78
|
+
status: text(part(raw, "status")?.lifeCycleStatus),
|
|
79
|
+
at: Date.parse(text(snippet?.actualStartTime) || text(snippet?.scheduledStartTime)) || 0,
|
|
80
|
+
streamId: text(details?.boundStreamId),
|
|
81
|
+
preview: part(details, "monitorStream")?.enableMonitorStream === true,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The one that went live last, of those that are live. */
|
|
86
|
+
export const newestLive = (broadcasts: readonly Broadcast[]): Broadcast | undefined =>
|
|
87
|
+
broadcasts.filter((b) => b.status === "live").sort((a, b) => b.at - a.at)[0];
|
|
88
|
+
|
|
89
|
+
export interface Health {
|
|
90
|
+
receiving: boolean;
|
|
91
|
+
/** `Good`, `OK`, `Bad`, `No data`; or `Offline`. */
|
|
92
|
+
name: string;
|
|
93
|
+
/** The worst problem YouTube sees. */
|
|
94
|
+
problem: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const HEALTH: Record<string, string> = { good: "Good", ok: "OK", bad: "Bad", noData: "No data" };
|
|
98
|
+
const SEVERITY = ["info", "warning", "error"];
|
|
99
|
+
|
|
100
|
+
export const isActive = (stream: Raw) => part(stream, "status")?.streamStatus === "active";
|
|
101
|
+
|
|
102
|
+
export function parseHealth(streams: readonly Raw[]): Health {
|
|
103
|
+
const health = part(part(streams.find(isActive), "status"), "healthStatus");
|
|
104
|
+
if (!streams.some(isActive)) return { receiving: false, name: "Offline", problem: "" };
|
|
105
|
+
const issues = (Array.isArray(health?.configurationIssues) ? health.configurationIssues : [])
|
|
106
|
+
.map((issue: Raw) => ({
|
|
107
|
+
rank: SEVERITY.indexOf(text(issue?.severity)),
|
|
108
|
+
reason: text(issue?.reason) || text(issue?.description),
|
|
109
|
+
}))
|
|
110
|
+
.filter(({ rank }) => rank > 0)
|
|
111
|
+
.sort((a, b) => b.rank - a.rank);
|
|
112
|
+
return {
|
|
113
|
+
receiving: true,
|
|
114
|
+
name: HEALTH[text(health?.status)] ?? "No data",
|
|
115
|
+
problem: issues[0]?.reason ?? "",
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// -- The channel --------------------------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
export interface Channel {
|
|
122
|
+
id: string;
|
|
123
|
+
name: string;
|
|
124
|
+
subscribers: number;
|
|
125
|
+
views: number;
|
|
126
|
+
videos: number;
|
|
127
|
+
/** The playlist with everything it uploaded. */
|
|
128
|
+
uploads: string;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function parseChannel(raw: Raw): Channel {
|
|
132
|
+
const statistics = part(raw, "statistics");
|
|
133
|
+
return {
|
|
134
|
+
id: text(raw?.id),
|
|
135
|
+
name: text(part(raw, "snippet")?.title),
|
|
136
|
+
subscribers: count(statistics?.subscriberCount),
|
|
137
|
+
views: count(statistics?.viewCount),
|
|
138
|
+
videos: count(statistics?.videoCount),
|
|
139
|
+
uploads: text(part(part(raw, "contentDetails"), "relatedPlaylists")?.uploads),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface Video {
|
|
144
|
+
id: string;
|
|
145
|
+
title: string;
|
|
146
|
+
views: number;
|
|
147
|
+
likes: number | undefined;
|
|
148
|
+
comments: number | undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The newest one that everyone can watch, and that is not a stream still to come or going on. */
|
|
152
|
+
export function newestVideo(videos: readonly Raw[]): Video | undefined {
|
|
153
|
+
const at = (video: Raw) => Date.parse(text(part(video, "snippet")?.publishedAt)) || 0;
|
|
154
|
+
const video = videos
|
|
155
|
+
.filter(
|
|
156
|
+
(v) =>
|
|
157
|
+
part(v, "status")?.privacyStatus === "public" &&
|
|
158
|
+
part(v, "snippet")?.liveBroadcastContent === "none",
|
|
159
|
+
)
|
|
160
|
+
.sort((a, b) => at(b) - at(a))[0];
|
|
161
|
+
if (!video) return undefined;
|
|
162
|
+
const statistics = part(video, "statistics");
|
|
163
|
+
return {
|
|
164
|
+
id: text(video.id),
|
|
165
|
+
title: text(part(video, "snippet")?.title),
|
|
166
|
+
views: count(statistics?.viewCount),
|
|
167
|
+
likes: maybe(statistics?.likeCount),
|
|
168
|
+
comments: maybe(statistics?.commentCount),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* What is new at the top of a list that has the newest first, oldest of them first. Something known
|
|
174
|
+
* ends it: when that goes away, older things move up, and they are not new.
|
|
175
|
+
*/
|
|
176
|
+
export function newAtTop<T extends { id: string }>(
|
|
177
|
+
items: readonly T[],
|
|
178
|
+
known: ReadonlySet<string>,
|
|
179
|
+
): T[] {
|
|
180
|
+
const end = items.findIndex((item) => known.has(item.id));
|
|
181
|
+
return items.slice(0, end < 0 ? items.length : end).reverse();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export const parseSubscriber = (raw: Raw) => {
|
|
185
|
+
const who = part(raw, "subscriberSnippet");
|
|
186
|
+
return { id: text(who?.channelId), user: text(who?.title), channelId: text(who?.channelId) };
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export function parseComment(raw: Raw) {
|
|
190
|
+
const snippet = part(raw, "snippet");
|
|
191
|
+
const comment = part(part(snippet, "topLevelComment"), "snippet");
|
|
192
|
+
const id = text(raw?.id);
|
|
193
|
+
const videoId = text(snippet?.videoId);
|
|
194
|
+
return {
|
|
195
|
+
id,
|
|
196
|
+
user: text(comment?.authorDisplayName),
|
|
197
|
+
channelId: text(part(comment, "authorChannelId")?.value),
|
|
198
|
+
text: text(comment?.textOriginal) || text(comment?.textDisplay),
|
|
199
|
+
videoId,
|
|
200
|
+
url: `https://www.youtube.com/watch?v=${videoId}&lc=${id}`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// -- Text ---------------------------------------------------------------------------------------
|
|
205
|
+
|
|
206
|
+
/** `3725` → `1:02:05`, `65` → `1:05`. */
|
|
207
|
+
export function formatDuration(seconds: number): string {
|
|
208
|
+
const s = Math.max(0, Math.floor(seconds));
|
|
209
|
+
const two = (n: number) => String(n).padStart(2, "0");
|
|
210
|
+
const hours = Math.floor(s / 3600);
|
|
211
|
+
const minutes = Math.floor((s % 3600) / 60);
|
|
212
|
+
return hours > 0 ? `${hours}:${two(minutes)}:${two(s % 60)}` : `${minutes}:${two(s % 60)}`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const CHAPTER = /^(?:\d+:)?\d{1,2}:\d{2}\s/;
|
|
216
|
+
|
|
217
|
+
/** `1:02:05 Win` → `3725`. */
|
|
218
|
+
const chapterSeconds = (line: string) =>
|
|
219
|
+
(line.split(/\s/)[0] ?? "").split(":").reduce((sum, n) => sum * 60 + Number(n), 0);
|
|
220
|
+
|
|
221
|
+
/** Adds a chapter among the others. YouTube wants them in order, and the first at 0:00. */
|
|
222
|
+
export function addChapter(description: string, line: string): string {
|
|
223
|
+
const lines = description.split("\n");
|
|
224
|
+
const last = lines.findLastIndex((l) => CHAPTER.test(l));
|
|
225
|
+
if (last < 0) {
|
|
226
|
+
const before = description.trimEnd();
|
|
227
|
+
return `${before}${before && "\n\n"}0:00 Start\n${line}`;
|
|
228
|
+
}
|
|
229
|
+
const at = chapterSeconds(line);
|
|
230
|
+
const later = lines.findIndex((l) => CHAPTER.test(l) && chapterSeconds(l) > at);
|
|
231
|
+
return lines.toSpliced(later < 0 ? last + 1 : later, 0, line).join("\n");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Takes out a chapter that {@link addChapter} added, and the start if it is the only one left. */
|
|
235
|
+
export function removeChapter(description: string, line: string): string {
|
|
236
|
+
const lines = description.split("\n");
|
|
237
|
+
const at = lines.lastIndexOf(line);
|
|
238
|
+
if (at < 0) return description;
|
|
239
|
+
const rest = lines.toSpliced(at, 1);
|
|
240
|
+
const others = rest.filter((l) => CHAPTER.test(l));
|
|
241
|
+
return others.length === 1 && others[0] === "0:00 Start"
|
|
242
|
+
? rest
|
|
243
|
+
.filter((l) => l !== "0:00 Start")
|
|
244
|
+
.join("\n")
|
|
245
|
+
.trimEnd()
|
|
246
|
+
: rest.join("\n");
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// -- Chat ---------------------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
export type Role = "everyone" | "member" | "moderator" | "owner";
|
|
252
|
+
const RANKS: readonly Role[] = ["everyone", "member", "moderator", "owner"];
|
|
253
|
+
|
|
254
|
+
/** Whether someone who is `mine` may do what `wanted` may. */
|
|
255
|
+
export const hasRole = (mine: Role, wanted: Role) => RANKS.indexOf(mine) >= RANKS.indexOf(wanted);
|
|
256
|
+
|
|
257
|
+
/** What follows `command` in a chat message, or `undefined` if the message is not that command. */
|
|
258
|
+
export function commandWords(message: string, command: string): string | undefined {
|
|
259
|
+
const wanted = command.trim().toLowerCase();
|
|
260
|
+
const said = message.trim();
|
|
261
|
+
if (!wanted || !said.toLowerCase().startsWith(wanted)) return undefined;
|
|
262
|
+
const rest = said.slice(wanted.length);
|
|
263
|
+
return rest === "" || /^\s/.test(rest) ? rest.trim() : undefined;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export interface Poll {
|
|
267
|
+
id: string;
|
|
268
|
+
question: string;
|
|
269
|
+
options: { text: string; votes: number }[];
|
|
270
|
+
votes: number;
|
|
271
|
+
/** The option with the most votes; empty when nobody voted, or it is a draw. */
|
|
272
|
+
winner: string;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function parsePoll(raw: Raw): Poll {
|
|
276
|
+
const metadata = part(part(part(raw, "snippet"), "pollDetails"), "metadata");
|
|
277
|
+
const options = (Array.isArray(metadata?.options) ? metadata.options : []).map((o: Raw) => ({
|
|
278
|
+
text: text(o?.optionText),
|
|
279
|
+
votes: count(o?.tally),
|
|
280
|
+
}));
|
|
281
|
+
const most = Math.max(0, ...options.map((o) => o.votes));
|
|
282
|
+
const best = options.filter((o) => o.votes === most);
|
|
283
|
+
return {
|
|
284
|
+
id: text(raw?.id),
|
|
285
|
+
question: text(metadata?.questionText),
|
|
286
|
+
options,
|
|
287
|
+
votes: options.reduce((sum, o) => sum + o.votes, 0),
|
|
288
|
+
winner: most > 0 && best.length === 1 ? (best[0]?.text ?? "") : "",
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Who did it, and the message it came with, for acting on either. */
|
|
293
|
+
function person(raw: Raw) {
|
|
294
|
+
const who = part(raw, "authorDetails");
|
|
295
|
+
return {
|
|
296
|
+
user: text(who?.displayName),
|
|
297
|
+
channelId: text(who?.channelId),
|
|
298
|
+
messageId: text(raw?.id),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const details = (raw: Raw, name: string) => part(part(raw, "snippet"), name);
|
|
303
|
+
|
|
304
|
+
const money = (raw: Raw) => ({
|
|
305
|
+
amount: count(raw?.amountMicros) / 1e6,
|
|
306
|
+
currency: text(raw?.currency),
|
|
307
|
+
amountText: text(raw?.amountDisplayString),
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
/** What the triggers give as `event`, by YouTube's type of message. */
|
|
311
|
+
export const CHAT = {
|
|
312
|
+
textMessageEvent: (raw: Raw) => {
|
|
313
|
+
const who = part(raw, "authorDetails");
|
|
314
|
+
const role: Role = who?.isChatOwner
|
|
315
|
+
? "owner"
|
|
316
|
+
: who?.isChatModerator
|
|
317
|
+
? "moderator"
|
|
318
|
+
: who?.isChatSponsor
|
|
319
|
+
? "member"
|
|
320
|
+
: "everyone";
|
|
321
|
+
return { ...person(raw), message: text(details(raw, "textMessageDetails")?.messageText), role };
|
|
322
|
+
},
|
|
323
|
+
superChatEvent: (raw: Raw) => {
|
|
324
|
+
const chat = details(raw, "superChatDetails");
|
|
325
|
+
return { ...person(raw), ...money(chat), message: text(chat?.userComment), sticker: false };
|
|
326
|
+
},
|
|
327
|
+
superStickerEvent: (raw: Raw) => {
|
|
328
|
+
const sticker = details(raw, "superStickerDetails");
|
|
329
|
+
const message = text(part(sticker, "superStickerMetadata")?.altText);
|
|
330
|
+
return { ...person(raw), ...money(sticker), message, sticker: true };
|
|
331
|
+
},
|
|
332
|
+
newSponsorEvent: (raw: Raw) => {
|
|
333
|
+
const member = details(raw, "newSponsorDetails");
|
|
334
|
+
return {
|
|
335
|
+
...person(raw),
|
|
336
|
+
level: text(member?.memberLevelName),
|
|
337
|
+
upgrade: member?.isUpgrade === true,
|
|
338
|
+
};
|
|
339
|
+
},
|
|
340
|
+
memberMilestoneChatEvent: (raw: Raw) => {
|
|
341
|
+
const member = details(raw, "memberMilestoneChatDetails");
|
|
342
|
+
return {
|
|
343
|
+
...person(raw),
|
|
344
|
+
level: text(member?.memberLevelName),
|
|
345
|
+
months: count(member?.memberMonth),
|
|
346
|
+
message: text(member?.userComment),
|
|
347
|
+
};
|
|
348
|
+
},
|
|
349
|
+
membershipGiftingEvent: (raw: Raw) => {
|
|
350
|
+
const gift = details(raw, "membershipGiftingDetails");
|
|
351
|
+
return {
|
|
352
|
+
...person(raw),
|
|
353
|
+
total: count(gift?.giftMembershipsCount),
|
|
354
|
+
level: text(gift?.giftMembershipsLevelName),
|
|
355
|
+
};
|
|
356
|
+
},
|
|
357
|
+
giftEvent: (raw: Raw) => {
|
|
358
|
+
const gift = details(raw, "giftDetails");
|
|
359
|
+
return {
|
|
360
|
+
...person(raw),
|
|
361
|
+
gift: text(gift?.giftName),
|
|
362
|
+
jewels: count(gift?.jewelsAmount),
|
|
363
|
+
combo: count(gift?.comboCount),
|
|
364
|
+
};
|
|
365
|
+
},
|
|
366
|
+
pollEvent: (raw: Raw) => {
|
|
367
|
+
const { question, winner, votes } = parsePoll(raw);
|
|
368
|
+
return {
|
|
369
|
+
question,
|
|
370
|
+
winner,
|
|
371
|
+
votes,
|
|
372
|
+
closed: details(raw, "pollDetails")?.status === "closed",
|
|
373
|
+
};
|
|
374
|
+
},
|
|
375
|
+
} as const;
|
|
376
|
+
|
|
377
|
+
export type ChatType = keyof typeof CHAT;
|
|
378
|
+
export type ChatData<T extends ChatType> = ReturnType<(typeof CHAT)[T]>;
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's connection to YouTube, and the channel's values while something uses them. An app may
|
|
3
|
+
* use 10,000 units a day; reading costs 1, a look at the chat 5, and most changes 50. So nothing is
|
|
4
|
+
* read that nobody looks at, and slowly.
|
|
5
|
+
*/
|
|
6
|
+
import { createPlugin, Permissions, Shared, setting } from "@sdeck/plugin";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { type Json, QuotaError, SCOPES, SignedOut, type SignIn, YouTubeClient } from "./api.ts";
|
|
9
|
+
import { type ChatEvent, QUOTA_PAUSE_MS, readChat } from "./chat.ts";
|
|
10
|
+
import {
|
|
11
|
+
newestLive,
|
|
12
|
+
newestVideo,
|
|
13
|
+
OFFLINE,
|
|
14
|
+
parseBroadcast,
|
|
15
|
+
parseChannel,
|
|
16
|
+
parseComment,
|
|
17
|
+
parseHealth,
|
|
18
|
+
parseStream,
|
|
19
|
+
parseSubscriber,
|
|
20
|
+
type Stream,
|
|
21
|
+
} from "./model.ts";
|
|
22
|
+
|
|
23
|
+
export const plugin = createPlugin({
|
|
24
|
+
id: "@sdeck/youtube",
|
|
25
|
+
name: "YouTube",
|
|
26
|
+
version: "1.0.1",
|
|
27
|
+
description:
|
|
28
|
+
"Run your YouTube channel: go live, chat, polls, ads, markers and goals, with live values and triggers.",
|
|
29
|
+
permissions: [Permissions.network],
|
|
30
|
+
settings: {
|
|
31
|
+
clientId: setting.text("Client ID of your own app", {
|
|
32
|
+
description:
|
|
33
|
+
"To use an app of your own instead of sdeck's, with a daily limit of its own. Sign in again after changing it.",
|
|
34
|
+
validate: z
|
|
35
|
+
.string()
|
|
36
|
+
.trim()
|
|
37
|
+
.regex(/\.apps\.googleusercontent\.com$/, "should end in .apps.googleusercontent.com"),
|
|
38
|
+
}),
|
|
39
|
+
clientSecret: setting.secret("Client secret of your own app"),
|
|
40
|
+
chatSeconds: setting.number("Seconds between looks at the chat", {
|
|
41
|
+
default: 10,
|
|
42
|
+
min: 3,
|
|
43
|
+
max: 120,
|
|
44
|
+
description:
|
|
45
|
+
"For triggers. Each look costs 5 of the 10,000 units an app has a day: every 10 seconds is enough for 5½ hours, every 20 for 11.",
|
|
46
|
+
}),
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const TOKEN = "refreshToken";
|
|
51
|
+
|
|
52
|
+
function running() {
|
|
53
|
+
if (!plugin.context) throw new Error("the YouTube plugin is off");
|
|
54
|
+
return plugin.context;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const youtube = new YouTubeClient({
|
|
58
|
+
app: () => {
|
|
59
|
+
const { clientId = "", clientSecret = "" } = plugin.context?.settings() ?? {};
|
|
60
|
+
const id = clientId.trim();
|
|
61
|
+
return id ? { clientId: id, clientSecret: clientSecret.trim() } : undefined;
|
|
62
|
+
},
|
|
63
|
+
broker: {
|
|
64
|
+
start: () => running().oauth.start("youtube", { scopes: SCOPES }),
|
|
65
|
+
refresh: (token) => running().oauth.refresh("youtube", token),
|
|
66
|
+
},
|
|
67
|
+
tokens: {
|
|
68
|
+
get: () => plugin.context?.secrets.get(TOKEN),
|
|
69
|
+
set: async (token) => {
|
|
70
|
+
await plugin.context?.secrets.set(TOKEN, token);
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
/** Whether the status says what went wrong. */
|
|
76
|
+
let trouble = false;
|
|
77
|
+
function report(error?: Error) {
|
|
78
|
+
if (error) {
|
|
79
|
+
trouble = true;
|
|
80
|
+
plugin.context?.status(error.message, error instanceof SignedOut ? "info" : "error");
|
|
81
|
+
} else if (trouble) {
|
|
82
|
+
trouble = false;
|
|
83
|
+
plugin.context?.status("Signed in to YouTube", "ok");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// -- The channel's values -----------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
const refreshers = new Set<() => void>();
|
|
90
|
+
|
|
91
|
+
/** Something read again and again while it is used, and at once after `refresh`. */
|
|
92
|
+
function polled<T>(everyMs: (value: T | undefined) => number, readNow: () => Promise<T>) {
|
|
93
|
+
let again: () => void = () => {};
|
|
94
|
+
const shared = new Shared<T | undefined>((emit) => {
|
|
95
|
+
let stopped = false;
|
|
96
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
97
|
+
/** The newest reading; an older one that answers later is not used. */
|
|
98
|
+
let latest = 0;
|
|
99
|
+
const tick = async () => {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
const mine = ++latest;
|
|
102
|
+
let value: T | undefined;
|
|
103
|
+
let waitMs: number | undefined;
|
|
104
|
+
try {
|
|
105
|
+
value = await readNow();
|
|
106
|
+
if (stopped || mine !== latest) return;
|
|
107
|
+
report();
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (stopped || mine !== latest) return;
|
|
110
|
+
report(error as Error);
|
|
111
|
+
if (error instanceof QuotaError) waitMs = QUOTA_PAUSE_MS;
|
|
112
|
+
}
|
|
113
|
+
timer = setTimeout(tick, waitMs ?? everyMs(value));
|
|
114
|
+
emit(value);
|
|
115
|
+
};
|
|
116
|
+
const mine = () => void tick();
|
|
117
|
+
again = mine;
|
|
118
|
+
refreshers.add(mine);
|
|
119
|
+
mine();
|
|
120
|
+
return () => {
|
|
121
|
+
stopped = true;
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
refreshers.delete(mine);
|
|
124
|
+
again = () => {};
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
return { shared, refresh: () => again() };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The stream that is live. Its video has everything, once it is known which that is. */
|
|
131
|
+
export async function readStream(known = ""): Promise<Stream> {
|
|
132
|
+
const read = async (id: string) =>
|
|
133
|
+
parseStream(
|
|
134
|
+
(await youtube.list("/videos", { part: "snippet,statistics,liveStreamingDetails", id }))[0],
|
|
135
|
+
);
|
|
136
|
+
if (known) {
|
|
137
|
+
const stream = await read(known);
|
|
138
|
+
if (stream.live) return stream;
|
|
139
|
+
}
|
|
140
|
+
const found = await youtube.list("/liveBroadcasts", {
|
|
141
|
+
part: "id,snippet,status",
|
|
142
|
+
broadcastStatus: "active",
|
|
143
|
+
broadcastType: "all",
|
|
144
|
+
maxResults: "50",
|
|
145
|
+
});
|
|
146
|
+
const live = newestLive(found.map(parseBroadcast));
|
|
147
|
+
return live ? read(live.id) : OFFLINE;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export const stream: { shared: Shared<Stream | undefined>; refresh: () => void } = polled<Stream>(
|
|
151
|
+
(now) => (now?.live ? 30_000 : 60_000),
|
|
152
|
+
() => readStream(stream.shared.last?.id),
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
/** The stream, for what only works while live. */
|
|
156
|
+
export async function liveStream(): Promise<Stream> {
|
|
157
|
+
const known = stream.shared.last;
|
|
158
|
+
const now = known?.live ? known : await readStream();
|
|
159
|
+
if (!now.live) throw new Error("this only works while you are live");
|
|
160
|
+
return now;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** As {@link liveStream}, for what needs its chat. */
|
|
164
|
+
export async function liveChat(): Promise<string> {
|
|
165
|
+
const { chatId } = await liveStream();
|
|
166
|
+
if (!chatId) throw new Error("chat is turned off for this stream");
|
|
167
|
+
return chatId;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function readChannel() {
|
|
171
|
+
const [own] = await youtube.list("/channels", {
|
|
172
|
+
part: "snippet,statistics,contentDetails",
|
|
173
|
+
mine: "true",
|
|
174
|
+
});
|
|
175
|
+
if (!own) throw new Error("this Google account has no YouTube channel");
|
|
176
|
+
return parseChannel(own);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export const channel = polled(() => 5 * 60_000, readChannel);
|
|
180
|
+
|
|
181
|
+
/** Every encoder setup the channel has. */
|
|
182
|
+
export const readEncoders = () =>
|
|
183
|
+
youtube.list("/liveStreams", { part: "id,status", mine: "true", maxResults: "50" });
|
|
184
|
+
|
|
185
|
+
export const health = polled(
|
|
186
|
+
() => 30_000,
|
|
187
|
+
async () => parseHealth(await readEncoders()),
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
const ownChannel = async () => channel.shared.last ?? (await readChannel());
|
|
191
|
+
|
|
192
|
+
export const video = polled(
|
|
193
|
+
() => 5 * 60_000,
|
|
194
|
+
async () => {
|
|
195
|
+
const { uploads } = await ownChannel();
|
|
196
|
+
const items = await youtube.list("/playlistItems", {
|
|
197
|
+
part: "contentDetails",
|
|
198
|
+
playlistId: uploads,
|
|
199
|
+
maxResults: "15",
|
|
200
|
+
});
|
|
201
|
+
const ids = items.map((item) => (item.contentDetails as Json | undefined)?.videoId);
|
|
202
|
+
if (ids.length === 0) return undefined;
|
|
203
|
+
return newestVideo(
|
|
204
|
+
await youtube.list("/videos", { part: "snippet,statistics,status", id: ids.join(",") }),
|
|
205
|
+
);
|
|
206
|
+
},
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
/** Newest first. Only people who show their subscriptions to everyone. */
|
|
210
|
+
export const subscribers = polled(
|
|
211
|
+
() => 2 * 60_000,
|
|
212
|
+
async () => {
|
|
213
|
+
const found = await youtube.list("/subscriptions", {
|
|
214
|
+
part: "subscriberSnippet",
|
|
215
|
+
myRecentSubscribers: "true",
|
|
216
|
+
maxResults: "50",
|
|
217
|
+
});
|
|
218
|
+
return found.map(parseSubscriber).filter(({ id }) => id);
|
|
219
|
+
},
|
|
220
|
+
);
|
|
221
|
+
|
|
222
|
+
/** On the channel's videos, newest first, without its own. */
|
|
223
|
+
export const comments = polled(
|
|
224
|
+
() => 2 * 60_000,
|
|
225
|
+
async () => {
|
|
226
|
+
const { id } = await ownChannel();
|
|
227
|
+
const found = await youtube.list("/commentThreads", {
|
|
228
|
+
part: "snippet",
|
|
229
|
+
allThreadsRelatedToChannelId: id,
|
|
230
|
+
order: "time",
|
|
231
|
+
maxResults: "50",
|
|
232
|
+
});
|
|
233
|
+
return found.map(parseComment).filter(({ channelId }) => channelId !== id);
|
|
234
|
+
},
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
// -- Chat ---------------------------------------------------------------------------------------
|
|
238
|
+
|
|
239
|
+
let restartChat: () => void = () => {};
|
|
240
|
+
|
|
241
|
+
/** What happens in the chat of the stream, whenever there is one. */
|
|
242
|
+
export const chat = new Shared<ChatEvent>((emit) => {
|
|
243
|
+
let reading: { id: string; stop: AbortController } | undefined;
|
|
244
|
+
const stopReading = () => {
|
|
245
|
+
reading?.stop.abort();
|
|
246
|
+
reading = undefined;
|
|
247
|
+
};
|
|
248
|
+
const follow = (now: Stream | undefined) => {
|
|
249
|
+
// Not known just now: it is probably still going on.
|
|
250
|
+
if (!now || now.chatId === (reading?.id ?? "")) return;
|
|
251
|
+
stopReading();
|
|
252
|
+
if (!now.chatId) return;
|
|
253
|
+
const stop = new AbortController();
|
|
254
|
+
reading = { id: now.chatId, stop };
|
|
255
|
+
void readChat({
|
|
256
|
+
client: youtube,
|
|
257
|
+
chatId: now.chatId,
|
|
258
|
+
everyMs: () => (plugin.context?.settings().chatSeconds ?? 10) * 1000,
|
|
259
|
+
onEvent: emit,
|
|
260
|
+
onError: report,
|
|
261
|
+
signal: stop.signal,
|
|
262
|
+
}).then(() => {
|
|
263
|
+
if (!stop.signal.aborted) stream.refresh();
|
|
264
|
+
});
|
|
265
|
+
};
|
|
266
|
+
restartChat = stopReading;
|
|
267
|
+
const stopFollowing = stream.shared.listen(follow);
|
|
268
|
+
follow(stream.shared.last);
|
|
269
|
+
return () => {
|
|
270
|
+
stopFollowing();
|
|
271
|
+
stopReading();
|
|
272
|
+
restartChat = () => {};
|
|
273
|
+
};
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
// -- Signing in ---------------------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
let signingIn: SignIn | undefined;
|
|
279
|
+
|
|
280
|
+
/** Reads everything again: someone else may be signed in. */
|
|
281
|
+
function startOver() {
|
|
282
|
+
restartChat();
|
|
283
|
+
for (const refresh of [...refreshers]) refresh();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export const signIn = plugin.command({
|
|
287
|
+
id: "sign-in",
|
|
288
|
+
name: "Sign in",
|
|
289
|
+
description: "Opens Google in your browser to allow access.",
|
|
290
|
+
run: async (context) => {
|
|
291
|
+
signingIn?.cancel();
|
|
292
|
+
const started = await youtube.signIn();
|
|
293
|
+
signingIn = started;
|
|
294
|
+
context.status("Allow access in the browser", "info");
|
|
295
|
+
started.done.then(
|
|
296
|
+
() => {
|
|
297
|
+
trouble = false;
|
|
298
|
+
context.status("Signed in to YouTube", "ok");
|
|
299
|
+
startOver();
|
|
300
|
+
},
|
|
301
|
+
(error: Error) => {
|
|
302
|
+
if (signingIn === started) context.status(error.message, "error");
|
|
303
|
+
},
|
|
304
|
+
);
|
|
305
|
+
return started.url;
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
export const signOut = plugin.command({
|
|
310
|
+
id: "sign-out",
|
|
311
|
+
name: "Sign out",
|
|
312
|
+
run: async (context) => {
|
|
313
|
+
signingIn?.cancel();
|
|
314
|
+
signingIn = undefined;
|
|
315
|
+
await youtube.signOut();
|
|
316
|
+
startOver();
|
|
317
|
+
context.status("Signed out", "info");
|
|
318
|
+
},
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
export const isSignedIn = () => youtube.signedIn;
|
|
322
|
+
|
|
323
|
+
export function stopAll() {
|
|
324
|
+
signingIn?.cancel();
|
|
325
|
+
signingIn = undefined;
|
|
326
|
+
}
|