-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
1372 lines (1277 loc) · 41.5 KB
/
background.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
// browser = (function () {
// return typeof browser === "undefined" ? chrome : browser;
// })();
browserf = function () {
let b = undefined;
try {
if (typeof browser !== "undefined") b = browser;
else if (typeof chrome !== "undefined") b = chrome;
else if (typeof edje !== "undefined") b = edje;
} catch (error) {
error.log("browserf", error);
}
return b;
};
let waitTimerSytate1 = 0;
let waitTimerSytateOK = 0;
const downloadQueue = [];
const downloadingList = [];
let isWriteInProgress = false;
let tabid = 0; //browserf().tabs.TAB_ID_NONE;
let scrolltotitle = false;
const saveObjects = {
init: false,
filename: "",
video: "",
subtitle: "",
videotext: "",
videotext_addon: "",
videotext_addon_lang: "",
subtitle_addon: "",
subtitle_addon_lang: "",
module: "",
topic: "",
};
//const saveObjects = {};
const saveObjectsReq = {
init: false,
// video: true,
// video_res: true,
// videoduration: false,
// subtitle: true,
// videotext: true,
// videotext_addon: true,
// videotext_addon_lang: "en",
// subtitle_addon: true,
// subtitle_addon_lang: "en",
// usesaveid: true,
};
const fileConfig = {
init: false,
// host_url: "coursera.org",
// course_prefix: "",
// module_prefix: "M",
// title_delimeter: "_",
// space_delimeter: "_",
// ext_video: ".mp4",
// ext_sub: ".vtt",
// ext_text: ".txt",
// lastfileid: 0,
// lastmodule: "",
// lasttopic: "",
// savemode: 1,
};
const otherConfig = {
init: false,
// scrolltotitle: false,
// automatic: false,
// automatic_mode: "a_mark",
};
browserf().runtime.onInstalled.addListener(() => {
console.log("onInstalled background");
saveVariable("tabid", tabid);
downloadId_initialze();
});
browserf().tabs.onUpdated.addListener(tab_onUpdated);
/**
* Messages long-live port
*/
browserf().runtime.onConnect.addListener((port) => {
console.assert(port.name === "csa-background");
// if (port.name !== "csa-background") {
// console.log("PORT MESSAGE ", port.name);
// return false;
// }
// port.onDisconnect.addListener((port) => {
// console.assert(port.name === "csa-background");
// console.log("onDisconnect", port.name);
// console.log("onDisconnect downloadingList", downloadingList);
// });
port.onMessage.addListener(async (request) => {
switch (request.command) {
case "counterClear":
downloadId_initialze();
break;
case "tabid":
//stateClear();
tabid = request?.message?.tabid;
//scrolltotitle = request.message?.scrolltotitle;
console.log("tabid message :", request.message, tabid);
tab_check(tabid);
saveVariable("tabid", tabid);
// saveVariable("scrolltotitle", scrolltotitle);
console.log("after saveVariable tabid:");
//console.log("mgs background tabid:", tabid);
break;
case "saveFile":
console.log("saveFile background port", downloadQueue.length);
//add message to Download Queue
downloadQueue.push(request.message);
break;
case "dosavevieo":
console.log("dosavevieo background port from content", request.message);
save_module();
break;
case "cst_load":
console.log("cst_load background port from content", request.message);
if (!tabid) {
let tab = await getCurrentTab();
tabid = tab.id;
}
cst_load(tabid);
break;
case "dotranslate":
console.log("dotranslate background port from content", request.message);
if (!tabid) {
let tab = await getCurrentTab();
tabid = tab.id;
}
browserf()
.tabs.sendMessage(tabid, { command: "translate" })
.then((response) => {
if (response?.command && response.command == "translated") {
console.log("Translated by CST");
//ok_state(checkButton);
//close_page();
} else {
console.log("Answer not from target page CST?");
//some_error(checkButton);
}
})
.catch(() => {
console.log("Not connected target page CST");
//some_error(checkButton);
});
break;
case "dosave":
console.log("dosave background ", downloadQueue.length);
sendMessage({ state: "saving", items: downloadQueue.length, confirm: true });
// setTimeout(() => {
downloadQueueSave(request.message).then((msg) => {
console.log("dosave background after downloadQueueSave", downloadQueue.length, msg);
// });
}, 0);
break;
}
return false;
});
});
/**
* Event operations with browser download list
*/
browserf().downloads.onCreated.addListener((s) => {
console.log("New Download created. Id:" + s.id + ", fileSize:" + s.fileSize);
});
browserf().downloads.onChanged.addListener((e) => {
//console.log("Download state", e);
if (typeof e.state !== "undefined") {
if (e.state.current === "complete") {
console.log("Download id" + e.id + " has completed.");
downloadId_check(e.id);
}
if (e.state.current === "interrupted" && e.error.current === "USER_CANCELED") {
console.log("Download id" + e.id + " has USER_CANCELED.");
downloadId_check(e.id);
}
}
});
function cst_load(tabid) {
browserf().scripting.executeScript({
target: { tabId: tabid },
files: ["module-cst.js"],
});
}
async function saveVariable(key, value) {
let item = {};
item[key] = value;
return browserf()
.storage.local.set(item)
.then(() => {
console.log("saveSession: saved item", key, value, item);
});
}
async function getOptions(key) {
let item = {};
item[key] = "";
return browserf()
.storage.sync.get(item)
.then((item) => {
console.log("getOptions: item", key, item[key]);
return item[key];
});
}
async function getVariable(key, defaultValue = "") {
let item = {};
item[key] = defaultValue;
return browserf()
.storage.local.get(item)
.then((item) => {
console.log("getVariable: item", key, item[key]);
return item[key];
});
}
/**
* Save all files thta prepared for save on array of Download Queue
* @param {*} items
* @returns items
*/
async function downloadQueueSave(items) {
if (downloadQueue?.length != items) console.log("ALARM downloadQueueSave not have all of elements", items);
//console.log(" downloadQueueSave run tab_onSaveDone preparing_mode:");
tab_onSaveDone(true);
while (downloadQueue?.length) {
console.log("downloadQueueSave total:", downloadQueue?.length);
let item = downloadQueue.pop();
await saveFile(item);
}
return items;
}
async function downloadId_check(id) {
await acquireWriteLock();
if (downloadingList.length) {
if (downloadingList.includes(id)) {
console.log("Download id" + id + " was mine, clearing...");
await downloadId_clear_downloaded(id);
stateSetValue(downloadingList.length);
}
}
isWriteInProgress = false;
}
// function xdownloadId_check(id) {
// browserf().storage.session.get({ downloadingnow: [] }, (items) => {
// if (items.downloadingnow.length) {
// if (items.downloadingnow.includes(id)) {
// console.log("Download id" + id + " was mine, clearing...");
// downloadId_clear_downloaded(id).then((m) => {
// console.log("afetr downloadId_clear_downloaded", m);
// stateSetValue(m);
// });
// //stateSetValue();
// }
// }
// });
// }
async function saveFile(obj) {
tabid = obj.tabid;
let url = String(obj.url).startsWith("http") ? obj.url : obj.baseurl + obj.url;
//console.log("saveFile :", url, obj);
await browserf()
.downloads.download({
url: url,
filename: obj.filename,
saveAs: false,
conflictAction: "overwrite",
})
.then((downloadId) => {
// If 'downloadId' is undefined, then there is an error
// so making sure it is not so before proceeding.
if (typeof downloadId !== "undefined") {
console.log("Download initiated, ID is: " + downloadId);
//increaseState();
downloadId_add_download(downloadId);
//sendMessage("downloading", downloadId);
}
});
}
function stateSet(c, tabid = 0) {
if (waitTimerSytateOK) {
clearTimeout(waitTimerSytateOK);
waitTimerSytateOK = 0;
}
//tabid = tabid ? tabid : getCurrentTab()?.id; , tabId: tabid
stateSetText(c);
stateSetColor(1);
if (waitTimerSytate1) clearTimeout(waitTimerSytate1);
waitTimerSytate1 = setTimeout(() => {
waitTimerSytate1 = 0;
stateSetColor(2);
}, 500);
}
function stateSetText(c) {
browserf().action.setBadgeText({ text: String(c).trim() });
}
function stateSetColor(color = 0, tabid = 0) {
//tabid = tabid ? tabid : getCurrentTab()?.id;
const colormodes = ["white", "red", "blue"];
browserf().action.setBadgeBackgroundColor({
color: colormodes[color],
});
}
function stateSetValue(c) {
console.log("stateSetValue", c);
c = Number(isNaN(c) ? 0 : c);
if (c <= 0) {
downloadId_initialze();
} else {
stateSet(c);
}
}
// function increaseState() {
// browserf().action.getBadgeText({}, (c) => {
// c = Number(isNaN(c) ? 0 : c) + 1;
// if (c > 30) {
// c = "";
// downloadId_initialze();
// }
// stateSet(c);
// });
// }
function stateCalc(c) {
console.log("stateCalc", c);
c = Number(isNaN(c) ? 0 : c);
if (c > 30 || c <= 0) {
c = "";
}
stateSet(c);
}
function stateClear(tabid = 0) {
//tabid = tabid ? tabid : getCurrentTab()?.id;
browserf().action.setBadgeText({ text: "", tabId: tabid });
browserf().action.setBadgeBackgroundColor({
color: "white",
});
}
function sendMessage(m) {
browserf().runtime.sendMessage({ greeting: "csa-save", message: m });
}
async function getCurrentTab() {
let queryOptions = {
active: true,
lastFocusedWindow: true,
};
// `tab` will either be a `tabs.Tab` instance or `undefined`.
let [tab] = await browserf().tabs.query(queryOptions);
return tab;
}
// Asynchronous function to acquire the write lock
async function acquireWriteLock() {
return new Promise((resolve) => {
const checkLock = () => {
if (!isWriteInProgress) {
isWriteInProgress = true;
resolve();
} else {
console.log("acquireWriteLock - locked, wait");
setTimeout(checkLock, 10);
}
};
checkLock();
});
}
async function downloadId_add_download(downloadId) {
console.log("downloadId_add_download begin", downloadId, downloadingList);
await acquireWriteLock();
//console.log("downloadId_add_download after lock", downloadId, downloadingList);
if (downloadingList) {
if (!downloadingList.includes(downloadId)) {
downloadingList.push(downloadId);
//console.log("downloadId_add_download added", downloadId, downloadingList);
stateCalc(downloadingList.length);
}
}
isWriteInProgress = false;
}
// async function downloadId_add_download(downloadId) {
// //console.log("downloadId_add_download begin", downloadId);
// await browserf().storage.session
// .get({
// downloadingnow: [downloadId],
// })
// .then(async (items) => {
// //console.log("downloadId_add_download then", items);
// //console.log("downloadId_add_download get", downloadId, items?.downloadingnow);
// if (items?.downloadingnow) {
// if (!items.downloadingnow.includes(downloadId)) {
// items.downloadingnow.push(downloadId);
// }
// //console.log("downloadId_add_download set", downloadId, items?.downloadingnow);
// await browserf().storage.session
// .set({
// downloadingnow: items.downloadingnow,
// })
// .then(() => {
// console.log("downloadId_add_download: ssaved items", items.downloadingnow);
// stateCalc(items.downloadingnow.length);
// });
// }
// });
// }
//stitle = "", ssavedTitle = "", isupdated = false, preparing_mode = false)
// params = {
// title: title,
// savedTitle: savedTitle,
// isupdated: isupdated,
// preparing_mode: preparing_mode,
// automatic: automatic,
// };
function tab_select_current_video_implode(params) {
let stitle = "",
ssavedTitle = "",
// isupdated = false,
preparing_mode = false,
automatic = false,
automatic_mode = "a_cst";
if (params) {
console.log("tab_select_current_video_implode", params);
stitle = params.title;
ssavedTitle = params.savedTitle;
// isupdated = Boolean(params.isupdated);
preparing_mode = params.preparing_mode ? params.preparing_mode : preparing_mode;
automatic = params.automatic ? params.automatic : automatic;
automatic_mode = params.automatic_mode ? params.automatic_mode : automatic_mode;
} else {
console.log("tab_select_current_video_implode empty", params);
return;
}
if (stitle == "") return;
let title = stitle.trim();
let savedTitle = typeof ssavedTitle == "string" ? ssavedTitle.trim() : "";
// console.log(
// "tab_select_current_video_implode. stitle:",
// stitle,
// "title:",
// title,
// "savedTitle:",
// savedTitle,
// "isupdated:",
// isupdated,
// "preparing_mode",
// preparing_mode
// );
window.browser = (function () {
return typeof window.browser === "undefined" ? window.chrome : window.browser;
})();
function sendMessage(command, message) {
let port = browser.runtime.connect({ name: "csa-background" });
port.postMessage({ command: command, message: message });
}
function analyseURL(type = "video") {
const loc = new URL(window.location);
let finding = "";
switch (type) {
case "video":
finding = "/lecture/";
break;
case "read":
finding = "/supplement/";
break;
case "quiz":
finding = "/quiz/";
break;
case "test":
finding = "/exam/";
break;
case "ungradedWidget":
finding = "/ungradedWidget/";
break;
case "ungradedLti":
finding = "/ungradedLti/";
break;
case "discussion":
finding = "/discussionPrompt/";
break;
case "gradedLti":
finding = "/gradedLti/";
break;
}
//console.log(`It page analyseURL - ${finding} ${loc.pathname} : ${loc.pathname.includes(finding)}`);
return finding ? loc.pathname.includes(finding) : false;
}
function isPageMarked(item) {
let obj = item?.closest(".rc-NavSingleItemDisplay");
let btn = obj.querySelector("div.rc-NavItemIcon > span.rc-TooltipWrapper");
result = btn === null;
console.log("isPageMarked", result);
return result;
}
async function isReadySkipPage() {
let cont = 15;
while (cont > 0) {
let btn = document.querySelectorAll("a.cds-button-disableElevation")[1];
if (btn) {
setTimeout(() => {
console.log("It ready to skip this page click to ", btn);
btn.click();
//btn.onclick.call(btn);
}, 2000);
break;
} else {
console.log("It page a href not found :", btn, cont);
await dcelay(1000, 1);
}
cont--;
}
}
async function isReadySaveVideo() {
if (!analyseURL("video")) {
console.log("It page without of video content, skip");
isReadySkipPage();
} else {
let cont = 15;
while (cont > 0) {
let video = document.getElementsByTagName("video");
if (video) video=video[0];
if (video && video.readyState > 0) {
console.log("Can save your video", video);
sendMessage("dosavevieo", document.title);
setTimeout(() => {
isReadySkipPage();
}, 5000);
break;
} else {
await dcelay(1000, 1);
}
cont--;
}
}
}
async function isReadyVideoTranslate() {
if (!analyseURL("video")) {
console.log("It page without of video content");
return;
}
let cont = 15;
load_cst_module();
while (cont > 0) {
let cst_state = check_cst_loaded();
let video = document.getElementsByTagName("video");
if (video) video=video[0];
if (cst_state && video && video.readyState > 0) {
translateVideo();
break;
} else {
await dcelay(1000, 1);
}
cont--;
}
}
async function isReadyVideo() {
if (!analyseURL("video")) {
console.log("It page without of video content");
return;
}
let cont = 15;
while (cont > 0) {
let video = document.getElementsByTagName("video");
if (video) video=video[0];
if (video && video.readyState > 0) {
setVideoPos(video);
break;
} else {
await dcelay(1000, 1);
}
cont--;
}
}
async function isReadyRead() {
if (!analyseURL("read")) {
console.log("It page without of read content");
return;
}
let cont = 15;
while (cont > 0) {
let btn = document.querySelector('button.cds-button-disableElevation[type="submit"]');
if (btn) {
setTimeout(() => {
console.log("It page click to ", btn);
btn.click();
setTimeout(() => {
let btn = document.querySelector('button.cds-button-disableElevation[type="submit"]');
console.log("It page click to next", btn);
btn.click();
}, 6000);
}, 2000);
break;
} else {
console.log("It page button not found :", btn, cont);
await dcelay(1000, 1);
}
cont--;
}
}
async function isReadyUWidget() {
if (!analyseURL("ungradedWidget")) {
console.log("It page without of ungradedWidget content");
return;
}
let cont = 15;
while (cont > 0) {
// rc - WidgetCompleteButton;
let btn = document.querySelector('button.mark-complete[type="button"]');
if (btn) {
setTimeout(() => {
console.log("It page click to ", btn);
btn.click();
setTimeout(() => {
let btn = document.querySelector('button.next-item[type="submit"]');
console.log("It page click to next", btn);
btn.click();
}, 6000);
}, 2000);
break;
} else {
console.log("It page ungradedWidget button not found :", btn, cont);
await dcelay(1000, 1);
}
cont--;
}
}
async function isReadyDiscussion() {
if (!analyseURL("discussion")) {
console.log("It page without of discussion content");
return;
}
isReadySkipPage();
}
async function isReadyQuiz() {
if (!analyseURL("quiz")) {
console.log("It page without of quiz content");
return;
}
isReadySkipPage();
}
async function isReadyTest() {
if (!analyseURL("test")) {
console.log("It page without of test content");
return;
}
isReadySkipPage();
}
async function isReadyULti() {
if (!(analyseURL("ungradedLti") || analyseURL("gradedLti"))) {
console.log("It page without of ULti content");
return;
}
isReadySkipPage();
}
function check_cst_loaded() {
result = document.body?.getAttribute("cst") === "loaded";
//if (result) console.log("CST module is already marked as loaded, skip");
return result;
}
function load_cst_module() {
let cst_loaded = check_cst_loaded();
if (!cst_loaded) {
console.log("command load cst module");
sendMessage("cst_load", { cst_loaded: cst_loaded });
}
}
function translateVideo() {
console.log("command translate Video...");
sendMessage("dotranslate");
//sendMessageToCST("translate");
}
function setVideoPos(video, pos = 0.95) {
if (video && video.readyState > 0) {
let duration = video.duration;
let position = Math.ceil(duration * pos);
video.currentTime = position;
}
}
function getModouleInfo() {
let result = {};
//result.module = document.querySelector("a.breadcrumb-title > span")?.innerHTML.split(" ")[1];
result.topic = document.querySelector("span.breadcrumb-title")?.innerHTML.trim();
if (result.topic === undefined) {
result.topic = document.title.split("|")[0].trim();
}
return result;
}
function dcelay(t, val) {
return new Promise((resolve) => setTimeout(resolve, t, val));
}
async function isReady(title) {
let cont = 25;
while (cont > 0) {
const items = document.querySelectorAll("div.rc-NavItemName");
if (items && items.length) {
break;
} else {
console.log("not found,sleep", cont);
await dcelay(1000, 1);
//console.log("not found,after sleep", cont);
}
cont--;
}
const items = document.querySelectorAll("div.rc-NavItemName");
searchSavedTitle(savedTitle, items);
let searchResult = searchtitle(title, items);
if (automatic) {
console.log("automatic_mode", automatic_mode);
if (automatic_mode == "a_cst") {
isReadyVideoTranslate();
} else if (automatic_mode == "a_save") {
console.log("automatic_mode save");
isReadySaveVideo();
} else {
if (searchResult && searchResult.pagemarked) {
console.log("Page already marked, skip it");
isReadySkipPage();
} else {
isReadyVideo();
isReadyRead();
isReadyQuiz();
isReadyUWidget();
isReadyTest();
isReadyULti();
isReadyDiscussion();
}
}
}
}
function markItemSaved(item, mode = 0) {
const colorsmodes = ["#ff00005c", "lightgreen", "#f7ff005c"];
let obj = item?.closest(".rc-NavSingleItemDisplay")?.getElementsByClassName("rc-NavItemIcon");
//console.log("markItemSaved", item, mode);
if (obj.length) {
let o = obj[0];
let w = o.width;
o.style.backgroundColor = colorsmodes[mode];
o.style.borderRadius = "30px";
o.style.paddingLeft = "4px";
o.style.margin = "0";
o.style.marginRight = "4px";
o.style.paddingTop = "4px";
if (w) {
o.style.width = w - 4 + "px";
} else {
o.style.width = "28px";
}
//console.log("markItemSaved style", item, o.style);
}
}
function searchSavedTitle(stitle, items) {
let title = stitle;
let pagemarked = undefined;
//const items = document.querySelectorAll("div.rc-NavItemName");
// console.log("searchtitle, items:", title, items.length);
if (title) {
for (const item of items) {
// items.forEach((item) => {
let titles = item.innerText.split("\n");
if (titles.length < 2) {
titles = item.innerHTML.split("</strong>");
}
titles = titles.pop().trim();
if (title && titles) {
//console.log("item titles", title, titles);
if (title.normalize("NFC") == titles.normalize("NFC")) {
//console.log("item - found. title:", title, "savedTitle:", savedTitle, "preparing_mode:", preparing_mode);
//item.scrollIntoView({ behavior: "smooth", block: "center" });
//pagemarked = isPageMarked(item);
if (stitle) {
let colormode = 0;
//if (preparing_mode) colormode = 2;
markItemSaved(item, colormode);
return { result: true, pagemarked: pagemarked };
}
}
}
}
}
return { result: false, pagemarked: pagemarked };
}
function searchtitle(stitle, items) {
let title = getModouleInfo()?.topic;
let pagemarked = undefined;
if (title === undefined) title = stitle.trim();
//const items = document.querySelectorAll("div.rc-NavItemName");
// console.log("searchtitle, items:", title, items.length);
if (title) {
for (const item of items) {
// items.forEach((item) => {
let titles = item.innerText.split("\n");
if (titles.length < 2) {
titles = item.innerHTML.split("</strong>");
}
titles = titles.pop().trim();
if (title && titles) {
//console.log("item titles", title, titles);
if (title.normalize("NFC") == titles.normalize("NFC")) {
//console.log("item - found. title:", title, "savedTitle:", savedTitle, "preparing_mode:", preparing_mode);
item.scrollIntoView({ behavior: "smooth", block: "center" });
pagemarked = isPageMarked(item);
if (analyseURL("video") && savedTitle) {
let colormode = savedTitle.normalize("NFC") != title.normalize("NFC") ? 1 : 0;
if (preparing_mode) colormode = 2;
markItemSaved(item, colormode);
return { result: true, pagemarked: pagemarked };
}
}
}
}
}
return { result: false, pagemarked: pagemarked };
}
if (document.readyState === "loading") {
console.log("Loading hasn't finished yet");
document.addEventListener("DOMContentLoaded", (event) => {
console.log("DOMContentLoaded run searchtitle");
isReady(title);
});
} else {
console.log("DOMContentLoaded has already fired,run searchtitle");
isReady(title);
}
// if (isupdated) {
// document.addEventListener("DOMContentLoaded", searchtitle);
// } else {
// searchtitle();
// }
}
async function tab_select_current_video(id, title, isupdated = false, preparing_mode = false) {
if (title == "") return;
title = String(title).split("|")[0].trim();
let savedTitle = await getOptions("lasttopic");
if (savedTitle) savedTitle = String(savedTitle)?.split("|")[0].trim();
const automatic = await getVariable("automatic");
const automatic_mode = await getOptions("automatic_mode");
//console.log("tab_select_current_video", id, title, "preparing_mode:", preparing_mode);
const params = {
title: title,
savedTitle: savedTitle,
isupdated: isupdated,
preparing_mode: preparing_mode,
automatic: automatic,
automatic_mode: automatic_mode,
};
browserf().scripting.executeScript({
target: { tabId: id },
args: [params],
func: tab_select_current_video_implode,
});
}
async function tab_check(tabid, preparing_mode = false) {
if (tabid) {
let scrolltotitle = await getOptions("scrolltotitle");
if (scrolltotitle) {
browserf().tabs.get(tabid, (tab) => {
if (tab.id == tabid && tab?.status == "complete") {
let title = tab?.title;
//console.log("tab_checked", tabid, title, "preparing_mode:", preparing_mode);
tab_select_current_video(tabid, title, false, preparing_mode);
}
});
}
}
}
async function tab_onSaveDone(preparing_mode = false) {
if (!tabid) {
tabid = await getVariable("tabid");
}
if (tabid) {
//sconsole.log("tab_onSaveDone preparing_mode:", preparing_mode);
tab_check(tabid, preparing_mode);
}
}
async function tab_onUpdated(id, changeInfo, tab) {
//console.log("tab_onUpdated init", id, tabid, tab?.title, changeInfo?.status);
//console.log("tab_onUpdated init get memory", id, tabid, tab?.title, changeInfo?.status);
if (changeInfo?.status == "complete") {
if (!tabid) {
tabid = await getVariable("tabid");
}
if (id == tabid) {
// console.log("tab_onUpdated", id, tab?.title, scrolltotitle);
scrolltotitle = await getOptions("scrolltotitle");
console.log("tab_onUpdated afrer read scrolltotitle", scrolltotitle);
if (scrolltotitle) {
tab_select_current_video(id, tab?.title, true);
} else {
console.log("tab_onUpdated but scrolltotitle:", scrolltotitle);
}
}
}
}
function downloadId_initialze() {
waitTimerSytateOK = setTimeout(() => {
stateSet("OK");
waitTimerSytateOK = setTimeout(() => {
waitTimerSytateOK = 0;
stateSet("");
tab_onSaveDone();
}, 5000);
}, 1000);
stateSetText("");
//await acquireWriteLock();
//downloadingList.splice(0, downloadingList.length);
//isWriteInProgress = false;
// browserf().storage.session.set({
// downloadingnow: [],
// });
}
async function downloadId_clear_downloaded(downloadId) {
console.log("downloadId_clear_downloaded get", downloadId, downloadingList);
return new Promise((resolve) => {
if (downloadingList.length) {
let index = downloadingList.indexOf(downloadId);
if (index != -1) {
downloadingList.splice(index, 1);
console.log("downloadId_clear_downloaded set", downloadId, index, downloadingList);
}
}
resolve();
});
}
// MOVE SAVING ACTIPON from POPUP *******************************************************************************
// TODO
function escapeRegExp(string) {
return string.replace(/([\\\/*&:<>$#@^?!\[\]]+)/gi, "_");
}
/**
*
* @returns
*/
async function restore_options() {
// Use default value color = 'red' and likesColor = true.