Repository navigation
Expand file tree
/
Copy pathInternetArchiveScript.js
More file actions
3339 lines (3020 loc) · 129 KB
/
Copy pathInternetArchiveScript.js
File metadata and controls
3339 lines (3020 loc) · 129 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
const PLATFORM = "Internet Archive";
const BASE_URL = "https://archive.org";
const SEARCH_URL = "https://archive.org/advancedsearch.php";
const SCRAPE_URL = "https://archive.org/services/search/v1/scrape";
const DETAILS_URL = "https://archive.org/details";
const CHANNEL_ICON_FALLBACK = "https://plugins.grayjay.app/InternetArchive/InternetArchiveIcon.png";
const PLAYLIST_URL_HINT = "isArchivePlaylist=1";
const CONTENT_URL_HINT = "isArchiveContent=1";
const MEDIA_TYPE_OPTIONS = ['all', 'movies', 'television', 'news', 'education', 'documentaries', 'concerts', 'audio'];
const YEAR_OPTIONS = ['all', '2020s', '2010s', '2000s', '1990s', '1980s', '1970s', '1960s', 'older'];
// Single source of truth for the language filter; `terms` ORs every form IA stores a language under (MARC
// code + English name + ISO 639-2/T variant). LANGUAGE_OPTIONS/LABELS/QUERY and the config derive from this.
const LANGUAGES = [
{ key: 'all', name: 'All', terms: null },
{ key: 'ara', name: 'Arabic', terms: 'ara OR Arabic' },
{ key: 'ben', name: 'Bengali', terms: 'ben OR Bengali' },
{ key: 'chi', name: 'Chinese', terms: 'chi OR zho OR Chinese' },
{ key: 'cze', name: 'Czech', terms: 'cze OR ces OR Czech' },
{ key: 'dan', name: 'Danish', terms: 'dan OR Danish' },
{ key: 'dut', name: 'Dutch', terms: 'dut OR nld OR Dutch' },
{ key: 'eng', name: 'English', terms: 'eng OR English' },
{ key: 'fin', name: 'Finnish', terms: 'fin OR Finnish' },
{ key: 'fre', name: 'French', terms: 'fre OR fra OR French' },
{ key: 'ger', name: 'German', terms: 'ger OR deu OR German' },
{ key: 'gre', name: 'Greek', terms: 'gre OR ell OR Greek' },
{ key: 'heb', name: 'Hebrew', terms: 'heb OR Hebrew' },
{ key: 'hin', name: 'Hindi', terms: 'hin OR Hindi' },
{ key: 'hun', name: 'Hungarian', terms: 'hun OR Hungarian' },
{ key: 'ind', name: 'Indonesian', terms: 'ind OR Indonesian' },
{ key: 'ita', name: 'Italian', terms: 'ita OR Italian' },
{ key: 'jpn', name: 'Japanese', terms: 'jpn OR Japanese' },
{ key: 'kor', name: 'Korean', terms: 'kor OR Korean' },
{ key: 'lat', name: 'Latin', terms: 'lat OR Latin' },
{ key: 'mar', name: 'Marathi', terms: 'mar OR Marathi' },
{ key: 'nor', name: 'Norwegian', terms: 'nor OR Norwegian' },
{ key: 'per', name: 'Persian', terms: 'per OR fas OR Persian' },
{ key: 'pol', name: 'Polish', terms: 'pol OR Polish' },
{ key: 'por', name: 'Portuguese', terms: 'por OR Portuguese' },
{ key: 'rum', name: 'Romanian', terms: 'rum OR ron OR Romanian' },
{ key: 'rus', name: 'Russian', terms: 'rus OR Russian' },
{ key: 'san', name: 'Sanskrit', terms: 'san OR Sanskrit' },
{ key: 'spa', name: 'Spanish', terms: 'spa OR Spanish' },
{ key: 'swe', name: 'Swedish', terms: 'swe OR Swedish' },
{ key: 'tam', name: 'Tamil', terms: 'tam OR Tamil' },
{ key: 'tel', name: 'Telugu', terms: 'tel OR Telugu' },
{ key: 'tha', name: 'Thai', terms: 'tha OR Thai' },
{ key: 'tur', name: 'Turkish', terms: 'tur OR Turkish' },
{ key: 'ukr', name: 'Ukrainian', terms: 'ukr OR Ukrainian' },
{ key: 'urd', name: 'Urdu', terms: 'urd OR Urdu' },
{ key: 'vie', name: 'Vietnamese', terms: 'vie OR Vietnamese' }
];
const LANGUAGE_OPTIONS = LANGUAGES.map(language => language.key);
const LANGUAGE_LABELS = {};
const LANGUAGE_QUERY = {};
LANGUAGES.forEach(language => {
LANGUAGE_LABELS[language.key] = language.name;
if (language.terms) LANGUAGE_QUERY[language.key] = `language:(${language.terms})`;
});
const PLAYABLE_MEDIATYPES = '(movies OR video OR audio OR etree)';
// Excludes items Archive.org has flagged as access-restricted (dark/withdrawn from public view).
const ACCESS_RESTRICTED_CLAUSE = ' AND NOT access-restricted-item:true';
// 'mpeg4' (not 'mpeg') so raw MPEG2/MXF originals aren't offered as playable; still matches "512Kb MPEG4"
// derivatives, and h.264 is matched on its own.
const VIDEO_FORMAT_TERMS = ['mp4', 'mpeg4', 'h.264', 'avi', 'mov', 'webm', 'ogg video', 'ogv', 'cinepack'];
// Legacy MPEG1/2 raw originals, offered only when an item has no preferred-format derivative above (so
// MPEG2-only items still play).
const FALLBACK_VIDEO_FORMAT_TERMS = ['mpeg', 'mpg'];
const AUDIO_FORMAT_TERMS = ['mp3', 'ogg', 'flac', 'wav', 'm4a', 'opus', 'aac'];
// Real audio extension required: skips sidecar files (e.g. ".ffp") whose format substring-matches an audio
// term. Trailing (?:[?#]|$) tolerates a ?query / #fragment after the extension.
const AUDIO_FILE_EXT = /\.(mp3|ogg|flac|wav|m4a|opus|aac)(?:[?#]|$)/i;
// Poster byte floor/cap (a rough resolution proxy): the floor skips sub-tile images, the cap skips multi-MB
// originals pulled just for a thumbnail.
const MIN_POSTER_BYTES = 15 * 1024;
const MAX_POSTER_BYTES = 2 * 1024 * 1024;
// jpg/png only: IA's derived poster is always jpg/png, while the item's `.gif` is a low-res animated
// preview whose large byte size (many frames) would beat the floor yet is smaller than the 180px tile.
const POSTER_IMAGE_EXT = /\.(jpe?g|png)(?:[?#]|$)/i;
const SUBTITLE_FORMAT_TERMS = ['srt', 'vtt', 'webvtt', 'ass', 'sub'];
const HLS_FILE_EXT = /\.m3u8(?:[?#]|$)/i;
const MEDIA_TYPE_QUERY = {
'movies': '(movies OR video)',
'television': '(movies OR video) AND subject:television',
'news': '(movies OR video) AND subject:news',
'education': '(movies OR video) AND subject:education',
'documentaries': '(movies OR video) AND subject:documentary',
'concerts': '(audio OR movies OR video OR etree) AND subject:concert',
'audio': '(audio OR etree)'
};
const YEAR_QUERY = {
'2020s': 'year:[2020 TO 2029]',
'2010s': 'year:[2010 TO 2019]',
'2000s': 'year:[2000 TO 2009]',
'1990s': 'year:[1990 TO 1999]',
'1980s': 'year:[1980 TO 1989]',
'1970s': 'year:[1970 TO 1979]',
'1960s': 'year:[1960 TO 1969]',
'older': 'year:[* TO 1959]'
};
// label -> advancedsearch sort[] clause, mirroring Archive.org's own search UI (verified live). Single source
// for the per-search sorts and the global `sortBy` setting. "Relevance" = null omits the sort param (_score).
const SEARCH_SORT_QUERY = {
'Relevance': null,
'All-time views': 'downloads desc',
'Weekly views': 'week desc',
'Title': 'titleSorter asc',
'Date published': 'date desc',
'Date archived': 'publicdate desc',
'Date reviewed': 'reviewdate desc',
'Date added': 'addeddate desc',
'Creator': 'creatorSorter asc'
};
// Popularity sort reused by recommendations (derived from the sort map above).
const POPULAR_SORT = SEARCH_SORT_QUERY['All-time views'];
// Global "Sort By" setting options (config dropdown, index-aligned). Excludes "Relevance" — it needs a
// query, so it's a search-only sort and meaningless for home/channel.
const GLOBAL_SORT_OPTIONS = Object.keys(SEARCH_SORT_QUERY).filter(key => key !== 'Relevance');
// "Item Date" setting options (config dropdown, index-aligned): which date to show on feed cards.
const DISPLAY_DATE_OPTIONS = ['Upload date', 'Original date'];
// Display labels for the per-search filter groups (built from the existing option arrays, minus 'all').
const MEDIA_TYPE_LABELS = {
all: 'All',
movies: 'Movies',
television: 'Television',
news: 'News',
education: 'Education',
documentaries: 'Documentaries',
concerts: 'Concerts',
audio: 'Audio'
};
const YEAR_LABELS = {
all: 'All',
'2020s': '2020s',
'2010s': '2010s',
'2000s': '2000s',
'1990s': '1990s',
'1980s': '1980s',
'1970s': '1970s',
'1960s': '1960s',
'older': 'Before 1960'
}
// Container derived from the file extension (IA's `format` is free-text, not a valid container); codec
// refined by `format` where named, left '' when unknown so the player sniffs the stream.
const VIDEO_CONTAINERS = {
// .mov labeled video/mp4 (it is mp4-family) so FCast plays it; video/quicktime makes FCast prompt a download.
mp4: 'video/mp4', m4v: 'video/mp4', mov: 'video/mp4', webm: 'video/webm',
ogv: 'video/ogg', ogg: 'video/ogg', mpg: 'video/mpeg', mpeg: 'video/mpeg',
avi: 'video/x-msvideo', mkv: 'video/x-matroska'
};
const VIDEO_EXT_CODECS = {
mp4: 'h264', m4v: 'h264', webm: 'vp8', ogv: 'theora', ogg: 'theora', mpg: 'mpeg2video', mpeg: 'mpeg2video'
};
const AUDIO_CONTAINERS = {
mp3: 'audio/mpeg', m4a: 'audio/mp4', aac: 'audio/aac', flac: 'audio/flac',
ogg: 'audio/ogg', oga: 'audio/ogg', opus: 'audio/ogg', wav: 'audio/wav'
};
const AUDIO_EXT_CODECS = {
mp3: 'mp3', m4a: 'aac', aac: 'aac', flac: 'flac', ogg: 'vorbis', oga: 'vorbis', opus: 'opus', wav: 'pcm'
};
// === Regex patterns ===
// Reusable regexes grouped here; trivial one-offs stay inline, and the ADULT_TERMS/ADULT_QUERY_* blocklists
// live at the file bottom.
// URL routing / identifiers
const REGEX_CHANNEL_SEARCH_URL = /archive\.org\/search(?:\.php)?\?query=(uploader|creator):/;
const REGEX_ACCOUNT_URL = /archive\.org\/(?:details\/)?@([^\/?]+)/;
const REGEX_DETAILS_URL = /archive\.org\/details\/[^\/?]+/;
const REGEX_DETAILS_ACCOUNT_URL = /archive\.org\/details\/@/;
const REGEX_IDENTIFIER = /details\/([^\/?]+)/;
const REGEX_SELECTED_FILE = /[?&]file=([^&]+)/;
const REGEX_CREATOR_QUERY = /creator:([^&#]+)/;
const REGEX_UPLOADER_QUERY = /uploader:([^&#]+)/;
const REGEX_HANDLE = /@([^\/?]+)/;
const REGEX_ABSOLUTE_URL = /^https?:\/\//;
// File / format / media
const REGEX_FILE_EXT = /\.([a-z0-9]+)(?:[?#]|$)/i;
const REGEX_STRIP_EXT = /\.[^\/.]+$/;
const REGEX_SRT_EXT = /\.srt(\?|$)/i;
const REGEX_ASR = /\.asr\./i;
const REGEX_KBPS = /(\d+)\s*kbps/i;
const REGEX_RESOLUTION = /^(\d{3,4})p$/; // a whole filename token like "720p"/"1080p"
const REGEX_QUERY_OR_FRAGMENT = /[?#]/;
// Query / search. /g regexes here are only used with .replace() (stateless); do not reuse them with .test().
const REGEX_LUCENE_OPERATORS = /[+\-&|!(){}\[\]^"~*?:\\/]/g;
const REGEX_WHITESPACE = /\s+/g;
// Text / time / date parsing
const REGEX_EMBED_PLAYLIST = /playlist='([\s\S]*?)'><\/play-av>/;
const REGEX_SRT_CUE = /\d{2}:\d{2}:\d{2}[,.]\d{3}\s*-->/;
const REGEX_SRT_TIMESTAMP_COMMA = /(\d{2}:\d{2}:\d{2}),(\d{3})/g;
const REGEX_DURATION_HMS = /(\d+):(\d+):(\d+)/;
const REGEX_DURATION_MS = /^(\d{1,3}):(\d{2})$/; // a bare MM:SS clock string
const REGEX_DURATION_MIN = /(\d+)\s*min/;
const REGEX_INTEGER = /^\d+$/;
const REGEX_DATE_PLACEHOLDER = /^0{4}(?:\D|$)/;
const REGEX_DATE_YEAR = /^\d{4}$/;
const REGEX_DATE_YEAR_MONTH = /^\d{4}[-\/]\d{1,2}$/;
// MAX_QUERY_CHARS: the content search interpolates the query twice, so it counts double against
// advancedsearch's 2047-char `q` cap (past which the API silently returns 0 results). Cap well under it.
const MAX_QUERY_CHARS = 300;
// Rows fetched per page; over-fetching leaves enough visible results after isAdultItem() drops page matches.
const FETCH_ROWS = 40;
// Scrape page size; the cursor only advances at >=~500 (smaller counts repeat the first page).
const SCRAPE_COUNT = 500;
// HTTP statuses worth one reduced-priority retry (rate-limit / overload / transient server error).
const TRANSIENT_HTTP_STATUSES = [429, 500, 501, 502, 503, 504];
// Metadata fields requested for feed items from advancedsearch/scrape.
const SCRAPE_FIELDS = 'identifier,title,description,creator,subject,date,publicdate,addeddate,runtime,downloads';
// Filename token / embed track label -> ISO 639-1 code; code -> display name. 'asr' and unknown tokens
// resolve to Language.UNKNOWN / 'Subtitles'.
const LANGUAGE_TOKEN_TO_CODE = {
en: 'en', eng: 'en', english: 'en',
es: 'es', spa: 'es', spanish: 'es',
fr: 'fr', fre: 'fr', fra: 'fr', french: 'fr',
de: 'de', ger: 'de', deu: 'de', german: 'de',
it: 'it', ita: 'it', italian: 'it',
pt: 'pt', por: 'pt', portuguese: 'pt',
ru: 'ru', rus: 'ru', russian: 'ru',
ja: 'ja', jpn: 'ja', japanese: 'ja',
zh: 'zh', chi: 'zh', zho: 'zh', chinese: 'zh'
};
const LANGUAGE_CODE_TO_NAME = {
en: 'English',
es: 'Spanish',
fr: 'French',
de: 'German',
it: 'Italian',
pt: 'Portuguese',
ru: 'Russian',
ja: 'Japanese',
zh: 'Chinese'
};
/**
* Community upload collections excluded when curated-only mode is enabled.
*/
const COMMUNITY_COLLECTIONS = ['opensource_movies', 'opensource_audio', 'opensource', 'opensource_media'];
let config = {};
let settings = {};
let state = {
collectionDocCache: {}, // identifier -> collection doc, or null when not a collection
runtimeItemInfoCache: {}, // identifier -> normalized /metadata
// identifier -> parsed /embed playlist entries (one per real part + caption tracks); /metadata doesn't
// mark which originals are real parts, so the embed playlist is the source of truth.
embedPlaylistCache: {},
lastServiceIssueToastAt: 0
};
source.enable = function(conf, _settings, savedState) {
config = conf ?? {};
settings = _settings ?? {};
if (savedState) {
try {
state = JSON.parse(savedState);
} catch (error) {
log("Failed to restore Archive.org saved state: " + error);
}
}
};
source.saveState = function() {
return JSON.stringify(state);
};
source.getHome = function() {
return new ArchiveOrgHomePager();
};
source.search = function(query, type, order, filters) {
if (isAdultFilterOn() && isAdultQuery(query)) {
return new ContentPager([], false);
}
const clean = sanitizeQuery(query);
if (!clean) return new ContentPager([], false);
return new ArchiveOrgSearchPager({ query: clean, order, filters, channelConstraint: null, authorLink: null, page: 1, seenIds: [], cursor: '' });
};
/**
* Advertises per-search sorts + filters so the search UI shows sort/filter controls. Sorts map to
* advancedsearch clauses (SEARCH_SORT_QUERY); filter groups are built from the existing option arrays.
* The host returns the chosen sort as `order` and selections as `filters` (keyed by group id → values),
* which source.search/ArchiveOrgSearchPager apply (overriding the global settings for that search).
* @returns {ResultCapabilities}
*/
source.getSearchCapabilities = function() {
return buildSearchCapabilities();
};
source.getSearchChannelContentsCapabilities = function() {
// In-channel search exposes the same sorts/filters as global search.
return buildSearchCapabilities();
};
/**
* ResultCapabilities (types, sort labels, filter groups) shared by getSearchCapabilities and
* getSearchChannelContentsCapabilities. Each group's leading "All" (value 'all') = no constraint.
* @returns {ResultCapabilities}
* @example
* buildSearchCapabilities() // => ResultCapabilities(['VIDEOS'], ['All-time views', ...], [MediaType, Decade, Language])
*/
function buildSearchCapabilities() {
const group = (name, id, options, labels) => new FilterGroup(
name,
options.map(option => new FilterCapability(labels[option] || option, option)),
false,
id
);
return new ResultCapabilities(
[Type.Feed.Videos],
Object.keys(SEARCH_SORT_QUERY),
[
group("Media Type", "mediaType", MEDIA_TYPE_OPTIONS, MEDIA_TYPE_LABELS),
group("Decade", "year", YEAR_OPTIONS, YEAR_LABELS),
group("Language", "language", LANGUAGE_OPTIONS, LANGUAGE_LABELS)
]
);
}
source.searchChannels = function(query) {
if (isAdultFilterOn() && isAdultQuery(query)) {
return new ChannelPager([], false);
}
const clean = sanitizeQuery(query);
if (!clean) return new ChannelPager([], false);
return new ArchiveOrgUploaderSearchPager(clean);
};
source.searchPlaylists = function(query, type, order, filters) {
if (isAdultFilterOn() && isAdultQuery(query)) {
return new PlaylistPager([], false);
}
const clean = sanitizeQuery(query);
if (!clean) return new PlaylistPager([], false);
return new ArchiveOrgPlaylistSearchPager({ query: clean, cursor: '' });
};
source.isChannelUrl = function(url) {
const normalizedUrl = normalizeArchiveUrl(url);
return REGEX_CHANNEL_SEARCH_URL.test(normalizedUrl) ||
REGEX_ACCOUNT_URL.test(normalizedUrl);
};
source.getChannel = function(url) {
if (!url) {
throw new ScriptException("Invalid channel URL");
}
const { field, value } = extractChannelQuery(url);
if (!value) {
throw new ScriptException("Invalid or unknown channel");
}
return buildChannel(field, value, url);
};
source.getChannelCapabilities = function() {
return {
types: [Type.Feed.Videos],
sorts: [],
filters: []
};
};
source.getChannelContents = function(url, type, order, filters) {
if (!url) {
throw new ScriptException("Invalid channel URL");
}
const { field, value } = extractChannelQuery(url);
if (!value) {
throw new ScriptException("Invalid or unknown channel");
}
const authorLink = new PlatformAuthorLink(
new PlatformID(PLATFORM, value, config.id),
value,
url,
CHANNEL_ICON_FALLBACK
);
return new ArchiveOrgUploaderPager({ field, uploader: value, authorLink, cursor: '' });
};
source.searchChannelContents = function(url, query, type, order, filters) {
if (!url) {
throw new ScriptException("Invalid channel URL");
}
if (isAdultFilterOn() && isAdultQuery(query)) {
return new ContentPager([], false);
}
const { field, value } = extractChannelQuery(url);
if (!value) {
return new ContentPager([], false);
}
const clean = sanitizeQuery(query);
if (!clean) {
return new ContentPager([], false);
}
const authorLink = new PlatformAuthorLink(
new PlatformID(PLATFORM, value, config.id),
value,
url,
CHANNEL_ICON_FALLBACK
);
return new ArchiveOrgSearchPager({ query: clean, order, filters, channelConstraint: fieldEquals(field, value), authorLink, page: 1, seenIds: [], cursor: '' });
};
source.isContentDetailsUrl = function(url) {
if (!url) return false;
if (url.includes(PLAYLIST_URL_HINT)) return false;
if (REGEX_DETAILS_ACCOUNT_URL.test(url)) return false; // details/@handle is an account page (channel), not an item
if (!REGEX_DETAILS_URL.test(url)) return false;
if (extractSelectedFileFromUrl(url)) return true;
if (url.includes(CONTENT_URL_HINT)) return true;
// No hint (external/pasted /details/ link): item vs collection can only be told apart by asking the
// server. isCollectionIdentifier() does that via a cached search; in-app URLs always carry a hint above.
return !isCollectionIdentifier(extractIdentifierFromUrl(url));
};
source.getContentDetails = function(url) {
const identifier = extractIdentifierFromUrl(url);
const itemInfo = fetchItemInfo(identifier);
assertItemCanOpen(itemInfo);
const selectedFile = extractSelectedFileFromUrl(url);
// HLS-package items list their segments as files; offer the whole-item manifest and skip the segments.
// mediatype gates it so a stray manifest can't override an audio item.
const manifestSources = manifestFilesToSources(itemInfo, playableManifestFiles(itemInfo));
const isAudioItem = ['audio', 'etree'].indexOf(ensureStringFromMetadata(itemInfo.metadata, 'mediatype')) !== -1;
let idValue, name, duration, videoDescriptor, shareTrackKey, subtitles;
if (manifestSources.length > 0 && !isAudioItem) {
idValue = itemInfo.identifier;
name = itemInfo.title || itemInfo.identifier;
duration = extractDuration(itemInfo);
videoDescriptor = new VideoSourceDescriptor(manifestSources);
shareTrackKey = '';
subtitles = extractSubtitles(itemInfo);
} else {
const videoSelection = selectVideoSources(itemInfo, selectedFile);
const audioSelection = selectAudioSources(itemInfo, selectedFile);
// Nothing playable: no direct video, no audio, no manifest.
if (videoSelection.sources.length === 0 && audioSelection.sources.length === 0 && manifestSources.length === 0) {
throw new UnavailableException(`No playable content available. This item may contain only private/restricted files, unsupported formats, or metadata-only content. (${itemInfo.files ? itemInfo.files.length : 0} total files, 0 playable)`);
}
// Audio-only item: unmuxed audio descriptor.
if (videoSelection.sources.length === 0 && audioSelection.sources.length > 0) {
idValue = audioSelection.trackKey ? `${itemInfo.identifier}/${audioSelection.trackKey}` : itemInfo.identifier;
name = audioDetailsTitle(itemInfo, audioSelection);
duration = audioSelection.duration || extractDuration(itemInfo);
videoDescriptor = new UnMuxVideoSourceDescriptor([], audioSelection.sources);
shareTrackKey = audioSelection.trackCount > 1 ? audioSelection.trackKey : '';
subtitles = extractSubtitles(itemInfo);
} else {
// Direct video, or the HLS manifest as a fallback when the item has no direct video or audio files.
const sources = videoSelection.sources.length > 0 ? videoSelection.sources : manifestSources;
const multiPart = videoSelection.trackCount > 1;
idValue = multiPart && videoSelection.trackKey ? `${itemInfo.identifier}/${videoSelection.trackKey}` : itemInfo.identifier;
name = (multiPart && videoSelection.trackName) ? videoSelection.trackName : (itemInfo.title || itemInfo.identifier);
duration = (sources[0] && sources[0].duration) || extractDuration(itemInfo);
videoDescriptor = new VideoSourceDescriptor(sources);
shareTrackKey = multiPart && videoSelection.trackKey ? videoSelection.trackKey : '';
subtitles = mergeSubtitles(extractSubtitles(itemInfo), extractEmbedSubtitles(videoSelection.entry));
}
}
return new PlatformVideoDetails({
id: new PlatformID(PLATFORM, idValue, config.id),
name: name,
thumbnails: extractThumbnails(itemInfo),
author: buildDetailAuthor(itemInfo),
datetime: archiveDateToUnix(itemInfo.addeddate),
duration: duration,
viewCount: itemInfo.downloads || 0,
url: url,
shareUrl: shareUrlForItem(itemInfo.identifier, shareTrackKey),
description: buildContentDetailsDescription(itemInfo, duration),
video: videoDescriptor,
subtitles: subtitles,
getContentRecommendations: function() { return source.getContentRecommendations(url); }
});
};
source.isPlaylistUrl = function(url) {
if (!url) return false;
if (url.includes(PLAYLIST_URL_HINT)) return true;
if (!REGEX_DETAILS_URL.test(url)) return false;
if (extractSelectedFileFromUrl(url)) return false;
if (url.includes(CONTENT_URL_HINT)) return false;
// External/pasted /details/ link with no hint: a cached server lookup decides collection vs item.
return isCollectionIdentifier(extractIdentifierFromUrl(url));
};
source.getPlaylist = function(url) {
const identifier = extractIdentifierFromUrl(url);
const doc = getCollectionDoc(identifier);
if (!doc) return getItemPlaylist(identifier);
const authorLink = buildItemAuthor(ensureString(doc.creator), null);
return new PlatformPlaylistDetails({
id: new PlatformID(PLATFORM, identifier, config.id),
name: ensureString(doc.title) || identifier || '',
author: authorLink,
url: `${DETAILS_URL}/${identifier}?${PLAYLIST_URL_HINT}`,
thumbnail: `${BASE_URL}/services/img/${identifier}`,
videoCount: doc.item_count || 0,
contents: new ArchiveOrgCollectionPager({ identifier, authorLink, cursor: '' })
});
};
source.getComments = function(url) {
return new ArchiveOrgCommentPager({ url, offset: 0 });
};
source.getContentRecommendations = function(url) {
try {
const itemInfo = fetchItemInfo(extractIdentifierFromUrl(url));
// Multi-track audio (concerts/albums) surface their own tracklist under the player — so the user
// sees and can play every track without a separate playlist view. Single items keep related recs.
if (isMultiTrackAudioItem(itemInfo)) {
const authorLink = buildItemAuthor(ensureStringFromMetadata(itemInfo.metadata, 'creator'), null);
return new ArchiveOrgItemAudioPager(itemInfo, authorLink);
}
if (isMultiPartVideoItem(itemInfo)) {
const authorLink = buildItemAuthor(ensureStringFromMetadata(itemInfo.metadata, 'creator'), null);
return new ArchiveOrgItemVideoPager(itemInfo, authorLink);
}
return new ArchiveOrgRecommendationsPager(itemInfo);
} catch (error) {
log("Error building recommendations: " + error);
return new ContentPager([], false);
}
};
/**
* PlatformPlaylistDetails for a single item opened as a playlist: a multi-part video's parts, a multi-track
* audio item's tracks, or one video.
* @param {string} identifier
* @returns {PlatformPlaylistDetails}
* @example
* getItemPlaylist('swami2026-06-07') // => PlatformPlaylistDetails with one row per track
*/
function getItemPlaylist(identifier) {
const itemInfo = fetchItemInfo(identifier);
assertItemCanOpen(itemInfo);
const authorLink = buildItemAuthor(ensureStringFromMetadata(itemInfo.metadata, 'creator'), null);
if (isMultiPartVideoItem(itemInfo)) {
return new PlatformPlaylistDetails({
id: new PlatformID(PLATFORM, identifier, config.id),
name: itemInfo.title || identifier,
author: authorLink,
url: `${DETAILS_URL}/${identifier}?${PLAYLIST_URL_HINT}`,
thumbnail: `${BASE_URL}/services/img/${identifier}`,
videoCount: videoParts(itemInfo).length,
contents: new ArchiveOrgItemVideoPager(itemInfo, authorLink)
});
}
if (!isMultiTrackAudioItem(itemInfo)) {
const video = itemToPlatformVideo({
identifier: itemInfo.identifier,
title: itemInfo.title,
description: itemInfo.description,
creator: ensureStringFromMetadata(itemInfo.metadata, 'creator'),
publicdate: itemInfo.publicdate,
addeddate: itemInfo.addeddate,
duration: extractDuration(itemInfo),
downloads: itemInfo.downloads
}, authorLink);
return new PlatformPlaylistDetails({
id: new PlatformID(PLATFORM, identifier, config.id),
name: itemInfo.title || identifier,
author: authorLink,
url: `${DETAILS_URL}/${identifier}?${PLAYLIST_URL_HINT}`,
thumbnail: `${BASE_URL}/services/img/${identifier}`,
videoCount: 1,
contents: new ContentPager([video], false)
});
}
const audioGroups = buildAudioGroups(itemInfo);
return new PlatformPlaylistDetails({
id: new PlatformID(PLATFORM, identifier, config.id),
name: itemInfo.title || identifier,
author: authorLink,
url: `${DETAILS_URL}/${identifier}?${PLAYLIST_URL_HINT}`,
thumbnail: `${BASE_URL}/services/img/${identifier}`,
videoCount: audioGroups.keys.length,
contents: new ArchiveOrgItemAudioPager(itemInfo, authorLink)
});
}
/**
* Coerce a value to a string (first element if an array, '' if empty/null).
* @param {*} value
* @returns {string}
* @example
* ensureString(['a','b']) // => 'a'
* ensureString(42) // => '42'
*/
function ensureString(value) {
if (Array.isArray(value)) {
return value.length > 0 ? String(value[0]) : '';
}
return value ? String(value) : '';
}
/**
* Read a metadata field as a string ('' if absent).
* @param {object} metadata
* @param {string} field
* @returns {string}
* @example
* ensureStringFromMetadata({creator:'NASA'}, 'creator') // => 'NASA'
*/
function ensureStringFromMetadata(metadata, field) {
if (!metadata || !metadata[field]) return '';
return ensureString(metadata[field]);
}
/**
* Read a metadata field as a compact comma-separated value list.
* @param {object} metadata
* @param {string} field
* @param {number} maxValues
* @returns {string}
* @example
* metadataList({language:['eng','English']}, 'language', 2) // => 'eng, English'
*/
function metadataList(metadata, field, maxValues) {
if (!metadata || !metadata[field]) return '';
const rawValues = Array.isArray(metadata[field]) ? metadata[field] : [metadata[field]];
const values = [];
for (const raw of rawValues) {
const value = ensureString(raw).trim();
if (value && values.indexOf(value) < 0) values.push(value);
if (values.length >= maxValues) break;
}
return values.join(', ');
}
/**
* Human-readable duration for the detail metadata block.
* @param {number} seconds
* @returns {string}
* @example
* formatDuration(3723) // => '1:02:03'
*/
function formatDuration(seconds) {
const total = Math.floor(seconds || 0);
if (total <= 0) return '';
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const secs = total % 60;
if (hours > 0) {
return `${hours}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
}
return `${minutes}:${String(secs).padStart(2, '0')}`;
}
/**
* Keep Archive.org partial dates readable, while normalizing full timestamps to YYYY-MM-DD.
* @param {*} value
* @returns {string}
* @example
* formatArchiveDateForDetails('2002-07-16 00:00:00') // => '2002-07-16'
*/
function formatArchiveDateForDetails(value) {
const raw = ensureString(value).trim();
if (!raw || REGEX_DATE_PLACEHOLDER.test(raw)) return '';
if (REGEX_DATE_YEAR.test(raw)) return raw;
if (REGEX_DATE_YEAR_MONTH.test(raw)) {
const parts = raw.replace(/\//g, '-').split('-');
return `${parts[0]}-${String(parseInt(parts[1], 10)).padStart(2, '0')}`;
}
// Take the YYYY-MM-DD prefix directly; going through Date/toISOString shifts the day in +UTC zones.
const iso = raw.replace(/\//g, '-').match(/^(\d{4}-\d{2}-\d{2})/);
return iso ? iso[1] : raw;
}
/**
* Human-readable language metadata, mapping common Archive.org language keys to display labels.
* @param {object} metadata
* @returns {string}
* @example
* formatMetadataLanguage({language:'eng'}) // => 'English'
*/
function formatMetadataLanguage(metadata) {
if (!metadata || !metadata.language) return '';
const rawValues = Array.isArray(metadata.language) ? metadata.language : [metadata.language];
const values = [];
for (const raw of rawValues) {
const value = ensureString(raw).trim();
if (!value) continue;
const display = LANGUAGE_LABELS[value] && value !== 'all' ? LANGUAGE_LABELS[value] : value;
if (values.indexOf(display) < 0) values.push(display);
if (values.length >= 3) break;
}
return values.join(', ');
}
/**
* Human-readable license or rights metadata.
* @param {object} itemInfo
* @returns {string}
* @example
* formatLicenseForDetails({metadata:{rights:'Public Domain'}}) // => 'Public Domain'
*/
function formatLicenseForDetails(itemInfo) {
if (isPublicDomain(itemInfo)) return 'Public Domain';
const raw = ensureStringFromMetadata(itemInfo.metadata, 'licenseurl') || ensureStringFromMetadata(itemInfo.metadata, 'rights');
if (!raw) return '';
const ccMatch = raw.match(/creativecommons\.org\/licenses\/([^/]+)\/([^/\s]+)/i);
if (ccMatch) return `CC ${ccMatch[1].toUpperCase()} ${ccMatch[2]}`;
return raw;
}
/**
* Enriched detail description: the original item description (HTML stripped), then a compact "Archive details"
* facts block.
* @param {object} itemInfo
* @param {number} duration
* @returns {string}
* @example
* buildContentDetailsDescription(itemInfo, 60) // => '<original>\n\nArchive details\n...'
*/
function buildContentDetailsDescription(itemInfo, duration) {
const meta = itemInfo.metadata || {};
const fields = [];
addDescriptionField(fields, 'Original date', formatArchiveDateForDetails(meta.date));
addDescriptionField(fields, 'Uploaded', formatArchiveDateForDetails(itemInfo.publicdate || itemInfo.addeddate));
addDescriptionField(fields, 'Creator', metadataList(meta, 'creator', 3));
addDescriptionField(fields, 'Runtime', formatDuration(duration));
addDescriptionField(fields, 'Language', formatMetadataLanguage(meta));
addDescriptionField(fields, 'License', formatLicenseForDetails(itemInfo));
addDescriptionField(fields, 'Identifier', itemInfo.identifier);
const details = ['Archive details'].concat(fields).join('\n');
const original = stripReviewHtml(itemInfo.description);
return original ? `${original}\n\n${details}` : details;
}
/**
* Append a non-empty "Label: value" field, skipping duplicate values already present under another label.
* @param {string[]} fields
* @param {string} label
* @param {*} value
* @returns {void}
*/
function addDescriptionField(fields, label, value) {
const clean = ensureString(value).replace(REGEX_WHITESPACE, ' ').trim();
if (!clean) return;
if (fields.some(field => field.slice(field.indexOf(':') + 1).trim() === clean)) return;
fields.push(`${label}: ${clean}`);
}
/**
* Strip Solr/Lucene operator characters from a user query, collapse whitespace, and cap the length so the
* doubled query plus the filter clauses stay under the 2047-char advancedsearch `q` cap.
* @param {string} query
* @returns {string}
* @example
* sanitizeQuery('moon (1969)!') // => 'moon 1969'
*/
function sanitizeQuery(query) {
const clean = String(query || '').replace(REGEX_LUCENE_OPERATORS, ' ').replace(REGEX_WHITESPACE, ' ').trim();
return clean.length > MAX_QUERY_CHARS ? clean.slice(0, MAX_QUERY_CHARS).replace(/\s\S*$/, '') : clean;
}
/**
* Percent-encode a file path for an Archive.org URL, per '/'-separated segment (so subdirectory separators
* like "<id>.thumbs/frame.jpg" are kept).
* @param {string} name
* @returns {string}
* @example
* encodePath('x.thumbs/frame 1.jpg') // => 'x.thumbs/frame%201.jpg'
*/
function encodePath(name) {
return String(name || '').split('/').map(encodePathSegment).join('/');
}
/**
* Percent-encode one path segment, including the ! ' ( ) * sub-delims that encodeURIComponent leaves raw
* (matches the platform's encodePathSegment).
* @param {string} segment
* @returns {string}
* @example
* encodePathSegment("(B)Movie.mkv") // => '%28B%29Movie.mkv'
*/
function encodePathSegment(segment) {
return encodeURIComponent(String(segment)).replace(/[!'()*]/g, function(char) {
return '%' + char.charCodeAt(0).toString(16).toUpperCase();
});
}
/**
* Strip quotes/backslashes and collapse spaces in a value for use inside a quoted Solr field query.
* @param {string} value
* @returns {string}
* @example
* searchValue('A "B" C') // => 'A B C'
*/
function searchValue(value) {
return ensureString(value).replace(/["\\]/g, ' ').replace(REGEX_WHITESPACE, ' ').trim();
}
/**
* Build a quoted Solr field-equals clause.
* @param {string} field
* @param {string} value
* @returns {string}
* @example
* fieldEquals('creator', 'NASA') // => 'creator:"NASA"'
*/
function fieldEquals(field, value) {
return `${field}:"${searchValue(value)}"`;
}
/**
* The file's Archive.org `format` string, lowercased.
* @param {object} file
* @returns {string}
* @example
* fileFormat({format:'h.264'}) // => 'h.264'
*/
function fileFormat(file) {
return ensureString(file && file.format).toLowerCase();
}
/**
* Whether the file's format contains any of the given substrings.
* @param {object} file
* @param {string[]} terms
* @returns {boolean}
* @example
* matchesFormat({format:'VBR MP3'}, ['mp3']) // => true
*/
function matchesFormat(file, terms) {
const format = fileFormat(file);
return !!format && terms.some(term => format.includes(term));
}
/**
* Whether a creator value is a usable name rather than a scraped page/nav blob. Archive.org's `creator` is
* user-supplied and sometimes holds a long "X | Y | Z" string; values over 100 chars or containing pipes or
* newlines are rejected.
* @param {string} name
* @returns {boolean}
* @example
* isReasonableCreator('Castle Films') // => true
* isReasonableCreator('Home | About | Login') // => false
*/
function isReasonableCreator(name) {
return !!name && name.length <= 100 && name.indexOf('|') < 0 && !/[\r\n]/.test(name);
}
/**
* Build a PlatformChannel for a creator, uploader, or account. /@handle account pages get an avatar from
* services/img/@handle; creator and uploader-name channels fall back to the plugin icon.
* @param {string} field - 'creator' or 'uploader'
* @param {string} value - creator/uploader name or account handle
* @param {string} url - the channel URL
* @returns {PlatformChannel}
* @example
* buildChannel('creator', 'CitiCable', 'https://archive.org/@citicable')
*/
function buildChannel(field, value, url) {
let description;
if (value === 'Internet Archive') {
description = 'Official uploads from the Internet Archive';
} else if (field === 'uploader') {
description = `Content uploaded by ${value}`;
} else {
description = `Content credited to ${value} on the Internet Archive`;
}
// @handle accounts have an avatar at services/img/@handle; other channels fall back to the plugin icon.
const accountMatch = (url || '').match(REGEX_ACCOUNT_URL);
const thumbnail = accountMatch ? `${BASE_URL}/services/img/@${accountMatch[1]}` : CHANNEL_ICON_FALLBACK;
return new PlatformChannel({
id: new PlatformID(PLATFORM, value, config.id),
name: value,
thumbnail: thumbnail,
banner: '',
subscribers: 0,
description: description,
url: url
});
}
/**
* Throw if an item must not open: a collection, hidden by an enabled safety setting (adult, sensitive,
* curated, no-preview, public-domain-only), or access-restricted.
* @param {object} itemInfo
* @returns {void}
* @throws {ScriptException|UnavailableException}
* @example
* assertItemCanOpen(itemInfo) // throws UnavailableException when access-restricted
*/
function assertItemCanOpen(itemInfo) {
if (ensureStringFromMetadata(itemInfo.metadata, 'mediatype') === 'collection') {
throw new ScriptException("This is an Internet Archive collection. Open it from search or playlists.");
}
if (itemInfo.isDark) {
throw new UnavailableException("This Internet Archive item is no longer available (it has been withdrawn).");
}
if (isAdultFilterOn() && isAdultItem({
title: itemInfo.title,
identifier: itemInfo.identifier,
subject: itemInfo.metadata && itemInfo.metadata.subject,
description: itemInfo.description
})) {
throw new UnavailableException('Hidden by the "Hide Explicit Content" setting. You can turn it off in this plugin\'s settings.');
}
const hiddenBy = hiddenByCollectionSetting(itemInfo);
if (hiddenBy) {
throw new UnavailableException(`Hidden by the "${hiddenBy}" setting. You can turn it off in this plugin's settings.`);
}
if (itemInfo.metadata && itemInfo.metadata['access-restricted-item'] === 'true') {
throw new UnavailableException("This content is access-restricted and not publicly available on Archive.org.");
}
if (isPublicDomainOnlyOn() && !isPublicDomain(itemInfo)) {
throw new UnavailableException('Hidden by the "Show Public Domain Only" setting. You can turn it off in this plugin\'s settings.');
}
}
/**
* Fetch and normalize an item's /metadata, cached per identifier for the session.
* @param {string} identifier
* @returns {object} { identifier, title, description, addeddate, downloads, files, reviews, metadata, server, dir, isDark }
* @throws {ScriptException} when the identifier is missing, the item doesn't exist, or the response is unreadable
* @throws {UnavailableException} when the item exists but Archive.org can't serve its metadata right now
* @example
* fetchItemInfo('AboutBan1935') // => { identifier:'AboutBan1935', title:'About Bananas', files:[...], ... }
*/
function fetchItemInfo(identifier) {
if (!identifier) {
throw new ScriptException("Invalid Archive.org item identifier");
}
const cached = state.runtimeItemInfoCache[identifier];
if (cached) return cached;
const url = `${BASE_URL}/metadata/${identifier}`;
let data;
try {
data = getJson(url);
} catch (error) {