-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitchuteScript.js
More file actions
1733 lines (1487 loc) · 47.4 KB
/
BitchuteScript.js
File metadata and controls
1733 lines (1487 loc) · 47.4 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
/**
* BitChute Plugin for GrayJay
* This plugin enables GrayJay to integrate with BitChute's video platform
*/
//================ CONSTANTS ================//
// Platform identifiers
const PLATFORM = 'Bitchute';
const PLATFORM_CLAIMTYPE = 30;
// API endpoints
const URL_API = {
VIDEOS_BETA9: 'https://api.bitchute.com/api/beta9/videos',
VIDEOS_BETA: 'https://api.bitchute.com/api/beta/videos',
CHANNEL: 'https://api.bitchute.com/api/beta/channel',
PROFILE: 'https://api.bitchute.com/api/beta/profile',
PROFILE_VIDEOS: 'https://api.bitchute.com/api/beta/profile/videos',
PROFILE_PLAYLISTS: 'https://api.bitchute.com/api/beta/profile/playlists',
LINKS: 'https://api.bitchute.com/api/beta/profile/links',
SEARCH_VIDEOS: 'https://api.bitchute.com/api/beta/search/videos',
CHANNEL_VIDEOS: 'https://api.bitchute.com/api/beta/channel/videos',
SEARCH_CHANNELS: 'https://api.bitchute.com/api/beta/search/channels',
MEDIA_INFO: 'https://api.bitchute.com/api/beta/video/media',
VIDEO_INFO: 'https://api.bitchute.com/api/beta9/video',
VIDEO_COUNTS: 'https://api.bitchute.com/api/beta/video/counts',
VIDEO_COMMENTS: 'https://commentfreely.bitchute.com/api/get_comments/',
VIDEO_COMMENTS_AUTH: 'https://api.bitchute.com/api/beta/apps/commentfreely/video',
LIVES: 'https://api.bitchute.com/api/beta9/cache/livestreams',
PLAYLIST: 'https://api.bitchute.com/api/beta/playlist',
PLAYLIST_VIDEOS: 'https://api.bitchute.com/api/beta/playlist/videos'
};
// Web URLs
const URL_WEB = {
BASE: 'https://www.bitchute.com',
BASE_OLD: 'https://old.bitchute.com',
LOGIN_OLD: 'https://old.bitchute.com/accounts/login/',
VIDEOS: 'https://www.bitchute.com/video/',
SUBSCRIPTIONS_OLD: 'https://old.bitchute.com/subscriptions/',
PLAYLISTS_OLD: 'https://old.bitchute.com/playlists/'
};
// Regular expressions for URL parsing
const REGEX = {
// Playlist URL patterns split by type
PLAYLIST_SYSTEM: /^https:\/\/(old|www)\.bitchute\.com\/playlist\/(favorites|watch-later|recently-viewed)\/?(?:[?&][^#]*)?$/,
PLAYLIST_USER: /^https:\/\/(old|www)\.bitchute\.com\/playlist\/([a-zA-Z0-9_\-]+)\/?(?:[?&][^#]*)?$/,
PLAYLIST_QUERY: /^https:\/\/(old|www)\.bitchute\.com\/video\/playlist\?playlistId=([a-zA-Z0-9_\-]+)$/,
CHANNEL_URL: /bitchute\.com\/channel\//,
PROFILE_URL: /bitchute\.com\/profile\//,
VIDEO_URL: /bitchute\.com\/video\//,
HLS_URL: /https:\/\/.*\.m3u8/,
MPEG_URL: /https:\/\/.*\.mp4/,
PLAYLIST_PRIVATE: /\/playlist\/(favorites|watch-later|recently-viewed)/,
IS_PRIVATE: /[?&]is-private=true(&|$)/,
EXTRACT_PROFILE_ID: /\/profile\/([A-Za-z0-9_\-]+)\/?/,
EXTRACT_CHANNEL_ID: /\/channel\/([A-Za-z0-9_\-]+)\/?/,
EXTRACT_VIDEO_ID: /bitchute\.com\/video\/([a-zA-Z0-9\-_]+)/
};
// Default HTTP headers
const REQUEST_HEADERS = {
'Content-Type': 'application/json'
};
// Default request configurations
const DEFAULT_REQUEST_CONFIG = {
root: 'videos',
total_property: 'video_count',
offset: 0,
limit: 20,
advertisable: true
};
// Private URL handling
const IS_PRIVATE_SUFFIX = 'is-private=true';
//================ PLUGIN STATE ================//
let _config = {};
let _settings = {};
let state = {
channel: {},
channelMeta: {},
channelContent: {},
profileLinks: {},
channelContentTimeToLive: {}
}
let CHANNEL_CONTENT_TTL_OPTIONS = [];
let CONTENT_SENSITIVITY_OPTIONS = [];
let RECOMMENDED_CONTEXT_OPTIONS = [];
let HOME_CONTENT_FEED_OPTIONS = [];
//================ SOURCE API IMPLEMENTATION ================//
/**
* Initializes the plugin with configuration and settings
*/
source.enable = function (conf, settings, saveStateStr) {
_config = conf ?? {};
_settings = settings ?? {};
if (IS_TESTING) {
_settings.showLiveVideosOnHome = false;
_settings.cacheChannelContent = true;
_settings.cacheChannelContentTimeToLiveIndex = 5; // 10 minutes
_settings.contentSensitivityIndex = 1; // Normal
_settings.RecommendedContentIndex = 0; // More from same channel
_settings.homeContentFeedIndex = 0; // Popular
}
CHANNEL_CONTENT_TTL_OPTIONS = loadOptionsForSetting('cacheChannelContentTimeToLiveIndex', (s) => parseInt(s))
CONTENT_SENSITIVITY_OPTIONS = loadOptionsForSetting('contentSensitivityIndex', (s) => {
return s.split('-')?.[0]?.trim()?.toLowerCase();
})
RECOMMENDED_CONTEXT_OPTIONS = loadOptionsForSetting('RecommendedContentIndex');
HOME_CONTENT_FEED_OPTIONS = loadOptionsForSetting('homeContentFeedIndex', (s) => s.toLowerCase().replace(/\s+/g, '-'));
let didSaveState = false;
try {
if (saveStateStr) {
state = JSON.parse(saveStateStr);
didSaveState = true;
}
} catch (ex) {
log('Failed to parse saveState:' + ex);
}
if (!didSaveState) {
// init state
}
};
/**
* Saves plugin state for persistence between sessions
*/
source.saveState = () => {
//no caching while testing
return IS_TESTING ? JSON.stringify({}) : JSON.stringify(state);
};
/**
* Gets home page content
*/
source.getHome = function() {
const sensitivity_id = CONTENT_SENSITIVITY_OPTIONS[_settings.contentSensitivityIndex];
const feedType = HOME_CONTENT_FEED_OPTIONS[_settings.homeContentFeedIndex ?? 0] || 'popular';
// Get live videos if enabled
let liveVideos = [];
if (_settings.showLiveVideosOnHome) {
const liveConfig = {
url: URL_API.LIVES,
root: 'videos',
total_property: 'video_count',
request_body: {},
transform: BitchuteVideoToPlatformVideo
};
try {
const livePager = createContentPager(liveConfig);
liveVideos = livePager.results;
} catch (e) {
log('Error loading live videos: ' + e);
}
}
// Configure main content feed based on settings
let config;
if (feedType === 'all' || feedType === 'suggested') {
config = {
url: URL_API.VIDEOS_BETA9,
root: 'videos',
total_property: 'video_count',
cacheKey: 'home',
cacheValue: feedType,
request_body: {
selection: feedType,
offset: 0,
limit: 20,
advertisable: true,
sensitivity_id
},
transform: BitchuteVideoToPlatformVideo
};
} else {
config = {
url: URL_API.VIDEOS_BETA,
root: 'videos',
total_property: 'video_count',
cacheKey: 'home',
cacheValue: feedType,
request_body: {
selection: feedType,
offset: 0,
limit: 20,
advertisable: true,
sensitivity_id
},
transform: BitchuteVideoToPlatformVideo
};
}
// Return pager with combined results
return createContentPager(config, liveVideos);
};
/**
* Gets search capabilities
*/
source.getSearchCapabilities = () => {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: [],
};
};
/**
* Searches for videos
*/
source.search = function (query) {
const config = {
url: URL_API.SEARCH_VIDEOS,
root: 'videos',
total_property: 'video_count',
cacheKey: 'search',
cacheValue: query,
request_body: {
offset: 0,
limit: 50,
query: query,
sensitivity_id: CONTENT_SENSITIVITY_OPTIONS[_settings.contentSensitivityIndex],
sort: 'new',
},
transform: BitchuteVideoToPlatformVideo
};
return createContentPager(config);
};
/**
* Gets search channel contents capabilities
*/
source.getSearchChannelContentsCapabilities = function () {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: [],
};
};
/**
* Searches for channels
*/
source.searchChannels = function (query) {
class SearchChannelsPager extends VideoPager {
constructor({ videos = [], hasMore = true, context = {} } = {}) {
super(videos, hasMore, context);
}
nextPage() {
const response = makeApiRequest(
URL_API.SEARCH_CHANNELS,
{
offset: this.context.offset,
limit: 50,
query: query,
sensitivity_id: CONTENT_SENSITIVITY_OPTIONS[_settings.contentSensitivityIndex],
sort: 'new',
}
);
const searchResultChannels = response.channels;
const channels = searchResultChannels.map((sourceChannel) => {
return new PlatformChannel({
id: new PlatformID(
PLATFORM,
sourceChannel?.channel_id ?? '',
_config.id,
PLATFORM_CLAIMTYPE,
),
name: sourceChannel?.channel_name ?? '',
thumbnail: sourceChannel?.thumbnail_url ?? '',
banner: '',
subscribers: sourceChannel.subscriber_count,
description: sourceChannel.description,
url: `${URL_WEB.BASE}${sourceChannel.channel_url}`,
});
});
return new SearchChannelsPager({
videos: channels,
hasMore: false,
context: { offset: (this?.context?.offset ?? 0) + 50 },
});
}
}
return new SearchChannelsPager().nextPage();
};
/**
* Checks if a URL is a channel URL
*/
source.isChannelUrl = function (url) {
return [REGEX.CHANNEL_URL, REGEX.PROFILE_URL].some((r) => r.test(url));
};
/**
* Gets channel information
*/
source.getChannel = function (url) {
if(state.channel[url]){
return state.channel[url];
}
if(REGEX.CHANNEL_URL.test(url)) {
state.channel[url] = getChannelWithBatch(url);
}
else if (REGEX.PROFILE_URL.test(url)) {
state.channel[url] = getProfile(url);
}
return state.channel[url];
};
/**
* Gets channel playlists
*/
source.getChannelPlaylists = (url) => {
const isChannelUrl = REGEX.CHANNEL_URL.test(url);
const isProfileUrl = REGEX.PROFILE_URL.test(url);
if(isChannelUrl) {
// Not supported yet on source platform
return new ContentPager([]);
} else if(isProfileUrl) {
const profile_id = extractProfileId(url);
const profileMeta = getProfile(url);
// Direct API request for playlists to ensure proper data handling
try {
const responseBody = makeApiRequest(
URL_API.PROFILE_PLAYLISTS,
{
offset: 0,
limit: 50,
profile_id: profile_id,
}
);
if (!responseBody || !responseBody.playlists) {
log(`No playlists found for profile ${profile_id}`);
return new ContentPager([]);
}
// Transform playlists into platform objects
const playlists = responseBody.playlists.map(playlist => {
return new PlatformPlaylist({
id: new PlatformID(
PLATFORM,
playlist.playlist_id,
_config.id,
PLATFORM_CLAIMTYPE,
),
author: new PlatformAuthorLink(
new PlatformID(PLATFORM, profile_id, _config.id),
profileMeta.name,
profileMeta.url,
profileMeta.thumbnail,
),
name: playlist.playlist_name,
thumbnail: playlist.thumbnail_url,
videoCount: playlist.video_count,
url: `${URL_WEB.BASE}/playlist/${playlist.playlist_id}`,
});
});
// Check if there are more pages (unlikey, but just in case)
const hasMore = responseBody.playlists && responseBody.playlists.length >= 50;
return new ContentPager(playlists, hasMore);
} catch (error) {
log(`Error fetching playlists: ${error.message}`);
return new ContentPager([]);
}
}
return new ContentPager([]);
};
/**
* Gets channel contents
*/
source.getChannelContents = function (url) {
if(REGEX.CHANNEL_URL.test(url)) {
return getChannelContents(url);
}
else if (REGEX.PROFILE_URL.test(url)) {
return getProfileContents(url);
}
else {
throw new ScriptException(`Invalid channel URL: ${url}`);
}
};
/**
* Checks if a URL is a content details URL
*/
source.isContentDetailsUrl = function (url) {
return REGEX.VIDEO_URL.test(url);
};
/**
* Gets content details
*/
source.getContentDetails = function (url) {
const videoId = extractVideoIDFromUrl(url);
const body = JSON.stringify({ video_id: videoId });
const [
mediaDetailsResponse,
videoDetailsResponse,
countsResponse,
embedResponse,
] = batchRequest([
{
url: URL_API.MEDIA_INFO,
method: 'POST',
headers: REQUEST_HEADERS,
body: body,
},
{
url: URL_API.VIDEO_INFO,
method: 'POST',
headers: REQUEST_HEADERS,
body: body,
},
{
url: URL_API.VIDEO_COUNTS,
method: 'POST',
headers: REQUEST_HEADERS,
body: body,
},
{
url: `${URL_WEB.BASE}/api/beta9/embed/${videoId}?videoID=${videoId}&startTime=0&autoPlay=true&theaterMode=true&showAds=true`,
},
]);
if (!mediaDetailsResponse.isOk) {
throw new ScriptException(
`Failed request mediaDetailsResponse (${mediaDetailsResponse.code})`,
);
}
if (!videoDetailsResponse.isOk) {
throw new ScriptException(
`Failed request videoDetailsResponse (${videoDetailsResponse.code})`,
);
}
if (!countsResponse.isOk) {
throw new ScriptException(
`Failed request countsResponse (${countsResponse.code})`,
);
}
const mediaDetails = JSON.parse(mediaDetailsResponse.body);
const videoDetails = JSON.parse(videoDetailsResponse.body);
const countDetails = JSON.parse(countsResponse.body);
const duration = convertToSeconds(videoDetails.duration);
let media_url;
let urlMatch = embedResponse.body.match(/var\s+media_url\s*=\s*'(.*?)'/);
// Extracting the URL
if (urlMatch && urlMatch[1]) {
media_url = urlMatch[1];
}
media_url = media_url || mediaDetails.media_url;
if (!media_url) {
throw new ScriptException('Failed to get media url');
}
const sources = [];
if (REGEX.HLS_URL.test(media_url)) {
sources.push(
new HLSSource({
name: 'HLS',
url: media_url,
duration: duration,
priority: true,
}),
);
} else if (REGEX.MPEG_URL.test(media_url)) {
sources.push(
new VideoUrlSource({
name: mediaDetails.media_type,
duration: duration,
url: media_url,
container: "video/mp4"
}),
);
}
const result = new PlatformVideoDetails({
id:
videoId &&
new PlatformID(PLATFORM, videoId, _config.id, PLATFORM_CLAIMTYPE),
name: videoDetails.video_name,
author: new PlatformAuthorLink(
new PlatformID(
PLATFORM,
videoDetails.channel.channel_id,
_config.id,
PLATFORM_CLAIMTYPE,
),
videoDetails.channel.channel_name,
`${URL_WEB.BASE}${videoDetails.channel.channel_url}`,
videoDetails.channel.thumbnail_url,
),
datetime: dateToUnixSeconds(videoDetails.date_published),
description: videoDetails.description,
shareUrl: url,
url: url,
video: new VideoSourceDescriptor(sources),
rating: new RatingLikesDislikes(
countDetails.like_count,
countDetails.dislike_count,
),
isLive: videoDetails.state_id == 'live',
duration: duration,
thumbnails:
videoDetails.thumbnail_url &&
new Thumbnails([new Thumbnail(videoDetails.thumbnail_url, 0)]),
viewCount: countDetails.view_count,
});
result.getContentRecommendations = function () {
return source.getContentRecommendations(url, videoDetails);
};
return result;
};
/**
* Gets content recommendations
*/
source.getContentRecommendations = (url, initialData) => {
const selectedRecommendedContent =
RECOMMENDED_CONTEXT_OPTIONS[_settings.RecommendedContentIndex];
const isMoreFromSameChannel =
selectedRecommendedContent === 'More from same channel';
const isRelated = selectedRecommendedContent === 'Related';
const isForYou = selectedRecommendedContent === 'For you';
const isRecentUploads = selectedRecommendedContent === 'Recent Uploads';
let requestUrl = '';
let body = {};
const videoId = extractVideoIDFromUrl(url);
if (!initialData) {
const [videoDetailsResponse] = batchRequest([
{
url: URL_API.VIDEO_INFO,
method: 'POST',
headers: REQUEST_HEADERS,
body: JSON.stringify({ video_id: videoId }),
},
]);
if (!videoDetailsResponse.isOk) {
throw new ScriptException(
`Failed request videoDetailsResponse (${videoDetailsResponse.code})`,
);
}
initialData = JSON.parse(videoDetailsResponse.body);
}
if (isMoreFromSameChannel) {
body = { channel_id: initialData.channel.channel_id, offset: 0, limit: 50 };
requestUrl = URL_API.CHANNEL_VIDEOS;
} else if (isRelated || isRecentUploads) { //currently they have same behavior as "Related"
body = {
selection: 'popular',
offset: 0,
limit: 10,
category_id: initialData.category_id,
};
requestUrl = URL_API.VIDEOS_BETA;
} else if (isForYou) {
body = { selection: 'popular', offset: 0, limit: 10, category_id: 'news' };
requestUrl = URL_API.VIDEOS_BETA;
}
let videos = makeApiRequest(
requestUrl,
JSON.stringify(body),
REQUEST_HEADERS,
false
).videos;
if (isMoreFromSameChannel) {
const channel = initialData?.channel ?? {
channel_id: '',
channel_name: '',
channel_url: '',
thumbnail_url: '',
};
videos = videos.map((v) => {
v.channel = channel;
return v;
});
}
const platformVideos = videos
.filter((v) => v.video_id !== videoId) // remove current video from recommendations
.map(v => BitchuteVideoToPlatformVideo(v));
return new VideoPager(platformVideos ?? [], false);
};
/**
* Gets comments for a video
*/
source.getComments = function (url) {
const videoId = extractVideoIDFromUrl(url);
const obj = getCommentAuthForVideo(videoId);
const formData = objectToUrlEncodedString({
cf_auth: obj.auth,
commentCount: '0',
isNameValuesArrays: 'true',
});
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
};
const comments = makeApiRequest(
URL_API.VIDEO_COMMENTS,
formData,
headers,
false
);
const allComments = convertToObjects(comments.names, comments.values);
const results = allComments
.filter((c) => !c.parent)
.map((comment) => ToComment(url, comment, allComments));
return new CommentPager(results, false);
};
/**
* Checks if a URL is a playlist URL
*/
source.isPlaylistUrl = function (url) {
return REGEX.PLAYLIST_SYSTEM.test(url) ||
REGEX.PLAYLIST_USER.test(url) ||
REGEX.PLAYLIST_QUERY.test(url);
};
/**
* Gets a playlist by URL
* Supports all playlist URL formats:
* - System playlists: https://(old|www).bitchute.com/playlist/(favorites|watch-later|recently-viewed)/
* - User playlists: https://(old|www).bitchute.com/playlist/PLAYLIST_ID/
* - Query playlists: https://(old|www).bitchute.com/video/playlist?playlistId=PLAYLIST_ID
*/
source.getPlaylist = function (url) {
const isPrivate = REGEX.IS_PRIVATE.test(url);
const isSystemGeneratedPlaylist = REGEX.PLAYLIST_PRIVATE.test(url);
if (isPrivate) {
if(!bridge.isLoggedIn()) {
throw new LoginRequiredException('Login to import Subscriptions');
}
url = url.replace(`&${IS_PRIVATE_SUFFIX}`, '');
}
// Extract playlist ID using our improved extraction functions
const playlist_id = extractPlaylistId(url);
// If that fails, try the query parameter extractor as a fallback
if (!playlist_id) {
throw new ScriptException(`Failed to extract playlist ID from URL: ${url}`);
}
let playlistInfo;
let channel = {};
let playlistName = playlist_id;
if(!isSystemGeneratedPlaylist) {
const playlistInfoResponse = http.POST(
URL_API.PLAYLIST,
JSON.stringify({ playlist_id }),
REQUEST_HEADERS,
true
);
if(playlistInfoResponse.isOk) {
playlistInfo = JSON.parse(playlistInfoResponse.body);
playlistName = playlistInfo?.playlist_name || playlist_id;
if(playlistInfo.profile_id) {
channel = {
channel_id: playlistInfo.profile_id,
channel_name: playlistInfo.profile_name,
channel_url: `${URL_WEB.BASE}/profile/${playlistInfo.profile_id}`,
thumbnail_url: playlistInfo.thumbnail_url,
};
} else {
channel = {
channel_id: playlistInfo.channel_id,
channel_name: playlistInfo.channel_name,
channel_url: `${URL_WEB.BASE}/channel/${playlistInfo.channel_id}`,
thumbnail_url: playlistInfo.thumbnail_url,
};
}
}
}
const config = {
cacheKey: 'playlist_id',
cacheValue: playlist_id,
url: URL_API.PLAYLIST_VIDEOS,
root: 'videos',
total: playlistInfo?.video_count ?? -1,
auth: isPrivate,
request_body: {
offset: 0,
limit: 50,
playlist_id: playlist_id,
},
transform: (v) => {
if(!isSystemGeneratedPlaylist && playlistInfo?.profile_id) {
v.channel = channel;
}
return BitchuteVideoToPlatformVideo(v.video);
},
};
const contentPager = createContentPager(config);
return new PlatformPlaylistDetails({
url: url,
id: new PlatformID(PLATFORM, channel.channel_id, _config.id, PLATFORM_CLAIMTYPE),
author: new PlatformAuthorLink(
new PlatformID(PLATFORM, '', _config.id, PLATFORM_CLAIMTYPE),
channel.channel_name,
channel.channel_url
),
name: playlistName,
thumbnail: '',
videoCount: playlistInfo?.video_count ?? -1,
contents: contentPager,
});
};
/**
* Gets user subscriptions
*/
source.getUserSubscriptions = () => {
if (!bridge.isLoggedIn()) {
log('Failed to retrieve subscriptions page because not logged in.');
throw new ScriptException('Not logged in');
}
const response = http.GET(URL_WEB.SUBSCRIPTIONS_OLD, {}, true);
if (!response.isOk) {
throw new ScriptException(`Failed request [${URL_WEB.SUBSCRIPTIONS_OLD}] (${response.code})`);
}
if (response.url.startsWith(URL_WEB.LOGIN_OLD)) {
throw new LoginRequiredException(
'Invalid session. login to import Subscriptions',
);
}
const detailsDocument = domParser
.parseFromString(response.body, 'text/html')
.querySelector('body');
const subscriptions = Array.from(
detailsDocument.querySelectorAll('#page-detail a.spa[href^="/channel/"]'),
).map((e) => `${URL_WEB.BASE}${e.getAttribute('href')}`);
return subscriptions;
};
/**
* Gets user playlists
*/
source.getUserPlaylists = function () {
if (!bridge.isLoggedIn()) {
log('Failed to retrieve subscriptions page because not logged in.');
throw new ScriptException('Not logged in');
}
const response = http.GET(URL_WEB.PLAYLISTS_OLD, {}, true);
if (!response.isOk) {
throw new ScriptException(`Failed request [${URL_WEB.PLAYLISTS_OLD}] (${response.code})`);
}
if (response.url.startsWith(URL_WEB.LOGIN_OLD)) {
throw new LoginRequiredException(
'Invalid session. login to import Subscriptions',
);
}
const detailsDocument = domParser
.parseFromString(response.body, 'text/html')
.querySelector('body');
const playlists = Array.from(
detailsDocument.querySelectorAll('#page-detail a.spa[href^="/playlist/"]'),
).map((e) => `${URL_WEB.BASE_OLD}${trimEndSlash(e.getAttribute('href'))}&${IS_PRIVATE_SUFFIX}`);
return playlists;
};
/**
* Returns chat window information for live bitchute streams with chat
* @param {string} url - The video URL
* @returns {Object|null} Chat window configuration or null if chat not available
*/
source.getLiveChatWindow = function (url) {
const videoId = extractVideoIDFromUrl(url);
if (videoId) {
return {
url: `https://www.bitchute.com/popChat/${videoId}`,
removeElements: [],
removeElementsInterval: []
};
}
};
//================ HELPER FUNCTIONS ================//
/**
* Parses settings options and applies transformations
*
* @param {string} settingKey - The key of the setting to load options for
* @param {Function} [transformCallback] - Optional function to transform each option
* @returns {Array} - Array of setting options, possibly transformed
*/
function loadOptionsForSetting(settingKey, transformCallback) {
transformCallback ??= (o) => o;
const setting = _config?.settings?.find((s) => s.variable == settingKey);
return setting?.options?.map(transformCallback) ?? [];
}
/**
* Removes the trailing slash from a string
*
* @param {string} str - The string to process
* @returns {string} - The string without trailing slash
*/
function trimEndSlash(str) {
return str.replace(/\/$/, "");
}
/**
* Converts a time string (HH:MM:SS or MM:SS) to seconds
*
* @param {string} time - Time string in format HH:MM:SS or MM:SS
* @returns {number} - Total seconds
*/
function convertToSeconds(time) {
if (!time || time.indexOf(':') === -1) {
return 0;
}
// Split the time string by the colon
const parts = time.split(':').map(part => parseInt(part, 10));
if (parts.length === 3) {
// Format is hh:mm:ss
const [hours, minutes, seconds] = parts;
return (hours * 3600) + (minutes * 60) + seconds;
} else if (parts.length === 2) {
// Format is mm:ss
const [minutes, seconds] = parts;
return (minutes * 60) + seconds;
}
// Invalid format
return 0;
}
/**
* Converts a date string to Unix timestamp in seconds
*
* @param {string} date - Date string
* @returns {number|null} - Unix timestamp in seconds or null if date is invalid
*/
function dateToUnixSeconds(date) {
if (!date) {
return null;
}
return Math.round(Date.parse(date) / 1000);
}
/**
* Extracts video ID from a BitChute video URL
*
* @param {string} url - BitChute video URL
* @returns {string|null} - Video ID or null if not found
*/
function extractVideoIDFromUrl(url) {
// Use regular expression to capture video IDs with letters, numbers, dashes, and underscores
const match = url.match(REGEX.EXTRACT_VIDEO_ID);
return match && match[1] ? match[1] : null;
}
/**
* Extracts channel ID from a BitChute channel URL
*
* @param {string} url - BitChute channel URL
* @returns {string|null} - Channel ID or null if not found
*/
function extractChannelId(url) {
const match = url.match(REGEX.EXTRACT_CHANNEL_ID);
return match && match[1] ? match[1] : null;
}
/**
* Extracts profile ID from a BitChute profile URL
*
* @param {string} url - BitChute profile URL
* @returns {string|null} - Profile ID or null if not found
*/
function extractProfileId(url) {
const match = url.match(REGEX.EXTRACT_PROFILE_ID);
return match && match[1] ? match[1] : null;
}
/**
* Extracts playlist ID from a BitChute playlist URL
* Supports all URL formats:
* - System playlists: https://www.bitchute.com/playlist/favorites/
* - User playlists: https://www.bitchute.com/playlist/PLAYLIST_ID/
* - Query playlists: https://www.bitchute.com/video/playlist?playlistId=PLAYLIST_ID
*
* @param {string} url - BitChute playlist URL
* @returns {string|null} - Playlist ID or null if not found
*/
function extractPlaylistId(url) {
// Check for system playlists (favorites, watch-later, recently-viewed)
let match = url.match(REGEX.PLAYLIST_SYSTEM);
if (match) {
return match[2]; // Return the system playlist name as the ID
}
// Check for user playlists
match = url.match(REGEX.PLAYLIST_USER);
if (match) {
return match[2]; // Return the user playlist ID
}
// Check for query parameter playlists
match = url.match(REGEX.PLAYLIST_QUERY);
if (match) {
return match[2]; // Return the playlist ID from query
}
return null;
}