-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeerTubeScript.js
More file actions
2854 lines (2429 loc) · 133 KB
/
PeerTubeScript.js
File metadata and controls
2854 lines (2429 loc) · 133 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 PLATFORM = "PeerTube";
const getUserAgent = () => bridge.authUserAgent ?? bridge.captchaUserAgent ?? 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.200 Mobile Safari/537.36';
const IS_DESKTOP = bridge.buildPlatform === "desktop";
const IMPERSONATION_TARGET = IS_DESKTOP ? 'chrome136' : 'chrome131_android';
const IS_IMPERSONATION_AVAILABLE = (typeof httpimp !== 'undefined');
const supportedResolutions = {
'1080p': { width: 1920, height: 1080 },
'720p': { width: 1280, height: 720 },
'480p': { width: 854, height: 480 },
'360p': { width: 640, height: 360 },
'240p': { width: 426, height: 240 },
'144p': { width: 256, height: 144 }
};
const URLS = {
PEERTUBE_LOGO: "https://plugins.grayjay.app/PeerTube/peertube.png"
}
const PAGE_SIZE_DEFAULT = 20;
const PAGE_SIZE_HISTORY = 100;
// Query parameter to flag private/unlisted playlists that require authentication
// This is added by getUserPlaylists and checked by getPlaylist
const PRIVATE_PLAYLIST_QUERY_PARAM = '&requiresAuth=1';
// instances are populated during deploy appended to the end of this javascript file
// this update process is done at update-instances.sh
// =============================================================================
// Regex patterns
// =============================================================================
// =============================================================================
// State
// =============================================================================
let config = {};
let _settings = {};
let state = {
serverVersion: '',
defaultHeaders: {
'User-Agent': getUserAgent()
}
}
let INDEX_INSTANCES = {
instances: []
};
if (IS_IMPERSONATION_AVAILABLE) {
const httpImpClient = httpimp.getDefaultClient(true);
if (httpImpClient.setDefaultImpersonateTarget) {
httpImpClient.setDefaultImpersonateTarget(IMPERSONATION_TARGET);
}
}
Type.Feed.Playlists = "PLAYLISTS";
// =============================================================================
// Source functions
// =============================================================================
source.enable = function (conf, settings, saveStateStr) {
config = conf ?? {};
_settings = settings ?? {};
let didSaveState = false;
if (IS_TESTING && !plugin?.config?.constants?.baseUrl) {
plugin = {
config: {
constants: {
baseUrl: "https://peertube.futo.org"
}
}
};
}
try {
if (saveStateStr) {
state = JSON.parse(saveStateStr);
didSaveState = true;
}
} catch (ex) {
log('Failed to parse saveState:' + ex);
}
if (!didSaveState) {
try {
const [{ body: serverConfig }] = httpGET({ url: `${plugin.config.constants.baseUrl}/api/v1/config`, parseResponse: true });
state.serverVersion = serverConfig.serverVersion;
} catch (e) {
log("Failed to detect server version, continuing with defaults: " + e);
}
}
};
source.saveState = function () {
return JSON.stringify(state)
}
source.getHome = function () {
let sort = '';
// Get the sorting preference from settings
const sortOptions = [
'best', // 0: Best (Algorithm)
'-publishedAt', // 1: Newest
'publishedAt', // 2: Oldest
'-views', // 3: Most Views
'-likes', // 4: Most Likes
'-trending', // 5: Trending
'-hot' // 6: Hot
];
const homeFeedSortIndex = _settings.homeFeedSortIndex || 0;
sort = sortOptions[homeFeedSortIndex] || 'best';
// Check version compatibility for certain sorting options
// v3.1.0+ introduced best, trending, and hot algorithms
// https://docs.joinpeertube.org/CHANGELOG#v3-1-0
const requiresV3_1 = ['best', '-trending', '-hot'];
if (requiresV3_1.includes(sort) && !ServerInstanceVersionIsSameOrNewer(state.serverVersion, '3.1.0')) {
// Fallback to newest for old versions
log(`Sort option '${sort}' requires PeerTube v3.1.0+, falling back to '-publishedAt'`);
sort = '-publishedAt';
}
const params = { sort };
// Collect category filters from settings
const settingSet = new Set([
_settings.mainCategoryIndex,
_settings.secondCategoryIndex,
_settings.thirdCategoryIndex,
_settings.fourthCategoryIndex,
_settings.fifthCategoryIndex
]);
const categoryIds = Array.from(settingSet)
.filter(categoryIndex => categoryIndex && parseInt(categoryIndex) > 0)
.map(categoryIndex => getCategoryId(categoryIndex))
.filter(Boolean);
// Collect language filters from settings
const languageSettingSet = new Set([
_settings.firstLanguageIndex,
_settings.secondLanguageIndex,
_settings.thirdLanguageIndex
]);
const languageCodes = Array.from(languageSettingSet)
.filter(languageIndex => languageIndex && parseInt(languageIndex) > 0)
.map(languageIndex => getLanguageCode(languageIndex))
.filter(Boolean);
// Apply category and language filters (shared across all sources)
if (categoryIds.length > 0) {
params.categoryOneOf = categoryIds;
}
if (languageCodes.length > 0) {
params.languageOneOf = languageCodes;
}
// Map PeerTube sort options to Sepia Search equivalents
const sepiaSearchSortMap = {
'best': 'match', // Best algorithm -> relevance match
'-publishedAt': '-createdAt', // Newest -> most recent
'publishedAt': 'createdAt', // Oldest -> least recent
'-views': '-views', // Most Views -> same
'-likes': '-likes', // Most Likes -> same
'-trending': '-views', // Trending -> most views (closest equivalent)
'-hot': '-views' // Hot -> most views (closest equivalent)
};
if (_settings.homeSourceCurrentInstance === true && _settings.homeSourceSepiaSearch === true) {
// Both sources: fetch in parallel, merge, deduplicate
const localContext = {
path: '/api/v1/videos',
params: { ...params },
page: 0,
sourceHost: plugin.config.constants.baseUrl
};
const sepiaContext = {
path: '/api/v1/search/videos',
params: { ...params, resultType: 'videos', sort: sepiaSearchSortMap[sort] || 'match' },
page: 0,
sourceHost: 'https://sepiasearch.org'
};
return getMixedVideoPager(localContext, sepiaContext);
} else if (_settings.homeSourceSepiaSearch === true) {
// Sepia Search only
params.resultType = 'videos';
params.sort = sepiaSearchSortMap[sort] || 'match';
return getVideoPager('/api/v1/search/videos', params, 0, 'https://sepiasearch.org', true);
} else {
// Current instance only (default)
return getVideoPager('/api/v1/videos', params, 0, plugin.config.constants.baseUrl, false);
}
};
source.searchSuggestions = function (query) {
if (!_settings.enableSearchSuggestions) return [];
if (!query || query.trim().length < 2) return [];
try {
const nsfwPolicy = getNSFWPolicy();
const baseParams = {
search: query.trim(),
start: 0,
count: 10
};
if (nsfwPolicy !== 'display') {
baseParams.nsfw = false;
}
// Fetch from enabled sources
const requests = [];
if (_settings.searchCurrentInstance === true) {
requests.push(`${plugin.config.constants.baseUrl}/api/v1/search/videos?${buildQuery(baseParams)}`);
}
if (_settings.searchSepiaSearch === true) {
requests.push(`https://sepiasearch.org/api/v1/search/videos?${buildQuery({ ...baseParams, resultType: 'videos' })}`);
}
if (requests.length === 0) {
requests.push(`${plugin.config.constants.baseUrl}/api/v1/search/videos?${buildQuery(baseParams)}`);
}
const allVideos = [];
if (requests.length === 1) {
const [resp] = httpGET(requests[0]);
const data = JSON.parse(resp.body);
if (data?.data) allVideos.push(...data.data);
} else {
const responses = httpGET(requests);
for (const resp of responses) {
if (!resp.isOk) continue;
try {
const data = JSON.parse(resp.body);
if (data?.data) allVideos.push(...data.data);
} catch (e) { /* ignore */ }
}
}
if (!allVideos.length) return [];
// Collect unique tags and video titles that match the query
const queryLower = query.trim().toLowerCase();
const seen = new Set();
const suggestions = [];
for (const video of allVideos) {
// Add matching video titles
if (video.name && video.name.toLowerCase().includes(queryLower)) {
const key = video.name.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
suggestions.push(video.name);
}
}
// Add matching tags
for (const tag of (video.tags ?? [])) {
if (tag.toLowerCase().includes(queryLower)) {
const key = tag.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
suggestions.push(tag);
}
}
}
}
return suggestions.slice(0, 10);
} catch (e) {
log("Failed to get search suggestions", e);
return [];
}
};
source.getSearchCapabilities = () => {
return new ResultCapabilities([Type.Feed.Mixed, Type.Feed.Videos], [], [
new FilterGroup("Upload Date", [
new FilterCapability("Last Hour", Type.Date.LastHour),
new FilterCapability("This Day", Type.Date.Today),
new FilterCapability("This Week", Type.Date.LastWeek),
new FilterCapability("This Month", Type.Date.LastMonth),
new FilterCapability("This Year", Type.Date.LastYear),
], false, "date"),
new FilterGroup("Duration", [
new FilterCapability("Under 4 minutes", Type.Duration.Short),
new FilterCapability("4-20 minutes", Type.Duration.Medium),
new FilterCapability("Over 20 minutes", Type.Duration.Long)
], false, "duration"),
new FilterGroup("Features", [
new FilterCapability("Live", "live", "live"),
], true, "features"),
new FilterGroup("License", [
new FilterCapability("Attribution", "1"),
new FilterCapability("Attribution - Share Alike", "2"),
new FilterCapability("Attribution - No Derivatives", "3"),
new FilterCapability("Attribution - Non Commercial", "4"),
new FilterCapability("Attribution - Non Commercial - Share Alike", "5"),
new FilterCapability("Attribution - Non Commercial - No Derivatives", "6"),
new FilterCapability("Public Domain Dedication", "7"),
], true, "license"),
new FilterGroup("Content", [
new FilterCapability("All Content", "all_content"),
new FilterCapability("Safe Content Only", "safe_only"),
new FilterCapability("NSFW Content Only", "nsfw_only"),
], false, "nsfw"),
new FilterGroup("Category", [
new FilterCapability("Music", "1"),
new FilterCapability("Films", "2"),
new FilterCapability("Vehicles", "3"),
new FilterCapability("Art", "4"),
new FilterCapability("Sports", "5"),
new FilterCapability("Travels", "6"),
new FilterCapability("Gaming", "7"),
new FilterCapability("People", "8"),
new FilterCapability("Comedy", "9"),
new FilterCapability("Entertainment", "10"),
new FilterCapability("News & Politics", "11"),
new FilterCapability("How To", "12"),
new FilterCapability("Education", "13"),
new FilterCapability("Activism", "14"),
new FilterCapability("Science & Technology", "15"),
new FilterCapability("Animals", "16"),
new FilterCapability("Kids", "17"),
new FilterCapability("Food", "18"),
], true, "category"),
new FilterGroup("Language", [
new FilterCapability("English", "en"),
new FilterCapability("Français", "fr"),
new FilterCapability("العربية", "ar"),
new FilterCapability("Català", "ca"),
new FilterCapability("Čeština", "cs"),
new FilterCapability("Deutsch", "de"),
new FilterCapability("ελληνικά", "el"),
new FilterCapability("Esperanto", "eo"),
new FilterCapability("Español", "es"),
new FilterCapability("Euskara", "eu"),
new FilterCapability("فارسی", "fa"),
new FilterCapability("Suomi", "fi"),
new FilterCapability("Gàidhlig", "gd"),
new FilterCapability("Galego", "gl"),
new FilterCapability("Hrvatski", "hr"),
new FilterCapability("Magyar", "hu"),
new FilterCapability("Íslenska", "is"),
new FilterCapability("Italiano", "it"),
new FilterCapability("日本語", "ja"),
new FilterCapability("Taqbaylit", "kab"),
new FilterCapability("Nederlands", "nl"),
new FilterCapability("Norsk", "no"),
new FilterCapability("Occitan", "oc"),
new FilterCapability("Polski", "pl"),
new FilterCapability("Português (Brasil)", "pt"),
new FilterCapability("Português (Portugal)", "pt-PT"),
new FilterCapability("Pусский", "ru"),
new FilterCapability("Slovenčina", "sk"),
new FilterCapability("Shqip", "sq"),
new FilterCapability("Svenska", "sv"),
new FilterCapability("ไทย", "th"),
new FilterCapability("Toki Pona", "tok"),
new FilterCapability("Türkçe", "tr"),
new FilterCapability("украї́нська мо́ва", "uk"),
new FilterCapability("Tiếng Việt", "vi"),
new FilterCapability("简体中文(中国)", "zh-Hans"),
new FilterCapability("繁體中文(台灣)", "zh-Hant"),
], true, "language"),
new FilterGroup("Search Scope", [
new FilterCapability("Federated Network", "federated"),
new FilterCapability("Local Instance Only", "local"),
new FilterCapability("Sepia Search", "sepia"),
], false, "scope")
]);
};
source.search = function (query, type, order, filters) {
if(IS_TESTING) {
/*
//filter example:
{"duration": ["SHORT"]}
*/
if(typeof filters === 'string') {
filters = JSON.parse(filters);
}
}
if(source.isContentDetailsUrl(query)) {
return new ContentPager([source.getContentDetails(query)], false);
}
// Handle tag search URLs as playlists
if(source.isPlaylistUrl(query)) {
return new PlaylistPager([source.getPlaylist(query)], false);
}
let sort = order;
if (sort === Type.Order.Chronological) {
sort = "-publishedAt";
}
const params = {
search: query,
sort
};
if (type == Type.Feed.Streams) {
params.isLive = true;
} else if (type == Type.Feed.Videos) {
params.isLive = false;
}
// Apply filters (YouTube-style object structure)
if (filters) {
// Date filter
if (filters.date && filters.date.length > 0) {
const dateFilter = filters.date[0];
const now = new Date();
if (dateFilter === Type.Date.LastHour) {
const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
params.publishedAfter = oneHourAgo.toISOString();
} else if (dateFilter === Type.Date.Today) {
const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
params.publishedAfter = startOfDay.toISOString();
} else if (dateFilter === Type.Date.LastWeek) {
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
params.publishedAfter = oneWeekAgo.toISOString();
} else if (dateFilter === Type.Date.LastMonth) {
const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
params.publishedAfter = oneMonthAgo.toISOString();
} else if (dateFilter === Type.Date.LastYear) {
const startOfYear = new Date(now.getFullYear(), 0, 1);
params.publishedAfter = startOfYear.toISOString();
}
}
// Duration filter
if (filters.duration && filters.duration.length > 0) {
const durationFilter = filters.duration[0];
if (durationFilter === Type.Duration.Short) {
params.durationMax = 240; // Under 4 minutes
} else if (durationFilter === Type.Duration.Medium) {
params.durationMin = 240; // 4 minutes
params.durationMax = 1200; // 20 minutes
} else if (durationFilter === Type.Duration.Long) {
params.durationMin = 1200; // Over 20 minutes
}
}
// Features filter (multi-select)
if (filters.features && filters.features.length > 0) {
// Check if "live" is selected
const hasLive = filters.features.includes("live");
if (hasLive) {
params.isLive = true;
}
// Note: If live is not selected, we don't set isLive parameter
// This allows both live and non-live videos to be returned
}
// NSFW Content filter
if (filters.nsfw && filters.nsfw.length > 0) {
const nsfwFilter = filters.nsfw[0];
if (nsfwFilter === "safe_only") {
params.nsfw = "false";
} else if (nsfwFilter === "nsfw_only") {
params.nsfw = "true";
}
// "all_content" doesn't set any filter
}
// Category filter (multi-select)
if (filters.category && filters.category.length > 0) {
params.categoryOneOf = filters.category;
}
// Language filter (multi-select)
if (filters.language && filters.language.length > 0) {
params.languageOneOf = filters.language;
}
// License filter (multi-select)
if (filters.license && filters.license.length > 0) {
params.licenceOneOf = filters.license;
}
// Search Scope filter
if (filters.scope && filters.scope.length > 0) {
const scopeFilter = filters.scope[0];
if (scopeFilter === "sepia") {
// Force Sepia Search mode - use Sepia Search directly
const sepiaParams = {
search: query,
resultType: 'videos',
sort: '-createdAt'
};
// Apply other filters to Sepia Search
if (params.categoryOneOf) sepiaParams.categoryOneOf = params.categoryOneOf;
if (params.languageOneOf) sepiaParams.languageOneOf = params.languageOneOf;
if (params.durationMin) sepiaParams.durationMin = params.durationMin;
if (params.durationMax) sepiaParams.durationMax = params.durationMax;
if (params.publishedAfter) sepiaParams.publishedAfter = params.publishedAfter;
if (params.isLive !== undefined) sepiaParams.isLive = params.isLive;
if (params.licenceOneOf) sepiaParams.licenceOneOf = params.licenceOneOf;
if (params.nsfw) sepiaParams.nsfw = params.nsfw;
return getVideoPager('/api/v1/search/videos', sepiaParams, 0, 'https://sepiasearch.org', true);
} else if (scopeFilter === "local" && _settings.searchCurrentInstance === true) {
params.searchTarget = "local";
}
// "federated" means federated (default), so no parameter needed
}
}
if (_settings.searchCurrentInstance === true && _settings.searchSepiaSearch === true) {
// Both sources: fetch in parallel, merge, deduplicate, sort
const localContext = {
path: '/api/v1/search/videos',
params: { ...params },
page: 0,
sourceHost: plugin.config.constants.baseUrl
};
const sepiaContext = {
path: '/api/v1/search/videos',
params: { ...params, resultType: 'videos', sort: '-createdAt' },
page: 0,
sourceHost: 'https://sepiasearch.org'
};
return getMixedVideoPager(localContext, sepiaContext);
} else if (_settings.searchSepiaSearch === true) {
params.resultType = 'videos';
params.sort = '-createdAt';
return getVideoPager('/api/v1/search/videos', params, 0, 'https://sepiasearch.org', true);
} else {
return getVideoPager('/api/v1/search/videos', params, 0, plugin.config.constants.baseUrl, true);
}
};
source.searchChannels = function (query) {
// Channel search doesn't support mixed pager (different result type),
// so use Sepia Search if enabled, otherwise current instance
const sourceHost = _settings.searchSepiaSearch === true
? 'https://sepiasearch.org'
: plugin.config.constants.baseUrl;
return getChannelPager('/api/v1/search/video-channels', {
search: query
}, 0, sourceHost, true);
};
source.searchPlaylists = function (query) {
// Playlist search doesn't support mixed pager (different result type),
// so use Sepia Search if enabled, otherwise current instance
const sourceHost = _settings.searchSepiaSearch === true
? 'https://sepiasearch.org'
: plugin.config.constants.baseUrl;
const params = {
search: query
};
if (_settings.searchSepiaSearch === true) {
params.resultType = 'video-playlists';
params.sort = '-createdAt';
}
return getPlaylistPager('/api/v1/search/video-playlists', params, 0, sourceHost, true);
};
source.isChannelUrl = function (url) {
try {
if (!url) return false;
// Check for URL hint
if (url.includes('isPeertubeChannel=1')) {
return true;
}
// Check if the URL belongs to the base instance
const baseUrl = plugin.config.constants.baseUrl;
const isInstanceChannel = url.startsWith(`${baseUrl}/video-channels/`) || url.startsWith(`${baseUrl}/c/`);
if (isInstanceChannel) return true;
const urlTest = new URL(url);
const { host, pathname, searchParams } = urlTest;
// Check for URL hint in searchParams
if (searchParams.has('isPeertubeChannel')) {
return true;
}
// Check if the URL is from a known PeerTube instance
const isKnownInstanceUrl = INDEX_INSTANCES.instances.includes(host);
// Match PeerTube channel paths:
// - /c/{channel} - Short form channel URL
// - /c/{channel}/videos - Channel videos listing
// - /c/{channel}/video - Alternate channel videos listing
// - /video-channels/{channel} - Long form channel URL
// - /video-channels/{channel}/videos - Channel videos listing
// - /api/v1/video-channels/{channel} - API URL (for compatibility)
// - Allow optional trailing slash
const isPeerTubeChannelPath = /^\/(c|video-channels|api\/v1\/video-channels)\/[a-zA-Z0-9-_.]+(\/(video|videos)?)?\/?$/.test(pathname);
return isKnownInstanceUrl && isPeerTubeChannelPath;
} catch (error) {
log('Error checking PeerTube channel URL:', error);
return false;
}
};
source.getChannel = function (url) {
const handle = extractChannelId(url);
if (!handle) {
throw new ScriptException(`Failed to extract channel ID from URL: ${url}`);
}
const sourceBaseUrl = getBaseUrl(url);
const urlWithParams = `${sourceBaseUrl}/api/v1/video-channels/${handle}`;
try {
const [{ body: obj }] = httpGET({ url: urlWithParams, parseResponse: true });
// Add URL hint using utility function
const channelUrl = obj.url || `${sourceBaseUrl}/video-channels/${handle}`;
const channelUrlWithHint = addChannelUrlHint(channelUrl);
return new PlatformChannel({
id: new PlatformID(PLATFORM, obj.name, config.id),
name: obj.displayName || obj.name || handle,
thumbnail: getAvatarUrl(obj, sourceBaseUrl),
banner: getBannerUrl(obj, sourceBaseUrl),
subscribers: obj.followersCount || 0,
description: obj.description ?? "",
url: channelUrlWithHint,
links: {},
urlAlternatives: [
channelUrl,
channelUrlWithHint
]
});
} catch (e) {
log("Failed to get channel", e);
return null;
}
};
/**
* Retrieves the list of subscriptions for the authenticated user.
*
* This function fetches all subscriptions from the PeerTube instance.
* It handles pagination automatically, using batch requests if multiple pages are needed
*
* @returns {string[]} An array of subscription URLs.
*/
source.getUserSubscriptions = function() {
if (!bridge.isLoggedIn()) {
bridge.log("Failed to retrieve subscriptions page because not logged in.");
throw new ScriptException("Not logged in");
}
const itemsPerPage = 100;
let subscriptionUrls = [];
const initialParams = { start: 0, count: itemsPerPage };
const endpointUrl = `${plugin.config.constants.baseUrl}/api/v1/users/me/subscriptions`;
const initialRequestUrl = `${endpointUrl}?${buildQuery(initialParams)}`;
let initialResponseBody;
try {
[{ body: initialResponseBody }] = httpGET({ url: initialRequestUrl, useAuthenticated: true, parseResponse: true });
} catch (e) {
log("Failed to get user subscriptions", e);
return [];
}
if (initialResponseBody.data && initialResponseBody.data.length > 0) {
initialResponseBody.data.forEach(subscription => {
if (subscription.url) subscriptionUrls.push(subscription.url);
});
}
const totalSubscriptions = initialResponseBody.total;
if (subscriptionUrls.length >= totalSubscriptions) {
return subscriptionUrls;
}
const remainingSubscriptions = totalSubscriptions - subscriptionUrls.length;
const remainingPages = Math.ceil(remainingSubscriptions / itemsPerPage);
if (remainingPages > 1) {
const batchUrls = [];
for (let pageIndex = 1; pageIndex <= remainingPages; pageIndex++) {
const pageParams = { start: pageIndex * itemsPerPage, count: itemsPerPage };
batchUrls.push({ url: `${endpointUrl}?${buildQuery(pageParams)}`, useAuthenticated: true, parseResponse: true });
}
const batchResponses = httpGET(batchUrls);
batchResponses.forEach(batchResponse => {
if (batchResponse.isOk && batchResponse.code === 200) {
if (batchResponse.body.data) {
batchResponse.body.data.forEach(subscription => {
if (subscription.url) subscriptionUrls.push(subscription.url);
});
}
}
});
} else {
for (let pageIndex = 1; pageIndex <= remainingPages; pageIndex++) {
const pageParams = { start: pageIndex * itemsPerPage, count: itemsPerPage };
try {
const [{ body: pageResponseBody }] = httpGET({ url: `${endpointUrl}?${buildQuery(pageParams)}`, useAuthenticated: true, parseResponse: true });
if (pageResponseBody.data) {
pageResponseBody.data.forEach(subscription => {
if (subscription.url) subscriptionUrls.push(subscription.url);
});
}
} catch (e) {
// Continue to next page on error
}
}
}
return subscriptionUrls;
};
// source.getUserHistory = function() {
// if (!bridge.isLoggedIn()) {
// bridge.log("Failed to retrieve history page because not logged in.");
// throw new ScriptException("Not logged in");
// }
// return getHistoryVideoPager("/api/v1/users/me/history/videos", {}, 0);
// };
source.getUserPlaylists = function() {
let meData;
try {
[{ body: meData }] = httpGET({ url: `${plugin.config.constants.baseUrl}/api/v1/users/me`, useAuthenticated: true, parseResponse: true });
} catch (e) {
return [];
}
const username = meData.account?.name;
if (!username) return [];
const itemsPerPage = 50;
let playlistUrls = [];
const endpointUrl = `${plugin.config.constants.baseUrl}/api/v1/accounts/${username}/video-playlists`;
const baseParams = { sort: '-updatedAt' };
// Helper to build playlist URL with auth flag for private/unlisted playlists
const buildPlaylistUrl = (p) => {
let url = p.uuid
? `${plugin.config.constants.baseUrl}/w/p/${p.uuid}`
: p.url;
if (url && p.privacy?.id !== 1) {
url += PRIVATE_PLAYLIST_QUERY_PARAM;
}
return url;
};
let initialResponseBody;
try {
[{ body: initialResponseBody }] = httpGET({ url: `${endpointUrl}?${buildQuery({ ...baseParams, start: 0, count: itemsPerPage })}`, useAuthenticated: true, parseResponse: true });
} catch (e) {
return [];
}
if (initialResponseBody.data) {
initialResponseBody.data.forEach(p => {
const url = buildPlaylistUrl(p);
if (url) playlistUrls.push(url);
});
}
const total = initialResponseBody.total;
if (playlistUrls.length >= total) return playlistUrls;
const remainingPages = Math.ceil((total - playlistUrls.length) / itemsPerPage);
if (remainingPages > 1) {
const batchUrls = [];
for (let i = 1; i <= remainingPages; i++) {
batchUrls.push({ url: `${endpointUrl}?${buildQuery({ ...baseParams, start: i * itemsPerPage, count: itemsPerPage })}`, useAuthenticated: true, parseResponse: true });
}
httpGET(batchUrls).forEach(r => {
if (r.isOk && r.code === 200) {
if (r.body.data) {
r.body.data.forEach(p => {
const url = buildPlaylistUrl(p);
if (url) playlistUrls.push(url);
});
}
}
});
} else {
for (let i = 1; i <= remainingPages; i++) {
try {
const [{ body: { data } }] = httpGET({ url: `${endpointUrl}?${buildQuery({ ...baseParams, start: i * itemsPerPage, count: itemsPerPage })}`, useAuthenticated: true, parseResponse: true });
if (data) {
data.forEach(p => {
const url = buildPlaylistUrl(p);
if (url) playlistUrls.push(url);
});
}
} catch (e) {
// Continue to next page on error
}
}
}
return playlistUrls;
};
source.getChannelCapabilities = () => {
return {
types: [Type.Feed.Mixed, Type.Feed.Streams, Type.Feed.Videos, Type.Feed.Playlists],
sorts: [Type.Order.Chronological, "publishedAt"]
};
};
source.getChannelContents = function (url, type, order, filters) {
let sort = order;
if (sort === Type.Order.Chronological) {
sort = "-publishedAt";
}
const params = {
sort
};
const handle = extractChannelId(url);
const sourceBaseUrl = getBaseUrl(url);
// Handle different content type requests
if (type === Type.Feed.Playlists) {
// For playlists from a channel
return source.getChannelPlaylists(url, order, filters);
} else {
// For video types (Mixed, Streams, Videos)
if (type == Type.Feed.Streams) {
params.isLive = true;
} else if (type == Type.Feed.Videos) {
params.isLive = false;
}
return getVideoPager(`/api/v1/video-channels/${handle}/videos`, params, 0, sourceBaseUrl, false, null, true);
}
};
source.searchChannelContents = function (channelUrl, query, type, order, filters) {
const handle = extractChannelId(channelUrl);
const sourceBaseUrl = getBaseUrl(channelUrl);
if (!handle) {
throw new ScriptException(`Failed to extract channel ID from URL: ${channelUrl}`);
}
const params = {
search: query.trim(),
sort: "-publishedAt"
};
// Use the channel-specific videos endpoint with search parameter
return getVideoPager(`/api/v1/video-channels/${handle}/videos`, params, 0, sourceBaseUrl, false, null, true);
};
source.getChannelPlaylists = function (url, order, filters) {
let sort = order;
if (sort === Type.Order.Chronological) {
sort = "-publishedAt";
}
const params = {
sort
};
const handle = extractChannelId(url);
if (!handle) {
return new PlaylistPager([], false);
}
const sourceBaseUrl = getBaseUrl(url);
return getPlaylistPager(`/api/v1/video-channels/${handle}/video-playlists`, params, 0, sourceBaseUrl);
};
// Adds support for checking if a URL is a playlist URL
source.isPlaylistUrl = function(url) {
try {
if (!url) return false;
// Check for URL hint
if (url.includes('isPeertubePlaylist=1') || url.includes('isPeertubeTagSearch=1')) {
return true;
}
// Check for tag search URLs
const urlObj = new URL(url);
if (urlObj.pathname === '/search' && urlObj.searchParams.has('tagsOneOf')) {
return true;
}
// Check if URL belongs to the base instance and matches playlist pattern
const baseUrl = plugin.config.constants.baseUrl;
const isInstancePlaylist = url.startsWith(`${baseUrl}/videos/watch/playlist/`) ||
url.startsWith(`${baseUrl}/w/p/`) ||
url.startsWith(`${baseUrl}/video-playlists/`) ||
(url.startsWith(`${baseUrl}/video-channels/`) && url.includes('/video-playlists/')) ||
(url.startsWith(`${baseUrl}/c/`) && url.includes('/video-playlists/'));
if (isInstancePlaylist) return true;
const urlTest = new URL(url);
const { host, pathname, searchParams } = urlTest;
// Check for URL hint in searchParams
if (searchParams.has('isPeertubePlaylist')) {
return true;
}
// Check if the URL is from a known PeerTube instance
const isKnownInstanceUrl = INDEX_INSTANCES.instances.includes(host);
// Match PeerTube playlist paths:
// - /videos/watch/playlist/{uuid} - Standard playlist URL
// - /w/p/{uuid} - Short form playlist URL
// - /video-playlists/{uuid} - Direct playlist URL format
// - /video-channels/{channelName}/video-playlists/{playlistId} - Channel playlist URL
// - /c/{channelName}/video-playlists/{playlistId} - Short form channel playlist URL
// - /api/v1/video-playlists/{uuid} - API URL (for compatibility)
const isPeerTubePlaylistPath = /^\/(videos\/watch\/playlist|w\/p)\/[a-zA-Z0-9-_]+$/.test(pathname) ||
/^\/(video-playlists|api\/v1\/video-playlists)\/[a-zA-Z0-9-_]+$/.test(pathname) ||
/^\/(video-channels|c)\/[a-zA-Z0-9-_.]+\/video-playlists\/[a-zA-Z0-9-_]+$/.test(pathname);
return isKnownInstanceUrl && isPeerTubePlaylistPath;
} catch (error) {
log('Error checking PeerTube playlist URL:', error);
return false;
}
};
// Gets a playlist and its information
source.getPlaylist = function(url) {
// Check if this is a tag search URL
try {
const urlObj = new URL(url);
if (urlObj.pathname === '/search' && urlObj.searchParams.has('tagsOneOf')) {
return getTagPlaylist(url);
}
} catch (e) {
// Continue with regular playlist handling
}
// Check if this is a private playlist that requires authentication
// Private playlists are flagged with PRIVATE_PLAYLIST_QUERY_PARAM by getUserPlaylists
// We also verify that the URL belongs to the base instance to prevent bad actors from triggering auth on external domains
const requiresAuth = url.includes(PRIVATE_PLAYLIST_QUERY_PARAM) && isBaseInstanceUrl(url);
// Remove the auth flag from URL before processing
const cleanUrl = url.replace(PRIVATE_PLAYLIST_QUERY_PARAM, '');
const playlistId = extractPlaylistId(cleanUrl);
if (!playlistId) {
return null;
}
const sourceBaseUrl = getBaseUrl(cleanUrl);
const urlWithParams = `${sourceBaseUrl}/api/v1/video-playlists/${playlistId}`;