forked from Windowsfreak/Mediathek
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediathekScript.js
More file actions
646 lines (572 loc) · 19.6 KB
/
MediathekScript.js
File metadata and controls
646 lines (572 loc) · 19.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
// =============================================================================
// CONSTANTS
// =============================================================================
const PLATFORM = "MediathekView";
const API_URL = 'https://mediathekviewweb.de/api/query';
const API_HEADERS = { 'Content-Type': 'application/json' };
const DEFAULT_PAGE_SIZE = 20;
const DEFAULT_SORT_BY = 'timestamp';
const DEFAULT_SORT_ORDER = 'desc';
const DEFAULT_FUTURE = false;
const DEFAULT_OFFSET = 0;
const BROADCASTER_DOMAINS = [
'ardmediathek.de',
'zdf.de',
'phoenix.de',
'br.de',
'mdr.de',
'ndr.de',
'wdr.de',
'swr.de',
'hr-fernsehen.de',
'rbb-online.de',
'sr-online.de',
'daserste.de',
'tagesschau.de',
'sportschau.de',
'orf.at',
'on.orf.at',
'arte.tv',
'3sat.de',
'kika.de',
'funk.net'
];
// =============================================================================
// REGEX PATTERNS
// =============================================================================
const REGEX_VIDEO_FILE = /\.(mp4|webm)/i;
const REGEX_HLS_FILE = /\.m3u8/i;
const REGEX_WEBM_FILE = /\.webm/i;
const REGEX_MEDIA_FILE = /\.(m3u8|mp4)(\?|$)/;
const REGEX_MEDIATHEK_DOMAIN = /mediathekviewweb\.de/;
const REGEX_CHANNEL_PATH = /\/(c|channel)\//;
const REGEX_CHANNEL_URL = /\/(c|channel)\/([^\/\?]+)/;
const REGEX_CHANNEL_HINT = /isMediathekChannel=1/; // Query parameter added to plugin-generated channel URLs for quick identification
const REGEX_CONTENT_HINT = /isMediathekContent=1/; // Query parameter added to plugin-generated content URLs for quick identification
const REGEX_PROTOCOL = /^https?:\/\//;
const REGEX_PATH_QUERY = /[\/\?#].*$/;
const REGEX_SLUG_SEPARATOR = /[-_]/g;
let config = {};
// =============================================================================
// SOURCE METHODS
// =============================================================================
/**
* Enables the plugin with configuration
* @param {object} conf - Plugin configuration from MediathekConfig.json
* @param {object} settings - User settings
* @param {object} savedState - Previously saved state
*/
source.enable = function (conf, settings, savedState) {
config = conf ?? {};
};
/**
* Gets the home feed with latest videos
* @returns {MediathekVideoPager} Pager with latest videos
*/
source.getHome = function () {
return getMediathekVideoPager({
queries: [],
sortBy: DEFAULT_SORT_BY,
sortOrder: DEFAULT_SORT_ORDER,
future: DEFAULT_FUTURE,
offset: DEFAULT_OFFSET,
size: DEFAULT_PAGE_SIZE
});
};
/**
* Gets search suggestions for a query
* @param {string} query - Search query
* @returns {string[]} Array of suggestions (currently empty)
*/
source.searchSuggestions = function (query) {
return [];
};
/**
* Gets the search capabilities
* @returns {object} Search capabilities configuration
*/
source.getSearchCapabilities = () => ({
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: []
});
/**
* Searches for videos matching the query
* @param {string} query - Search query
* @param {string} type - Content type
* @param {string} order - Sort order
* @param {object} filters - Search filters
* @returns {MediathekVideoPager} Pager with search results
*/
source.search = function (query, type, order, filters) {
const queries = [{
fields: ['title', 'topic', 'channel', 'description'],
query: query
}];
return getMediathekVideoPager({
queries,
sortBy: DEFAULT_SORT_BY,
sortOrder: DEFAULT_SORT_ORDER,
future: DEFAULT_FUTURE,
offset: DEFAULT_OFFSET,
size: DEFAULT_PAGE_SIZE
});
};
/**
* Gets channel content search capabilities
* @returns {object} Search capabilities for channel contents
*/
source.getSearchChannelContentsCapabilities = function () {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: []
};
};
/**
* Searches within a specific channel's contents
* @param {string} channelUrl - Channel URL
* @param {string} query - Search query
* @param {string} type - Content type
* @param {string} order - Sort order
* @param {object} filters - Search filters
* @returns {MediathekVideoPager} Pager with filtered channel videos
*/
source.searchChannelContents = function (channelUrl, query, type, order, filters) {
const channelId = REGEX_CHANNEL_URL.exec(channelUrl)?.[2];
if (!channelId || !query) {
return new VideoPager([], false, {});
}
const topicName = decodeURIComponent(channelId);
const queries = [
{ fields: ['topic'], query: topicName },
{ fields: ['title', 'description'], query: query }
];
return getMediathekVideoPager({
queries,
sortBy: DEFAULT_SORT_BY,
sortOrder: DEFAULT_SORT_ORDER,
future: DEFAULT_FUTURE,
offset: DEFAULT_OFFSET,
size: DEFAULT_PAGE_SIZE
});
};
/**
* Searches for channels matching the query
* @param {string} query - Search query
* @returns {ChannelPager} Empty pager (channel search not implemented)
*/
source.searchChannels = function (query) {
return new ChannelPager([], false, {});
};
/**
* Checks if a URL is a channel URL
* @param {string} url - URL to check
* @returns {boolean} True if URL is a channel URL
*/
source.isChannelUrl = function (url) {
if (!url) return false;
if (REGEX_CHANNEL_HINT.test(url)) {
return true;
}
if (REGEX_MEDIATHEK_DOMAIN.test(url) && REGEX_CHANNEL_PATH.test(url)) {
return true;
}
return false;
};
/**
* Gets channel information from URL
* @param {string} url - Channel URL
* @returns {PlatformChannel} Channel object
* @throws {ScriptException} If URL is invalid
*/
source.getChannel = function (url) {
if (!url) {
throw new ScriptException('URL is required');
}
const match = REGEX_CHANNEL_URL.exec(url);
const channelId = match ? match[2] : null;
if (!channelId) {
const fallbackId = url.replace(REGEX_PROTOCOL, '').replace(REGEX_PATH_QUERY, '');
if (fallbackId) {
return new PlatformChannel({
id: new PlatformID(PLATFORM, fallbackId, config.id),
name: decodeURIComponent(fallbackId),
thumbnail: '',
banner: '',
subscribers: 0,
description: 'MediathekView channel: ' + decodeURIComponent(fallbackId),
url: url,
links: {}
});
}
throw new ScriptException('Invalid channel URL');
}
return new PlatformChannel({
id: new PlatformID(PLATFORM, channelId, config.id),
name: decodeURIComponent(channelId),
thumbnail: '',
banner: '',
subscribers: 0,
description: 'MediathekView channel: ' + decodeURIComponent(channelId),
url: url,
links: {}
});
};
/**
* Gets all videos from a channel
* @param {string} url - Channel URL
* @returns {MediathekVideoPager} Pager with channel videos
*/
source.getChannelContents = function (url) {
const channelId = REGEX_CHANNEL_URL.exec(url)?.[2];
if (!channelId) {
return new VideoPager([], false, {});
}
const topicName = decodeURIComponent(channelId);
const queries = [{ fields: ['topic'], query: topicName }];
return getMediathekVideoPager({
queries,
sortBy: DEFAULT_SORT_BY,
sortOrder: DEFAULT_SORT_ORDER,
future: DEFAULT_FUTURE,
offset: DEFAULT_OFFSET,
size: DEFAULT_PAGE_SIZE
});
};
/**
* Checks if a URL is a content details URL
* @param {string} url - URL to check
* @returns {boolean} True if URL is a content URL
*/
source.isContentDetailsUrl = function (url) {
if (!url) return false;
if (REGEX_CONTENT_HINT.test(url)) {
return true;
}
if (REGEX_MEDIA_FILE.test(url)) {
return true;
}
if (isValidBroadcasterUrl(url)) {
return true;
}
if (REGEX_MEDIATHEK_DOMAIN.test(url)) {
return false;
}
return false;
};
/**
* Gets detailed information about a video from its URL
* @param {string} url - Video URL
* @returns {PlatformVideoDetails} Detailed video information
* @throws {UnavailableException} If content is not found
*/
source.getContentDetails = function (url) {
// Try exact URL match first
try {
const exactJson = apiQuery({
queries: [{
fields: ['url_website'],
query: url
}],
sortBy: DEFAULT_SORT_BY,
sortOrder: DEFAULT_SORT_ORDER,
future: DEFAULT_FUTURE,
offset: DEFAULT_OFFSET,
size: 1
});
const exactEntry = exactJson?.result?.results?.[0];
if (exactEntry && exactEntry.url_website === url) {
return entryToDetails({ entry: exactEntry, url });
}
} catch (e) {
log('Exact URL match failed: ' + e);
}
// Fallback: Try fuzzy search
try {
const json = apiQuery({
queries: [{
fields: ['url_website', 'title', 'description'],
query: url
}],
sortBy: DEFAULT_SORT_BY,
sortOrder: DEFAULT_SORT_ORDER,
future: true,
offset: DEFAULT_OFFSET,
size: 3
});
const results = json?.result?.results || [];
for (const entry of results) {
if (entry.url_website === url || entry.url_website?.includes(url) || url.includes(entry.url_website || '')) {
return entryToDetails({ entry, url });
}
}
if (results.length > 0) {
return entryToDetails({ entry: results[0], url });
}
} catch (e) {
log('Fuzzy search failed: ' + e);
}
// Last resort: search by title extracted from URL
const slug = (url.split('/').pop() || '').split('?')[0].replace(REGEX_SLUG_SEPARATOR, ' ');
if (slug && slug.length > 3) {
try {
const json2 = apiQuery({
queries: [{
fields: ['title'],
query: slug
}],
sortBy: DEFAULT_SORT_BY,
sortOrder: DEFAULT_SORT_ORDER,
future: true,
offset: DEFAULT_OFFSET,
size: 1
});
const entry2 = json2?.result?.results?.[0];
if (entry2) return entryToDetails({ entry: entry2, url });
} catch (e) {
log('Title search failed: ' + e);
}
}
throw new UnavailableException('Content not found in MediathekView database. Try opening the broadcaster\'s website directly: ' + url);
};
/**
* Gets comments for a video
* @param {string} url - Video URL
* @returns {CommentPager} Empty pager (comments not supported)
*/
source.getComments = function (url) {
return new CommentPager([], false, {});
};
/**
* Gets replies to a comment
* @param {object} comment - Parent comment
* @returns {CommentPager} Empty pager (comments not supported)
*/
source.getSubComments = function (comment) {
return new CommentPager([], false, {});
};
// =============================================================================
// PAGER CLASSES
// =============================================================================
/**
* Custom video pager for MediathekView with pagination support
*/
class MediathekVideoPager extends VideoPager {
constructor(results, hasMore, { queries, sortBy, sortOrder, future, offset, size }) {
super(results, hasMore, { queries, sortBy, sortOrder, future, offset, size });
}
nextPage() {
const nextOffset = this.context.offset + this.context.size;
return getMediathekVideoPager({
queries: this.context.queries,
sortBy: this.context.sortBy,
sortOrder: this.context.sortOrder,
future: this.context.future,
offset: nextOffset,
size: this.context.size
});
}
}
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
/**
* Makes a query to the MediathekView API
* @param {object} body - Request body with queries and parameters
* @returns {object} Parsed API response
* @throws {ScriptException} On API errors
*/
function apiQuery(body) {
const resp = http.POST(API_URL, JSON.stringify(body), API_HEADERS);
if (resp.code !== 200) {
throw new ScriptException('API error ' + resp.code + ': ' + resp.body);
}
return JSON.parse(resp.body);
}
/**
* Safely converts a value to an integer
* @param {*} x - Value to convert
* @returns {number} Integer value or 0
*/
function toInt(x) {
try {
return parseInt(x ?? 0) || 0;
} catch {
return 0;
}
}
/**
* Safely adds a query parameter to a URL
* @param {string} url - URL to add parameter to
* @param {string} key - Parameter key
* @param {string} value - Parameter value
* @returns {string} URL with added parameter, or original URL if invalid
*/
function addUrlParam(url, key, value) {
if (!url) return url;
try {
const urlObj = new URL(url);
urlObj.searchParams.set(key, value);
return urlObj.toString();
} catch (e) {
// If URL parsing fails, fall back to string concatenation
return url + (url.includes('?') ? '&' : '?') + key + '=' + value;
}
}
/**
* Custom video pager for MediathekView with pagination support
* @param {PlatformVideo[]} results - Array of videos
* @param {boolean} hasMore - Whether more pages are available
* @param {object} context - Pagination context
* @param {Array} context.queries - Search queries
* @param {string} context.sortBy - Sort field
* @param {string} context.sortOrder - Sort order
* @param {boolean} context.future - Include future content
* @param {number} context.offset - Current offset
* @param {number} context.size - Page size
*/
function getMediathekVideoPager({ queries, sortBy, sortOrder, future, offset, size }) {
const json = apiQuery({ queries, sortBy, sortOrder, future, offset, size });
const results = json?.result?.results || [];
const total = json?.result?.queryInfo?.totalResults || 0;
// Filter out videos with timestamps in the future (later today)
const now = Math.floor(Date.now() / 1000);
const filteredResults = results.filter(r => (r.timestamp || 0) <= now);
const videos = resultsToPlatformVideos(filteredResults);
const hasMore = offset + size < total;
return new MediathekVideoPager(videos, hasMore, { queries, sortBy, sortOrder, future, offset, size });
}
/**
* Converts API results to PlatformVideo objects
* @param {Array} results - Array of API result entries
* @returns {PlatformVideo[]} Array of platform videos
*/
function resultsToPlatformVideos(results) {
return (results || []).map((e) => {
const channelName = e.topic || e.channel || 'MediathekView';
const channelId = encodeURIComponent(channelName);
const channelUrl = addUrlParam(`https://mediathekviewweb.de/c/${channelId}`, 'isMediathekChannel', '1');
const idVal = (e._id ? String(e._id) : (e.url_website || e.url_video || e.id || e.title || ''));
// Add content hint to video URLs from API (not broadcaster URLs)
let videoUrl = e.url_website || e.url_video || '';
if (videoUrl && !isValidBroadcasterUrl(videoUrl)) {
videoUrl = addUrlParam(videoUrl, 'isMediathekContent', '1');
}
return new PlatformVideo({
id: new PlatformID(PLATFORM, idVal, config.id),
name: e.title || e.topic || e.filename || '',
thumbnails: new Thumbnails([new Thumbnail('', 0)]),
author: new PlatformAuthorLink(
new PlatformID(PLATFORM, channelName, config.id),
channelName,
channelUrl,
''
),
uploadDate: toInt(e.timestamp || e.time),
url: videoUrl,
duration: toInt(e.duration),
isLive: false,
});
});
}
/**
* Checks if a URL is from a valid German broadcaster
* @param {string} url - URL to check
* @returns {boolean} True if URL is from a known broadcaster
*/
function isValidBroadcasterUrl(url) {
if (!url) return false;
try {
const urlObj = new URL(url);
const host = urlObj.hostname.toLowerCase();
return BROADCASTER_DOMAINS.some(domain => host === domain || host.endsWith('.' + domain));
} catch (e) {
return false;
}
}
/**
* Converts a MediathekView entry to PlatformVideoDetails
* @param {object} params - Parameters
* @param {object} params.entry - MediathekView entry
* @param {string} params.url - Video URL
* @returns {PlatformVideoDetails} Detailed video information
*/
function entryToDetails({ entry, url }) {
const sources = [];
const subtitles = [];
const dur = toInt(entry?.duration);
const cands = [
{ key: 'url_video', name: 'SD', priority: false },
{ key: 'url_video_hd', name: 'HD', priority: true },
{ key: 'url_video_low', name: 'Low', priority: false },
];
for (const c of cands) {
const u = entry?.[c.key];
if (!u) continue;
try {
if (REGEX_HLS_FILE.test(u)) {
sources.push(new HLSSource({
name: c.name,
duration: dur,
url: u,
priority: c.priority
}));
} else if (REGEX_VIDEO_FILE.test(u)) {
sources.push(new VideoUrlSource({
name: c.name,
duration: dur,
url: u,
container: REGEX_WEBM_FILE.test(u) ? 'video/webm' : 'video/mp4',
priority: c.priority
}));
}
} catch (e) {
log('Error adding video source: ' + e);
}
}
// Fallback if no sources from entry but we have a direct URL
if (!sources.length && url) {
if (REGEX_HLS_FILE.test(url)) {
sources.push(new HLSSource({ name: 'Stream', duration: dur, url }));
} else if (REGEX_VIDEO_FILE.test(url)) {
sources.push(new VideoUrlSource({
name: 'Video',
duration: dur,
url,
container: REGEX_WEBM_FILE.test(url) ? 'video/webm' : 'video/mp4'
}));
}
}
// Add subtitles if available
if (entry?.url_subtitle) {
try {
subtitles.push({
name: 'German',
url: entry.url_subtitle,
format: 'text/vtt',
autoGenerated: false
});
} catch (e) {
log('Error adding subtitles: ' + e);
}
}
const channelName = entry?.topic || entry?.channel || 'MediathekView';
const channelId = encodeURIComponent(channelName);
const channelUrl = addUrlParam(`https://mediathekviewweb.de/c/${channelId}`, 'isMediathekChannel', '1');
return new PlatformVideoDetails({
id: new PlatformID(PLATFORM, entry?._id ? String(entry._id) : (entry?.url_website || entry?.url_video || entry?.title || url), config.id),
name: entry?.title || entry?.topic || '',
thumbnails: new Thumbnails([new Thumbnail('', 0)]),
author: new PlatformAuthorLink(new PlatformID(PLATFORM, channelName, config.id), channelName, channelUrl, ''),
uploadDate: toInt(entry?.timestamp),
duration: dur,
viewCount: 0,
url: entry?.url_website || url || '',
isLive: false,
description: entry?.description || '',
video: new VideoSourceDescriptor(sources),
subtitles: subtitles
});
}
log('loaded');