-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYtBetterNotifications.user.js
2592 lines (2218 loc) · 94.4 KB
/
YtBetterNotifications.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 YtBetterNotifications (Alpha)
// @namespace Yt.Better.Notifications
// @version 1.1.30
// @description A new youtube desktop notifications panel with extra functionality.
// @author Onurtag
// @match https://www.youtube.com/new*
// @match https://www.youtube.com/reporthistory*
// @grant none
// @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment-with-locales.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/dexie/3.2.6/dexie.min.js
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/FileSaver.min.js
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/dexie-export-import.min.js
// @require https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js
// @run-at document-idle
// ==/UserScript==
let db,
selectedfile,
currentPage = 0,
buttonElement = null,
shouldSendEmail = false,
emailGAPIReady = false,
GAPIClientID = null,
GAPIClientKey = null,
useEmailSecureToken = false,
useRelativeTime = false,
useDailyLargeCheck = false,
largeCheck = false,
filterString = "",
maxPages = 99999;
const MAX_LOG_SIZE = 600,
LOG_PURGE_AMOUNT = 100;
ytbnDebugEmail = false;
console.time("YTBN");
console.log("🚀 YTBN ~ ", { ytbnDebugEmail });
let dontSendEmailsOver = 150;
let itemsPerPage = 50;
let liveTitlePrependString = "🔴 ";
const regexVideoURLtoID = /(.*?(watch.v=|watch_videos.video_ids=)(.*?)($|,.*$))/;
const regexImageURLtoID = /https?:\/\/i.ytimg.com\/(vi|vi_webp)\/(.*?)\/.*?.(jpg|webp)/;
/*
TODO: Increment Version Number
TODO: (optionally) Get more data while saving notifications (instead of doing it before sending emails.) Needs to be batched to prevent throttling.
LATER: Link channel image to channel if I have the data
LATER: Add a "Saved!" popup when you click save
LATER: switch moment.js with a better library (or native)
LATER: Constrict selector queries (use node.querySelector instead of document.querySelector etc...)
LATER MAYBE: Email error log window with a table
LATER MAYBE: Switch to a build setup (separate js, css, html files) BUT; for now I don't need it as I use Template Literal Editor.
--other info--
1. alternative youtube library: https://github.com/LuanRT/YouTube.js
+ node.js
+ has notifications
+ cookies or oauth
!!!: main account might get in trouble (etc.)
----
*/
//Play silent audio to prevent background tab throttling
//This might require "autoplay" to be turned on for the website
//original source: https://github.com/t-mullen/silent-audio/blob/master/src/index.js
class SilentAudio {
constructor() {
this.ctx = new AudioContext();
this.source = this.ctx.createConstantSource();
this.gainNode = this.ctx.createGain();
this.gainNode.gain.value = 0.001; // required to prevent popping on start
this.source.connect(this.gainNode);
this.gainNode.connect(this.ctx.destination);
//suspend context and start the source
this.ctx.suspend();
this.source.start();
}
play() {
this.ctx.resume();
}
pause() {
this.ctx.suspend();
}
}
let silentAudio = new SilentAudio();
silentAudio.play();
/* Restore fetch for our context (because the website hijacks it) */
const ifr = document.createElement('iframe');
ifr.style.display = 'none';
document.body.appendChild(ifr);
const fetch = ifr.contentWindow.fetch; //only for our context (not window.fetch)
function startup() {
let startInterval = setInterval(async () => {
//wait for the notification button to appear (first load)
buttonElement = document.querySelector("[class*='notification-topbar-button'] > button") ||
document.querySelector("div#button.ytd-notification-topbar-button-renderer") ||
document.querySelector(".ytd-notification-topbar-button-shape-renderer #button.yt-icon-button");
if (buttonElement == null) {
return;
}
clearInterval(startInterval);
//set moment.js locale
moment.locale(document.querySelector("html").lang);
//Setup dexie db
await setupDB();
//read settings from the database
await readSettings();
//Setup the notifications div (with the "loading..." spinner)
addStyles();
setupNotificationDiv();
//Check if there are any existing failure logs (and update the button)
await checkErrorLogs();
//Enable the smaller notifications panel css which loads notifications faster
document.querySelector("#smallernotpanel").disabled = false;
//Open notifications panel for scrolling
buttonElement.click();
let waiting = 0;
let startInterval2 = setInterval(() => {
//Wait for the GAPI if we are using it.
if (shouldSendEmail == false || GAPIClientID == null || emailGAPIReady == true || waiting > 5000) {
//Wait for any notification element to appear
if (document.querySelector('ytd-notification-renderer') != null) {
clearInterval(startInterval2);
//default scroll settings
let scrolls = 2;
let scrollInterval = 155;
largeCheck = false;
if (useDailyLargeCheck) {
let storedTime = parseInt(localStorage.getItem("ytbnLastLargeCheck")) || 0;
let nowTime = Date.now();
//86400000 = 1 day
if (!storedTime || nowTime > storedTime + 86000000) {
//daily long scroll settings
scrolls = 3;
scrollInterval = 195;
largeCheck = true;
}
}
scrollNotifications(scrolls, scrollInterval);
}
}
//LATER: this might not work correctly if the tab is throttled. Probably a better idea to use Now() etc.
waiting += 100;
}, 100);
return;
}, 100);
}
function scrollNotifications(scrolltimes = 1, interval = 155) {
cleanLogsOverQuota();
//Play silent audio
silentAudio.play();
let scrollcount = 0,
nullcount = 0,
fixCount = 0,
toBeFixed = 0,
maxnullcount = 34, //Minimum 4. Increase this if you have a small interval timer
finalAmount = -1,
startedChecking = false;
let prev_lastNode;
let scrollInterval = setInterval(() => {
//verify and correct scroll count
let notificationcount = document.querySelectorAll("ytd-notification-renderer").length;
if (scrollcount != notificationcount / 20) {
scrollcount = notificationcount / 20;
}
if (!startedChecking && (scrollcount <= scrolltimes) && (nullcount <= maxnullcount)) {
try {
//document.querySelector('[menu-style="multi-page-menu-style-type-notifications"] ytd-continuation-item-renderer').scrollIntoView();
let lastNode = document.querySelector("ytd-notification-renderer:last-of-type");
if (lastNode == prev_lastNode) {
nullcount++;
if (nullcount % 2 == 0) {
//Scroll up and down to trigger loading again
document.querySelector("ytd-notification-renderer:first-of-type").scrollIntoView();
}
} else {
//reset nullcount whenever we successfully do a scroll
nullcount = 0;
prev_lastNode = lastNode;
}
lastNode.scrollIntoView();
scrollcount++; //cosmetic
} catch (error) {
console.log("🚀 YTBN ~ scrolling error:", { error });
}
} else {
//---FORWARD Scrolling finished---
//---FORWARD Scrolling finished---
//---FORWARD Scrolling finished---
startedChecking = true;
// console.log("🚀 YTBN ~ attempting to fix:", fixCount++);
//Scroll lazy nodes to wake them up (load lazy loaded images & urls)
let loadedNotifs = document.querySelectorAll("ytd-notification-renderer");
if (finalAmount == -1) {
finalAmount = loadedNotifs.length;
}
// loadedNotifs.slice(0, finalAmount); //requires [...blabla]
let count = 0;
toBeFixed = 0;
for (let index = 0; index < finalAmount; index++) {
const element = loadedNotifs[index];
if (element.querySelector("img[src]")) {
count++;
} else {
// console.log("🚀 YTBN ~ attempting to fix:", element.innerText, index);
element.scrollIntoView();
toBeFixed++;
}
}
fixCount++;
if (count == finalAmount) {
//---ALL Scrolling finished---
//---ALL Scrolling finished---
//---ALL Scrolling finished---
console.log("🚀 YTBN ~ All good. Notification count & fix count:", count, fixCount);
//Stop interval
clearInterval(scrollInterval);
//Continue the rest of the loading process
continuing(count);
}
}
console.log("🚀 YTBN ~ scrollInterval ~ notificationcount:", notificationcount, "nullcount:", nullcount, "toBeFixed:", toBeFixed);
}, interval);
}
//LATER convert to async
function continuing(nC) {
//Async update the notifications database
saveNotifications(nC).then(result => {
//Close notifications panel
buttonElement.click();
//Disable smaller notifications panel
document.querySelector("#smallernotpanel").disabled = true;
return;
}).then(result => {
//load notifications database into the table
return loadNotifications();
}).then(result => {
//disable spinner
showSpinner(false);
return setupPaginationButtons();
}).then(result => {
//pause silent audio
silentAudio.pause();
if (largeCheck) {
localStorage.setItem("ytbnLastLargeCheck", Date.now());
}
});
}
//create random ids (without extra libraries)
function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
//create SHA-256 hashes from strings for duplicate checks
async function digestToSHA256(message) {
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
return hashHex;
}
async function exportDB(event) {
try {
const blob = await db.export({
prettyJson: true,
progressCallback
});
saveAs(blob, "ytbetternotifications-export-" + Date.now().toString().slice(0, -8) + "00000000" + ".json");
} catch (error) {
console.error('🚀 YTBN ~ File export error: ', error);
}
}
function fileInputOnchange(event) {
let files = event.target?.files || event.target?.$?.nativeInput?.files || null;
if (files) {
selectedfile = files[0];
}
}
async function importDB(event) {
var r = confirm("Are you sure? This will delete all your current data.");
if (r != true) {
return;
}
let file = selectedfile;
try {
if (!file) {
throw new Error(`Only files can be input here.`);
}
console.log("🚀 YTBN ~ Importing file: ", file.name);
cleanTable();
showSpinner();
document.querySelector("#notificationOptions").remove();
await db.delete();
db = await Dexie.import(file, {
progressCallback
});
await loadNotifications(0);
currentPage = 0;
setupPaginationButtons();
showSpinner(false);
console.log("🚀 YTBN ~ Import complete.");
return;
} catch (error) {
console.error('🚀 YTBN ~ File import error: ', { error });
}
}
function progressCallback({
totalRows,
completedRows
}) {
console.log(`🚀 YTBN ~ Export/Import Progress: ${completedRows} of ${totalRows} rows completed.`);
}
async function setupDB() {
db = new Dexie("NotificationsDatabase");
await db.version(2).stores({
notifications: '++number, &id, hash, url, title, time, userimgurl, videoimgurl, channelname, duration, read, live, notvideo, extras',
settings: 'key, value, extra',
logs: '++number, type, time, extra, log',
});
// db.version(2).stores({
//
//
// }).upgrade(trans => {
// /*
// var YEAR = 365 * 24 * 60 * 60 * 1000;
// return trans.friends.toCollection().modify (friend => {
// friend.birthdate = new Date(Date.now() - (friend.age * YEAR));
// delete friend.age;
// });
// */
// });
await db.open().catch(function (err) {
console.error("🚀 YTBN open", err.stack || err);
});
//db.delete();
}
function filterPage() {
//set filter string, should be blank "" by default
filterString = document.querySelector("#sidebuttonsTop #sidebarFilterInput").value;
// Reload notifications
// cleanTable(false);
currentPage = 0;
loadNotifications(0).then(function (result) {
console.log("🚀 ~ filterPage result:", { result });
setupPaginationButtons(result);
return result;
});
}
function previousPage(event) {
if (currentPage == 0) {
return;
}
// cleanTable(false);
loadNotifications(currentPage - 1).then(function (result) {
--currentPage;
setupPaginationButtons();
return result;
});
}
function nextPage(event) {
if (currentPage == maxPages - 1) {
return;
}
// cleanTable(false);
loadNotifications(currentPage + 1).then(function (result) {
++currentPage;
setupPaginationButtons();
return result;
});
}
function firstPage(event) {
if (currentPage == 0) {
return;
}
// cleanTable(false);
loadNotifications(0).then(function (result) {
currentPage = 0;
setupPaginationButtons();
return result;
});
}
function lastPage(event) {
if (currentPage == maxPages - 1) {
return;
}
// cleanTable(false);
loadNotifications(maxPages - 1).then(function (result) {
currentPage = maxPages - 1;
setupPaginationButtons();
return result;
});
}
function discardLogs(event) {
var r = confirm("Are you sure you want to discard all logs?");
if (r != true) {
return;
}
db.logs.clear();
//setupdb is not needed
setupDB();
}
function discardNotifications(event) {
var r = confirm("Are you sure you want to clear the notification database?");
if (r != true) {
return;
}
cleanTable();
db.notifications.clear();
//setupdb is not needed
setupDB();
}
function discardSettings(event) {
var r = confirm("Are you sure you want to clear all settings?");
if (r != true) {
return;
}
//cleanTable();
db.settings.clear();
//setupdb is not needed
setupDB();
//"close" settings menu
document.querySelector("#notificationOptions").remove();
}
function showSpinner(showit = true) {
if (showit) {
//Enable spinner
document.querySelector("#outerNotifications tp-yt-paper-spinner").setAttribute("active", "");
document.querySelector("#loadindicator").hidden = false;
} else {
//Disable the spinner
document.querySelector("#outerNotifications tp-yt-paper-spinner").removeAttribute("active");
document.querySelector("#loadindicator").hidden = true;
}
}
function loadAll(event) {
//"close" settings menu
document.querySelector("#notificationOptions").remove();
cleanTable();
showSpinner();
//Enable the smaller notifications panel which loads notifications faster
document.querySelector("#smallernotpanel").disabled = false;
buttonElement.click();
scrollNotifications(6666);
}
function livetransparency(event) {
document.querySelector("#livetransparencycss").disabled = !document.querySelector("#livetransparencycss").disabled;
}
function readtransparency(event) {
document.querySelector("#readtransparencycss").disabled = !document.querySelector("#readtransparencycss").disabled;
}
function commenttransparency(event) {
document.querySelector("#commenttransparencycss").disabled = !document.querySelector("#commenttransparencycss").disabled;
}
function hideLive(event) {
document.querySelector("#hidelivecss").disabled = !document.querySelector("#hidelivecss").disabled;
}
function hideRead(event) {
document.querySelector("#hidereadcss").disabled = !document.querySelector("#hidereadcss").disabled;
}
function hideReplies(event) {
document.querySelector("#hiderepliescss").disabled = !document.querySelector("#hiderepliescss").disabled;
}
function cleanTable(removeButtons = true) {
const innerNotifications = document.querySelector("#innerNotifications");
if (innerNotifications) {
if (removeButtons) {
innerNotifications.innerHTML = "";
} else {
innerNotifications.innerHTML = innerNotifications.querySelector("#pagingButtonsOuter")?.outerHTML || "";
}
}
}
async function saveNotifications(nC) {
//let nodeArray = Array.from(document.querySelectorAll("ytd-notification-renderer"));
//Re-parse the notifications container node to work on it. Usual methods like .children, .firstElementChild are set to null on youtube's custom nodes.
let parser = new DOMParser();
let container = parser.parseFromString(document.querySelector("ytd-notification-renderer").parentElement.outerHTML, 'text/html');
container = container.body.firstElementChild;
let nodeArray = [...container.querySelectorAll("ytd-notification-renderer")];
nodeArray = nodeArray.slice(0, nC);
let newCount = 0;
let emailDictArray = [];
let promiseResults = await Promise.all(nodeArray.map(async (element) => {
let notVideo = false;
let rowUrl = element.querySelector('[role="link"]')?.href;
if (rowUrl.includes("&pp=")) {
rowUrl = rowUrl.replace(/&pp=.*/, "")
}
//if the notification thumbnail images aren't there, skip.
let userImg = element.querySelectorAll("img")[0]?.src || "";
// if (!userImg) {
// return "userimagedidnotload";
// }
let videoImage = element.querySelectorAll("img")[1]?.src || "";
// if (!videoImage) {
// return "videoimagedidnotload";
// }
if (rowUrl == "" && videoImage) {
//if the notification is not a video link, mark as notvideo (comment)
//and instead parse the video url from the videoimgurl
notVideo = true;
let matchingID = videoImage.match(regexImageURLtoID)[2];
rowUrl = 'https://www.youtube.com/watch?v=' + matchingID;
}
const strings = element.querySelectorAll("yt-formatted-string");
let currDict = {
id: uuidv4(),
hash: "",
url: rowUrl,
title: strings[0]?.innerText,
time: reversefromNow(strings[2]?.innerText),
userimgurl: userImg,
videoimgurl: videoImage,
live: false,
read: false,
notvideo: notVideo,
};
//detect duplications
//concenate "url + userimgurl + title/comment" strings and hash the result. This will be used to prevent saving duplicate notifications.
//LATER MAYBE: remove userimgurl from the hash (warning!)
currDict.hash = await digestToSHA256(currDict.url + currDict.userimgurl + currDict.title);
//duplicate check using hash
const count = await db.notifications
.where('hash')
.equals(currDict.hash)
.count().then(function (count) {
return count;
});
//the notification already exists so skip it.
if (count > 0) {
return "alreadyexists";
}
console.log("🚀 YTBN ~ saveNotifications -> currDict", { currDict });
//detect livestreams
if (currDict.title.includes(" is live: ")) {
currDict.live = true;
//set livestreams as read automatically
currDict.read = true;
}
//put the notification into the database
const dbput = await db.notifications.put(currDict);
if (shouldSendEmail) {
//Log with Email_Send_Failure type. The log will be updated later.
let logDict = {
type: "Email_Send_Failure",
time: moment().format("YYYY-MM-DD HH:mm:SSS"),
extra: {
notifData: currDict
},
log: "YTBN Status: Email_After_dbput",
};
const log_number = await db.logs.put(logDict);
//Keep the log number with the notification data
currDict.log_number = log_number;
//We are done here, but; currDict gets modified so duplicate it.
emailDictArray.push(JSON.parse(JSON.stringify(currDict)));
}
newCount++;
return dbput;
}));
console.log("🚀 YTBN ~ saveNotifications ~ promiseResults:", { promiseResults });
//get db size and set max pages
const itemcount = await db.notifications
.count().then(function (count) {
return count;
});
maxPages = Math.ceil(itemcount / itemsPerPage);
console.log("🚀 YTBN ~ " + newCount + " new notifications were saved into the db.");
console.timeEnd("YTBN");
//send all emails
if (emailDictArray.length > 0) {
sendEmailBatch(emailDictArray);
}
}
async function loadNotifications(page = 0) {
try {
let filteredCollection = null;
if (filterString == "") {
//NO Filter (everything)
filteredCollection = await db.notifications
.orderBy('time')
.reverse();
} else {
//YES Filter
const filterregex = new RegExp(filterString, 'i');
filteredCollection = await db.notifications
.orderBy('time')
.reverse()
.filter((notification) => {
return filterregex.test(notification.title);
});
}
//Set max pages
const itemcount = await filteredCollection
.count().then(function (count) {
return count;
});
maxPages = Math.ceil(itemcount / itemsPerPage);
if (itemcount == 0) {
document.querySelector("#outerNotifications #innerNotifications").classList.add("empty");
cleanTable(false);
//stop here
return itemcount;
} else {
document.querySelector("#outerNotifications #innerNotifications").classList.remove("empty");
}
//Get current page
let notificationsArray = await filteredCollection
.offset(page * itemsPerPage)
.limit(itemsPerPage)
.toArray()
.then(function (result) {
return result;
});
//Clear notifications right before inserting the new ones (for smoothness)
cleanTable(false);
notificationsArray.forEach(dict => {
displayNotification(dict);
});
//Scroll to the top of the list for consistence (scroll to buttom when going to a previous page?)
document.querySelector("#innerNotifications > .notificationsRow")?.scrollIntoView();
// console.log("🚀 ~ loadNotifications ~ itemcount:", itemcount);
return itemcount;
} catch (error) {
console.error("🚀 YTBN ~ loadNotifications ~ error:", error);
}
}
function displayNotification(currDict) {
//display notifications also send the dictionary to save as well.
const dummyHTML = `
<div data-id="DUMMYDATASETID" class="notificationsRow">
<div class="notifRowItem notcol1">ROWDUMMYROW1</div>
<div class="notifRowItem notcol2">ROWDUMMYROW2</div>
<div class="notifRowItem notcol3">ROWDUMMYROW3</div>
<div class="notifRowItem notcol4">ROWDUMMYROW4</div>
<div class="notifRowItem notcol5">
<tp-yt-paper-checkbox noink READCHECKED>Read</tp-yt-paper-checkbox>
</div>
</div>
`;
let elemDiv = document.createElement("div");
let elemHTML = dummyHTML;
//columns: usericon, url+title, time, videothumb, read
let col1, col2, col3, col4, col5;
//usericon
col1 = '<img src="' + currDict.userimgurl + '"></img>';
//time
if (useRelativeTime) {
col3 = moment(currDict.time).fromNow();
} else {
col3 = moment(currDict.time).format('lll');
}
//title
if (currDict.live) {
//handle live & live title prepend
elemHTML = elemHTML.replace('notificationsRow', 'notificationsRow notificationLive');
col2 = '<a target="_blank" href="' + currDict.url + '">' + liveTitlePrependString + currDict.title + '</a>';
} else {
col2 = '<a target="_blank" href="' + currDict.url + '">' + currDict.title + '</a>';
}
//Handle comments
if (currDict.notvideo) {
elemHTML = elemHTML.replace('notificationsRow', 'notificationsRow notificationComment');
//currDict.url = "javascript:void(0);";
}
//videothumb
let col4img = '<img src="' + currDict.videoimgurl + '"></img>';
col4 = '<a target="_blank" class="nvimgc" href="' + currDict.url + '">' + col4img + '</a>';
if (currDict.read) {
col5 = "checked";
elemHTML = elemHTML.replace('notificationsRow', 'notificationsRow notificationRead');
} else {
col5 = "";
}
//Replace dummy values
//LATER Can use ${var}
elemHTML = elemHTML.replace("ROWDUMMYROW1", col1);
elemHTML = elemHTML.replace("ROWDUMMYROW2", col2);
elemHTML = elemHTML.replace("ROWDUMMYROW3", col3);
elemHTML = elemHTML.replace("ROWDUMMYROW4", col4);
elemHTML = elemHTML.replace("READCHECKED", col5);
//Could have used a row number - id hashmap instead here
elemHTML = elemHTML.replace("DUMMYDATASETID", currDict.id);
document.querySelector("#innerNotifications").append(elemDiv);
elemDiv.outerHTML = elemHTML;
//add read checkbox click event
document.querySelector(".notificationsRow:last-of-type tp-yt-paper-checkbox").addEventListener('click', checkboxReadClicked);
}
async function togglereadAll(event) {
let theCheckbox = event.target.closest("tp-yt-paper-checkbox");
var r = confirm("Are you sure? This can not be undone! (unless you export your notifications)");
if (r != true) {
theCheckbox.checked = !theCheckbox.checked;
return;
}
let readvalue;
if (theCheckbox.checked == true) {
readvalue = true;
} else {
readvalue = false;
}
//use toArray() instead
await db.notifications.toCollection().modify({
"read": readvalue
}).then(result => {
//console.log("checked:" + readvalue);
}).catch(Dexie.ModifyError, function (e) {
console.error("🚀 YTBN ~ failed to modify read value", e.failures.length);
throw e;
});
document.querySelectorAll(".notificationsRow").forEach(element => {
if (readvalue) {
element.classList.add("notificationRead");
} else {
element.classList.remove("notificationRead");
}
element.querySelector("tp-yt-paper-checkbox").checked = readvalue;
});
return;
}
async function checkboxReadClicked(event) {
let eventRow = event.target.closest("div.notificationsRow");
let rowId = eventRow.dataset.id;
if (rowId == "" || !rowId) {
console.log("🚀 YTBN ~ Error while reading row ID", { rowId });
return "Error while reading row ID";
}
let readvalue;
if (eventRow.querySelector("tp-yt-paper-checkbox").checked == true) {
readvalue = true;
} else {
readvalue = false;
}
return await db.notifications.where("id").equals(rowId).modify({
"read": readvalue
}).then(result => {
const notifCol2 = eventRow.querySelector(".notcol2");
const notifTitle = notifCol2?.textContent;
const notifVidURL = notifCol2?.firstElementChild?.href;
if (readvalue) {
eventRow.classList.add("notificationRead");
} else {
eventRow.classList.remove("notificationRead");
}
console.log(`🚀 YTBN ~ Notification set as ${readvalue ? "Read" : "Unread"}:`, { notifTitle }, { notifVidURL }, { rowId });
return result;
}).catch(Dexie.ModifyError, function (e) {
console.error("🚀 YTBN ~ failed to modify read value", e.failures.length);
throw e;
});
}
function reversefromNow(input) {
let relativeLocale = JSON.parse(JSON.stringify(moment.localeData()._relativeTime));
let pastfutureObject = {
future: relativeLocale.future,
past: relativeLocale.past
};
delete relativeLocale.future;
delete relativeLocale.past;
//detect if past or future
let pastfuture;
for (const [key, value] of Object.entries(pastfutureObject)) {
if (input.includes(value.replace("%s", ""))) {
pastfuture = key;
}
}
//detect the time unit
let unitkey;
for (const [key, value] of Object.entries(relativeLocale)) {
if (input.includes(value.replace("%d", ""))) {
unitkey = key.charAt(0);
}
}
//if its not in the data, then assume that it is a week
if (unitkey == null) {
unitkey = "w";
}
const units = {
M: "month",
d: "day",
h: "hour",
m: "minute",
s: "second",
w: "week",
y: "year"
};
//Detect number value
const regex = /(\d+)/g;
let numbervalue = input.match(regex) || [1];
//Add if future, subtract if past
if (pastfuture == "past") {
//console.log(`moment input: ${input}, output: ${moment().subtract(numbervalue, units[unitkey]).toString()}`);
return moment().subtract(numbervalue, units[unitkey]).valueOf();
} else {
//console.log(`moment input: ${input}, output: ${moment().add(numbervalue, units[unitkey]).toString()}`);
return moment().add(numbervalue, units[unitkey]).valueOf();
}
}
function addStyles() {
let newstyle = document.createElement("style");
newstyle.innerHTML = `
#outerNotifications {
background-color: rgb(15, 15, 15);
border: 2px rgb(15, 15, 15) solid;
display: block;
position: fixed;
width: 75%;
height: 82%;
border-radius: 15px;
z-index: 2201;
top: 50%;
left: 50%;
/*transform: translate(-50%, -50%);*/
transform: translateX(calc(-50% - 0.5px)) translateY(calc(-50% - 0.5px));
color: #ddd;
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4), 0 -2px 4px rgba(0, 0, 0, 0.4), -2px 0 4px rgba(0, 0, 0, 0.4), 4px 0 4px rgba(0, 0, 0, 0.4);
}
#sidebuttons {
display: flex;
flex-direction: column;
font-size: 1.5em;
position: absolute;
top: 8px;
left: 8px;
width: 140px;
background-color: #151515;
height: calc(100% - 16px);
border-radius: 8px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 1px 4px rgba(0, 0, 0, 0.3);
user-select: none;
}
#sidebuttonsTop {
display: flex;
flex-direction: column;
margin-top: 12px;
}
#sidebuttonsBottom {
display: flex;
flex-direction: column;
margin-top: auto;
margin-bottom: 1em;
}
#filterClearButton:hover {
background: #47474787;
filter: brightness(120%);
}
#filterClearButton {
border: 1px solid transparent;
border-radius: 50%;
font-size: 10pt;
position: relative;
width: 26px;
height: 22px;
margin: auto -7px auto auto;
display: flex;
justify-content: center;
align-items: center;
}
/* Message for when there are no notifications (rchk :empty selector is slow?) */
#innerNotifications.empty:before {
content: "No notifications were found.\\a Suggestion: Clear the filter.";
font-size: 18pt;