-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplePodcastsScript.js
663 lines (547 loc) · 22.4 KB
/
ApplePodcastsScript.js
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
const PLATFORM = "Apple Podcasts";
const PLATFORM_BASE_URL = "https://podcasts.apple.com";
const PLATFORM_SAVED_EPISODES_URL = "https://podcasts.apple.com/{country}/library/saved-episodes";
const PLATFORM_BASE_URL_API = 'https://amp-api.podcasts.apple.com'
const PLATFORM_BASE_ASSETS_URL = "https://podcasts.apple.com/assets/";
const URL_CHANNEL = "https://podcasts.apple.com/us/podcast/";
const API_SEARCH_URL_TEMPLATE = 'https://amp-api.podcasts.apple.com/v1/catalog/us/search/groups?groups=episode&l=en-US&offset=25&term={0}&types=podcast-episodes&platform=web&extend[podcast-channels]=availableShowCount&include[podcast-episodes]=channel,podcast&limit=25&with=entitlements';
const API_SEARCH_PODCASTS_URL_TEMPLATE = 'https://itunes.apple.com/search?media=podcast&term={query}';
const API_GET_PODCAST_EPISODES_URL_TEMPLATE = 'https://amp-api.podcasts.apple.com/v1/catalog/{country}/podcasts/{podcast-id}/episodes?l=en-US&offset={offset}';
const API_GET_EPISODE_DETAILS_URL_TEMPLATE = 'https://amp-api.podcasts.apple.com/v1/catalog/{country}/podcast-episodes/{episode-id}?include=channel,podcast&include[podcasts]=episodes,podcast-seasons,trailers&include[podcast-seasons]=episodes&fields=artistName,artwork,assetUrl,contentRating,description,durationInMilliseconds,episodeNumber,guid,isExplicit,kind,mediaKind,name,offers,releaseDateTime,season,seasonNumber,storeUrl,summary,title,url&with=entitlements&l=en-US';
const API_GET_TRENDING_EPISODES_URL_PATH_TEMPLATE = '/v1/catalog/{country}/charts?chart=top&genre=26&l=en-US&limit=10&offset=0&types=podcast-episodes'
const API_GET_TRENDING_EPISODES_URL_QUERY_PARAMS = 'extend[podcasts]=editorialArtwork,feedUrl&include[podcast-episodes]=podcast&types=podcast-episodes&with=entitlements';
const API_GET_SUBSCRIPTIONS_FIRST_PAGE_PATH = '/v1/me/library/podcasts?limit=30&relate[podcasts]=channel&with=entitlements&l=en-US';//next pages are gotten from the next field (cursor) in the response
const API_GET_SAVED_EPISODES_FIRST_PAGE_PATH = '/v1/me/library/podcast-episodes?include[podcast-episodes]=channel,playback-position,podcast&limit=30&fields[podcast-channels]=subscriptionName,isSubscribed&with=entitlements&l=en-US';//next pages are gotten from the next field (cursor) in the response
const REGEX_CONTENT_URL = /https:\/\/podcasts\.apple\.com\/[a-zA-Z]*\/podcast\/.*?\/id([0-9]*)\?i=([0-9]*).*?/s
const REGEX_CHANNEL_URL = /https:\/\/podcasts\.apple\.com\/[a-zA-Z]{2}\/podcast(?:\/[^/]+)?\/(?:id)?([0-9]+)/si;
const REGEX_CHANNEL_SHOW = /<script id=schema:show type="application\/ld\+json">(.*?)<\/script>/s
const REGEX_EPISODE = /<script name="schema:podcast-episode" type="application\/ld\+json">(.*?)<\/script>/s
const REGEX_EPISODE_ID = /[?&]i=([^&]+)/;
const REGEX_IMAGE = /<meta property="og:image" content="(.*?)">/s
const REGEX_CANONICAL_URL = /<link rel="canonical" href="(https:\/\/podcasts.apple.com\/[a-zA-Z]*\/podcast\/.*?)">/s
const REGEX_MAIN_SCRIPT_FILENAME = /index-\w+\.js/;
const REGEX_JWT = /\beyJhbGci[A-Za-z0-9-_]+?\.[A-Za-z0-9-_]+?\.[A-Za-z0-9-_]{43,}\b/;
const REGEX_COUNTRY_CODE = /^https:\/\/podcasts\.apple\.com\/([a-z]{2})\//;
const SAVED_EPISODES_KEY = 'applepodcasts:playlist:savedepisodes';
let state = {
headers: {},
channel: {}
};
let COUNTRY_CODES = [];
let config = {};
let _settings = {
countryIndex: 0,
allowExplicit: false
};
//Source Methods
source.enable = function(conf, settings, savedState){
try {
config = conf ?? {};
_settings = settings ?? {};
if (IS_TESTING) {
_settings.countryIndex = 0; //countrycode=us
_settings.allowExplicit = false;
}
COUNTRY_CODES = loadOptionsForSetting('countryIndex').map((c) => c.toLowerCase().split(' - ')[0]);
let didSaveState = false;
try {
if (savedState) {
state = JSON.parse(savedState);
didSaveState = true;
}
} catch (ex) {
log('Failed to parse saveState:' + ex);
}
if (!didSaveState) {
// init state
const indexRes = http.GET(PLATFORM_BASE_URL, { 'User-Agent': config.authentication.userAgent });
if(!indexRes.isOk) {
throw new ScriptException("Failed to get index page [" + indexRes.code + "]");
}
// Extract the main script file name from the index page
const scriptFileName = extractScriptFileName(indexRes.body);
if(!scriptFileName) {
throw new ScriptException("Failed to extract script file name");
}
// Get the main script file content
const scriptRes = http.GET(`${PLATFORM_BASE_ASSETS_URL}${scriptFileName}`, {'User-Agent': config.authentication.userAgent });
if(!scriptRes.isOk) {
throw new ScriptException(`Failed to get script file ${scriptFileName} [" ${scriptRes.code } "]`);
}
// Extract the JWT token from the main script content
const token = extractJWT(scriptRes.body);
if(!token) {
throw new ScriptException("Failed to extract Token");
}
state.headers = { Authorization: `Bearer ${token}`, Origin: PLATFORM_BASE_URL, 'User-Agent': config.authentication.userAgent };
}
} catch(e) {
console.error(e);
}
}
source.getHome = function () {
const selectedCountry = COUNTRY_CODES[_settings.countryIndex] ?? 'us';
const requestPath = API_GET_TRENDING_EPISODES_URL_PATH_TEMPLATE.replace("{country}", selectedCountry);
class RecommendedVideoPager extends VideoPager {
constructor({ media = [], hasMore = true, context = { requestPath } } = {}) {
super(media, hasMore, context);
this.url = `${PLATFORM_BASE_URL_API}${context.requestPath}&${API_GET_TRENDING_EPISODES_URL_QUERY_PARAMS}`;
}
nextPage() {
const resp = http.GET(this.url, state.headers);
if (!resp.isOk)
return new ContentPager([], false);
const episodes = JSON.parse(resp.body)?.results?.['podcast-episodes']?.find(x => x.chart == "top");
const contents = (episodes?.data ?? [])
.map(x => {
const podcast = x.relationships?.podcast?.data?.find(p => p.type == 'podcasts');
const podcastAttributes = podcast?.attributes;
return new PlatformVideo({
id: new PlatformID(PLATFORM, x.id + "", config?.id),
name: x.attributes.itunesTitle ?? x.attributes.name ?? '',
thumbnails: new Thumbnails([new Thumbnail(getArtworkUrl(x.attributes.artwork.url), 0)]),
author: new PlatformAuthorLink(new PlatformID(PLATFORM, podcast.id, config.id, undefined), podcastAttributes?.name, podcastAttributes.url, getArtworkUrl(podcastAttributes.artwork.url) ?? ""),
uploadDate: parseInt(new Date(x.attributes.releaseDateTime).getTime() / 1000),
duration: x.attributes.durationInMilliseconds / 1000,
viewCount: -1,
url: x.attributes.url,
isLive: false
})
})
.sort((a, b) => b.datetime - a.datetime);
return new RecommendedVideoPager({
media: contents,
hasMore: !!episodes.next,
context: { requestPath: episodes.next },
});
}
}
return new RecommendedVideoPager({ context: { requestPath } }).nextPage();
};
source.searchSuggestions = function(query) {
return [];
};
source.getSearchCapabilities = () => {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: [ ]
};
};
source.search = function (query, type, order, filters) {
const url = API_SEARCH_URL_TEMPLATE.replace("{0}", query);
const resp = http.GET(url, state.headers);
if(!resp.isOk)
throw new ScriptException("Failed to get search results [" + resp.code + "]");
const result = JSON.parse(resp.body);
const results = result.results.groups
.find(x=>x.groupId == "episode")?.data
.map(x=>{
const podcast = x.relationships?.podcast?.data?.find(p => p.type == 'podcasts');
const podcastAttributes = podcast?.attributes;
return new PlatformVideo({
id: new PlatformID(PLATFORM, x.id + "", config?.id),
name: x?.attributes?.name ?? '',
thumbnails: new Thumbnails([new Thumbnail(getArtworkUrl(x.attributes.artwork.url), 0)]),
author: new PlatformAuthorLink(new PlatformID(PLATFORM, podcast.id, config.id, undefined), podcastAttributes?.name ?? '', podcastAttributes.url, getArtworkUrl(podcastAttributes.artwork.url) ?? ""),
uploadDate: parseInt(new Date(x.attributes.releaseDateTime).getTime() / 1000),
duration: x.attributes.durationInMilliseconds / 1000,
viewCount: -1,
url: x.attributes.url,
isLive: false
})});
return new ContentPager(results, false);
};
source.getSearchChannelContentsCapabilities = function () {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: []
};
};
source.searchChannels = function(query) {
const url = API_SEARCH_PODCASTS_URL_TEMPLATE.replace("{query}", query);
const resp = http.GET(url, state.headers);
if(!resp.isOk)
throw new ScriptException("Failed to get search results [" + resp.code + "]");
const result = JSON.parse(resp.body);
const results = result.results.map(x=>new PlatformAuthorLink(new PlatformID(PLATFORM, "" + x.artistId, config.id, undefined), x?.collectionName ?? x?.trackName ?? x?.collectionCensoredName ?? '', x.collectionViewUrl, x.artworkUrl100 ?? ""));
return new ChannelPager(results, false);
};
//Channel
source.isChannelUrl = function(url) {
return REGEX_CHANNEL_URL.test(url);
};
source.getChannel = function(url) {
const matchUrl = url.match(REGEX_CHANNEL_URL);
const podcastId = matchUrl[1];
// check if channel is cached and return it
if(state.channel[podcastId]) {
return state.channel[podcastId];
}
const resp = http.GET(url, state.headers);
if(!resp.isOk)
throw new ScriptException("Failed to get channel [" + resp.code + "]");
const showMatch = resp.body.match(REGEX_CHANNEL_SHOW);
if(!showMatch || showMatch.length != 2) {
console.log("No show data", resp.body);
throw new ScriptException("Could not find show data");
}
const showData = JSON.parse(showMatch[1]);
const banner = matchFirstOrDefault(resp.body, REGEX_IMAGE);
// save channel info to state (cache)
state.channel[podcastId] = new PlatformChannel({
id: new PlatformID(PLATFORM, podcastId, config.id, undefined),
name: showData.name,
thumbnail: banner,
banner: banner,
subscribers: -1,
description: showData.description,
url: removeQuery(url),
urlAlternatives: [removeQuery(url)],
links: {}
});
return state.channel[podcastId];
};
source.getChannelContents = function(url) {
const id = removeRemainingQuery(url.match(REGEX_CHANNEL_URL)[1]);
return new AppleChannelContentPager(id, extractCountryCode(url));
};
class AppleChannelContentPager extends ContentPager {
constructor(id, countryCode) {
super(fetchEpisodesPage(id, 0, countryCode), true);
this.offset = this.results.length;
this.id = id;
this.countryCode = countryCode;
}
nextPage() {
this.offset += 10;
this.results = fetchEpisodesPage(this.id, this.offset, this.countryCode);
this.hasMore = this.results.length > 0;
return this;
}
}
function fetchEpisodesPage(id, offset=0, countryCode='us') {
const urlEpisodes = API_GET_PODCAST_EPISODES_URL_TEMPLATE
.replace("{country}", countryCode)
.replace("{podcast-id}", id)
.replace("{offset}", offset);
const resp = http.GET(urlEpisodes, state.headers);
if(!resp.isOk)
return [];
const channelUrl = `${URL_CHANNEL}id${id}`;
const channel = source.getChannel(channelUrl); // cached request
const author = new PlatformAuthorLink(new PlatformID(PLATFORM, id, config.id, undefined), channel.name, URL_CHANNEL + id, channel.thumbnail);
const episodes = JSON.parse(resp.body);
return episodes.data.map(x=> {
return new PlatformVideo({
id: new PlatformID(PLATFORM, "" + x.id, config?.id),
name: x.attributes.name,
thumbnails: new Thumbnails([new Thumbnail(getArtworkUrl(x.attributes.artwork.url), 0)]),
author: author,
uploadDate: parseInt(new Date(x.attributes.releaseDateTime).getTime() / 1000),
duration: parseInt(x.attributes.durationInMilliseconds / 1000),
viewCount: -1,
url: x.attributes.url,
isLive: false,
description: x.attributes.description.standard,
video: getVideoSource(x)
})});
}
//Video
source.isContentDetailsUrl = function(url) {
return REGEX_CONTENT_URL.test(url);
};
source.getContentDetails = function(url) {
const episodeId = extractEpisodeId(url);
if(!episodeId) {
throw new ScriptException(`Failed to extract episode id from url ${url}`);
}
const episodeApiUrl = API_GET_EPISODE_DETAILS_URL_TEMPLATE
.replace("{country}", extractCountryCode(url))
.replace("{episode-id}", episodeId);
const resp = http.GET(episodeApiUrl, state.headers, false);
if(!resp.isOk)
{
throw new ScriptException("Failed to get content details [" + resp.code + "]");
}
const episodeData = JSON.parse(resp.body).data.find(x => x.type == "podcast-episodes");
if(!episodeData?.attributes?.assetUrl) {
throw new UnavailableException("This episode is not available yet");
}
if(episodeData.attributes.contentRating == 'explicit' && !_settings["allowExplicit"]) {
throw new UnavailableException("Explicit videos can be allowed using the plugin settings");
}
const podcastData = episodeData.relationships.podcast.data.find(r => r.type == 'podcasts');
return new PlatformVideoDetails({
id: new PlatformID(PLATFORM, episodeData.id, config?.id),
name: episodeData.attributes.name,
thumbnails: new Thumbnails([new Thumbnail(getArtworkUrl(episodeData.attributes.artwork.url), 0)]),
author: new PlatformAuthorLink(new PlatformID(PLATFORM, podcastData.id, config.id, undefined), podcastData.attributes.name, podcastData.attributes.url, getArtworkUrl(podcastData.attributes.artwork.url)),
uploadDate: parseInt(new Date(episodeData.attributes.releaseDateTime).getTime() / 1000),
duration: parseInt(episodeData.attributes.durationInMilliseconds / 1000),
viewCount: -1,
url: episodeData.attributes.url,
isLive: false,
description: episodeData.attributes.description.standard,
video: getVideoSource(episodeData)
});
};
source.saveState = () => {
return JSON.stringify(state);
};
source.getUserSubscriptions = () => {
if (!bridge.isLoggedIn()) {
log('Failed to retrieve subscriptions page because not logged in.');
throw new ScriptException('Not logged in');
}
let next = API_GET_SUBSCRIPTIONS_FIRST_PAGE_PATH;
let hasMore = false;
const subscriptionUrlList = [];
do {
const resp = http.GET(`${PLATFORM_BASE_URL_API}${next}`, state.headers , true);
if(!resp.isOk)
return [];
const podcasts = JSON.parse(resp.body);
podcasts.data.forEach(podcast => {
subscriptionUrlList.push(podcast.attributes.url);
});
hasMore = !!podcasts.next;
next = podcasts.next;
} while(hasMore);
return subscriptionUrlList;
}
source.isPlaylistUrl = function(url) {
// currently only playlists are saved episodes
return url == SAVED_EPISODES_KEY;
}
source.getUserPlaylists = function () {
// currently only playlists are saved episodes
return [SAVED_EPISODES_KEY];
}
source.getPlaylist = function (url) {
// currently only playlists are saved episodes
if(url == SAVED_EPISODES_KEY) {
if (!bridge.isLoggedIn()) {
log('Failed to retrieve subscriptions page because not logged in.');
throw new ScriptException('Not logged in');
}
let next = API_GET_SAVED_EPISODES_FIRST_PAGE_PATH;
let hasMore = false;
const playlistItems = [];
do {
const resp = http.GET(`${PLATFORM_BASE_URL_API}${next}`, state.headers , true);
if(!resp.isOk)
return [];
const podcasts = JSON.parse(resp.body);
podcasts.data.forEach(podcast => {
playlistItems.push(podcast);
});
hasMore = !!podcasts.next;
next = podcasts.next;
} while(hasMore);
const all = playlistItems.map(x => {
const podcast = x?.relationships?.podcast?.data?.find(p => p.type == 'podcasts');
const podcastId = podcast?.id ?? extractPodcastId(x.attributes.url) ?? '';
const podcastAttributes = podcast?.attributes;
return new PlatformVideo({
id: new PlatformID(PLATFORM, x?.id ?? '', config?.id),
name: x.attributes.itunesTitle ?? x.attributes.name ?? '',
thumbnails: new Thumbnails([new Thumbnail(getArtworkUrl(x.attributes.artwork.url), 0)]),
author: new PlatformAuthorLink(new PlatformID(PLATFORM, podcastId, config.id, undefined), podcastAttributes?.name ?? '', podcastAttributes?.url ?? '', podcastAttributes?.artwork?.url ? getArtworkUrl(podcastAttributes.artwork.url) : ''),
uploadDate: parseInt(new Date(x.attributes.releaseDateTime).getTime() / 1000),
duration: x.attributes.durationInMilliseconds / 1000,
viewCount: -1,
url: x.attributes.url,
isLive: false
})
})
.filter(x => x != null)
.sort((a, b) => b.datetime - a.datetime);
const thumbnailUrl = all.length ? (all?.[0]?.thumbnails?.sources?.[0].url ?? '') : '';
const savedEpisodesPlaylistUrl = PLATFORM_SAVED_EPISODES_URL.replace("{country}", COUNTRY_CODES[_settings.countryIndex]);
return new PlatformPlaylistDetails({
url: savedEpisodesPlaylistUrl,
id: new PlatformID(PLATFORM, 'playlistid', config.id),
author: new PlatformAuthorLink(
new PlatformID(PLATFORM, '', config.id),
'',// author name
'',// author url
),
name: 'Saved Episodes',// playlist name
thumbnail: thumbnailUrl,
videoCount: all.length,
contents: new VideoPager(all),
});
} else {
throw new ScriptException('Invalid playlist url');
}
}
/**
* Generates a video or audio source descriptor based on the provided episode data.
*
* @param {Object} episodeData - The data object containing episode attributes.
* @param {Object} episodeData.attributes - The attributes of the episode.
* @param {string} episodeData.attributes.mediaKind - Type of media, either "audio" or "video".
* @param {string} episodeData.attributes.assetUrl - The URL of the media asset.
* @param {number} episodeData.attributes.durationInMilliseconds - The duration of the audio in milliseconds.
*
* @returns {(UnMuxVideoSourceDescriptor|VideoSourceDescriptor)} - A descriptor for audio or video sources.
*
* @throws {ScriptException} Throws an error if the media kind is not supported.
*
* @example
* const episodeData = {
* attributes: {
* mediaKind: "audio",
* assetUrl: "https://example.com/audio.mp3",
* durationInMilliseconds: 300000
* }
* };
* const source = getVideoSource(episodeData);
* // Returns an UnMuxVideoSourceDescriptor for audio or a VideoSourceDescriptor for video
*/
function getVideoSource(episodeData) {
switch(episodeData.attributes.mediaKind) {
case "audio":
return new UnMuxVideoSourceDescriptor([], [
new AudioUrlSource({
name: "Podcast",
container: "audio/mp3",
bitrate: 0,
url: episodeData.attributes.assetUrl,
duration: parseInt(episodeData.attributes.durationInMilliseconds / 1000),
})
]);
case "video":
return new VideoSourceDescriptor([
new VideoUrlSource({
name: "Podcast",
container: "video/mp4",
url: episodeData.attributes.assetUrl,
})
]);
default:
throw new ScriptException(`Unsupported media kind: "${episodeData.attributes.mediaKind}" for url: ${episodeData.attributes.assetUrl}`);
}
}
/**
* Prepare the artwork URL by replacing the placeholders with the actual values
* @param {string} url
* @returns {string}
*/
function getArtworkUrl(url) {
return url
.replace("{w}", "500")
.replace("{h}", "500")
.replace("{f}", "png");
}
/**
* Match the first group of the regex and return the default value if not found
* @param {string} data
* @param {any} regex
* @param {string} def
* @returns {string}
*/
function matchFirstOrDefault(data, regex, def) {
const match = data.match(regex);
if(match && match.length > 0)
return match[1];
return def;
}
/**
* Remove the remaining query from the URL
* @param {string} query
* @returns {string}
*/
function removeRemainingQuery(query) {
const indexSlash = query.indexOf("/");
if(indexSlash >= 0)
return query.substring(0, indexSlash);
const indexQuestion = query.indexOf("?");
if(indexQuestion >= 0)
return query.substring(0, indexQuestion);
const indexAnd = query.indexOf("&");
if(indexAnd >= 0)
return query.substring(0, indexAnd);
return query;
}
/**
* Remove the query from the URL
* @param {string} query
* @returns {string}
*/
function removeQuery(query) {
const indexQuestion = query.indexOf("?");
if(indexQuestion >= 0)
return query.substring(0, indexQuestion);
return query;
}
/**
* Extract the main script file name from the HTML content
* @param {string} htmlContent
* @returns {string}
*/
function extractScriptFileName(htmlContent) {
// Define the regex pattern to match 'index-*.js'
const match = htmlContent.match(REGEX_MAIN_SCRIPT_FILENAME);
// Return the matched file name if found, otherwise return null
return match ? match[0] : null;
}
/**
* Extract the JWT token from the main script
* Looks for a string that starts with 'eyJhbGci' representing the encoded header
* @param {string} scriptContent
* @returns {string}
*/
function extractJWT(scriptContent) {
// Use the match method to find the JWT token in the script content
const match = scriptContent.match(REGEX_JWT);
// Return the matched JWT if found, otherwise return null
return match ? match[0] : null;
}
/**
* Extract the episode ID from the URL
* @param {string} url
* @returns {string}
*/
function extractEpisodeId(url) {
const match = url.match(REGEX_EPISODE_ID);
return match ? match[1] : null;
}
/**
* Extract the podcast ID from the URL
* @param {string} url
* @returns {string}
*/
function extractPodcastId(url) {
// Regular expression to match the podcast ID in the URL
const regex = /\/id(\d+)/;
// Match the URL against the regex
const match = url.match(regex);
// If a match is found, return the podcast ID (without the 'id' prefix)
if (match) {
return match[1];
}
// If no match is found, return null
return null;
}
/**
* Returs the options values for a setting. If the setting is not found, an empty array is returned.
* @param {string} settingKey
* @returns {string[]}
*/
function loadOptionsForSetting(settingKey) {
return config?.settings?.find((s) => s.variable == settingKey)
?.options ?? [];
}
/**
* Extract the country code from the URL since it is needed for the API requests
* @param {string} url
* @returns {string}
*/
function extractCountryCode(url) {
const match = url.match(REGEX_COUNTRY_CODE);
return match ? match[1] : null; // Returns the country code or null if not found
}
console.log("LOADED");