-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
500 lines (387 loc) · 15.3 KB
/
index.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
import {launch} from 'puppeteer';
import {XMLParser} from 'fast-xml-parser';
import getWvKeys from './getwvkeys.js';
import {existsSync, mkdirSync, readFileSync, writeFile, promises} from 'fs';
import {unlink} from 'fs/promises';
import {spawn} from 'child_process';
import {resolve, join} from "path";
const options = {
ignoreAttributes: false, removeNSPrefix: true
};
const parser = new XMLParser(options);
const WidevineProxyUrl = 'https://npo-drm-gateway.samgcloud.nepworldwide.nl/authentication';
//set as environment variable or replace with your own key
const authKey = process.env.AUTH_KEY || "";
const email = process.env.NPO_EMAIL || "";
const password = process.env.NPO_PASSW || "";
const videoPath = resolve("./videos") + "/";
if (!existsSync(videoPath)) {
mkdirSync(videoPath);
mkdirSync(videoPath + '/keys');
}
let browser = null;
//enter the npo start show name and download all episodes from all seasons.
//second parameter = season count (0 = all)
//third parameter = reverse seasons (false = Start from latest, true = Start from first)
// getAllEpisodesFromShow("https://npo.nl/start/serie/keuringsdienst-van-waarde").then((urls) => {
// getEpisodes(urls).then((result) => {
// console.log(result);
// });
// });
// enter the npo start show name and download all episodes from the chosen season.
/*
getAllEpisodesFromSeason("keuringsdienst-van-waarde", "seizoen-3").then((urls) => {
getEpisodes(urls);
});
*/
/*
enter the video id here, you can find it in the url of the video, full url should look like this: https://www.npostart.nl/AT_300003151
if the video ids are sequential you can use the second parameter to download multiple episodes
*/
// getEpisodesInOrder("AT_300003161", 1).then((result) => {
// console.log(result);
// });
getEpisode("https://npo.nl/start/serie/dertigers/seizoen-6_1/dertigers_203/afspelen").then((result) => {
console.log(result);
});
async function npoLogin() {
// check if browser is already running
if (browser === null) {
browser = await launch({headless: false});
}
console.log('Running tests..');
const page = await browser.newPage();
await page.goto('https://npo.nl/start');
await page.waitForSelector('div[data-testid=\'btn-login\']');
await page.click('div[data-testid=\'btn-login\']');
await page.waitForSelector('#EmailAddress');
await page.$eval('#EmailAddress', (el, secret) => el.value = secret, email);
await page.$eval('#Password', (el, secret) => el.value = secret, password);
await sleep(1000);
await page.waitForSelector('button[value=\'login\']');
await page.click('button[value=\'login\']');
await page.waitForSelector('button[class=\'bg-transparent group w-full cursor-pointer\']');
await page.click('button[class=\'bg-transparent group w-full cursor-pointer\']');
try {
await page.waitForNetworkIdle();
} catch (TimeoutError) {
// keep going
}
await page.close();
}
async function getEpisode(url) {
const promiseLogin = npoLogin();
await promiseLogin;
const result = await getInformation(url);
await browser.close();
return downloadFromID(result);
}
async function getEpisodesInOrder(firstId, episodeCount) {
const index = firstId.lastIndexOf('_') + 1;
const id = firstId.substring(index, firstId.length);
let prefix = firstId.substring(0, index);
// if id start with 0 add 0 to the prefix
if (id.startsWith('0')) {
prefix += '0';
}
const urls = [];
for (let i = 0; i < episodeCount; i++) {
const episodeId = prefix + (parseInt(id) + i);
urls.push(`https://www.npostart.nl/${episodeId}`);
}
return getEpisodes(urls);
}
async function getAllEpisodesFromShow(url, seasonCount = -1, reverse = false) {
if (browser == null) {
browser = await launch({headless: false});
}
const page = await browser.newPage();
await page.goto(url);
const jsonData = await page.evaluate(() => {
return JSON.parse(document.getElementById('__NEXT_DATA__').innerText) || null;
});
if (jsonData === null) {
console.log('Error retrieving show data');
return null;
}
await page.close();
const show = jsonData['props']['pageProps']['dehydratedState']['queries'][0]['state']['data']['slug'];
const seasons = jsonData['props']['pageProps']['dehydratedState']['queries'][1]['state']['data'];
if (!reverse) // the normal season order is already reversed
seasons.reverse();
const seasonsLength = seasonCount !== -1 ? seasonCount : seasons.length;
const urls = [];
const perSeasonEpisodes = [];
for (let i = 0; i < seasonsLength; i++) {
const seasonEpisodes = getAllEpisodesFromSeason(`https://npo.nl/start/serie/${show}/${seasons[i]['slug']}`, reverse);
perSeasonEpisodes.push(seasonEpisodes);
}
await Promise.all(perSeasonEpisodes)
.then((result) => {
for (const season of result) {
urls.push(...season);
}
});
return urls;
}
async function getAllEpisodesFromSeason(url, reverse = false) {
if (browser == null) {
browser = await launch({headless: false});
}
const page = await browser.newPage();
const urls = [];
await page.goto(url);
await page.waitForSelector('div[data-testid=\'btn-login\']');
const jsonData = await page.evaluate(() => {
return JSON.parse(document.getElementById('__NEXT_DATA__').innerText) || null;
});
if (jsonData === null) {
console.log('Error retrieving episode data');
return null;
}
const show = jsonData['query']['seriesSlug'];
const season = jsonData['query']['seriesParams'][0];
const episodes = jsonData['props']['pageProps']['dehydratedState']['queries'][2]['state']['data'];
if (!reverse) // the normal is already reversed, so if we want to start from the first episode we need to reverse it
episodes.reverse();
for (let x = 0; x < episodes.length; x++) {
let programKey = episodes[x]['programKey'];
let slug = episodes[x]['slug'];
let productId = episodes[x]['productId'];
console.log(`ep. ${programKey} - ${slug} - ${productId}`);
urls.push(`https://npo.nl/start/serie/${show}/${season}/${slug}/afspelen`);
}
await page.close();
return urls;
}
async function getEpisodes(urls) {
const promiseLogin = npoLogin();
let informationList = [];
await promiseLogin;
let count = 0;
for (const npo_url of urls) {
informationList.push(getInformation(npo_url));
if (count % 10 === 0) {
await Promise.all(informationList);
}
}
const list = await Promise.all(informationList);
await browser.close();
return downloadMulti(list, true);
}
async function downloadMulti(InformationList, runParallel = false) {
if (runParallel === true) {
let downloadPromises = [];
for (const information of InformationList) {
downloadPromises.push(downloadFromID(information));
}
return await Promise.all(downloadPromises);
}
let result = [];
for (const information of InformationList) {
result.push(await downloadFromID(information));
}
return result;
}
async function getInformation(url) {
const page = await browser.newPage();
await page.goto(url);
if (page.url() === "https://npo.nl/start") {
await page.close();
console.log(`Error wrong episode ID ${url}`);
return null;
}
// const iframe = await page.waitForSelector(`#iframe-${id}`);
await page.waitForSelector(`.bmpui-image`);
const filename = await generateFileName(page);
console.log(`${filename} - ${url}`);
const keyPath = getKeyPath(filename);
if (await fileExists(keyPath)) {
await page.close();
console.log('information already gathered');
return JSON.parse(readFileSync(keyPath, 'utf8'));
}
const mpdPromise = page.waitForResponse((response) => {
if (response.request().method().toUpperCase() != "OPTIONS" && response.url().endsWith('.mpd')) {
return response;
}
});
// wait for post request that ends with 'stream-link'
const streamResponsePromise = page.waitForResponse((response) => {
if (response.request().method().toUpperCase() != "OPTIONS" && response.url().endsWith('stream-link')) {
return response;
}
});
// reload the page to get the stream link
await page.reload();
page.waitForNetworkIdle();
const streamData = await (await streamResponsePromise).json();
let x_custom_data = "";
try {
x_custom_data = streamData['stream']['drmToken'] || "";
} catch (TypeError) {
const pageContent = await page.content();
if (pageContent.includes("Alleen te zien met NPO Plus")) {
console.log('Error content needs NPO Plus subscription');
return null;
}
}
const mpdData = parser.parse(await (await mpdPromise).text());
let pssh = "";
// check if the mpdData contains the necessary information
if ('ContentProtection' in mpdData["MPD"]["Period"]["AdaptationSet"][1]) {
pssh = mpdData["MPD"]["Period"]["AdaptationSet"][1]["ContentProtection"][3].pssh || "";
}
const information = {
"filename": filename,
"pssh": pssh,
"x_custom_data": x_custom_data,
"mpdUrl": streamData['stream']['streamURL'],
"wideVineKeyResponse": null
};
//if pssh and x_custom_data are not empty, get the keys
if (pssh.length !== 0 && x_custom_data.length !== 0) {
information.wideVineKeyResponse = ((await getWVKeys(pssh, x_custom_data)).trim());
} else {
console.log('probably no drm');
}
await writeKeyFile(keyPath, JSON.stringify(information));
page.close();
console.log(information);
return information;
}
function getKeyPath(filename) {
return join(videoPath, '/keys/', filename + '.json');
}
async function writeKeyFile(path, data) {
await writeFile(path, data, 'utf8', (err) => {
if (err) {
console.log(`Error writing file: ${err}`);
} else {
console.log(`${path} is written successfully!`);
}
});
}
async function deleteFile(path) {
// check if file exists
if (await fileExists(path)) {
try {
await unlink(path.toString());
console.log(`successfully deleted ${path}`);
} catch (error) {
console.error('there was an error:', error.message);
}
} else {
console.warn(`file ${path} does not exist`);
}
}
async function downloadFromID(information) {
if (information === null) {
return null;
}
let filename = information.filename.toString();
console.log(filename);
const combinedFileName = videoPath + filename + '.mkv';
if (await fileExists(combinedFileName)) {
console.log("File already downloaded");
return combinedFileName;
}
console.log(information);
filename = await downloadMpd(information.mpdUrl.toString(), filename);
console.log(filename);
let key = null;
if (information.wideVineKeyResponse !== null) {
key = information.wideVineKeyResponse.toString();
}
return await decryptFiles(filename, key);
}
async function decryptFiles(filename, key) {
//console.log(videoPath);
let encryptedFilename = 'encrypted#' + filename;
const mp4File = videoPath + encryptedFilename + '.mp4';
const m4aFile = videoPath + encryptedFilename + '.m4a';
//if key is none then file probably not encrypted
let [mp4DecryptedFile, m4aDecryptedFile] = [mp4File, m4aFile];
// if (key != null) {
// const mp4Decrypted = mp4Decrypt(mp4File, key);
// const m4aDecrypted = mp4Decrypt(m4aFile, key);
// [mp4DecryptedFile, m4aDecryptedFile] = await Promise.all([mp4Decrypted, m4aDecrypted]);
// }
if (key != null) {
key = key.split(':')[1];
}
const resultFileName = await combineVideoAndAudio(filename, mp4DecryptedFile, m4aDecryptedFile, key);
await sleep(1000);
if (await fileExists(resultFileName)) {
await deleteFile(mp4File);
await deleteFile(m4aFile);
await deleteFile(mp4DecryptedFile);
await deleteFile(m4aDecryptedFile);
}
return resultFileName;
}
async function runCommand(command, args, result) {
return new Promise((success, reject) => {
const cmd = spawn(command, args);
const stdout = cmd.stdout;
let stdoutData = null;
stdout.on('end', () => {
console.log(`finished: ${command} ${args}`);
success(result);
});
stdout.on('readable', () => {
stdoutData = stdout.read();
if (stdoutData != null) console.log(stdoutData + `\t [${result}]`);
});
cmd.stderr.on('error', (data) => {
reject(data);
});
});
}
async function combineVideoAndAudio(filename, video, audio, key) {
const combinedFileName = videoPath + filename + '.mkv';
let args = ['-i', video, '-i', audio, '-c', 'copy', combinedFileName];
if (key != null) {
args = ['-decryption_key', key, '-i', video, '-decryption_key', key, '-i', audio, '-c', 'copy', combinedFileName];
}
return runCommand('ffmpeg', args, combinedFileName);
}
async function downloadMpd(mpdUrl, filename) {
const filenameFormat = 'encrypted#' + filename + '.%(ext)s';
const args = ['--allow-u', '--downloader', 'aria2c', '-f', 'bv,ba', '-P', videoPath, '-o', filenameFormat, mpdUrl];
return runCommand('yt-dlp', args, filename);
}
function getWVKeys(pssh, x_custom_data) {
console.log('getting keys from website');
return new Promise((success, reject) => {
if (authKey === "") {
reject('no auth key');
}
const js_getWVKeys = new getWvKeys(pssh, WidevineProxyUrl, authKey, x_custom_data);
js_getWVKeys.getWvKeys().then((result) => {
success(result);
});
});
}
async function generateFileName(page) {
const rawSerie = page.$eval('.font-bold.font-npo-scandia.leading-130.text-30 .line-clamp-2', el => el["innerText"]);
const rawTitle = page.$eval('h2.font-bold.font-npo-scandia.leading-130.text-22', el => el["innerText"]);
const rawNumber = page.$eval('.mb-24 .flex.items-center .leading-130.text-13 .line-clamp-1', el => el["innerText"]);
const rawSeason = page.$eval('.bg-card-3.font-bold.font-npo-scandia.inline-flex.items-center', el => el["innerText"]);
let filename = "";
filename += (await rawSerie) + " - ";
// remove word "Seizoen" from rawSeason
const seasonNumber = parseInt((await rawSeason).replace("Seizoen ", ""));
const episodeNumber = parseInt((await rawNumber).replace("Afl. ", "").split("•")[0]);
// add season and episode number to filename formatted as SxxExx
filename += "S" + seasonNumber.toString().padStart(2, '0') + "E" + episodeNumber.toString().padStart(2, '0') + " - ";
filename += (await rawTitle);
// remove illegal characters from filename
filename = filename.replace(/[/\\?%*:|"<>]/g, '#');
return filename;
}
const fileExists = async path => !!(await promises.stat(path).catch(() => false));
const sleep = (milliseconds) => {
return new Promise(success => setTimeout(success, milliseconds));
};
export default {getInformation, getAllEpisodesFromShow, getAllEpisodesFromSeason};