/
twitchAddonsClient.ts
447 lines (419 loc) · 13.2 KB
/
twitchAddonsClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import fetch from "node-fetch";
import { getTokenInfo, TwitchServiceConfig, normalizeToken } from "nodecg-io-twitch-auth";
export class TwitchAddonsClient {
private readonly clientId: string;
private readonly token: string;
constructor(clientId: string, token: string) {
this.clientId = clientId;
this.token = token;
}
/**
* Gets the global emotes of BetterTTV
*/
async getBetterTTVGlobalEmotes(): Promise<BetterTTVEmote[]> {
return await (await fetch("https://api.betterttv.net/3/cached/emotes/global")).json();
}
/**
* Gets the BetterTTV channel data associated with a twitch channel or undefined if that twitch user has
* not registered for BetterTTV.
*/
async getBetterTTVChannel(channel: string): Promise<BetterTTVChannel | undefined> {
const channelId = await this.getUserId(channel);
if (channelId === undefined) {
throw new Error(`Unknown twitch channel: ${channel}`);
}
const response = await (await fetch(`https://api.betterttv.net/3/cached/users/twitch/${channelId}`)).json();
if (response.message === "user not found") {
// The user has no channel at BTTV (probably never logged in there)
return undefined;
} else if (response.message !== undefined) {
throw new Error(`Failed to get BTTV channel: ${response.message}`);
}
return response;
}
/**
* Gets the FFZ global emotes
*/
async getFFZGlobalEmotes(): Promise<FFZGlobalEmotes> {
return await (await fetch("https://api.frankerfacez.com/v1/set/global")).json();
}
/**
* Gets the FFZ channel data associated with a twitch channel or undefined if that twitch user has
* not registered for FFZ.
*/
async getFFZChannel(channel: string): Promise<FFZChannel | undefined> {
const channelId = await this.getUserId(channel);
if (channelId === undefined) {
throw new Error(`Unknown twitch channel: ${channel}`);
}
const response = await (await fetch(`https://api.frankerfacez.com/v1/room/id/${channelId}`)).json();
if (response.error !== undefined) {
if (response.message === "No such room") {
// The user has no room at FFZ (probably never logged in there)
return undefined;
} else {
throw new Error(`Failed to get FFZ channel: ${response.message}`);
}
}
return response;
}
/**
* Gets an emote collection for a channel. Here all emotes are stored so you can access all of them
* without always sending requests to the APIs and caring about undefined values. (If someone is not
* registered somewhere, there'll just be empty lists here).
*/
async getEmoteCollection(channel: string, includeGlobal: boolean): Promise<EmoteCollection> {
const bttv = await this.getBetterTTVChannel(channel);
const ffz = await this.getFFZChannel(channel);
const bttvGlobal = includeGlobal ? await this.getBetterTTVGlobalEmotes() : undefined;
const ffzGlobal = includeGlobal ? await this.getFFZGlobalEmotes() : undefined;
const ffzGlobalSets: FFZEmoteSet[] = [];
if (ffzGlobal !== undefined) {
for (const set of ffzGlobal.default_sets) {
const setObj = ffzGlobal.sets[set.toString()];
if (setObj !== undefined) {
ffzGlobalSets.push(setObj);
}
}
}
return {
bttvChannel: bttv === undefined ? [] : bttv.channelEmotes,
bttvShared: bttv === undefined ? [] : bttv.sharedEmotes,
bttvGlobal: bttvGlobal === undefined ? [] : bttvGlobal,
ffz: ffz === undefined ? [] : Object.values(ffz.sets),
ffzGlobal: ffzGlobalSets,
};
}
/**
* Gets all emote names from an emote collection.
*/
getEmoteNames(emotes: EmoteCollection): string[] {
const emotes_list: Set<string> = new Set();
for (const emote of emotes.bttvChannel) {
emotes_list.add(emote.code);
}
for (const emote of emotes.bttvShared) {
emotes_list.add(emote.code);
}
for (const set of emotes.ffz) {
for (const emote of set.emoticons) {
emotes_list.add(emote.name);
}
}
for (const emote of emotes.bttvGlobal) {
emotes_list.add(emote.code);
}
for (const set of emotes.ffzGlobal) {
for (const emote of set.emoticons) {
emotes_list.add(emote.name);
}
}
return [...emotes_list];
}
/**
* Gets the emote URL for an emote name from an emote collection. If the requested resolution is
* not available, you'll get the next available resolution that is smaller than the one you gave.
* If there's no smaller resolution, you'll get the next bigger one.
*/
async getEmoteURL(
emote: string,
emotes: EmoteCollection,
resolution: EmoteResolution,
): Promise<string | undefined> {
// BTTV has resolutions 1, 2 and 3, ffz and twitch use 1, 2, and 4
const bttvResolution = resolution === 4 ? "3" : resolution.toString();
for (const entry of emotes.bttvChannel) {
if (entry.code === emote) {
return `https://cdn.betterttv.net/emote/${entry.id}/${bttvResolution}x.${entry.imageType}`;
}
}
for (const entry of emotes.bttvShared) {
if (entry.code === emote) {
return `https://cdn.betterttv.net/emote/${entry.id}/${bttvResolution}x.${entry.imageType}`;
}
}
for (const set of emotes.ffz) {
for (const entry of set.emoticons) {
if (entry.name === emote) {
const url: FFZUrl | undefined = TwitchAddonsClient.getFFZUrl(entry.urls, resolution);
if (url !== undefined) {
return this.getURL(url);
}
}
}
}
for (const entry of emotes.bttvGlobal) {
if (entry.code === emote) {
return `https://cdn.betterttv.net/emote/${entry.id}/${bttvResolution}x.${entry.imageType}`;
}
}
for (const set of emotes.ffzGlobal) {
for (const entry of set.emoticons) {
if (entry.name === emote) {
const url: FFZUrl | undefined = TwitchAddonsClient.getFFZUrl(entry.urls, resolution);
if (url !== undefined) {
return this.getURL(url);
}
}
}
}
return undefined;
}
/**
* Gets a complete URL from a ffz URL. (This prepends `https:` to the ffz url)
* @param part
*/
getURL(part: FFZUrl): string {
return "https:" + part;
}
private async getUserId(channelId: string): Promise<string | undefined> {
const username = channelId.startsWith("#") ? channelId.substr(1) : channelId;
const response = await (
await fetch(`https://api.twitch.tv/helix/users?login=${username}`, {
headers: {
"Client-ID": this.clientId,
Authorization: `Bearer ${this.token}`,
},
})
).json();
if ((response.data as unknown[]).length > 0) {
return response.data[0].id;
} else {
return undefined;
}
}
private static getFFZUrl(urls: Record<string, FFZUrl>, resolution: EmoteResolution): FFZUrl | undefined {
for (let i = resolution; i > 0; i--) {
const resolutionStr = resolution.toString();
if (resolutionStr in urls) {
return urls[resolutionStr];
}
}
for (let i = resolution + 1; i <= 4; i++) {
const resolutionStr = resolution.toString();
if (resolutionStr in urls) {
return urls[resolutionStr];
}
}
// Should not happen...
return undefined;
}
static async createClient(config: TwitchServiceConfig): Promise<TwitchAddonsClient> {
const tokenInfo = await getTokenInfo(config);
return new TwitchAddonsClient(tokenInfo.clientId, normalizeToken(config));
}
}
/**
* The data the better twitch tv API gives for a twitch channel
*/
export type BetterTTVChannel = {
/**
* UUID used by BetterTTV for this channel
*/
id: string;
/**
* A list of names of accounts marked as bots in this channel.
*/
bots: string[];
/**
* A list of emotes that were created by this channel's owner and uploaded to BetterTTV
*/
channelEmotes: BetterTTVChannelEmote[];
/**
* A list of emotes that are not uploaded by this channel's owner but are available on this channel.
*/
sharedEmotes: BetterTTVSharedEmote[];
};
/**
* One emote from BetterTTV
*/
export type BetterTTVEmote = {
/**
* A UUID used to identify this emote
*/
id: string;
/**
* The text in chat that trigger this emote to show up
*/
code: string;
/**
* The type of the image.
*/
imageType: "png" | "gif";
};
/**
* One channel emote from BetterTTV
*/
export type BetterTTVChannelEmote = BetterTTVEmote & {
/**
* UUID of the user who created this emote. Pretty useless as it seems to be
* always the same id that is also available in BetterTTVChannel
*/
userId: string;
};
/**
* One shared emote from BetterTTV
*/
export type BetterTTVSharedEmote = BetterTTVEmote & {
/**
* The user who created this emote
*/
user: BetterTTVUser;
};
/**
* A BetterTTV user
*/
export type BetterTTVUser = {
/**
* UUID used by BetterTTV for this user
*/
id: string;
/**
* The login name of this user
*/
name: string;
/**
* The display name (name with capitalisation) of this user
*/
displayName: string;
/**
* This seems to be the helix id of the user.
*/
providerId: string;
};
/**
* A FFZ URL is always only a part of a URL. Use getURL() to get a complete URL.
*/
export type FFZUrl = string;
/**
* A channel in the FrankerFaceZ API
*/
export type FFZChannel = {
/**
* Generic information about the channel
*/
room: FFZRoom;
/**
* A record containing emote sets. The key of the record is the id of the emote set.
*/
sets: Record<string, FFZEmoteSet>;
};
/**
* Generic information abou a FFZ channel.
*/
export type FFZRoom = {
/**
* The helix id of the user
*/
twitch_id: number;
/**
* The login name of the user
*/
id: string;
/**
* I can not really say what this is and it seems to be false in most cases.
*/
is_group: boolean;
/**
* The display name (name with capitalisation) of the user
*/
display_name: string;
/**
* The custom moderator badge url.
*/
moderatorBadge: string | null;
// If anyone can tell what the next four are, please extend the type definition.
// They were always null or empty for the channels I tested it with
mod_urls: unknown;
user_badges: Record<string, unknown>;
user_badge_ids: Record<string, unknown>;
css: unknown;
};
/**
* A set of FFZ emotes
*/
export type FFZEmoteSet = {
/**
* The id of the emote set.
*/
id: number;
/**
* The title of the emote set.
*/
title: string;
// If anyone can tell what the next two are, please extend the type definition.
// They were always null or empty for the channels I tested it with
icon: unknown;
css: unknown;
emoticons: FFZEmote[];
};
/**
* One FFZ emote
*/
export type FFZEmote = {
/**
* The id of the emote
*/
id: number;
/**
* The code used in chat to display this emote
*/
name: string;
// Whatever this means. There are different resolutions anyways.
width: number;
height: number;
public: boolean;
offset: unknown;
margins: unknown;
css: unknown;
owner: FFZUser;
status: number;
usage_count: number;
// The next two are date strings
created_at: string;
last_updated: string;
/**
* URLS of the emote. The key is the resolution, which is always a number string.
*/
urls: Record<string, FFZUrl>;
};
/**
* A FFZ user
*/
export type FFZUser = {
/**
* The login name of the user
*/
name: string;
/**
* The display name (name with capitalisation) of the user
*/
display_name: string;
};
/**
* Global emotes from FFZ
*/
export type FFZGlobalEmotes = {
/**
* Contains the ids of sets that everyone can use.
*/
default_sets: number[];
/**
* The global emote sets. The key of the record is the id of the emote set.
*/
sets: Record<string, FFZEmoteSet>;
};
/**
* Contains a list of emote sets from BTTV and / or FFZ
*/
export type EmoteCollection = {
bttvChannel: BetterTTVChannelEmote[];
bttvShared: BetterTTVSharedEmote[];
bttvGlobal: BetterTTVEmote[];
ffz: FFZEmoteSet[];
ffzGlobal: FFZEmoteSet[];
};
/**
* Resolution of an emote image
*/
export type EmoteResolution = 1 | 2 | 4;