-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnpo-dl.js
395 lines (326 loc) · 10.7 KB
/
npo-dl.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
import { HTTPResponse, launch, Page } from "puppeteer";
import { XMLParser } from "fast-xml-parser";
import getWvKeys from "./getwvkeys.js";
import { existsSync, mkdirSync, readFileSync, writeFile } from "node:fs";
import { unlink } from "node:fs/promises";
import process from "node:process";
import { fileExists, getKeyPath, getVideoPath, parseBoolean } from "./utils.js";
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 headless = parseBoolean(process.env.HEADLESS);
const videoPath = getVideoPath();
if (!existsSync(videoPath)) {
mkdirSync(videoPath);
mkdirSync(videoPath + "/keys");
}
const browser = await launch({ headless: headless });
async function npoLogin() {
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']",
);
await waitResponseSuffix(page, "session");
await page.close();
console.log("Login successful");
}
async function getEpisode(url) {
const promiseLogin = npoLogin();
await promiseLogin;
const result = await getInformation(url);
await browser.close();
return result;
}
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) {
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) {
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;
}
/**
* @param {Page} page
* @param {str} suffix
* @returns {Promise<HTTPResponse>}
*/
async function waitResponseSuffix(page, suffix) {
const response = page.waitForResponse(async (response) => {
const request = response.request();
const method = request.method().toUpperCase();
if (method != "GET" && method != "POST") {
return false;
}
const url = response.url();
if (!url.endsWith(suffix)) {
return false;
}
console.log(`request: ${url} method: ${method}`);
try {
const body = await response.buffer();
} catch (error) {
console.error("preflicht error");
return false;
}
return url.endsWith(suffix);
});
return await response;
}
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"));
}
console.log("gathering information");
const mpdPromise = waitResponseSuffix(page, "mpd");
const streamResponsePromise = waitResponseSuffix(page, "stream-link");
// reload the page to get the stream link
await page.reload();
const streamResponse = await streamResponsePromise;
const streamData = await streamResponse.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 mpdResponse = await mpdPromise;
const mpdText = await mpdResponse.text();
const mpdData = parser.parse(mpdText);
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) {
const WVKey = await getWVKeys(pssh, x_custom_data);
information.wideVineKeyResponse = WVKey.trim();
} else {
console.log("probably no drm");
}
writeKeyFile(keyPath, JSON.stringify(information));
try {
await page.close();
} catch (error) {
console.error(error);
}
return information;
}
function writeKeyFile(path, data) {
writeFile(path, data, "utf8", (err) => {
if (err) {
console.log(`Error writing file: ${err}`);
} else {
console.log(`${path} is written successfully!`);
}
});
}
async function getWVKeys(pssh, x_custom_data) {
console.log("getting keys from website");
const promise = 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);
});
});
return await promise;
}
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 sleep = (milliseconds) => {
return new Promise((success) => setTimeout(success, milliseconds));
};
export { getEpisode, getInformation, npoLogin };