-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathgcpd_link_collector.user.js
More file actions
916 lines (831 loc) · 26.2 KB
/
gcpd_link_collector.user.js
File metadata and controls
916 lines (831 loc) · 26.2 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
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
// ==UserScript==
// @name gcpd link collector
// @namespace https://github.com/snhplayer/GetCoursePythonDownloader
// @version 0.7.1
// @description Collect m3u8 links for gcpd.py batch downloads
// Добавьте свой домен здесь (см. README для подробных инструкций)
// Add your own domain here to allow Violentmonkey to handle it
// @match *://getcourse.ru/*
// @match *://*.getcourse.ru/*
// @match *://*.muzkursi.ru/*
// @match *://kinescope.io/*
// @match *://*.kinescope.io/*
// @run-at document-start
// @inject-into page
// @grant GM_download
// @grant GM_getValue
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_addValueChangeListener
// ==/UserScript==
(function () {
"use strict";
const STORAGE_KEY = "gcpd_collected";
const DEBUG_KEY = "gcpd_debug";
const DEFAULT_DATA = { getcourse: [], kinescope: [] };
const TITLE_POLL_INTERVAL_MS = 500;
const TITLE_POLL_TIMEOUT_MS = 30000;
const STATUS_MENU_ID = "gcpd-status";
const stored = GM_getValue(STORAGE_KEY, DEFAULT_DATA);
const data = normalizeStored(stored);
const pendingKinescope = new Map();
const debugStats = {
totalRequests: 0,
failedExtractions: 0,
failedParsing: 0,
noMatch: 0,
kinescopeRejected: 0,
getCourseProcessed: 0,
kinescopeProcessed: 0,
edgeCases: []
};
let didInitPageLoadFill = false;
let titleObserver = null;
let lastKnownTitle = "";
let titleCaptured = false;
let didShowTitleTimeout = false;
const hookedWindows = new WeakSet();
const loggedIframes = new Set();
let iframeObserver = null;
let iframeScanInterval = null;
const isTopWindow = window === window.top;
// Log frame context on initialization
debugLog("INIT", "Script initialized", {
location: window.location.href.substring(0, 100),
isTopWindow,
parentLocation: !isTopWindow ? document.referrer?.substring(0, 100) : null
});
// Listen for changes from other frames (only in top window)
if (isTopWindow) {
GM_addValueChangeListener(STORAGE_KEY, function(name, oldValue, newValue, remote) {
if (remote && newValue) {
const normalized = normalizeStored(newValue);
let newEntriesAdded = false;
// Merge getcourse links
normalized.getcourse.forEach(entry => {
if (!data.getcourse.some(e => e.url === entry.url)) {
data.getcourse.push(entry);
newEntriesAdded = true;
}
});
// Merge kinescope links
normalized.kinescope.forEach(entry => {
if (!data.kinescope.some(e => e.videoId === entry.videoId)) {
data.kinescope.push(entry);
newEntriesAdded = true;
}
});
updateStatusMenu();
debugLog("SYNC", "Merged data from iframe", {
getcourseCount: data.getcourse.length,
kinescopeCount: data.kinescope.length,
remote,
newEntriesAdded
});
// Trigger title filling for newly merged entries
if (newEntriesAdded) {
titleCaptured = false;
waitForTitleThenFill(false);
}
}
});
}
registerMenu();
hookNetwork(window);
// Only run title observation in parent frame
if (isTopWindow) {
onPageLoadFillTitles();
ensureTitleObserver();
monitorIframes();
} else {
// In iframes, only monitor for new iframes (though unlikely)
monitorIframes();
}
window.addEventListener("load", reattachHandlers);
function normalizeStored(raw) {
const safe = raw && typeof raw === "object" ? raw : {};
return {
getcourse: Array.isArray(safe.getcourse) ? safe.getcourse : [],
kinescope: Array.isArray(safe.kinescope) ? safe.kinescope : [],
};
}
function registerMenu() {
if (!isTopWindow) {
debugLog("INIT", "Iframe context - menu disabled", {
location: window.location.href.substring(0, 100)
});
return;
}
updateStatusMenu();
GM_registerMenuCommand("Download gcpd links", downloadCollectedLinks);
GM_registerMenuCommand("Clear collection and rescan", clearCollectedLinks);
GM_registerMenuCommand("Toggle debug mode", toggleDebugMode);
GM_registerMenuCommand("Show debug stats", showDebugStats);
GM_registerMenuCommand("Clear debug stats", clearDebugStats);
}
function isDebugEnabled() {
return GM_getValue(DEBUG_KEY, false);
}
function toggleDebugMode() {
const current = isDebugEnabled();
GM_setValue(DEBUG_KEY, !current);
showToast(`Debug mode ${!current ? "enabled" : "disabled"}`);
}
function debugLog(category, message, details) {
if (!isDebugEnabled()) return;
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
category,
message,
details
};
console.log(`[GCPD Debug ${category}]`, message, details || "");
// Keep last 100 edge cases
if (details && details.edgeCase) {
debugStats.edgeCases.push(logEntry);
if (debugStats.edgeCases.length > 100) {
debugStats.edgeCases.shift();
}
}
}
function showDebugStats() {
const stats = [
`Total Requests: ${debugStats.totalRequests}`,
`Failed Extractions: ${debugStats.failedExtractions}`,
`Failed Parsing: ${debugStats.failedParsing}`,
`No Match: ${debugStats.noMatch}`,
`Kinescope Rejected: ${debugStats.kinescopeRejected}`,
`Kinescope Processed: ${debugStats.kinescopeProcessed}`,
`GetCourse Processed: ${debugStats.getCourseProcessed}`,
`Edge Cases Logged: ${debugStats.edgeCases.length}`
].join("\n");
console.log("[GCPD Debug Stats]\n" + stats);
console.log("[GCPD Edge Cases]", debugStats.edgeCases);
alert(stats);
}
function clearDebugStats() {
debugStats.totalRequests = 0;
debugStats.failedExtractions = 0;
debugStats.failedParsing = 0;
debugStats.noMatch = 0;
debugStats.kinescopeRejected = 0;
debugStats.getCourseProcessed = 0;
debugStats.kinescopeProcessed = 0;
debugStats.edgeCases = [];
showToast("Debug stats cleared");
}
function hookNetwork(targetWindow) {
if (!targetWindow) {
debugLog("HOOK", "Target window is null/undefined", {
edgeCase: true
});
return;
}
if (hookedWindows.has(targetWindow)) {
debugLog("HOOK", "Window already hooked", {
location: targetWindow.location?.href?.substring(0, 100)
});
return;
}
hookedWindows.add(targetWindow);
debugLog("HOOK", "Hooking network in window", {
location: targetWindow.location?.href?.substring(0, 100),
hasFetch: typeof targetWindow.fetch === "function",
hasXHR: !!(targetWindow.XMLHttpRequest && targetWindow.XMLHttpRequest.prototype)
});
const originalFetch = targetWindow.fetch;
if (typeof originalFetch === "function") {
targetWindow.fetch = function (input, init) {
tryHandleRequest(input);
return originalFetch.apply(this, arguments);
};
debugLog("HOOK", "Fetch hooked successfully", {});
} else {
debugLog("HOOK", "Fetch not available", {
fetchType: typeof targetWindow.fetch,
edgeCase: true
});
}
const targetXHR = targetWindow.XMLHttpRequest;
if (targetXHR && targetXHR.prototype) {
const originalOpen = targetXHR.prototype.open;
targetXHR.prototype.open = function (method, url) {
tryHandleRequest(url);
return originalOpen.apply(this, arguments);
};
debugLog("HOOK", "XHR hooked successfully", {});
} else {
debugLog("HOOK", "XHR not available", {
hasXHR: !!targetXHR,
hasPrototype: !!(targetXHR && targetXHR.prototype),
edgeCase: true
});
}
}
function totalCollected() {
return data.getcourse.length + data.kinescope.length;
}
function clearCollectedLinks() {
data.getcourse = [];
data.kinescope = [];
pendingKinescope.clear();
titleCaptured = false;
didShowTitleTimeout = false;
lastKnownTitle = "";
if (titleObserver) {
titleObserver.disconnect();
titleObserver = null;
}
persistData();
updateStatusMenu();
window.location.reload();
}
/** Only master URLs contain the real playlist; /api/playlist/media/ are not per-video. */
function isGetCourseMasterPath(pathname) {
return pathname && pathname.includes("/api/playlist/master/");
}
function tryHandleRequest(input) {
debugStats.totalRequests++;
const urlString = extractUrl(input);
if (!urlString) {
debugStats.failedExtractions++;
debugLog("EXTRACTION_FAILED", "Could not extract URL from input", {
inputType: typeof input,
inputConstructor: input?.constructor?.name,
inputKeys: input && typeof input === 'object' ? Object.keys(input) : null,
edgeCase: true
});
return;
}
debugLog("REQUEST", "Processing request", {
url: urlString,
urlLength: urlString.length,
truncated: urlString.substring(0, 100)
});
let parsedUrl;
try {
parsedUrl = new URL(urlString, window.location.href);
} catch (error) {
debugStats.failedParsing++;
debugLog("PARSE_FAILED", "URL parsing failed", {
url: urlString.substring(0, 200),
error: error.message,
baseUrl: window.location.href,
edgeCase: true
});
return;
}
const hostname = parsedUrl.hostname;
const pathname = parsedUrl.pathname;
debugLog("PARSED", "URL parsed successfully", {
hostname,
pathname: pathname.substring(0, 100),
search: parsedUrl.search.substring(0, 100),
hasM3u8: pathname.includes(".m3u8")
});
if (isKinescopeHost(hostname)) {
if (!urlString.includes(".m3u8") || !pathname.includes(".m3u8")) {
debugStats.kinescopeRejected++;
debugLog("KINESCOPE_REJECTED", "Kinescope host but no .m3u8", {
hostname,
pathname: pathname.substring(0, 100),
urlHasM3u8: urlString.includes(".m3u8"),
pathHasM3u8: pathname.includes(".m3u8"),
edgeCase: true
});
return;
}
debugStats.kinescopeProcessed++;
debugLog("KINESCOPE", "Processing Kinescope URL", {
hostname,
pathname: pathname.substring(0, 100)
});
handleKinescope(parsedUrl);
return;
}
const isMasterPath = isGetCourseMasterPath(pathname);
const hasM3u8 = pathname.includes(".m3u8");
if (isMasterPath) {
debugStats.getCourseProcessed++;
debugLog("GETCOURSE", "Processing GetCourse master path", {
hostname,
pathname: pathname.substring(0, 100)
});
handleGetCourse(parsedUrl);
return;
}
if (hasM3u8) {
debugStats.getCourseProcessed++;
debugLog("GETCOURSE", "Processing GetCourse m3u8 path", {
hostname,
pathname: pathname.substring(0, 100)
});
handleGetCourse(parsedUrl);
return;
}
// No match - log as potential edge case
debugStats.noMatch++;
debugLog("NO_MATCH", "URL didn't match any pattern", {
hostname,
pathname: pathname.substring(0, 100),
isKinescopeHost: isKinescopeHost(hostname),
isMasterPath,
hasM3u8,
edgeCase: true
});
}
function extractUrl(input) {
if (!input) {
debugLog("EXTRACT", "Input is null/undefined", {
input,
edgeCase: true
});
return "";
}
if (typeof input === "string") {
return input;
}
if (typeof input !== "object") {
debugLog("EXTRACT", "Input is not string or object", {
inputType: typeof input,
edgeCase: true
});
return "";
}
if (typeof input.url === "string") {
return input.url;
}
if (typeof input.href === "string" && (input instanceof URL || (input.constructor && input.constructor.name === "URL"))) {
return input.href;
}
// Edge case: object without expected properties
debugLog("EXTRACT", "Object input without url or href", {
hasUrl: "url" in input,
hasHref: "href" in input,
urlType: typeof input.url,
hrefType: typeof input.href,
isURL: input instanceof URL,
constructor: input.constructor?.name,
keys: Object.keys(input).slice(0, 10),
edgeCase: true
});
return "";
}
function isKinescopeHost(hostname) {
return hostname === "kinescope.io" || hostname.endsWith(".kinescope.io");
}
function handleKinescope(parsedUrl) {
const videoId = getKinescopeVideoId(parsedUrl);
if (!videoId) {
debugLog("KINESCOPE_HANDLER", "No video ID extracted", {
pathname: parsedUrl.pathname,
url: parsedUrl.href.substring(0, 100),
edgeCase: true
});
return;
}
if (isKinescopeCollected(videoId)) {
debugLog("KINESCOPE_HANDLER", "Video already collected", {
videoId
});
return;
}
const streamType = parsedUrl.searchParams.get("type");
if (streamType !== "video" && streamType !== "audio") {
debugLog("KINESCOPE_HANDLER", "Invalid or missing stream type", {
videoId,
streamType,
allParams: Array.from(parsedUrl.searchParams.entries()),
edgeCase: true
});
return;
}
const current = pendingKinescope.get(videoId) || {};
if (streamType === "video") {
current.videoUrl = parsedUrl.href;
} else {
current.audioUrl = parsedUrl.href;
}
pendingKinescope.set(videoId, current);
debugLog("KINESCOPE_HANDLER", "Stream added to pending", {
videoId,
streamType,
hasVideo: !!current.videoUrl,
hasAudio: !!current.audioUrl,
complete: !!(current.videoUrl && current.audioUrl)
});
if (current.videoUrl && current.audioUrl) {
const name = nextName("kinescope");
data.kinescope.push({
videoId,
videoUrl: current.videoUrl,
audioUrl: current.audioUrl,
name,
});
// Only trigger title capture in parent frame
if (isTopWindow) {
titleCaptured = false;
didShowTitleTimeout = false;
}
persistData();
updateStatusMenu();
debugLog("KINESCOPE_HANDLER", "Complete video saved", {
videoId,
name,
isTopWindow
});
}
}
function handleGetCourse(parsedUrl) {
const url = parsedUrl.href;
if (data.getcourse.some((entry) => entry.url === url)) {
debugLog("GETCOURSE_HANDLER", "URL already collected", {
url: url.substring(0, 100)
});
return;
}
const name = nextName("getcourse");
data.getcourse.push({ url, name, pageTitle: null });
// Only trigger title capture in parent frame
if (isTopWindow) {
titleCaptured = false;
didShowTitleTimeout = false;
}
persistData();
updateStatusMenu();
debugLog("GETCOURSE_HANDLER", "URL saved", {
url: url.substring(0, 100),
name,
totalCollected: data.getcourse.length,
isTopWindow
});
}
/** Fill trailing GetCourse entries with null pageTitle. */
function fillTrailingNullTitles(title, isRetry) {
if (!title) {
return;
}
const finalTitle = title;
let filled = 0;
for (let j = data.getcourse.length - 1; j >= 0; j--) {
const entry = data.getcourse[j];
const canReplaceVideo = entry.pageTitle === "video" && finalTitle !== "video";
const canFill =
entry.pageTitle == null ||
entry.pageTitle === "" ||
canReplaceVideo ||
(isRetry && entry.pageTitle === "video");
if (canFill) {
data.getcourse[j].pageTitle = finalTitle;
filled++;
} else {
break;
}
}
if (filled > 0) {
persistData();
updateStatusMenu();
}
if (!isRetry && finalTitle === "video" && filled > 0) {
setTimeout(function () {
waitForTitleThenFill(true);
}, 1500);
}
}
function waitForTitleThenFill(isRetry) {
const start = Date.now();
(function poll() {
if (titleCaptured) {
return;
}
const { title, ready } = getPageTitleCandidate();
const timedOut = Date.now() - start >= TITLE_POLL_TIMEOUT_MS;
if (ready || title) {
fillTrailingNullTitles(title, isRetry);
titleCaptured = true;
if (titleObserver) {
titleObserver.disconnect();
titleObserver = null;
}
return;
}
if (timedOut) {
if (!didShowTitleTimeout) {
didShowTitleTimeout = true;
}
return;
}
setTimeout(poll, TITLE_POLL_INTERVAL_MS);
})();
}
/** On load, delay 1s then fill titles so React concurrent render has time to update DOM/tab. */
function onPageLoadFillTitles() {
if (didInitPageLoadFill) {
return;
}
didInitPageLoadFill = true;
function runAfterLoad() {
setTimeout(function () {
waitForTitleThenFill(false);
}, 1000);
}
if (document.readyState === "complete") {
runAfterLoad();
return;
}
window.addEventListener("load", function onLoad() {
window.removeEventListener("load", onLoad);
runAfterLoad();
});
}
function ensureTitleObserver() {
if (titleObserver || typeof MutationObserver !== "function") {
return;
}
titleObserver = new MutationObserver(function () {
if (titleCaptured) {
return;
}
const { title, ready } = getPageTitleCandidate();
if (ready || title) {
fillTrailingNullTitles(title, false);
titleCaptured = true;
if (titleObserver) {
titleObserver.disconnect();
titleObserver = null;
}
}
});
const pageDoc = getPageDocument();
const target = pageDoc.head || pageDoc.documentElement || pageDoc;
const hasHead = !!pageDoc.head;
titleObserver.observe(target, {
childList: true,
subtree: hasHead,
characterData: true,
});
}
function hookIframe(iframe) {
try {
const iframeWindow = iframe.contentWindow;
if (!iframeWindow) {
debugLog("IFRAME", "No contentWindow, waiting for load", {
src: iframe.src?.substring(0, 100),
id: iframe.id
});
iframe.addEventListener(
"load",
function () {
hookIframe(iframe);
},
{ once: true }
);
return;
}
const testAccess = iframeWindow.location.href;
debugLog("IFRAME", "Hooking iframe", {
location: testAccess?.substring(0, 100),
src: iframe.src?.substring(0, 100),
id: iframe.id
});
hookNetwork(iframeWindow);
} catch (e) {
const iframeKey = iframe.src + '|' + iframe.id;
if (!loggedIframes.has(iframeKey)) {
loggedIframes.add(iframeKey);
debugLog("IFRAME", "Cannot access iframe (cross-origin)", {
src: iframe.src?.substring(0, 100),
id: iframe.id,
error: e.message,
edgeCase: true
});
}
}
}
function scanAndHookIframes() {
const doc = getPageDocument();
const iframes = doc.querySelectorAll("iframe");
iframes.forEach(hookIframe);
}
function monitorIframes() {
scanAndHookIframes();
if (typeof MutationObserver === "function" && !iframeObserver) {
iframeObserver = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
mutation.addedNodes.forEach(function (node) {
if (node.nodeType === 1) {
if (node.tagName === "IFRAME") {
hookIframe(node);
}
const iframes = node.querySelectorAll && node.querySelectorAll("iframe");
if (iframes) {
iframes.forEach(hookIframe);
}
}
});
});
});
const doc = getPageDocument();
if (doc.documentElement) {
iframeObserver.observe(doc.documentElement, {
childList: true,
subtree: true,
});
}
}
if (!iframeScanInterval) {
iframeScanInterval = setInterval(scanAndHookIframes, 2000);
}
}
function reattachHandlers() {
if (titleObserver) {
titleObserver.disconnect();
titleObserver = null;
}
if (iframeObserver) {
iframeObserver.disconnect();
iframeObserver = null;
}
if (iframeScanInterval) {
clearInterval(iframeScanInterval);
iframeScanInterval = null;
}
didInitPageLoadFill = false;
hookNetwork(window);
if (isTopWindow) {
ensureTitleObserver();
onPageLoadFillTitles();
}
monitorIframes();
}
function getPageDocument() {
const pageWindow = typeof unsafeWindow !== "undefined" && unsafeWindow ? unsafeWindow : window;
return pageWindow.document;
}
function getTitleElementByXpath() {
try {
const pageDoc = getPageDocument();
const result = pageDoc.evaluate(
"/html/head/title",
pageDoc,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
);
const node = result && result.singleNodeValue ? result.singleNodeValue : null;
return node;
} catch (error) {
return null;
}
}
function getTitleTextByXpath() {
const titleEl = getTitleElementByXpath();
const text = titleEl && titleEl.textContent ? titleEl.textContent.trim() : "";
if (text) {
lastKnownTitle = text;
}
if (!text && lastKnownTitle) {
return lastKnownTitle;
}
return text;
}
function getKinescopeVideoId(parsedUrl) {
const parts = parsedUrl.pathname.split("/").filter(Boolean);
return parts.length ? parts[0] : "";
}
function isKinescopeCollected(videoId) {
return data.kinescope.some((entry) => entry.videoId === videoId);
}
function persistData() {
GM_setValue(STORAGE_KEY, data);
debugLog("PERSIST", "Data saved to storage", {
isTopWindow,
getcourseCount: data.getcourse.length,
kinescopeCount: data.kinescope.length
});
}
function getPageTitleCandidate() {
const titleText = getTitleTextByXpath();
const pageDoc = getPageDocument();
const tabTitle = (pageDoc.title && pageDoc.title.trim()) ? pageDoc.title.trim() : "";
const lessonEl = pageDoc.querySelector && pageDoc.querySelector(".lesson-title-value");
const lessonRaw = (lessonEl && lessonEl.textContent && lessonEl.textContent.trim()) ? lessonEl.textContent.trim() : "";
const h1El = pageDoc.querySelector && pageDoc.querySelector("h1");
const h1Raw = (h1El && h1El.textContent && h1El.textContent.trim()) ? h1El.textContent.trim() : "";
const cleanedTitleEl = sanitizeName(titleText || "");
const cleanedTab = sanitizeName(tabTitle || "");
const cleanedLesson = sanitizeName(lessonRaw || "");
const cleanedH1 = sanitizeName(h1Raw || "");
const ordered = [cleanedTitleEl, cleanedTab, cleanedLesson, cleanedH1];
const nonGeneric = ordered.find((value) => value && !isGenericTitle(value));
if (nonGeneric) {
return { title: nonGeneric, ready: true };
}
const fallback = ordered.find((value) => value) || "";
return { title: fallback, ready: false };
}
function isGenericTitle(value) {
const lower = String(value || "").trim().toLowerCase();
return lower === "video" || lower === "player";
}
function nextName(kind) {
const base = sanitizeName(document.title || "video") || "video";
const existing =
kind === "kinescope" ? data.kinescope : data.getcourse;
const index = existing.filter((entry) =>
entry.name ? entry.name.startsWith(base) : false
).length;
const suffix = kind === "kinescope" ? "kinescope" : "gc";
return `${base}-${suffix}-${index + 1}`;
}
function sanitizeName(name) {
return name
.replace(/[\\/:*?"<>|]+/g, "_")
.replace(/\s+/g, "_")
.replace(/_+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 80);
}
function showToast(message) {
function show() {
const doc = getPageDocument();
if (!doc.body) {
setTimeout(show, 50);
return;
}
const el = doc.createElement("div");
el.textContent = message;
el.style.cssText =
"position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:rgba(0,0,0,0.85);color:#fff;padding:10px 16px;border-radius:8px;font-family:sans-serif;font-size:14px;z-index:2147483647;max-width:90%;";
doc.body.appendChild(el);
setTimeout(function () {
el.remove();
}, 3000);
}
show();
}
function updateStatusMenu() {
const statusText = `Status: total ${totalCollected()}`;
const inplace =
STATUS_MENU_ID ===
GM_registerMenuCommand(statusText, () => {}, {
id: STATUS_MENU_ID,
title: "Collected total",
autoClose: false,
});
return inplace;
}
function downloadCollectedLinks() {
const content = buildFileContent();
if (!content.trim()) {
showToast("No links collected yet");
return;
}
const filename = `gcpd_links_${getTimestamp()}.txt`;
const blob = new Blob([content], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const revoke = () => URL.revokeObjectURL(url);
GM_download({
url,
name: filename,
onload: revoke,
onerror: revoke,
});
window.setTimeout(revoke, 60000);
}
function buildFileContent() {
const lines = [];
data.kinescope.forEach((entry) => {
if (entry.videoUrl && entry.audioUrl && entry.name) {
lines.push(entry.videoUrl, entry.audioUrl, entry.name);
}
});
let currentPageTitle = null;
data.getcourse.forEach((entry) => {
if (!entry.url) return;
if (entry.pageTitle != null && entry.pageTitle !== "") {
if (entry.pageTitle !== currentPageTitle) {
currentPageTitle = entry.pageTitle;
lines.push("TITLE: " + currentPageTitle);
}
lines.push(entry.url);
} else {
lines.push(entry.url);
if (entry.name) lines.push(entry.name);
}
});
return lines.join("\n") + (lines.length ? "\n" : "");
}
function getTimestamp() {
const now = new Date();
const pad = (value) => String(value).padStart(2, "0");
const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(
now.getDate()
)}`;
const time = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(
now.getSeconds()
)}`;
return `${date}_${time}`;
}
})();