Repository navigation
Expand file tree
/
Copy pathCuriosityStreamScript.js
More file actions
1836 lines (1586 loc) · 56.6 KB
/
Copy pathCuriosityStreamScript.js
File metadata and controls
1836 lines (1586 loc) · 56.6 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
/**
* Curiosity Stream Plugin for Grayjay
*
* This plugin enables browsing, searching, and viewing Curiosity Stream content.
* It provides access to categories, media items, and collections.
*/
// ---------------------- Constants ----------------------
const PLATFORM = 'CuriosityStream';
// Base URLs
const BASE_URLS = {
MAIN: 'https://curiositystream.com',
API: 'https://api.curiositystream.com',
API_USE1: 'https://api-use1.curiositystream.com',
CDN: 'https://cdn.curiositystream.com'
};
BASE_URLS.API_V1 = `${BASE_URLS.API_USE1}/v1`;
BASE_URLS.API_V2 = `${BASE_URLS.API}/v2`;
// Then define URLS using BASE_URLS
const URLS = {
// Base URLs
BASE: BASE_URLS.MAIN,
API_V1: BASE_URLS.API_V1,
API_V2: BASE_URLS.API_V2,
CDN: BASE_URLS.CDN,
// Static resources
MISSING_IMG: `${BASE_URLS.CDN}/missing.png`,
// Web URLs
WEB_VIDEO: (id) => `${BASE_URLS.MAIN}/video/${id}`,
// API endpoints
MEDIA: (id) => `${BASE_URLS.API_V1}/media/${id}`,
MEDIA_HLS: (id) => `${BASE_URLS.API_V1}/media/${id}?encodingsNew=true&encodingsFormat=m3u8`,
MEDIA_DASH: (id) => `${BASE_URLS.API_V1}/media/${id}?encodingsNew=true&encodingsFormat=mpd`,
COLLECTION: (id) => `${BASE_URLS.API_V1}/series/${id}`,
SEARCH_V2: `${BASE_URLS.API_V2}/search`,
SEARCH: `${BASE_URLS.API}/search`,
FREE_PAGE: `${BASE_URLS.MAIN}/free`,
PLAYBACK_PROGRESS: `${BASE_URLS.API_V1}/user_media`,
// Content URLs
SERIES_PAGE: (id) => `${BASE_URLS.MAIN}/series/${id}`,
CATEGORY_PAGE: (slug) => `${BASE_URLS.MAIN}/categories/${slug}`,
// API query endpoints
MEDIA_QUERY: `${BASE_URLS.API_V1}/media`,
COLLECTIONS_QUERY: `${BASE_URLS.API_V1}/collections`,
PLUGIN_ICON: 'https://plugins.grayjay.app/CuriosityStream/CuriosityStreamIcon.png'
};
// Regular expressions for URL matching
const REGEX = {
CONTENT_URL: new RegExp(`^${BASE_URLS.MAIN}/(?:title|video|media|documentary|episode)/(\\d+)/?`),
CATEGORY_URL: new RegExp(`^${BASE_URLS.MAIN}/categories/([a-zA-Z0-9_-]+)/?`),
SERIES_URL: new RegExp(`^${BASE_URLS.MAIN}/series/(\\d+)/?`),
CHANNEL_URL: new RegExp(`^${BASE_URLS.MAIN}/(?:categories/([a-zA-Z0-9_-]+)|series/(\\d+))/?`),
// Video format detection
IS_HLS: /\.m3u8($|\?)|[?&].*m3u8/i,
IS_DASH: /\.mpd($|\?)|[?&].*mpd/i,
// Script extraction patterns
SCRIPT_URL: /src=["'](\/_next\/static\/chunks\/pages\/free-[^"']*?)["']/i,
FREE_VIDEOS_DATA: /t\.Z\s*=\s*(\[.*?\])/s,
};
// API settings
const API = {
VIDEOS_PER_PAGE: 10,
PROGRESS_REPORT_INTERVAL: 15, // Report progress every 15 seconds
MIN_TRACKING_DURATION: 5 // Minimum playback duration to track (5 seconds)
};
// Default HTTP headers
const DEFAULT_HEADERS = {
'content-type': 'application/json',
'user-agent': 'Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.230 Mobile Safari/537.36'
};
// Plugin state
let config = {};
let state = {
buildId: '',
has_subscription: false,
categories: {},
collections: {} // Cache for collection data
};
let settings = {};
// ====================== PLUGIN ENTRY POINTS ======================
/**
* Initialize the plugin with configuration
* @param {Object} conf - Plugin configuration
* @param {Object} setting - User settings
* @param {string} saveStateStr - Saved state from previous sessions
*/
source.enable = function(conf, setting, saveStateStr) {
config = conf;
settings = setting;
if (saveStateStr) {
try {
state = JSON.parse(saveStateStr);
// Ensure collections object exists
if (!state.collections) {
state.collections = {};
}
} catch (e) {
log(e);
bridge.log('Failed to restore state');
}
} else {
loadInitialState();
}
};
/**
* Save the current plugin state
* @returns {string} State data as JSON string
*/
source.saveState = () => {
return JSON.stringify(state);
};
/**
* Get home page content
* @returns {ContentPager} Paged results for home page
*/
source.getHome = function () {
// Fetch regular content
const result = fetchContentDataWithCollections({
url: `${URLS.API_V1}/media?collections=true&limit=${API.VIDEOS_PER_PAGE}`
});
// Get combined content (with free videos first for non-subscribers)
const combinedResults = getCombinedContent(
result.items || [],
state.has_subscription
);
return new CuriosityStreamHomePager(
combinedResults,
result.hasMore,
{ page: 1, hasShownFreeVideos: true }
);
};
/**
* Check if a URL is a Curiosity Stream content page
* @param {string} url - URL to check
* @returns {boolean} True if URL points to content
*/
source.isContentDetailsUrl = function (url) {
return REGEX.CONTENT_URL.test(url);
};
/**
* Get detailed information for content
* @param {string} url - Content URL
* @returns {PlatformVideoDetails} Video details
*/
source.getContentDetails = function (url) {
const contentId = getContentIdFromUrl(url);
if (!contentId) {
throw new ScriptException('Invalid Curiosity Stream URL');
}
if (url.includes('free=true')) {
const freeVideo = findFreeVideoById(contentId);
if (freeVideo) {
return createPlatformVideoDetails({
media: freeVideo,
manifest: freeVideo.manifest,
isFreeVideo: true
});
}
}
// Get regular content details
const isLoggedIn = bridge.isLoggedIn();
const details = fetchMediaDetails(contentId, isLoggedIn);
if (!details.media) {
throw new ScriptException('Content not found');
}
// If the media is part of a collection, fetch collection details
const media = details.media;
let collection = null;
if (media.collection_id) {
try {
collection = fetchCollectionDetails(media.collection_id);
// Cache the collection for future use
if (collection) {
state.collections[media.collection_id] = collection;
}
} catch (e) {
log(`Failed to fetch collection details: ${e.message}`);
}
}
return createPlatformVideoDetails({
media,
collection,
isFreeVideo: false
});
};
/**
* Check if a URL is a Curiosity Stream channel
* @param {string} url - URL to check
* @returns {boolean} True if URL points to a channel
*/
source.isChannelUrl = function(url) {
return REGEX.CHANNEL_URL.test(url);
};
/**
* Get channel information
* @param {string} url - Channel URL
* @returns {PlatformChannel} Channel information
*/
source.getChannel = function(url) {
// Check if this is a category URL
const categoryMatch = url.match(REGEX.CATEGORY_URL);
if (categoryMatch) {
const categorySlug = categoryMatch[1];
return getCategoryChannel(categorySlug, url);
}
// Check if this is a series URL
const seriesMatch = url.match(REGEX.SERIES_URL);
if (seriesMatch) {
const seriesId = seriesMatch[1];
const collection = fetchCollectionDetails(seriesId);
return createChannelFromCollection(collection);
}
throw new ScriptException('Invalid Channel URL');
};
/**
* Get channel contents
* @param {string} url - Channel URL
* @returns {ContentPager} Paged results for channel content
*/
source.getChannelContents = function(url) {
// Check if this is a category URL
const categoryMatch = url.match(REGEX.CATEGORY_URL);
if (categoryMatch) {
const categorySlug = categoryMatch[1];
// Get the category from state to ensure we have correct data
const category = Object.values(state.categories)
.find(cat => cat.name === categorySlug);
const result = fetchContentDataWithCollections({
url: `${URLS.API_V1}/media?filterBy=category&term=${categorySlug}&collections=true&limit=${API.VIDEOS_PER_PAGE}&sort=creation_date_desc`,
processingInfo: {
categorySlug,
categoryName: category.label
}
});
return new CategoryContentPager(
result.items,
result.hasMore,
{ page: 1, category }
);
}
// Check if this is a series URL
const seriesMatch = url.match(REGEX.SERIES_URL);
if (seriesMatch) {
const seriesId = seriesMatch[1];
const collection = fetchCollectionDetails(seriesId);
if (!collection) {
throw new ScriptException('Collection not found');
}
// For collections, we already have all the videos in the collection object
// Sort in reverse order to show recent episodes first
const videos = collection.media
.sort((a, b) => b.collection_order - a.collection_order)
.map(media => createVideoFromMedia(media, collection));
// Return a content pager with all videos (no paging needed for collections)
return new ContentPager(videos, false);
}
throw new ScriptException('Invalid Channel URL');
};
/**
* Get search capabilities
* @returns {Object} Search capabilities
*/
source.getSearchCapabilities = () => {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: []
};
};
/**
* Search for content
* @param {string} query - Search query
* @returns {ContentPager} Paged search results
*/
source.search = function(query, type, order, filters) {
const result = fetchSearchData(query);
return new SearchPager(
result.items,
result.hasMore,
{ query, page: 1, totalPages: result.body.nbPages }
);
};
/**
* Search for channels
* @param {string} query - Search query
* @returns {ContentPager} Paged search results
*/
source.searchChannels = function(query) {
const channels = [];
const searchQuery = query.toLowerCase().trim();
const addedChannelIds = new Set(); // Track channel IDs to avoid duplicates
// Search in categories
Object.values(state.categories)
.forEach(category => {
const fullName = category.label.toLowerCase();
if (fullName.includes(searchQuery)) {
const channelId = category.name;
if (!addedChannelIds.has(channelId)) {
channels.push(createChannelFromCategory(category));
addedChannelIds.add(channelId);
}
}
});
// Search for series/collections that match the query
try {
const searchBody = {
query: searchQuery,
hitsPerPage: 20,
page: 0,
filters: {
obj_type: ["collection"] // Only search for collections
}
};
const headers = {
"Content-Type": "application/json"
};
const res = http.POST(URLS.SEARCH_V2, JSON.stringify(searchBody), headers);
if (res.isOk) {
const body = JSON.parse(res.body);
const seriesHits = body.hits || [];
// Process each series and add to channels
seriesHits.forEach(hit => {
// Always use collection_id as the series identifier
const collectionId = hit.collection_id;
// Skip entries without a collection_id
if (!collectionId) {
return;
}
const seriesChannelId = `series_${collectionId}`;
// Skip if we've already added this channel
if (addedChannelIds.has(seriesChannelId)) {
return;
}
// Check if we have complete collection data in cache
let collection = null;
// Try to get from cache first using the correct ID
if (collectionId && state.collections[collectionId]) {
collection = state.collections[collectionId];
}
// If not in cache, create minimal collection object from search result
if (!collection) {
collection = {
id: collectionId,
title: hit.title,
description: hit.description || hit.short_description || "",
image_large: hit.image_large,
image_medium: hit.image_medium,
media_count: hit.media_count || 0
};
}
channels.push(createChannelFromCollection(collection));
addedChannelIds.add(seriesChannelId);
});
}
} catch (error) {
log(`Error searching for series channels: ${error.message}`);
}
return new ContentPager(channels, false);
};
/**
* Check if a URL is a playlist
* @param {string} url - URL to check
* @returns {boolean} True if URL points to a playlist
*/
source.isPlaylistUrl = function(url) {
return REGEX.SERIES_URL.test(url);
};
/**
* Get playlist details
* @param {string} url - Playlist URL
* @returns {PlatformPlaylistDetails} Playlist details
*/
source.getPlaylist = function(url) {
const match = url.match(REGEX.SERIES_URL);
if (!match) {
throw new ScriptException('Invalid Collection URL');
}
const seriesId = match[1];
const collection = fetchCollectionDetails(seriesId);
return createPlaylistDetails(collection);
};
/**
* Get comments for content
* @returns {CommentPager} Empty comment pager (comments not supported)
*/
source.getComments = function(url) {
return new CommentPager([], false);
};
/**
* Get playback tracker for tracking video progress
* @param {string} url - Content URL
* @returns {PlaybackTracker|null} Playback tracker if available
*/
source.getPlaybackTracker = function(url) {
// Only track playback if user is logged in and setting is enabled
if (!bridge.isLoggedIn() || !settings.curiositystreamActivity) {
return null;
}
try {
const contentId = getContentIdFromUrl(url);
if (contentId) {
return new CuriosityStreamPlaybackTracker(contentId, API.PROGRESS_REPORT_INTERVAL);
}
} catch (error) {
log(`Error creating playback tracker: ${error.message}`);
}
return null;
};
/**
* Gets playlists for a channel (currently only for series)
* @param {string} url - Channel URL
* @returns {PlaylistPager} Paged results for channel playlists
*/
source.getChannelPlaylists = function(url) {
const seriesMatch = url.match(REGEX.SERIES_URL);
if (seriesMatch) {
const seriesId = seriesMatch[1];
const collection = fetchCollectionDetails(seriesId);
if (!collection) {
return new PlaylistPager([], false);
}
const playlist = createPlaylistFromCollection(collection);
if (collection.media && Array.isArray(collection.media)) {
collection.media = collection.media.sort((a, b) => b.collection_order - a.collection_order);
state.collections[seriesId] = collection;
}
// Return a playlist pager with just this series
return new PlaylistPager([playlist], false);
}
// For categories or other channel types, return empty pager
return new PlaylistPager([], false);
};
// ====================== CORE FUNCTIONALITY ======================
/**
* Loads initial state data, including categories and subscription status
*/
function loadInitialState() {
// Initialize collections cache
state.collections = {};
// Check subscription status if logged in
if (bridge.isLoggedIn()) {
const res = http.GET(`${URLS.API_V1}/user`, DEFAULT_HEADERS, true);
if (res.isOk) {
const body = JSON.parse(res.body);
state.has_subscription = body.data.is_active && !body.data.is_free;
}
}
// Load categories
const url = `${URLS.API_V1}/categories`;
const res = http.GET(url, DEFAULT_HEADERS);
if (res.isOk) {
const data = JSON.parse(res.body)?.data ?? [];
processCategories(data);
}
}
/**
* Process categories data and store in state
* @param {Array} categories - Category data from API
*/
function processCategories(categories) {
categories.forEach(category => {
const { background_url, description, image_url, label, name } = category;
const parentCategory = {
background_url: background_url !== URLS.MISSING_IMG ? background_url : '',
description,
image_url: image_url !== URLS.MISSING_IMG ? image_url : '',
label,
name
};
state.categories[name] = parentCategory;
// Process subcategories
if (category.subcategories) {
category.subcategories.forEach(subCategory => {
const existingCategoryNames = Object.values(state.categories).map(cat => cat.label);
let { background_url, description, image_url, label, name } = subCategory;
if(image_url === URLS.MISSING_IMG || !image_url) {
image_url = URLS.PLUGIN_ICON;
}
if(existingCategoryNames.includes(label)) {
label = `${parentCategory.label} - ${label}`
}
state.categories[name] = {
background_url: background_url !== URLS.MISSING_IMG ? background_url : '',
description,
image_url: image_url !== URLS.MISSING_IMG ? image_url : '',
label,
name
};
});
}
});
}
/**
* Fetches media details from the API
* @param {string} contentId - Content ID
* @param {boolean} isLoggedIn - Whether user is logged in
* @returns {Object} Media details
*/
function fetchMediaDetails(contentId, isLoggedIn) {
const batch = http.batch();
batch.GET(URLS.MEDIA_HLS(contentId), DEFAULT_HEADERS, isLoggedIn);
batch.GET(URLS.MEDIA_DASH(contentId), DEFAULT_HEADERS, isLoggedIn);
const [hlsResponse, dashResponse] = batch.execute();
if (!hlsResponse.isOk && !dashResponse.isOk) {
throw new ScriptException('Failed to fetch content details');
}
// Prefer HLS if available, since dash is not supported on desktop yet
const mainDetails = hlsResponse.isOk ?
JSON.parse(hlsResponse.body) :
JSON.parse(dashResponse.body);
return {
media: mainDetails.data
};
}
/**
* Creates a PlatformVideoDetails object with consistent handling for both regular and free videos
*
* @param {Object} options - Options for creating the video details
* @param {Object} options.media - Media data (API or free video format)
* @param {boolean} options.isFreeVideo - Whether this is a free video
* @param {Object} options.manifest - Manifest data for free videos
* @param {Object} options.collection - Collection data if part of a collection
* @returns {PlatformVideoDetails} Video details object
*/
function createPlatformVideoDetails(options) {
const {
media,
isFreeVideo = false,
manifest = null,
collection = null
} = options;
if (!media) {
throw new ScriptException("Media object is required");
}
const isPreview = !isFreeVideo && isMediaPreview(media) && !state.has_subscription;
function getDuration() {
const rawDuration = isFreeVideo ? parseDuration(media.duration) : (media.duration || 0);
// 5 minutes (300 seconds) is the standard preview length for Curiosity Stream videos
return isPreview ? 300 : rawDuration;
}
function getMediaId() {
return isFreeVideo ? media.media.toString() : media.id.toString();
}
// Extract basic properties based on video type
const mediaId = getMediaId();
let title = isFreeVideo
? (media.subtitle ? `${media.title}: ${media.subtitle}` : media.title)
: formatMediaTitle(media);
if(isPreview) {
title += ' (preview)';
}
const description = isFreeVideo
? `${media.subtitle || ''}\n\nCategory: ${media.category}\nYear: ${media.year_produced}\n\nFree video from Curiosity Stream`
: formatMediaDescription(media, isMediaPreview(media) && !state.has_subscription, collection);
// Create appropriate thumbnails
const thumbnails = isFreeVideo
? new Thumbnails([new Thumbnail(media.thumbnail || '', 0)])
: createThumbnails(media);
// Determine the video URL
const videoUrl = isFreeVideo
? `${URLS.BASE}/video/${mediaId}?free=true`
: constructMediaUrl(media);
// Determine share URL
const shareUrl = isFreeVideo
? `${BASE_URLS.MAIN}/free/title/${media.id}`
: constructMediaUrl(media);
// Set up author/channel link
let author;
if (isFreeVideo) {
// For free videos, use category
const categoryObj = getCategoryByLabel(media.category);
author = categoryObj
? createChannelLinkFromCategory(categoryObj)
: createCategoryAuthorLink(media.category.toLowerCase(), media.category);
} else if (collection) {
// For collection videos, use collection
author = createAuthorLinkFromCollection(collection);
} else {
// For standalone videos, use category
const category = getCategoryByLabel(media.primary_category);
author = category ? createChannelLinkFromCategory(category) : createDefaultChannelLink();
}
// Create video sources with validation and fallbacks
const sources = [];
const duration = getDuration();
if (isFreeVideo) {
// Handle free video sources
if (manifest && manifest.m3u8) {
sources.push(new HLSSource({
name: "HLS",
url: manifest.m3u8,
duration: duration,
priority: true
}));
} else if (manifest && manifest.mpd) {
// Add DASH as fallback
sources.push(new DashSource({
name: "DASH",
url: manifest.mpd,
duration: duration
}));
log("Warning: Only DASH format available for free video, which may not work on desktop");
}
} else {
// Handle regular video sources
if (media.encodings?.length) {
for (const encoding of media.encodings) {
const url = encoding.master_playlist_url;
if (!url) continue;
if (REGEX.IS_HLS.test(url)) {
sources.push(new HLSSource({
name: "HLS",
url: url,
duration: duration,
priority: true
}));
} else if (REGEX.IS_DASH.test(url)) {
sources.push(new DashSource({
name: "DASH",
url: url,
duration: duration
}));
}
}
}
}
// If we couldn't get any sources, log the issue
if (sources.length === 0) {
throw new UnavailableException(`No playable sources found for ${isFreeVideo ? 'free ' : ''}video ${mediaId}`);
}
const rating = isFreeVideo
? null
: createMediaRating(media);
const viewCount = isFreeVideo ? -1 : (media.num_views || media.view_count || -1);
// Create and return the PlatformVideoDetails object
const videoDetails = new PlatformVideoDetails({
id: new PlatformID(PLATFORM, mediaId, config.id),
name: title,
author: author,
thumbnails: thumbnails,
description: description,
duration: duration,
url: videoUrl,
shareUrl: shareUrl,
isLive: false,
video: sources.length > 0 ? new VideoSourceDescriptor(sources) : null,
rating: rating,
viewCount: viewCount,
datetime: 0 // Without additional metadata request, we don't have this
});
if(!isFreeVideo) {
videoDetails.getContentRecommendations = function() {
return getRecommendations(mediaId);
};
}
return videoDetails;
}
/**
* Create video sources based on available encodings
* @param {Object} media - Media data
* @returns {Array} Array of video sources
*/
function createVideoSources(media) {
const sources = [];
// Set duration, limiting to 5 minutes for preview videos without subscription
const duration = (isMediaPreview(media) && !state.has_subscription) ? 300 : (media.duration || 0);
if (media.encodings?.length) {
for (const encoding of media.encodings) {
const url = encoding.master_playlist_url;
if (!url) continue;
if (REGEX.IS_HLS.test(url)) {
sources.push(new HLSSource({
name: "HLS",
url,
duration,
priority: true
}));
} else if (REGEX.IS_DASH.test(url)) {
sources.push(new DashSource({
name: "DASH",
url,
duration
}));
} else {
log(`Unknown streaming format for URL: ${url}`);
}
}
}
return sources;
}
/**
* Parse duration string to seconds
* @param {string} durationStr - Duration string (e.g., "50m", "1h 30m")
* @returns {number} Duration in seconds
*/
function parseDuration(durationStr) {
if (!durationStr) return 0;
// Regular expressions to extract hours, minutes and seconds
const hoursMatch = durationStr.match(/(\d+)h/);
const minutesMatch = durationStr.match(/(\d+)m/);
const secondsMatch = durationStr.match(/(\d+)s/);
let hours = hoursMatch ? parseInt(hoursMatch[1]) : 0;
let minutes = minutesMatch ? parseInt(minutesMatch[1]) : 0;
let seconds = secondsMatch ? parseInt(secondsMatch[1]) : 0;
return (hours * 3600) + (minutes * 60) + seconds;
}
/**
* Gets free videos from the Curiosity Stream free page
* @returns {Array} Array of free video objects
*/
function getFreeVideos() {
try {
const scriptUrl = getFreePageScriptUrl();
if (!scriptUrl) return [];
const freeVideos = extractFreeVideosFromScript(scriptUrl);
log(`Loaded ${freeVideos.length} free videos`);
return freeVideos;
} catch (error) {
log(`Error fetching free videos: ${error.message}`);
return [];
}
}
/**
* Gets the script URL containing free videos data
* @returns {string|null} Script URL if found
*/
function getFreePageScriptUrl() {
try {
const res = http.GET(URLS.FREE_PAGE, DEFAULT_HEADERS);
if (!res.isOk) {
log(`Failed to fetch free page: HTTP ${res.code}`);
return null;
}
const scriptUrl = extractScriptUrl(res.body);
if (!scriptUrl) {
log("Script URL pattern not found in page content");
}
return scriptUrl;
} catch (error) {
log(`Error in getFreePageScriptUrl: ${error.message}`);
return null;
}
}
/**
* Extracts free videos data from script content
* @param {string} scriptUrl - URL of the script file
* @returns {Array} Array of free video objects
*/
function extractFreeVideosFromScript(scriptUrl) {
try {
const scriptRes = http.GET(`${BASE_URLS.MAIN}${scriptUrl}`, DEFAULT_HEADERS);
if (!scriptRes.isOk) {
log(`Failed to fetch script: HTTP ${scriptRes.code}`);
return [];
}
const match = scriptRes.body.match(REGEX.FREE_VIDEOS_DATA);
if (!match || !match[1]) {
log("Free videos data pattern not found in script content");
return [];
}
// Try to parse the content
try {
const freeVideos = parseJsObject(match[1]);
return Array.isArray(freeVideos) ? freeVideos : [];
} catch (parseError) {
log(`Error parsing free videos data: ${parseError.message}`);
return [];
}
} catch (error) {
log(`Error in extractFreeVideosFromScript: ${error.message}`);
return [];
}
}
/**
* Finds a free video by its media ID
* @param {string} mediaId - Media ID to search for
* @returns {Object|undefined} Free video object if found
*/
function findFreeVideoById(mediaId) {
const freeVideos = getFreeVideos();
return freeVideos.find(video => video.media.toString() === mediaId);
}
/**
* Creates a video object from a free video
* @param {Object} freeVideo - Free video data
* @returns {PlatformVideo} Video object
*/
function createVideoFromFreeVideo(freeVideo) {
// Extract information from the free video object
const {
media,
title,
subtitle,
thumbnail,
rating_percentage,
year_produced,
category,
duration
} = freeVideo;
// Parse the duration string (e.g., "50m" to seconds)
const durationSeconds = parseDuration(duration);
// Create a category-based author
const categoryObj = getCategoryByLabel(category);
const author = categoryObj
? createChannelLinkFromCategory(categoryObj)
: createCategoryAuthorLink(category.toLowerCase(), category);
return new PlatformVideo({
id: new PlatformID(PLATFORM, media.toString(), config.id),
name: subtitle ? `${title}: ${subtitle}` : title,
author,
thumbnails: new Thumbnails([new Thumbnail(thumbnail, 0)]),
duration: durationSeconds,
viewCount: -1, // We don't have view count for free videos
// datetime: year_produced ? new Date(`${year_produced}-01-01`).getTime() / 1000 : 0,
url: `${URLS.BASE}/video/${media}?free=true`,
isLive: false,
description: subtitle || title
});
}
/**
* Get a category channel by slug
* @param {string} categorySlug - Category slug
* @param {string} url - Full channel URL
* @returns {PlatformChannel} Channel object
*/
function getCategoryChannel(categorySlug, url) {
let category = Object.values(state.categories)
.find(category => category.name === categorySlug);
if (!category) {
category = {
id: new PlatformID(PLATFORM, '', config.id),
name: categorySlug,
thumbnail: '',
banner: '',
subscribers: 0,
description: '',
url: url
};
}
return createChannelFromCategory(category);
}
/**
* Creates playlist details from collection data
* @param {Object} collection - Collection data
* @returns {PlatformPlaylistDetails} Playlist details
*/
function createPlaylistDetails(collection) {
if (!collection) {
throw new ScriptException('Collection not found');
}
// Get media (videos) in the collection
const videos = collection.media
.sort((a, b) => a.collection_order - b.collection_order)
.map(media => createVideoFromMedia(media, collection));
// Create PlatformPlaylistDetails
return new PlatformPlaylistDetails({
id: new PlatformID(PLATFORM, collection.id.toString(), config.id),
name: collection.title,