summaryrefslogtreecommitdiffstats
path: root/assets/js/notifications.js
blob: fcfc01e7dcbc2a862a95155cb7ac4865193a41ae (plain)
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
var notifications, delivered;

function get_subscriptions(callback, retries) {
    if (retries == undefined) retries = 5;

    if (retries <= 0) {
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.responseType = 'json';
    xhr.timeout = 10000;
    xhr.open('GET', '/api/v1/auth/subscriptions?fields=authorId', true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                subscriptions = xhr.response;
                callback(subscriptions);
            }
        }
    }

    xhr.onerror = function () {
        console.log('Pulling subscriptions failed... ' + retries + '/5');
        setTimeout(function () { get_subscriptions(callback, retries - 1) }, 1000);
    }

    xhr.ontimeout = function () {
        console.log('Pulling subscriptions failed... ' + retries + '/5');
        get_subscriptions(callback, retries - 1);
    }

    xhr.send();
}

function create_notification_stream(subscriptions) {
    notifications = new SSE(
        '/api/v1/auth/notifications?fields=videoId,title,author,authorId,publishedText,published,authorThumbnails,liveNow', {
            withCredentials: true,
            payload: 'topics=' + subscriptions.map(function (subscription) { return subscription.authorId }).join(','),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });
    delivered = [];

    var start_time = Math.round(new Date() / 1000);

    notifications.onmessage = function (event) {
        if (!event.id) {
            return;
        }

        var notification = JSON.parse(event.data);
        console.log('Got notification:', notification);

        if (start_time < notification.published && !delivered.includes(notification.videoId)) {
            if (Notification.permission === 'granted') {
                var system_notification =
                    new Notification((notification.liveNow ? notification_data.live_now_text : notification_data.upload_text).replace('`x`', notification.author), {
                        body: notification.title,
                        icon: '/ggpht' + new URL(notification.authorThumbnails[2].url).pathname,
                        img: '/ggpht' + new URL(notification.authorThumbnails[4].url).pathname,
                        tag: notification.videoId
                    });

                system_notification.onclick = function (event) {
                    window.open('/watch?v=' + event.currentTarget.tag, '_blank');
                }
            }

            delivered.push(notification.videoId);
            localStorage.setItem('notification_count', parseInt(localStorage.getItem('notification_count') || '0') + 1);
            var notification_ticker = document.getElementById('notification_ticker');

            if (parseInt(localStorage.getItem('notification_count')) > 0) {
                notification_ticker.innerHTML =
                    '<span id="notification_count">' + localStorage.getItem('notification_count') + '</span> <i class="icon ion-ios-notifications"></i>';
            } else {
                notification_ticker.innerHTML =
                    '<i class="icon ion-ios-notifications-outline"></i>';
            }
        }
    }

    notifications.addEventListener('error', handle_notification_error);
    notifications.stream();
}

function handle_notification_error(event) {
    console.log('Something went wrong with notifications, trying to reconnect...');
    notifications = { close: function () { } };
    setTimeout(function () { get_subscriptions(create_notification_stream) }, 1000);
}

window.addEventListener('load', function (e) {
    localStorage.setItem('notification_count', document.getElementById('notification_count') ? document.getElementById('notification_count').innerText : '0');

    if (localStorage.getItem('stream')) {
        localStorage.removeItem('stream');
    } else {
        setTimeout(function () {
            if (!localStorage.getItem('stream')) {
                notifications = { close: function () { } };
                localStorage.setItem('stream', true);
                get_subscriptions(create_notification_stream);
            }
        }, Math.random() * 1000 + 50);
    }

    window.addEventListener('storage', function (e) {
        if (e.key === 'stream' && !e.newValue) {
            if (notifications) {
                localStorage.setItem('stream', true);
            } else {
                setTimeout(function () {
                    if (!localStorage.getItem('stream')) {
                        notifications = { close: function () { } };
                        localStorage.setItem('stream', true);
                        get_subscriptions(create_notification_stream);
                    }
                }, Math.random() * 1000 + 50);
            }
        } else if (e.key === 'notification_count') {
            var notification_ticker = document.getElementById('notification_ticker');

            if (parseInt(e.newValue) > 0) {
                notification_ticker.innerHTML =
                    '<span id="notification_count">' + e.newValue + '</span> <i class="icon ion-ios-notifications"></i>';
            } else {
                notification_ticker.innerHTML =
                    '<i class="icon ion-ios-notifications-outline"></i>';
            }
        }
    });
});

window.addEventListener('unload', function (e) {
    if (notifications) {
        localStorage.removeItem('stream');
    }
});
colspan='3' class='logmsg'> 2020-11-09Update options.jsYumi Izumi 2020-11-09Update options.htmlYumi Izumi 2020-11-08Update popup.jsYumi Izumi 2020-11-08Update popup.htmlYumi Izumi 2020-11-08Update background.jsYumi Izumi 2020-11-08Closes #111 - Adds ability to customise random instance poolsv1.1.43SimonBrazell 2020-11-08Fixes #119 - Change zh-CN to zh_CN.SimonBrazell 2020-11-07Update README.mdKunio Some suggestions, added FreeTube, updated invidious links, added permissions. 2020-11-05Update Russian translationTotalCaesar659 2020-11-04Update store listing templatesSimonBrazell 2020-11-04Update Bibliogram linksbopol Bibliogram has moved to source hut (for a while now) 2020-11-04Remove duplicate entry in instagramReservedPaths arraySimonBrazell 2020-11-04Remove "https://yewtu.be" from random instance listSimonBrazell 2020-11-04Ignore embedded videos for FreeTube redirectsSimonBrazell 2020-11-04Fixes #99 - Bibliogram, handle /igtv/, /tv/ and /reel/v1.1.42SimonBrazell 2020-11-04Fixes #104 - /remove-twitter-sw.js stopping Twitter redirectsSimonBrazell 2020-11-04Closes #113 - Added support for FreeTubeSimonBrazell 2020-11-04Clean up invidious random instance listSimonBrazell 2020-10-23Rename _locales/store.md to _locales/pl/store.mdAustin Huang