-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTwitchScript.js
More file actions
2088 lines (1856 loc) · 84.9 KB
/
TwitchScript.js
File metadata and controls
2088 lines (1856 loc) · 84.9 KB
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//* Constants
const BASE_URL = 'https://www.twitch.tv/'
const GQL_URL = 'https://gql.twitch.tv/gql#origin=twilight'
const PLATFORM = 'Twitch'
// Twitch web client identity. Mimicking these values makes usher.ttvnw.net
// return ad-free manifests that a real-browser visit would get.
// Refresh periodically
const CLIENT_ID = 'ue6666qo983tsx6so1t0vnawi233wa' // old: kimne78kx3ncx6brgo4mv6wki5h1ko
const TWITCH_CLIENT_VERSION = 'e3516258-d65a-44d0-9562-6a0288a94079';
const TWITCH_PLAYER_VERSION = '1.52.0-rc.1';
const ACMB_VALUE = btoa(JSON.stringify({ AppVersion: TWITCH_CLIENT_VERSION, ClientApp: 'web' }));
const PLATFORM_CLAIMTYPE = 14;
const IS_DESKTOP = bridge.buildPlatform === "desktop";
const USER_AGENT_FALLBACK = IS_DESKTOP
? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.200 Safari/537.36'
: 'Mozilla/5.0 (Linux; Android 16) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.7559.133 Mobile Safari/537.36';
const getUserAgent = () => bridge.authUserAgent ?? bridge.captchaUserAgent ?? USER_AGENT_FALLBACK;
const IS_IMPERSONATION_AVAILABLE = typeof httpimp !== 'undefined';
const IMPERSONATION_TARGET = IS_DESKTOP ? 'chrome136' : 'chrome131_android';
const OLD_REGEX_URL_VIDEO_DETAILS = /^https?:\/\/(www\.|m\.)?twitch\.tv\/videos\/(\d+)(\?.*)?$/
const REGEX_URL_VIDEO_DETAILS = /^https?:\/\/(www\.|m\.)?twitch\.tv\/[a-zA-Z0-9-_]+\/video\/(\d+)(\?.*)?$/
const REGEX_URL_CHANNEL = /^https?:\/\/(?:www\.|m\.)?twitch\.tv\/(?!login|signup|directory|p\/|search|settings|subscriptions|inventory|friends|help|jobs|partner|moderation|store|bits|subs|creators|ads|extensions|prime|giftcard|turbo)([a-zA-Z0-9-_]+)(?:[?/].*)?$/;
const REGEX_URL_CHANNEL_CLIPS_FILTER = /^https?:\/\/(www\.|m\.)?twitch\.tv\/[a-zA-Z0-9_-]+\/clips\/?\?.*$/
const REGEX_URL_CLIP_DETAILS_LIST = [
// Matches embedded clip URLs like https://clips.twitch.tv/embed?clip=clip-id
/^https?:\/\/(www\.)?clips\.twitch\.tv\/embed\?clip=([a-zA-Z0-9_-]+)(&.*)?$/,
// Matches URLs like https://clips.twitch.tv/clip-id
/^https?:\/\/(www\.)?clips\.twitch\.tv\/([a-zA-Z0-9_-]+)(\?.*)?$/,
// Matches URLs like https://www.twitch.tv/user-id/clip/clip-id or https://m.twitch.tv/user-id/clip/clip-id
/^https?:\/\/(www\.|m\.)?twitch\.tv\/[a-zA-Z0-9_-]+\/clip\/([a-zA-Z0-9_-]+)(\?.*)?$/,
// Matches URLs like https://www.twitch.tv/clip/clip-id or https://m.twitch.tv/clip/clip-id
/^https?:\/\/(www\.|m\.)?twitch\.tv\/clip\/([a-zA-Z0-9_-]+)(\?.*)?$/
];
const MAX_RECOMMENDATION_TAGS = 3;
const RECOMMENDATION_LIMIT = 20;
//* Global Variables
let state = { integrity: '', integrityExpiresAt: 0, deviceId: '', sessionId: '' };
let config = {}
let _settings = {};
let webclient = http;
// Integrity tokens are documented as valid for ~16 hours. Cache a little under that
// so saved state doesn't hand out a token that's about to expire mid-session.
const INTEGRITY_TTL_MS = 15 * 60 * 60 * 1000;
function randomHex32() {
let s = '';
for (let i = 0; i < 32; i++) s += Math.floor(Math.random() * 16).toString(16);
return s;
}
function ensureDeviceIds() {
if (!state.deviceId) state.deviceId = randomHex32();
if (!state.sessionId) state.sessionId = randomHex32();
}
//* Source
/**
* The enable endpoint gets an integrity token. These integrity tokens must be passed into the stream playback access token endpoint. The integrity endpoint always returns a token but it is not always valid. Valid tokens work for 16 hours. Valid tokens are generated through a kasada challenge. The way to tell if a token is invalid is to try an endpoint and see if it fails.
*/
source.enable = function (conf, settings, savedState) {
config = conf ?? {}
_settings = settings ?? {};
if (IS_IMPERSONATION_AVAILABLE && _settings.impersonateApiRequests) {
const client = httpimp.getDefaultClient(true);
client?.setDefaultImpersonateTarget?.(IMPERSONATION_TARGET);
webclient = httpimp;
} else {
webclient = http;
}
if (savedState) {
try {
const restored = JSON.parse(savedState);
if (restored?.integrity && restored.integrityExpiresAt > Date.now()) {
state = {
integrity: restored.integrity,
integrityExpiresAt: restored.integrityExpiresAt,
deviceId: restored.deviceId || '',
sessionId: restored.sessionId || '',
};
ensureDeviceIds();
trace('Restored valid integrity token from saved state');
return;
}
} catch (e) {
trace(`Failed to restore saved state: ${e.message}`);
}
}
ensureDeviceIds();
const resp = webclient.POST('https://gql.twitch.tv/integrity', '', {
...buildApiHeaders(),
'Client-Request-Id': randomHex32(),
})
ensureHttpOk(resp, 'Integrity fetch');
trace('Integrity fetch succeeded');
const json = JSON.parse(resp.body);
state.integrity = json.token;
state.integrityExpiresAt = Date.now() + INTEGRITY_TTL_MS;
}
source.saveState = function () {
return JSON.stringify(state);
}
source.getHome = function () {
return getHomePagerPopular({ cursor: null, page_size: 20 })
}
source.searchSuggestions = function (query) {
const gql = {
extensions: {
persistedQuery: {
sha256Hash: 'b71566f2c593dd906493b0ab2012e5626c7f277d3e435504d4454de2ff15788a',
version: 1,
},
},
query: 'query SearchTray_SearchSuggestions($queryFragment: String! $requestID: ID $withOfflineChannelContent: Boolean) { searchSuggestions(queryFragment: $queryFragment requestID: $requestID withOfflineChannelContent: $withOfflineChannelContent){ edges { ...searchSuggestionNode } tracking { modelTrackingID responseID } } } fragment searchSuggestionNode on SearchSuggestionEdge { node { content { __typename ... on SearchSuggestionChannel { id isLive isVerified login profileImageURL(width: 50) user { id stream { id game { id } } } } ... on SearchSuggestionCategory { id boxArtURL(width: 30 height: 40) } } matchingCharacters { start end } id text } }',
operationName: 'SearchTray_SearchSuggestions',
variables: {
queryFragment: query,
requestID: '',
skipSchedule: false,
},
}
/** @type {import("./types.d.ts").SearchSuggestionsResponse} */
const json = callGQL(gql)
return json.data.searchSuggestions.edges.map((edge) => edge.node.text)
}
source.getSearchCapabilities = () => {
return { types: [Type.Feed.Mixed], sorts: [], filters: [] }
}
source.search = function (query, type, order, filters) {
return getSearchPagerAll({ q: query })
}
source.searchChannels = function (query) {
return getSearchPagerChannels({ q: query, page_size: 20, results_returned: 0, cursor: null })
}
source.isChannelUrl = function (url) {
return isChannelUrl(url);
};
source.getChannel = function (url) {
const login = extractChannelId(url);
const gql = [
{
query: 'query ChannelRoot_AboutPanel($channelLogin: String! $skipSchedule: Boolean!) { currentUser { id login } user(login: $channelLogin) { id description displayName isPartner primaryColorHex profileImageURL(width: 300) followers { totalCount } channel { id socialMedias { ...SocialMedia } schedule @skip(if: $skipSchedule) { id nextSegment { id startAt hasReminder } } } lastBroadcast { id game { id displayName } } primaryTeam { id name displayName } videos(first: 30 sort: TIME type: ARCHIVE) { edges { ...userBioVideo } } } } fragment userBioVideo on VideoEdge { node { id game { id displayName } status } } fragment SocialMedia on SocialMedia { id name title url }',
operationName: 'ChannelRoot_AboutPanel',
variables: {
channelLogin: login,
skipSchedule: false,
},
extensions: {
persistedQuery: {
sha256Hash: '6089531acef6c09ece01b440c41978f4c8dc60cb4fa0124c9a9d3f896709b6c6',
version: 1,
},
},
},
{
query: '#import "./query-channel-with-home-prefs-fragment.gql" query ChannelShell($login: String!) { userOrError: userResultByLogin(login: $login) { ...coreChannelWithHomePrefsFragment ... on UserDoesNotExist { userDoesNotExist: key reason } ... on UserError { userError: key } } }',
operationName: 'ChannelShell',
variables: {
login: login,
},
extensions: {
persistedQuery: {
sha256Hash: '580ab410bcd0c1ad194224957ae2241e5d252b2c5173d8e0cce9d32d5bb14efe',
version: 1,
},
},
},
]
// Opt-in: fetch user-authored channel-page panels. Complements socialMedias;
// some channels (e.g. riotgames) keep most of their links in panels rather
// than in Twitch's curated socialMedias list. Non-persisted query works.
const includePanels = !!_settings?.includeChannelPanels;
if (includePanels) {
gql.push({
operationName: 'ChannelPanels',
query: 'query ChannelPanels($login: String!) { user(login: $login) { id panels { ... on DefaultPanel { id title linkURL } } } }',
variables: { login: login },
});
}
const json = callGQL(gql)
/** @type {import("./types.d.ts").ChannelAboutResponse} */
const user_resp = json[0]
const user = user_resp.data.user
if (!user) {
throw new UnavailableException('Channel not found')
}
/** @type {import("./types.d.ts").ChannelShellResponse} */
const shell_resp = json[1]
const shell = shell_resp.data.userOrError
const panels = includePanels ? (json[2]?.data?.user?.panels ?? []) : [];
// Normalize URL for dedup — lowercase + strip trailing slash. Users often
// have the same link as both a curated socialMedias entry AND a panel.
const normUrl = u => (u ?? '').toLowerCase().replace(/\/+$/, '');
const links = {};
const seenUrls = new Set();
const addLink = (rawKey, url) => {
if (!url) return;
const n = normUrl(url);
if (seenUrls.has(n)) return;
seenUrls.add(n);
let key = rawKey || (() => {
try { return new URL(url).hostname.replace('www.', '') || url; }
catch { return url; }
})();
// Resolve title collisions (panels sometimes duplicate labels).
if (links[key]) {
let i = 2;
while (links[`${key} (${i})`]) i++;
key = `${key} (${i})`;
}
links[key] = url;
};
// Prefer `title` (user-curated display name, e.g. "Twitter" even when name is "x")
// over capitalized `name`. Falls through addLink's hostname fallback if both absent.
for (const s of user?.channel?.socialMedias ?? []) {
const key = s.title || (s.name ? s.name.charAt(0).toUpperCase() + s.name.slice(1) : null);
addLink(key, s.url);
}
for (const p of panels) {
addLink(p?.title, p?.linkURL);
}
return new PlatformChannel({
id: new PlatformID(PLATFORM, user.id, config.id, PLATFORM_CLAIMTYPE),
name: user.displayName,
thumbnail: user.profileImageURL,
banner: shell.bannerImageURL,
subscribers: user.followers.totalCount,
description: user.description,
url: BASE_URL + login,
links,
})
}
source.getChannelContents = function (url) {
return getChannelPager({ url, page_size: 20, VideoCursor: null })
}
source.getChannelTemplateByClaimMap = () => {
return {
14: {
0: BASE_URL + "{{CLAIMVALUE}}"
}
};
};
source.isContentDetailsUrl = function (url) {
// https://www.twitch.tv/user (for livestreams) or https://www.twitch.tv/videos/123456789 or clips
return (isChannelUrl(url) || isVideoUrl(url) || isTwitchClipDetailsUrl(url)) && !REGEX_URL_CHANNEL_CLIPS_FILTER.test(url);
}
source.getContentDetails = function (url) {
if (url.includes('/video/') || url.includes('/videos/')) {
return getSavedVideo(url)
} else if(isTwitchClipDetailsUrl(url)) {
return getClippedVideo(url);
}
else if(!url.includes('/clips?')) {
return getLiveVideo(url)
}
}
source.getContentRecommendations = function (url, obj) {
// Extract content information for recommendations
let gameId = null;
let gameName = null;
let tags = [];
let broadcasterId = null;
// Try to get information from the provided object first
if (obj) {
if (obj.game) {
gameId = obj.game.id;
gameName = obj.game.name || obj.game.displayName;
}
if (obj.freeformTags) {
tags = obj.freeformTags.map(tag => tag.name);
}
if (obj.broadcaster) {
broadcasterId = obj.broadcaster.id;
} else if (obj?.author?.id) {
broadcasterId = obj.author.id.value;
}
}
// Build recommendation query based on available information
return getRecommendationsPager({
gameId: gameId,
gameName: gameName,
tags: tags,
broadcasterId: broadcasterId,
excludeUrl: url
});
}
source.getUserSubscriptions = function () {
const gql = {
"operationName": "ChannelFollows",
"variables": {
"limit": 100,
"order": "DESC"
},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "eecf815273d3d949e5cf0085cc5084cd8a1b5b7b6f7990cf43cb0beadf546907"
}
}
};
/** @type {import("./types.d.ts").PersonalSectionsFollowedResponse} */
const json = callGQL(gql, true)
const user = json.data.user;
if (!user) {
throw new ScriptException('Authentication Failed')
}
return user.follows.edges.map((e) => BASE_URL + e.node.login)
}
function getClippedVideo(url) {
const clipSlug = extractTwitchClipSlug(url);
const gql1 = [
{
"operationName": "VideoAccessToken_Clip",
"variables": {
"platform": "web",
"slug": clipSlug
},
"query": `query VideoAccessToken_Clip($slug: ID!) {
clip(slug: $slug) {
playbackAccessToken(params: {platform: "web", playerType: "site"}) {
signature
value
}
videoQualities {
frameRate
quality
sourceURL
}
}
}`
},
{
"operationName": "ShareClipRenderStatus",
"variables": {
"slug": clipSlug
},
"query": `query ShareClipRenderStatus($slug: ID!) {
clip(slug: $slug) {
id
title
thumbnailURL
createdAt
durationSeconds
viewCount
broadcaster {
id
displayName
login
profileImageURL(width: 150)
}
curator {
displayName
}
game {
displayName
}
}
}`
},
];
const gqlResponses = callGQL(gql1, true);
const clip = gqlResponses[1]?.data?.clip;
// Check if clip exists
if (!clip) {
throw new UnavailableException('Clip not found or unavailable');
}
const clipPlayback = gqlResponses[0]?.data?.clip;
const qualities = clipPlayback?.videoQualities ?? [];
const sources = qualities.map(quality => {
const sourceUrl = `${quality.sourceURL}?sig=${clipPlayback.playbackAccessToken.signature}&token=${encodeURIComponent(clipPlayback.playbackAccessToken.value)}`
return new VideoUrlSource({
name: `${quality.quality}p`,
duration: clip.durationSeconds,
url: sourceUrl,
width: parseInt(quality.quality),
container: "video/mp4"
});
})
const description = [
clip?.game?.displayName ? `${clip.game.displayName} ` : '',
clip?.curator?.displayName ? `Clipped by ${clip.curator.displayName}` : ''
]
.filter(Boolean)
.join('\n ');
const result = new PlatformVideoDetails({
id: new PlatformID(PLATFORM, clipSlug, config.id),
name: clip.title,
thumbnails: new Thumbnails([new Thumbnail(clip.thumbnailURL, 0)]),
author: new PlatformAuthorLink(
new PlatformID(PLATFORM, clip.broadcaster.id, config.id, PLATFORM_CLAIMTYPE),
clip.broadcaster.displayName,
`${BASE_URL}${clip.broadcaster.login}`,
clip.broadcaster.profileImageURL
),
uploadDate: parseInt(new Date(clip.createdAt).getTime() / 1000),
duration: clip.durationSeconds,
viewCount: clip.viewCount,
url: url,
isLive: false,
description,
video: new VideoSourceDescriptor(sources),
});
const clipMetadata = {
game: clip.game,
broadcaster: clip.broadcaster
};
if (IS_TESTING) {
source.getContentRecommendations(url, clipMetadata);
} else {
result.getContentRecommendations = function () {
return source.getContentRecommendations(url, clipMetadata);
};
}
return result;
}
/**
* Returns a saved video
* @param {string} url
* @returns {PlatformVideoDetails}
*/
function getSavedVideo(url) {
// get whatever is after the last slash in twitch.tv/videos/____/
const id = extractTwitchVideoId(url)
const gql1 = [
{
extensions: {
persistedQuery: {
sha256Hash: 'ed230aa1e33e07eebb8928504583da78a5173989fadfb1ac94be06a04f3cdbe9',
version: 1,
},
},
operationName: 'PlaybackAccessToken',
variables: {
isLive: false,
isVod: true,
login: '',
platform: 'web',
playerType: 'site',
vodID: id,
},
query: 'query PlaybackAccessToken($login: String! $isLive: Boolean! $vodID: ID! $isVod: Boolean! $playerType: String!) { streamPlaybackAccessToken(channelName: $login params: {platform: "web" playerBackend: "mediaplayer" playerType: $playerType}) @include(if: $isLive) { value signature } videoPlaybackAccessToken(id: $vodID params: {platform: "web" playerBackend: "mediaplayer" playerType: $playerType}) @include(if: $isVod) { value signature } }',
},
{
extensions: {
persistedQuery: {
sha256Hash: 'cf1ccf6f5b94c94d662efec5223dfb260c9f8bf053239a76125a58118769e8e2',
version: 1,
},
},
operationName: 'ChannelVideoCore',
variables: {
videoID: id,
},
query: 'query ChannelVideoCore($videoID: ID!) { video(id: $videoID) { id owner { id login profileImageURL(width: 50) } } }',
},
]
const json1 = callGQL(gql1, true)
/** @type {import("./types.d.ts").PlaybackAccessTokenResponse} */
const hls_json = json1[0]
/** @type {import("./types.d.ts").ChannelVideoCoreResponse} */
const channel_video_core = json1[1]
const cvc = channel_video_core.data.video
const spat = hls_json.data.videoPlaybackAccessToken
if (!spat) {
throw new UnavailableException('Video playback access token unavailable. Video may be subscriber-only, deleted, or geo-blocked.')
}
if (isRestrictedToSubscriberOnly(spat)) {
throw new UnavailableException('This video is only available to subscribers.')
}
const hls_url = buildVodHlsUrl(id, spat.signature, spat.value);
const gql2 = [
{
operationName: 'VideoMetadata',
variables: {
videoID: id,
},
query: 'query VideoMetadata($videoID: ID!) { video(id: $videoID) { id title description previewThumbnailURL(height: 240, width: 360) createdAt viewCount publishedAt lengthSeconds broadcastType owner { id login displayName } game { id boxArtURL name displayName } } }',
},
]
const json2 = callGQL(gql2)
/** @type {import("./types.d.ts").VideoMetadataResponse}*/
const video_metadata = json2[0]
const vm = video_metadata.data
return buildVodVideoDetails({
id: id,
title: vm.video.title,
thumbnail: vm.video.previewThumbnailURL,
ownerId: cvc.owner.id,
ownerDisplayName: cvc.owner.login,
ownerLogin: cvc.owner.login,
ownerProfileImageURL: cvc.owner.profileImageURL,
uploadDate: vm.video.publishedAt,
duration: vm.video.lengthSeconds,
viewCount: vm.video.viewCount,
url: url,
description: vm.video.description,
hlsUrl: hls_url,
game: vm.video.game,
});
}
/**
* Returns a live video
* @param {string} url
* @param {boolean} video_details
* @returns {PlatformVideoDetails | PlatformVideo}
*/
function getLiveVideo(url, video_details = true) {
// get whatever is after the last slash in twitch.tv/_____/
const login = extractChannelId(url);
const gql_for_metadata = [
{
operationName: 'StreamMetadata',
query: 'query StreamMetadata($channelLogin: String!) { user(login: $channelLogin) { id primaryColorHex isPartner profileImageURL(width: 70) primaryTeam { id name displayName } squadStream { id members { id } status } channel { id chanlets { id } } lastBroadcast { id title } stream { id type createdAt game { id name } } } }',
variables: {
channelLogin: login,
},
extensions: {
persistedQuery: {
version: 1,
sha256Hash: 'a647c2a13599e5991e175155f798ca7f1ecddde73f7f341f39009c14dbf59962',
},
},
},
{
query: 'query UseViewCount($channelLogin: String!) { user(login: $channelLogin) { id stream { id viewersCount } } }',
operationName: 'UseViewCount',
variables: {
channelLogin: login,
},
extensions: {
persistedQuery: {
sha256Hash: '00b11c9c428f79ae228f30080a06ffd8226a1f068d6f52fbc057cbde66e994c2',
version: 1,
},
},
},
{
extensions: {
persistedQuery: {
sha256Hash: '639d5f11bfb8bf3053b424d9ef650d04c4ebb7d94711d644afb08fe9a0fad5d9',
version: 1,
},
},
query: 'query UseLive($channelLogin: String!) { user(login: $channelLogin) { id login stream { id createdAt } } }',
operationName: 'UseLive',
variables: {
channelLogin: login,
},
},
{
extensions: {
persistedQuery: {
sha256Hash: 'ed230aa1e33e07eebb8928504583da78a5173989fadfb1ac94be06a04f3cdbe9',
version: 1,
},
},
operationName: 'PlaybackAccessToken',
variables: {
isLive: true,
isVod: false,
login: login,
platform: 'web',
playerType: 'site',
vodID: '',
},
query: 'query PlaybackAccessToken($login: String! $isLive: Boolean! $vodID: ID! $isVod: Boolean! $playerType: String!) { streamPlaybackAccessToken(channelName: $login params: {platform: "web" playerBackend: "mediaplayer" playerType: $playerType}) @include(if: $isLive) { value signature } videoPlaybackAccessToken(id: $vodID params: {platform: "web" playerBackend: "mediaplayer" playerType: $playerType}) @include(if: $isVod) { value signature } }',
},
]
const json = callGQL(gql_for_metadata, true)
/** @type {import("./types.d.ts").StreamMetadataResponse}*/
const stream_metadata = json[0]
/** @type {import("./types.d.ts").ViewCountResponse}*/
const view_count = json[1]
/** @type {import("./types.d.ts").UseLiveResponse}*/
const use_live = json[2]
/** @type {import("./types.d.ts").PlaybackAccessTokenResponse} */
const playback_access_token = json[3]
const sm = stream_metadata.data.user
const vc = view_count.data.user
const ul = use_live.data.user
// Check if channel exists
if (!sm || !vc || !ul) {
throw new UnavailableException('Channel not found')
}
if (ul?.stream === null) {
throw new UnavailableException('Channel is not live')
}
const spat = playback_access_token.data.streamPlaybackAccessToken
// Check if playback access token is available
if (!spat) {
throw new UnavailableException('Unable to get playback access token')
}
const hls_url = buildLiveHlsUrl(login, spat);
const hls_source_opts = { name: 'live', duration: 0, url: hls_url, requestModifier: mediaRequestModifier() };
const hls_source = new HLSSource(hls_source_opts)
const cacheBust = Math.floor(Date.now() / 300000); // refresh every 5 min
const pv = new PlatformVideo({
id: new PlatformID(PLATFORM, sm.id, config.id),
name: sm.lastBroadcast.title,
thumbnails: new Thumbnails([
new Thumbnail(`https://static-cdn.jtvnw.net/previews-ttv/live_user_${login}-1280x720.jpg?t=${cacheBust}`, 720),
new Thumbnail(`https://static-cdn.jtvnw.net/previews-ttv/live_user_${login}-854x480.jpg?t=${cacheBust}`, 480),
]),
author: new PlatformAuthorLink(new PlatformID(PLATFORM, sm.channel.id, config.id, PLATFORM_CLAIMTYPE), login, url, sm.profileImageURL),
uploadDate: parseInt(new Date(ul.stream.createdAt).getTime() / 1000),
duration: 0,
viewCount: vc.stream.viewersCount,
url: url,
shareUrl: url,
isLive: true,
})
if (video_details) {
const result = new PlatformVideoDetails({
...pv,
description: '',
video: new VideoSourceDescriptor([]),
live: hls_source,
});
const liveMetadata = {
game: sm.stream?.game,
broadcaster: {
id: sm.channel.id,
login: login,
displayName: login
}
};
if (IS_TESTING) {
source.getContentRecommendations(url, liveMetadata);
} else {
result.getContentRecommendations = function () {
return source.getContentRecommendations(url, liveMetadata);
};
}
return result;
} else {
return pv
}
}
source.getComments = function (url) {
return getCommentPager({ url: url, page: 1, page_size: 20 })
}
source.getSubComments = function (comment) {
return new CommentPager([], false, {}) //Not implemented
}
source.getLiveChatWindow = function (url) {
const login = extractChannelId(url);
return {
url: "https://www.twitch.tv/popout/" + login + "/chat",
removeElements: [".stream-chat-header", ".chat-room__content > div:first-child"],
removeElementsInterval: [".consent-banner"]
};
}
source.getVODEvents = function (url) {
return new TwitchVODEventPager(extractTwitchVideoId(url));
}
source.getLiveEvents = function (url) {
const login = extractChannelId(url);
const gql = [
{
query: '#import "./query-channel-with-home-prefs-fragment.gql" query ChannelShell($login: String!) { userOrError: userResultByLogin(login: $login) { ...coreChannelWithHomePrefsFragment ... on UserDoesNotExist { userDoesNotExist: key reason } ... on UserError { userError: key } } }',
operationName: 'ChannelShell',
variables: {
login: login,
},
extensions: {
persistedQuery: {
sha256Hash: '580ab410bcd0c1ad194224957ae2241e5d252b2c5173d8e0cce9d32d5bb14efe',
version: 1,
},
},
},
{
query: '#import "twilight/features/badges/models/badge-fragment.gql" #import "twilight/features/squad-stream/models/squad-stream-fragment.gql" query ChatList_Badges($channelLogin: String!) { badges { ...badge } user(login: $channelLogin) { id primaryColorHex broadcastBadges { ...badge } self { selectedBadge { ...badge } displayBadges { ...badge } } squadStream { ...squadStreamData } } }',
extensions: {
persistedQuery: {
sha256Hash: '86f43113c04606e6476e39dcd432dee47c994d77a83e54b732e11d4935f0cd08',
version: 1,
},
},
operationName: 'ChatList_Badges',
variables: {
channelLogin: login,
},
},
]
const json = callGQL(gql)
/** @type {import("./types.d.ts").ChannelShellResponse} */
const ChannelShellResponse = json[0]
const userOrError = ChannelShellResponse.data.userOrError
const chats = [];
/** @type {import("./types.d.ts").BadgeListResponse} */
const BadgeListResponse = json[1]
let badge_url_map = {}
BadgeListResponse.data.badges.forEach((badge) => {
badge_url_map[badge.setID] = badge.image2x
})
return new TwitchLiveEventPager(userOrError.id, login, chats, badge_url_map)
}
class TwitchLiveEventPager extends LiveEventPager {
/**
* @param {string} channelId
* @param {string} channelName
* @param {LiveEventComment[]} chats
* @param {{[key: string]: string}} badge_url_map
*/
constructor(channelId, channelName, chats, badge_url_map) {
super([], true)
const me = this
this.channelId = channelId
this.channelName = channelName
this.events = [...chats]
this.emojis = {}
this.lastFetch = new Date().getTime()
let socket_irc = http.socket('wss://irc-ws.chat.twitch.tv', {}, false)
socket_irc.connect(
{
open() {
const justin_fan_number = Math.floor(Math.random() * 9999)
const jf = `justinfan${justin_fan_number}`
socket_irc.send('CAP REQ :twitch.tv/tags')
socket_irc.send('PASS SCHMOOPIIE')
socket_irc.send(`NICK ${jf}`)
socket_irc.send(`USER ${jf} 8 * :${jf}`)
socket_irc.send(`JOIN #${me.channelName}`)
if (IS_TESTING) console.log(`Sent JOIN #${me.channelName}`)
},
message(msg) {
if (((new Date()).getTime() - me.lastFetch) / 1000 > 10) socket_irc.close()
if (!msg.startsWith('@badge-info')) return
if (msg.includes(';msg-id=')) {
const msg_id = msg.match(/;msg-id=([^;]+);/)[1]
let months_param, display_name_param
if (msg_id === 'sub' || msg_id === 'resub') {
months_param = 'msg-param-cumulative-months'
display_name_param = 'display-name'
} else {
months_param = 'msg-param-gift-months'
display_name_param = 'msg-param-recipient-display-name'
}
const regex = new RegExp(`;${months_param}=(\\d+);.*;${display_name_param}=([^;]+);.*;system-msg=([^;]+);`)
const result = regex.exec(msg)
const months = parseInt(result[1])
const display_name = result[2]
const system_message = result[3].replace(/\\s/g, ' ')
me.events.push(new LiveEventDonation(months + ' Months', display_name, system_message, ''))
return
}
//TODO: Make this a separate function
const parsedMessage = parseEmojiMessage(me.channelName, msg)
let newEmojis = {}
for (let key of Object.keys(parsedMessage.emojis)) {
if (!me.emojis[key]) {
me.emojis[key] = parsedMessage.emojis[key]
newEmojis[key] = parsedMessage.emojis[key]
}
}
const nameMatch = msg.match(/;display-name=([^;]+);/);
const name = (nameMatch && nameMatch.length >= 2) ? nameMatch[1] : null;
const colorMatch = msg.match(/;color=([^;]+);/);
const color = (colorMatch && colorMatch.length >= 2) ? colorMatch[1] : null;
const badges = msg.match(/;badges=([^;]+);/)
const badge_array = (badges && badges.length >= 2) ? badges[1].split(',') : [];
badge_array.forEach((badge) => {
newEmojis[badge] = badge_url_map[badge]
})
if (Object.keys(newEmojis).length > 0)
me.events.push(new LiveEventEmojis(newEmojis))
if (name)
me.events.push(new LiveEventComment(name, parsedMessage.msg, '', color, badge_array))
else if (IS_TESTING)
console.log("Failed name/color: " + msg);
},
},
false
)
let socket_pub_sub = http.socket('wss://pubsub-edge.twitch.tv/v1', {}, false)
socket_pub_sub.connect({
open() {
socket_pub_sub.send(JSON.stringify({ type: 'LISTEN', nonce: '', data: { topics: [`video-playback-by-id.${me.channelId}`] } }))
// socket_pub_sub.send(JSON.stringify({"type":"LISTEN","nonce":"","data":{"topics":[`channel-bits-events-v2.${context.channel_id}`]}}))
socket_pub_sub.send(JSON.stringify({ type: 'LISTEN', nonce: '', data: { topics: [`raid.${me.channelId}`] } }))
// socket_pub_sub.send(JSON.stringify({"type":"LISTEN","nonce":"","data":{"topics":[`channel-subscribe-events-v1.${context.channel_id}`]}}))
if (IS_TESTING) console.log(`Sent LISTEN to ${me.channelId}`)
},
message(msg) {
if (((new Date()).getTime() - me.lastFetch) / 1000 > 10) socket_pub_sub.close()
const json = JSON.parse(msg)
if (json.type === 'MESSAGE') {
// {"type":"MESSAGE","data":{"topic":"video-playback-by-id.156037856","message":"{\"type\":\"viewcount\",\"server_time\":1686777651.803572,\"viewers\":40549}"}}
const data = JSON.parse(json.data.message)
const messageType = json.data.topic.split('.')[0]
switch (messageType) {
case 'video-playback-by-id':
me.events.push(new LiveEventViewCount(data.viewers))
break
case 'channel-bits-events-v2':
me.events.push(new LiveEventDonation(parseFloat(data.badge_tier) + ' Bits', data.user_name, data.chat_message, null))
break
case 'raid':
me.events.push(new LiveEventRaid(data.display_name, data.viewer_count))
break
case 'channel-subscribe-events-v1':
me.events.push(
new LiveEventDonation(parseFloat(data.cumulative_months) + ' Months', data.display_name, data.sub_message.message, null)
)
break
}
}
},
closed() {
this.hasMore = false
},
})
}
nextPage() {
this.lastFetch = new Date().getTime()
this.results = [...this.events]
this.events = []
return this
}
}
class TwitchVODEventPager extends LiveEventPager {
/**
* @param {string} videoId
*/
constructor(videoId) {
super([], true);
this.videoId = videoId;
this.nextRequest = 1000;
this._cached = [];
this._fetchedAt = -1;
this._cacheMaxMs = -1;
}
nextPage(ms) {
const msNum = ms ?? 0;
// Grayjay Android drops events with time >= msNum + 1500 (LiveChatManager.kt drip-feed window).
// Keep in sync if that filter changes.
const windowEnd = msNum + 1500;
// Cache is authoritative for [_fetchedAt, _cacheMaxMs]: if the Android
// filter window [msNum, windowEnd) falls inside that range, skip the fetch.
const cacheCovers = this._fetchedAt >= 0
&& msNum >= this._fetchedAt
&& this._cacheMaxMs >= windowEnd;
if (!cacheCovers) {
this._fetchPage(msNum);
}
this.results = this._cached.filter(e => e.time >= msNum);
return this;
}
_fetchPage(msNum) {
const offsetSeconds = Math.floor(msNum / 1000);
const gql = [{
operationName: 'VideoCommentsByOffsetOrCursor',
variables: { videoID: this.videoId, contentOffsetSeconds: offsetSeconds },
extensions: {
persistedQuery: {
version: 1,
sha256Hash: 'b70a3591ff0f4e0313d126c6a1502d79a1c02baebb288227c582044aa76adf6a',
},
},
}];
const resp = callGQL(gql);
const comments = resp?.[0]?.data?.video?.comments;
if (!comments) {
this._cached = [];
this._fetchedAt = -1;
this._cacheMaxMs = -1;
this.hasMore = false;
return;
}
const events = [];
for (const edge of comments.edges ?? []) {
const node = edge?.node;
if (!node) continue;
const name = node.commenter?.displayName ?? node.commenter?.login ?? '';
const message = (node.message?.fragments ?? []).map(f => f?.text ?? '').join('');
if (!message) continue;
const color = node.message?.userColor ?? null;
const ev = new LiveEventComment(name, message, '', color, []);
ev.time = (node.contentOffsetSeconds ?? 0) * 1000;
events.push(ev);
}
this._cached = events;
this._fetchedAt = msNum;
// If the page has events, trust it up to the last event time.
// If the page is empty, assume ~30s of forward coverage to avoid a refetch storm on silent stretches.
this._cacheMaxMs = events.length ? events[events.length - 1].time : msNum + 30000;