-
Notifications
You must be signed in to change notification settings - Fork 3
/
youtubeDL.user.js
1287 lines (1034 loc) · 49.4 KB
/
youtubeDL.user.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
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
// ==UserScript==
// @name YoutubeDL
// @namespace https://www.youtube.com/
// @version 1.1.0
// @description Download youtube videos at the comfort of your browser.
// @author realcoloride
// @match https://www.youtube.com/*
// @match https://www.youtube.com/watch*
// @match https://www.youtube.com/shorts*
// @match https://www.youtube.com/embed*
// @match */*
// @connect savetube.io
// @connect googlevideo.com
// @connect aadika.xyz
// @connect dlsnap11.xyz
// @connect githubusercontent.com
// @connect *
// @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @license MIT
// @grant GM.xmlHttpRequest
// ==/UserScript==
(function() {
'use strict';
let pageInformation = {
loaded : false,
website : "https://savetube.io",
searchEndpoint : null,
convertEndpoint : null,
checkingEndpoint : null,
pageValues : {}
}
// Process:
// Search -> Checking -> Convert by -> Convert using c_server
const githubAssetEndpoint = "https://raw.githubusercontent.com/realcoloride/YoutubeDL/main/";
let videoInformation;
const fetchHeaders = {
'Accept': '*/*',
'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Sec-Ch-Ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"Windows"',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'none',
};
const convertHeaders = {
"accept": "*/*",
"accept-language": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Google Chrome\";v=\"114\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"x-requested-key": "de0cfuirtgf67a"
};
const downloadHeaders = {
"accept": "*/*",
"accept-language": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Google Chrome\";v=\"114\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
};
const popupHTML = `
<div id="youtubeDL-popup">
<span class="youtubeDL-text bigger float">
<img src="{asset}YoutubeDL.png" class="youtubeDL-logo float">
YoutubeDL - Download video
<button id="youtubeDL-close" class="youtubeDL-button youtubeDL-align right" aria-label="Cancel">
<span>Close</span>
</button>
</span>
<div id="youtubeDL-loading">
<span class="youtubeDL-text medium center float" style="display: flex;">
<img src="{asset}loading.svg" style="width:21px; padding-right: 6px;"> Loading...
</span>
</div>
<div id="youtubeDL-quality">
<span class="youtubeDL-text medium center float" >Select a quality and click on Download.</span><br>
<span class="youtubeDL-text medium center float" style="margin-bottom: 10px;">
⚠️ CLICK
<a href="{asset}allow.gif" target="_blank"><strong>"ALWAYS ALLOW ALL DOMAINS"</strong></a>
WHEN DOWNLOADING FOR THE FIRST TIME.
<span class="youtubeDL-text center float">Some providers may have a bigger file size than estimated.</span>
</span>
<table id="youtubeDL-quality-table" style="width: 100%; border-spacing: 0;">
<thead class="youtubeDL-row">
<th class="youtubeDL-column youtubeDL-text">Format</th>
<th class="youtubeDL-column youtubeDL-text">Quality</th>
<th class="youtubeDL-column youtubeDL-text">Estimated Size</th>
<th class="youtubeDL-column youtubeDL-text">Download</th>
</thead>
<tbody id="youtubeDL-quality-container">
</tbody>
</table>
</div>
<div class="youtubeDL-credits">
<span class="youtubeDL-text medium">YoutubeDL by (real)coloride - 2023-2024</span>
<br>
<a class="youtubeDL-text medium" href="https://www.github.com/realcoloride/YoutubeDL">
<img src="{asset}github.png" width="21px">Github</a>
<a class="youtubeDL-text medium" href="https://opensource.org/license/mit/">
<img src="{asset}mit.png" width="21px">MIT license
</a>
</div>
</div>
`;
const pageLoadingFailedMessage =
`[YoutubeDL] An error has occured while fetching data.
This can possibly mean your firewall or IP might be blocking the requests and make sure you've set up the proper permissions to the script.
Please check your firewall or try using a VPN.`;
const mediaErrorMessage =
`[YoutubeDL] Failed fetching media.
This could be either because:
- An unhandled error
- Your tampermonkey settings
or an issue with the API.
Try to refresh the page, otherwise, reinstall the plugin.`;
// Element definitions
const ytdAppContainer = document.querySelector("ytd-app");
let popupElement;
// Information gathering
function getVideoInformation(url) {
const regex = /(?:https?:\/\/(?:www\.)?youtube\.com\/(?:watch\?v=|shorts\/|embed\/)?)([\w-]+)/i;
const match = regex.exec(url);
let videoId = match ? match[1] : null;
let type = null;
if (url.includes("/shorts/")) type = "shorts";
else if (url.includes("/watch?v=")) type = "video";
else if (url.includes("/embed/")) type = "embed";
return { type, videoId };
};
function getVideoUrlFromEmbed(player) {
return player.parentNode.parentNode.documentURI || window.location.href; // in case not in embed but in embed page itself
}
// Fetching
function convertSizeToBytes(size) {
const units = {
B: 1,
KB: 1024,
MB: 1024 * 1024,
GB: 1024 * 1024 * 1024,
};
const regex = /^(\d+(?:\.\d+)?)\s*([A-Z]+)$/i;
const match = size.match(regex);
if (!match) return 0;
const value = parseFloat(match[1]);
const unit = match[2].toUpperCase();
if (!units.hasOwnProperty(unit)) return 0;
return value * units[unit];
}
function decipherVariables(variableString) {
const variableDict = {};
const variableAssignments = variableString.match(/var\s+(\w+)\s*=\s*(.+?);/g);
variableAssignments.forEach((assignment) => {
const [, variableName, variableValue] = assignment.match(/var\s+(\w+)\s*=\s*['"](.+?)['"];/);
const trimmedValue = variableValue.trim().replace(/^['"]|['"]$/g, '');
variableDict[variableName] = trimmedValue;
});
return variableDict;
}
function isTimestampExpired(timestamp) {
const currentTimestamp = Math.floor(Date.now() / 1000);
return currentTimestamp > timestamp;
}
async function fetchPageInformation() {
if (pageInformation.searchEndpoint != null || window.self !== window.top) return;
// Scrapping internal values
const pageRequest = await GM.xmlHttpRequest({
url: `${pageInformation.website}`,
method: "GET",
headers: fetchHeaders,
});
const parser = new DOMParser();
const pageDocument = parser.parseFromString(pageRequest.responseText, "text/html");
let scrappedScriptElement;
pageDocument.querySelectorAll("script").forEach((scriptElement) => {
const scriptHTML = scriptElement.innerHTML;
if (scriptHTML.includes("k_time") && scriptHTML.includes("k_page")) {
scrappedScriptElement = scriptElement;
return;
}
});
const pageValues = decipherVariables(scrappedScriptElement.innerHTML);
pageInformation.pageValues = pageValues;
pageInformation.searchEndpoint = pageValues['k_url_search'];
pageInformation.convertEndpoint = pageValues['k_url_convert'];
pageInformation.checkingEndpoint = pageValues['k_url_check_task'];
pageInformation.loaded = true;
}
async function startConversion(fileExtension, fileQuality, timeExpires, token, filename, button) {
const videoType = videoInformation.type;
const videoId = videoInformation.videoId;
if (!videoType) return;
const initialFormData = new FormData();
initialFormData.append('v_id', videoId);
initialFormData.append('ftype', fileExtension);
initialFormData.append('fquality', fileQuality);
initialFormData.append('token', token);
initialFormData.append('timeExpire', timeExpires);
initialFormData.append('client', 'SaveTube.io');
const initialRequestBody = new URLSearchParams(initialFormData).toString();
let result = null;
try {
const payload = {
url: pageInformation.convertEndpoint,
method: "POST",
headers: convertHeaders,
data: initialRequestBody,
responseType: 'text',
referrerPolicy: "strict-origin-when-cross-origin",
mode: "cors",
credentials: "omit"
};
const initialRequest = await GM.xmlHttpRequest(payload);
const initialResponse = JSON.parse(initialRequest.responseText);
// Needs conversion is it links to a server
const downloadLink = initialResponse.d_url;
const needsConversation = (downloadLink == null);
if (needsConversation) {
updatePopupButton(button, 'Converting...');
const conversionServerEndpoint = initialResponse.c_server;
const convertFormData = new FormData();
convertFormData.append('v_id', videoId);
convertFormData.append('ftype', fileExtension);
convertFormData.append('fquality', fileQuality);
convertFormData.append('fname', filename);
convertFormData.append('token', token);
convertFormData.append('timeExpire', timeExpires);
const convertRequestBody = new URLSearchParams(convertFormData).toString();
const convertRequest = await GM.xmlHttpRequest({
url: `${conversionServerEndpoint}/api/json/convert`,
method: "POST",
headers: convertHeaders,
data: convertRequestBody,
responseType: 'text',
});
let convertResponse;
let adaptedResponse = {};
let result;
try {
convertResponse = JSON.parse(convertRequest.responseText);
result = convertResponse.result;
adaptedResponse = {
c_status : convertResponse.status,
d_url: result
}
} catch (error) {
alert("[YoutubeDL] Converting failed.\nYou might have been downloading too fast and have been rate limited or your antivirus may be blocking the media.\n(💡 If so, refresh the page or check your antivirus's settings.)")
result = "error";
adaptedResponse = {
c_status : "error"
}
return adaptedResponse;
}
if (result == 'Converting') { // Not converted
const jobId = convertResponse.jobId;
console.log(`[YoutubeDL] Download needs to be checked on, jobId: ${jobId}, waiting...`);
updatePopupButton(button, 'Waiting for server...');
async function gatherResult() {
return new Promise(async(resolve, reject) => {
const parsedURL = new URL(conversionServerEndpoint);
const protocol = parsedURL.protocol === "https:" ? "wss:" : "ws:";
const websocketURL = `${protocol}//${parsedURL.host}/sub/${jobId}?fname=${pageInformation.pageValues.k_prefix_name}`;
const socket = new WebSocket(websocketURL);
socket.onmessage = function(event) {
const message = JSON.parse(event.data);
switch (message.action) {
case "success":
socket.close();
resolve(message.url);
case "progress":
updatePopupButton(button, `Converting... ${message.value}%`)
case "error":
socket.close();
reject("WSCheck fail");
};
};
});
};
try {
const conversionUrl = await gatherResult();
adaptedResponse.d_url = conversionUrl;
} catch (error) {
console.error("[YoutubeDL] Error while checking for job converstion:", error);
adaptedResponse.c_status = 'error';
updatePopupButton(button, 'Converting Failed');
setTimeout(() => {
button.disabled = false;
updatePopupButton(button, 'Download');
}, 1000);
}
}
return adaptedResponse;
} else {
result = initialResponse;
}
} catch (error) {
console.error(error);
return null;
}
return result;
}
async function getMediaInformation() {
const videoType = videoInformation.type;
const videoId = videoInformation.videoId;
if (!videoType) return;
const formData = new FormData();
formData.append('q', `https://www.youtube.com/watch?v=${videoId}`);
formData.append('vt', 'home');
const requestBody = new URLSearchParams(formData).toString();
let result = {
status: 'notok'
};
try {
const request = await GM.xmlHttpRequest({
url: pageInformation.searchEndpoint,
method: "POST",
headers: fetchHeaders,
data: requestBody,
responseType: 'text',
});
result = JSON.parse(request.responseText);
} catch (error) {
console.error(error);
return result;
}
return result;
}
// Light mode/Dark mode
function isDarkMode() {
if (videoInformation.type == 'embed') return true;
const computedStyles = window.getComputedStyle(ytdAppContainer);
const backgroundColor = computedStyles["background-color"];
return backgroundColor.endsWith('15)');
}
function toggleLightClass(queryTarget) {
const elements = document.querySelectorAll(queryTarget);
elements.forEach((element) => {
element.classList.toggle("light");
toggleLightClassRecursive(element);
});
}
function toggleLightClassRecursive(element) {
const children = element.children;
for (let i = 0; i < children.length; i++) {
children[i].classList.toggle("light");
toggleLightClassRecursive(children[i]);
}
}
// Popup
// Links
// Downloading
async function downloadFile(button, url, filename) {
const baseText = `Download`;
button.disabled = true;
updatePopupButton(button, "Downloading...");
console.log(`[YoutubeDL] Downloading media URL: ${url}`);
function finish() {
updatePopupButton(button, baseText);
if (button.disabled) button.disabled = false
}
GM.xmlHttpRequest({
method: 'GET',
headers: downloadHeaders,
url: url,
responseType: 'blob',
onload: async function(response) {
if (response.status == 403) {
alert("[YoutubeDL] Media expired or may be impossible to download, please retry or try with another format, sorry!");
await reloadMedia();
return;
}
const blob = response.response;
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', filename);
link.click();
URL.revokeObjectURL(link.href);
updatePopupButton(button, 'Downloaded!');
button.disabled = false;
setTimeout(finish, 1000);
},
onerror: function(error) {
console.error('[YoutubeDL] Download Error:', error);
updatePopupButton(button, 'Download Failed');
setTimeout(finish, 1000);
},
onprogress: function(progressEvent) {
if (progressEvent.lengthComputable) {
const percentComplete = Math.round((progressEvent.loaded / progressEvent.total) * 100);
updatePopupButton(button, `Downloading: ${percentComplete}%`);
} else
updatePopupButton(button, 'Downloading...');
}
});
}
function updatePopupButton(button, text) {
button.innerHTML = `<strong>${text}</strong>`;
if (!isDarkMode()) button.classList.add('light');
}
async function createMediaFile(params) {
let { format, quality, size, extension, timeExpires, videoTitle, token } = params;
const qualityContainer = getPopupElement("quality-container");
const row = document.createElement("tr");
row.classList.add("youtubeDL-row");
function createRowElement() {
const rowElement = document.createElement("td");
rowElement.classList.add("youtubeDL-row-element");
return rowElement;
}
function addRowElement(rowElement) {
row.appendChild(rowElement);
}
function createSpanText(text, targetElement) {
const spanText = document.createElement("span");
spanText.classList.add("youtubeDL-text");
spanText.innerHTML = `<strong>${text}</strong>`;
if (!isDarkMode()) spanText.classList.add('light');
targetElement.appendChild(spanText);
}
// Format
const formatRowElement = createRowElement();
createSpanText(format, formatRowElement);
addRowElement(formatRowElement);
// Quality
const qualityRowElement = createRowElement();
createSpanText(quality, qualityRowElement);
addRowElement(qualityRowElement);
// Size
const sizeRowElement = createRowElement();
createSpanText(size, sizeRowElement);
addRowElement(sizeRowElement);
const downloadRowElement = createRowElement();
const downloadButton = document.createElement("button");
downloadButton.classList.add("youtubeDL-button");
downloadButton.ariaLabel = "Download";
updatePopupButton(downloadButton, "Download");
downloadButton.addEventListener("click", async(_) => {
try {
downloadButton.disabled = true;
updatePopupButton(downloadButton, "Fetching info...");
if (isTimestampExpired(pageInformation.pageValues.k_time)) {
await reloadMedia();
return;
}
extension = extension.replace(/ \(audio\)|kbps/g, '');
quality = quality.replace(/ \(audio\)|kbps/g, '');
let filename = `YoutubeDL_${videoTitle}_${quality}.${extension}`;
if (extension == "mp3") filename = `YoutubeDL_${videoTitle}.${extension}`;
const conversionRequest = await startConversion(extension, quality, timeExpires, token, filename, downloadButton);
const conversionStatus = conversionRequest.c_status;
async function fail() {
throw Error("Failed to download.");
}
if (!conversionStatus) { fail(); return; }
if (conversionStatus != 'ok' && conversionStatus != 'success') { fail(); return; }
const downloadLink = conversionRequest.d_url;
await downloadFile(downloadButton, downloadLink, filename);
} catch (error) {
console.error(error);
downloadButton.disabled = true;
updatePopupButton(downloadButton, '');
setTimeout(() => {
downloadButton.disabled = false;
updatePopupButton(downloadButton, 'Download');
}, 2000);
}
});
downloadRowElement.appendChild(downloadButton);
addRowElement(downloadRowElement);
qualityContainer.appendChild(row);
}
let hasMediaError = false;
async function loadMediaFromLinks(response) {
try {
const links = response.links;
const token = response.token;
const timeExpires = response.timeExpires;
const videoTitle = response.title;
const audioLinks = links.mp3;
let videoLinks = links.mp4;
function addFormat(information) {
const format = information.f;
if (!format) return;
const quality = information.q;
let size = information.size;
const regex = /\s[BKMGT]?B/;
const unit = size.match(regex)[0];
const sizeNoUnit = size.replace(regex, "");
const roundedSize = Math.round(parseFloat(sizeNoUnit));
size = `${roundedSize}${unit}`;
createMediaFile({
extension: format,
quality,
timeExpires,
videoTitle,
format: format.toUpperCase(),
size,
token
});
}
// Audio will only have this one so it doesnt matter
const defaultAudioFormat = audioLinks[Object.keys(audioLinks)[0]];
defaultAudioFormat.f = "mp3 (audio)";
addFormat(defaultAudioFormat);
// Format sorting first
// Remove auto quality
videoLinks["auto"] = null;
// Store 3gp quality if available
const low3gpFormat = { ...videoLinks["3gp@144p"] };
delete videoLinks["3gp@144p"];
// Sort from highest to lowest quality
const qualities = {};
for (const [qualityId, information] of Object.entries(videoLinks)) {
if (!information) continue;
const qualityName = information.q;
const strippedQualityName = qualityName.replace('p', '');
const quality = parseInt(strippedQualityName);
qualities[quality] = qualityId;
}
const newOrder = Object.keys(qualities).sort((a, b) => a - b);
function swapKeys(object, victimKeys, targetKeys) {
const swappedObj = {};
victimKeys.forEach((key, index) => {
swappedObj[targetKeys[index]] = object[key];
});
return swappedObj;
}
videoLinks = swapKeys(videoLinks, Object.keys(videoLinks), newOrder);
// Bubble swapping estimated qualities if incorrect (by provider)
function bubbleSwap() {
const videoLinkIds = Object.keys(videoLinks);
videoLinkIds.forEach((qualityId) => {
const currentQualityInformation = videoLinks[qualityId];
if (!currentQualityInformation) return;
const currentQualityIndex = videoLinkIds.findIndex((id) => id === qualityId);
if (currentQualityIndex - 1 < 0) return;
const previousQualityIndex = currentQualityIndex - 1;
const previousQualityId = videoLinkIds[previousQualityIndex];
if (!previousQualityId) return;
const previousQualityInformation = videoLinks[previousQualityId];
function getQualityOf(information) {
const qualityName = information.q;
const strippedQualityName = qualityName.replace('p', '');
const quality = parseInt(strippedQualityName);
return { qualityName, strippedQualityName, quality };
}
const previousQuality = getQualityOf(previousQualityInformation);
const currentQuality = getQualityOf(currentQualityInformation);
function swap() {
console.log(`[YoutubeDL] Swapping incorrect formats: [${previousQuality.qualityName}] ${previousQualityInformation.size} -> [${currentQuality.qualityName}] ${currentQualityInformation.size}`);
const previousClone = { ... previousQualityInformation};
const currentClone = { ... currentQualityInformation};
previousQualityInformation.size = currentClone.size;
currentQualityInformation.size = previousClone.size;
}
const previousSize = previousQualityInformation.size;
const previousSizeBytes = convertSizeToBytes(previousSize);
const currentSize = currentQualityInformation.size;
const currentSizeBytes = convertSizeToBytes(currentSize);
if (previousSizeBytes < currentSizeBytes) swap();
});
};
for (let i = 0; i < Object.keys(videoLinks).length; i++) bubbleSwap();
for (const [qualityId, information] of Object.entries(videoLinks)) {
if (!information) continue;
const qualityName = information.q;
const strippedQualityName = qualityName.replace('p', '');
const quality = parseInt(strippedQualityName);
qualities[quality] = qualityId;
addFormat(information);
}
if (low3gpFormat) addFormat(low3gpFormat);
} catch (error) {
console.error("[YoutubeDL] Failed loading media:", error);
alert(mediaErrorMessage);
hasMediaError = true;
showErrorOnDownloadButtons();
togglePopup();
popupElement.hidden = true;
}
}
let isLoadingMedia = false;
let hasLoadedMedia = false;
function clearMedia() {
const qualityContainer = getPopupElement("quality-container");
qualityContainer.innerHTML = "";
isLoadingMedia = false;
hasLoadedMedia = false;
}
async function reloadMedia() {
console.log("[YoutubeDL] Hot reloading...");
const loadingBarSpan = getPopupElement("loading > span");
loadingBarSpan.textContent = "Reloading...";
togglePopupLoading(true);
clearMedia();
await fetchPageInformation();
await loadMedia();
loadingBarSpan.textContent = "Loading...";
}
async function loadMedia() {
if (isLoadingMedia || hasLoadedMedia) return;
isLoadingMedia = true;
function fail() {
isLoadingMedia = false;
console.error("[YoutubeDL] Failed fetching media.");
}
if (!isLoadingMedia) { togglePopup(); return; };
const request = await getMediaInformation();
if (request.status != 'ok') { fail(); return; }
try {
await loadMediaFromLinks(request);
hasLoadedMedia = true;
togglePopupLoading(false);
} catch (error) {
console.error("[YoutubeDL] Failed fetching media content: ", error);
hasLoadedMedia = false;
}
}
// Getters
function getPopupElement(element) {
return document.querySelector(`#youtubeDL-${element}`);
}
// Loading and injection
function togglePopupLoading(loading) {
const loadingBar = getPopupElement("loading");
const qualityContainer = getPopupElement("quality");
loadingBar.hidden = !loading;
qualityContainer.hidden = loading;
}
let hasPreparedForOuterInjection = false;
let hasOuterInjectedFromTop = false;
function prepareOuterInjection() {
// check if in top window or already prepared
if (window.self !== window.top || hasPreparedForOuterInjection) return;
// check if link is different (other pages than youtube's)
const youtubeRegex = /(?:https?:\/\/(?:www\.)?youtube\.com\/(?:watch\?v=|shorts\/|embed\/)?)([\w-]+)/i;
if (youtubeRegex.test(window.location.href)) return;
window.top.addEventListener('message', async (event) => {
if (typeof(event.data) != 'object' || !event.isTrusted) return;
const data = event.data;
const title = data["title"];
const object = data["object"];
if (title == null) return;
// check if in youtube no cookie domain (with extra acceptance for regular youtube embed)
if (event.origin !== "https://www.youtube.com" &&
event.origin !== "https://www.youtube-nocookie.com") return;
switch (title) {
case "YoutubeDL_outerInject":
if (hasOuterInjectedFromTop) return;
// cross window communication for proxy windows to have interactivity
try {
// show flickering and loading
sendToBottomWindows("YoutubeDL_topLoadingShow", true);
// load everything needed on top window if not done
console.log("[YoutubeDL/Proxy] Fetching page information...");
await fetchPageInformation();
console.log("[YoutubeDL/Proxy] Loading custom styles...");
await injectStyles();
console.log("[YoutubeDL/Proxy] Loading popup...");
injectPopup();
hasOuterInjectedFromTop = true;
sendToBottomWindows("YoutubeDL_topLoadingShow", false);
} catch (error) {
sendToBottomWindows("YoutubeDL_topLoadingShow", false);
sendToBottomWindows("YoutubeDL_showError", error);
}
break;
case "YoutubeDL_togglePopup":
togglePopup();
break;
case "YoutubeDL_togglePopupElement":
await togglePopupElement(object);
break;
}
});
hasPreparedForOuterInjection = true;
console.log("[YoutubeDL] Has prepared for outer injection.");
}
let hasPreparedForInnerProxyInjection = false;
let outerProxyLoading = false;
function prepareOuterInjectionForProxy() {
// check if in top window or already prepared
if (window.self === window.top || hasPreparedForInnerProxyInjection) return;
window.self.addEventListener('message', async (event) => {
if (typeof(event.data) != 'object' || !event.isTrusted) return;
const data = event.data;
const title = data["title"];
const object = data["object"];
const passcode = data["passcode"];
if (title == null || passcode != "spaghetti") return;
switch (title) {
case "YoutubeDL_topLoadingShow":
// object is now a boolean
const downloadButtonImage = document.querySelector("#youtubeDL-download > img");
if (downloadButtonImage == null) return;
outerProxyLoading = object;
// set loading icon and flicker if loading else reset
downloadButtonImage.src = getAsset(object == true ? "YoutubeDL-loading.png" : "YoutubeDL.png");
if (object == true) downloadButtonImage.classList.add("youtubeDL-flicker");
else downloadButtonImage.classList.remove("youtubeDL-flicker");
break;
case "YoutubeDL_showError":
console.error("[YoutubeDL] Error coming from proxy window:", object);
break;
}
});
hasPreparedForInnerProxyInjection = true;
}
function injectPopup() {
/*<div id="youtubeDL-popup-bg" class="shown">
</div>*/
// if in proxy window/embed
if (window.self !== window.top) {
console.log("[YoutubeDL] Embed or internal window detected. Outer-injecting the popup of the iframe.");
// outer injection
sendToTopWindow("YoutubeDL_outerInject", null);
return;
}
// check if existing already then set
const existingElement = window.top.document.querySelector("#youtubeDL-popup-bg");
if (existingElement) {
popupElement = existingElement;
return;
}
popupElement = document.createElement("div");
popupElement.id = "youtubeDL-popup-bg";
// avoids replacement
popupElement.style = "line-height: initial; font-size: initial; z-index: " + Number.MAX_SAFE_INTEGER;
const revisedHTML = popupHTML.replaceAll('{asset}', githubAssetEndpoint);
popupElement.innerHTML = revisedHTML;
document.body.appendChild(popupElement);
togglePopupLoading(true);
createButtonConnections();
popupElement.hidden = true;
}
function sendToTopWindow(title, object) {
window.top.postMessage({ title, object }, '*');
}
function sendToBottomWindows(title, object) {
const iframes = document.querySelectorAll('iframe');
iframes.forEach((iframe) => iframe.contentWindow.postMessage({ title, object, passcode: "spaghetti" }, '*'));
}
let hideTimeout;
let waitingReload = false;
function togglePopup() {
// if proxy window, send message via outer injection
if (window.self !== window.top) {
// outer injection
sendToTopWindow("YoutubeDL_togglePopup", null);
return;
}
popupElement.classList.toggle("shown");
if (waitingReload) { reloadMedia(); waitingReload = false;}
else loadMedia();
// Avoid overlap
if (popupElement.hidden) {
clearTimeout(hideTimeout);
hideTimeout = setTimeout(() => popupElement.hidden = false, 200);
};
}
async function togglePopupElement(embedLink) {
if (popupElement.hidden == false) return;
popupElement.hidden = false;
const oldId = videoInformation.videoId;
if (embedLink != null) {
// reset video information
videoInformation = getVideoInformation(embedLink);
// youtube & no cookie support
// replace embed via normal page for api support
if (embedLink.includes('youtube.com/embed/') ||
embedLink.includes('youtube-nocookie.com/embed/')) {
const videoId = embedLink.split('/embed/')[1].split('?')[0];
videoInformation.type = 'embed';
videoInformation.videoId = videoId;
}
}
togglePopup();
// if changed from embed to another, reload media
if (oldId != videoInformation.videoId)
await reloadMedia();
}
// Button
let injectedShorts = [];
function injectDownloadButton() {
let targets = [];
let style;
const onShorts = (videoInformation.type == 'shorts');
const onEmbed = (videoInformation.type == 'embed');
if (onShorts) {
// Button for shorts
const playerControls = document.querySelectorAll('ytd-shorts-player-controls');
targets = playerControls;
style = "margin-bottom: 16px; transform: translate(36%, 10%); pointer-events: auto;";
} else if (onEmbed) {