-
Notifications
You must be signed in to change notification settings - Fork 1
/
Show_Edited_Votes.user.js
301 lines (279 loc) · 10.5 KB
/
Show_Edited_Votes.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
// ==UserScript==
// @name Show Edited Votes
// @namespace com.tuggy.nathan
// @description Displays a list of posts that have been edited since voting
// @include /^https?:\/\/(?:meta\.)?(?:stackoverflow|stackapps|askubuntu|serverfault|superuser|[^\/\.]+\.stackexchange)\.com\/users\/\d+\/.*\?tab=votes/
// @version 1.6.00
// @grant none
// ==/UserScript==//
/* Copyright Nathan Tuggy 2016-2019
Thanks to https://github.com/Elikill58 for fixes in 1.6.00
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Throttling implementation borrowed from rene's Match Against Peers In Review
function parseIsoDatetime(dtstr) { // From http://stackoverflow.com/a/26434619
var dt = dtstr.split(/[: T-]/).map(parseFloat);
return new Date(dt[0], dt[1] - 1, dt[2], dt[3] || 0, dt[4] || 0, dt[5] || 0, 0);
}
function parseInt(str) {
return Number.parseInt(str.replace(",", ""));
}
(function ($, window) {
"use strict";
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var tasks = [],
intervalTime = 200, // milliseconds (make this larger when throttled often)
per = 90000, // milliseconds
penalty = 60000, // milliseconds to wait after 503
rate = 150, // per 90000 milliseconds (make this smaller when throttled often, but on 80 you're safe)
interval,
handler,
ids = [],
lastVoted = [],
voteTypes = [],
filters = $('.js-user-tab-sorts').first(),
table = $('.history-table > tbody').first(),
editedFilter = $('<a href="?tab=votes&sort=edited" class="s-btn s-btn__muted s-btn__outlined s-btn__xs js-user-tab-sort">Edited since voting</a>'),
idCurrentUser = new Number(/\/(\d+)\//.exec(document.location.href)[1]),
counter = $('h1 > span.count').first(),
progress = $('<img src="/content/img/progress-dots.gif"></img>'),
state = "start",
voteAddPendingCounter,
currentFilterText = $('.js-user-tab-sorts > a.is-selected').first().text().trim(),
includeDown = currentFilterText != "upvote",
includeUp = currentFilterText != "downvote";
// Add first page of given vote type
function addFirstPage(voteType) {
var urlBase = document.location.href.replace(/&sort=.*$/, ''), urlFirst = urlBase + '&sort=' + voteType;
state = voteType;
handler = addPages.bind(urlFirst);
voteAddPendingCounter = 0;
tasks.push(urlFirst);
}
// For each page of the type from the page given, put a task in the queue
function addPages(docFirst) {
var urlFirst = this,
maxPage = parseInt($('a:not([rel=next]) > span.page-numbers', docFirst).last().text());
pageHandler(docFirst);
state += '-paging';
handler = pageHandler;
for (let i = 2; i <= maxPage; i++) {
tasks.push(urlFirst + '&page=' + i);
}
}
// For each 100 post IDs, put a task in the queue, doing preliminary filtering by the earliest of those posts' vote dates
function addAPICalls() {
const methodBase = 'https://api.stackexchange.com/2.2/posts/',
paramBaseA = '?pagesize=100&order=desc&key=V8Sw6puqD0eUqphKLGadPw((&min=',
paramBaseB = '&sort=activity&filter=!)4k-FmSEkrkChRkSHXPXHE2SxOhY&site=',
sitePattern = /(?:meta\.)?(?:[^\.\/]+(?=\.stackexchange)|stackoverflow|stackapps|askubuntu|serverfault|superuser)/;
var siteMatch = sitePattern.exec(document.location.hostname), siteParam;
state = "API-calling";
handler = apiHandler;
if (siteMatch) {
siteParam = siteMatch[0];
} else {
alert("Show Edited Votes: Couldn't find site abbreviation in URL! ('" + document.location.hostname + "')");
return;
}
//console.log(siteMatch);
//console.log(siteParam);
while (ids.length > 0) {
let paramIDs = ids.slice(0, 100), idParam = paramIDs.join(';');
let minParam = paramIDs.map(function (e) {
return new Number(lastVoted[e]);
}).reduce(function (a, b) {
return Math.min(a, b);
}, Date.now() / 1000);
let url = methodBase + idParam + paramBaseA + minParam + paramBaseB + siteParam;
tasks.push(url);
ids = ids.slice(100);
}
}
function pageHandler(data) {
// Grab post TDs
var posts = $('td.async-load', data), noVote = [], voteType = state.split('-')[0];
for (let i = 0; i < posts.length; i++) {
let id = new Number(posts[i].id.replace('enable-load-body-', ''));
let voted = $(posts[i]).parent().find('.date_brick[title], .date[title]')[0].title;
if (voted) {
ids.push(id);
lastVoted[id] = parseIsoDatetime(voted).valueOf() / 1000;
voteTypes[id] = voteType;
}
else {
noVote.push(id);
}
}
if (noVote.length > 0) {
alert("Show Edited Votes: Posts " + noVote.join(", ") + " have no vote date!");
}
}
function apiHandler(data) {
const spanDownvote = '<span class="fc-red-600">downvote</span>',
spanUpvote = '<span class="fc-green-500">upvote</span>';
if (data.backoff) {
alert("Show Edited Votes: Backing off for " + data.backoff + " seconds");
setThrottle(Date.now() + data.backoff);
return;
}
var modified = [];
if (data.items) {
modified = data.items.filter(function (item) {
return item.last_edit_date && item.last_editor &&
new Number(item.last_edit_date) > lastVoted[item.post_id] &&
item.last_editor.user_id != idCurrentUser;
});
}
// Add to visible list
// TODO: Sort by date before vote type
modified.forEach(function (item) {
let date = new Date(lastVoted[item.post_id] * 1000);
// TODO: Add edited date to display
table.append('<tr><td><div class="date_brick" title="' +
date.toLocaleString() +
'">' +
months[date.getMonth()] + " " + date.getDate() +
'</div></td><td>' +
('downvote' == voteTypes[item.post_id] ? spanDownvote : spanUpvote) +
'</td><td><b><a href="' +
item.link +
'" class="answer-hyperlink timeline-answers">' +
item.title +
'</a></b></td></tr>');
});
counter.text(parseInt(counter.text()) + modified.length);
if (0 === data.quota_remaining) {
alert("Show Edited Votes: Out of quota!");
window.clearInterval(interval); // Drop the rest on the floor
// TODO? Set date flag to not even try until tomorrow
}
}
// get array with timestamps from localstorage
function getThrottle() {
var calls = window.localStorage.getItem('se-throttle');
if (calls === null) {
calls = [ Date.now() ];
} else {
calls = JSON.parse(calls);
if (!Array.isArray(calls)) {
calls = [ Date.now() ];
}
}
return calls;
}
// update timestamp array for throttle
function setThrottle(time) {
var calls = getThrottle(),
i;
if (time === undefined) {
time = Date.now();
}
for (i = 0; ((i < calls.length - 1) && (calls[0] < Date.now() - per)); i++) {
calls.shift();
}
if (calls.length > rate) {
calls.shift();
}
calls.push(time);
window.localStorage.setItem('se-throttle', JSON.stringify(calls));
}
// gets called by the setInterval
function taskWorker() {
var url = tasks.shift(), jqXHR;
if (url) {
$.get(url)
.done(function (data) {
setThrottle();
handler(data);
})
.fail(function (xhr, stat, error) {
// Service Unavailable means we're throttled, panic
//console.log(xhr);
if (xhr.status === 503) {
// wait a full minute to get free
setThrottle(Date.now() + penalty);
}
});
}
else {
// current state empty, what's next?
switch (state) {
case "upvote-paging":
setThrottle();
if (includeDown) {
addFirstPage("downvote");
break;
}
// otherwise, fall through
case "downvote-paging":
// API calls, if there's anything to do
if (ids.length > 0) {
setThrottle();
addAPICalls();
break;
}
case "upvote":
case "downvote":
if (voteAddPendingCounter < 10) {
voteAddPendingCounter++;
break;
}
// fall through
default:
// nothing left to do
progress.hide();
setThrottle();
window.clearInterval(interval);
if ("API-calling" != state) alert("Show Edited Votes: Finished '" + state + "' state unexpectedly");
}
}
}
// check if we are within the throttle boundaries
function isAllowed() {
var calls = getThrottle(),
timepassed;
timepassed = Date.now() - calls[0];
//console.log(timepassed);
return (((calls.length < rate) ||
(timepassed > per)) &&
(calls[calls.length-1] < Date.now()));
}
// handle a task
function task() {
if (isAllowed()) {
taskWorker();
} else {
//console.log('<< throttle >> ' + getThrottle());
}
}
editedFilter.click(function () {
filters.find('.is-selected').removeClass('is-selected');
editedFilter.addClass('is-selected');
counter.parent().html('<span class="count">0</span> Edits Since Votes Cast');
counter = $('h1 > span.count').first();
table.empty();
$('.pager').remove();
progress.show();
if (includeUp) {
addFirstPage("upvote");
} else {
addFirstPage("downvote");
}
interval = window.setInterval(task, intervalTime);
return false;
});
editedFilter.append(progress);
progress.css('margin-left', '0.5em');
progress.hide();
filters.append(editedFilter);
}($ || unsafeWindow.$, window || unsafeWindow));