forked from samliew/SO-mod-userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserActivityNotifications.user.js
193 lines (155 loc) · 6.2 KB
/
UserActivityNotifications.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
// ==UserScript==
// @name User Activity Notifications
// @description Display notifications on user profile when new activity is detected since page load
// @homepage https://github.com/samliew/SO-mod-userscripts
// @author @samliew
// @version 0.2
//
// @include https://*stackoverflow.com/*
// @include https://*serverfault.com/*
// @include https://*superuser.com/*
// @include https://*askubuntu.com/*
// @include https://*mathoverflow.net/*
// @include https://*.stackexchange.com/*
//
// @exclude *chat.*
// @exclude https://stackoverflow.com/c/*
//
// @require https://github.com/samliew/SO-mod-userscripts/raw/master/lib/common.js
// ==/UserScript==
// If user accepts, we can show native notifications
var notifyperm = "Notification" in window;
if(!notifyperm) {
console.log("This browser does not support desktop notifications.");
}
(function() {
'use strict';
const apikey = 'dhFaTnM59qx5gK807L7dNw((';
const pollInterval = 30;
let lastCheckedDate = Math.floor(Date.now() / 1000) - 30 * 60; // Start from x minutes ago
let interval;
let userId, username, shortname;
// Get site favicon, adapted from https://stackoverflow.com/a/10283308
let siteIcon = (function() {
let ico = undefined;
const nodeList = document.getElementsByTagName("link");
for (var i = 0; i < nodeList.length; i++)
{
if(nodeList[i].getAttribute("rel") == "icon" || nodeList[i].getAttribute("rel") == "shortcut icon")
{
ico = nodeList[i].getAttribute("href");
break;
}
}
return ico;
})();
// Show native notification
function notify(title, link, options = {}, dismissAfter = 15) {
// User has not enabled notifications yet
if(Notification.permission !== 'granted') {
console.log('Notifications permission not granted.');
return false;
}
// Sanitize
title = htmlDecode(title);
options.body = htmlDecode(options.body);
$.extend(options, {
silent: true,
noscreen: true,
icon: siteIcon,
badge: siteIcon,
});
let n = new Notification(title, options);
// Open content if notification clicked
if(typeof link !== 'undefined' && link != null) {
n.onclick = function(evt) {
evt.preventDefault(); // prevent the browser from focusing the triggering Notification's tab
window.open(link, '_blank');
}
}
// Auto-dismiss notification
if(dismissAfter > 0) setTimeout(n.close.bind(n), dismissAfter * 1000);
}
// Get user timeline
function getUserInfo(uid, fromdate = 0) {
return new Promise(function(resolve, reject) {
if(hasBackoff()) { reject(); return; }
if(typeof uid === 'undefined' || uid === null) { reject(); return; }
$.get(`http://api.stackexchange.com/2.2/users/${uid}/timeline?pagesize=${Math.ceil(pollInterval/2)}&fromdate=${lastCheckedDate}&site=${location.hostname}&filter=!))yem8S&key=${apikey}`)
.done(function(data) {
lastCheckedDate = Math.floor(Date.now() / 1000);
if(data.backoff) backoff = addBackoff(data.backoff);
resolve(data.items);
return;
})
.fail(function() {
addBackoff(5);
reject();
});
});
}
function scheduledTask() {
getUserInfo(userId).then(function(v) {
// Take last(latest) three
v.slice(-3).forEach(function(w) {
let action = w.timeline_type;
let text = w.title;
let url = w.link;
switch(w.timeline_type) {
case 'commented': action = 'commented'; text = w.detail;
break;
case 'revision': action = 'edited post';
break;
case 'suggested': action = 'suggested edit';
break;
case 'reviewed': action = 'reviewed edit';
break;
case 'answer': action = 'posted answer';
break;
case 'question': action = 'asked question';
break;
case 'accepted': action = 'accepted answer';
break;
case 'badge': action = 'earned badge'; text = w.detail; url = null;
break;
}
notify(`${shortname} ${action}`, url, {
body: text
});
});
});
}
function doPageLoad() {
// Do not run if not on user page
if(!document.body.classList.contains('user-page') || !location.pathname.includes('/users/')) return;
// Do not run if user is deleted
if(document.title.contains('User deleted')) return;
// Get user details
userId = Number(location.pathname.match(/\/\d+/)[0].replace('/', ''));
username = $('.profile-user--name > div:first, .mini-avatar .name').text().replace('♦', '').replace(/\s+/g, ' ').trim();
shortname = username.split(' ')[0].substr(0, 12).trim();
// Get notification permissions
if(notifyperm) Notification.requestPermission();
// Run once on page load, then start polling API occasionally
scheduledTask();
interval = setInterval(scheduledTask, pollInterval * 1000);
}
function loadPnotify() {
$('body').append('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pnotify/3.2.1/pnotify.css" />');
// Load pnotify - https://sciactive.com/pnotify/
$.getScript('https://cdnjs.cloudflare.com/ajax/libs/pnotify/3.2.1/pnotify.js', function() {
console.log('pnotify loaded');
// TODO
});
}
function appendStyles() {
const styles = `
<style>
</style>
`;
$('body').append(styles);
}
// On page load
appendStyles();
doPageLoad();
})();