-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnodelay.js
477 lines (414 loc) · 14.6 KB
/
nodelay.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
// these globals are for the Flash WebSocket implementation
WEB_SOCKET_SWF_LOCATION = "web-socket-js/WebSocketMain.swf";
WEB_SOCKET_DEBUG = true;
var url, message, status;
var minRetryWait = 5000,
retryWait = minRetryWait,
maxRetryWait = 60000;
window.onload = function() {
url = "ws://"+document.location.host+":8080";
messageel = document.getElementById('messages');
statusel = document.getElementById('status');
statusel.innerHTML = "Connecting...";
if (window.WebSocket) {
var ws = new WebSocket(url);
}
if (ws) {
setUpEvents(ws);
} else {
startPolling();
}
loadLanguages();
initVis();
}
function loadjson(url, callback) {
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4 && req.status == 200) {
callback(JSON.parse(req.responseText));
}
};
req.send(null);
}
function loadLanguages() {
loadjson('/?language=', function(languages) {
var queryurl = document.location.search;
var langel = document.getElementById('languages');
var currentlang = '';
var langcount = 0;
if (queryurl.indexOf('language=') == -1) {
var langhtml = '<a href="/" class="selected">All</a> ';
} else {
var langhtml = '<a href="/">All</a> ';
}
for (var desc in languages) {
var langcode = languages[desc];
var cssclass = ''
if (queryurl.indexOf(langcode) != -1) {
currentlang += (currentlang !== '' ? ' and ' : '') + desc;
cssclass = ' class="selected"'
langcount++;
}
langhtml += '<a href="' + '/?language=' + langcode + '"' + cssclass + '>' + desc + '</a> ';
}
langel.innerHTML = langhtml;
langel = document.getElementById('lang');
langel.innerHTML = (langcount == 1 ? 'the ' : '') + (currentlang || ' all') + ' wikipedia page' + (langcount != 1 ? 's' : '');
})
}
// Receive data from a poll
function receivePoll(json) {
statusel.innerHTML = "";
clearTimeout(timeoutid);
processEdit(json);
polling = false;
//console.log('loaded', pollurl);
startPolling();
}
// Start polling for JS when WebSocket and Flash aren't available
var polling = false;
var editcount = 0;
var timeoutid;
function startPolling() {
if (polling) return;
polling = true;
var pollurl = "http://"+document.location.host+'/poll' + editcount;
//console.log('startPolling', pollurl);
var self = this;
clearTimeout(timeoutid);
timeoutid = setTimeout(function() {
// if we get here, start polling again if needed
if (polling) {
polling = false;
statusel.innerHTML = "Retrying...";
startPolling();
}
},15000)
utils.loadJSLib(pollurl);
}
function setUpEvents(ws) {
ws.onclose = function() {
statusel.innerHTML = "WebSocket closed, retrying in " + Math.round(retryWait/1000) + " seconds!";
setTimeout(function() {
statusel.innerHTML = "Reconnecting...";
var retryWs = new WebSocket(url);
setUpEvents(retryWs);
}, retryWait);
retryWait *= 2;
retryWait = Math.min(maxRetryWait, retryWait);
};
ws.onerror = function() {
statusel.innerHTML = "Error with WebSocket, try refreshing?";
};
ws.onopen = function() {
statusel.innerHTML = "Connected! Waiting for messages...";
retryWait = minRetryWait;
};
ws.onmessage = function(evt) {
if (statusel.innerHTML == "Connected! Waiting for messages...") {
statusel.innerHTML = "";
}
processEdit(evt.data);
}
}
function processEdit(json) {
try {
var edit = JSON.parse(json);
} catch (e) {
window.console && console.error && console.error('Failed to parse: ' + e + ' for: ' + json);
return;
}
editcount = edit.editcount;
// Update user count
usercountel = document.getElementById('updates');
var usercounttext = commaSeparated(edit.usercount) + ' user' + (edit.usercount == 1 ? '' : 's')
var uniqueiptext = ' from ' + commaSeparated(edit.uniqueips) + ' unique address' + (edit.uniqueips == 1 ? '' : 'es');
var editcounttext = commaSeparated(edit.editcount) + ' edit' + (edit.editcount == 1 ? '' : 's');
var userstring = 'Nodelay has served ' + editcounttext + ' to ' + usercounttext + uniqueiptext + '!';
usercountel.innerHTML = userstring;
top.document.title = usercounttext + ' online now';
var queryurl = document.location.search;
// Filter by language
var sourcelang = edit.source.substring(1,3);
if (queryurl.indexOf('language=') != -1 && queryurl.indexOf(sourcelang) == -1) {
//console.log('skipping source', edit.source, sourcelang);
return;
}
//console.log(json);
// Update the list
var li = document.createElement('li');
li.innerHTML = formatEdit(edit);
messageel.appendChild(li);
if (messageel.children.length > 20) {
messageel.removeChild(messageel.firstChild);
}
if (visRunning) {
updateVis(edit);
}
}
function commaSeparated(n) {
var s = n.toString();
for (var i = s.length-3; i >= 1; i -= 3) {
s = s.substring(0,i) + "," + s.substring(i,s.length);
}
return s;
}
function formatEdit(edit) {
// Add wikipedia metadata
for (var pageid in edit.metadata.pages) {
var page = edit.metadata.pages[pageid];
var size = page.length;
var time = ' <span class="time">' + relativeDate(parseDate(page.touched)) + '<\/span>'
}
var out = '<a target="_blank" href="'+edit.url+'">' + edit.title + '<\/a> '
// Add types from metaweb
if (edit.types) {
var typetext = [];
for (var i = 0, l = edit.types.length; i < l; i++) {
var type = edit.types[i];
typetext.push(type.text);
}
out += ' (' + typetext.join(', ') + ') ';
}
var user = ' by <span class="user">' + edit.user + '<\/span>';
if (edit.flags.indexOf('B') >= 0) {
// http://upload.wikimedia.org/wikipedia/commons/thumb/0/05/Robot_icon.svg/40px-Robot_icon.svg.png
user += " <img src=\"images/robot.png\">";
}
out += (size ? size : '') + '<span class="change">' + edit.change + '<\/span> <span class="comment">' + edit.text + '<\/span>' + time + user;
var rank = edit.googlerank;
if (rank != null) {
//console.log('google rank', rank);
out = '<span style="opacity:' + ((10 - rank) / 10) + ';">' + out + '</span>';
}
return out;
}
// adapted from http://stackoverflow.com/questions/3085937/safari-js-cannot-parse-yyyy-mm-dd-date-format
function parseDate(input, format) {
if (!input) return null;
format = format || 'yyyy-mm-dd HH:MM:SS'; // default format
var parts = input.match(/(\d+)/g),
i = 0,
fmt = {};
// extract date-part indexes from the format
format.replace(/(yyyy|dd|mm|HH|MM|SS)/g, function(part) { fmt[part] = i++; });
return new Date(Date.UTC(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']], parts[fmt['HH']], parts[fmt['MM']], parts[fmt['SS']]));
}
function relativeDate(then) {
if(!then) return 'never';
then = Math.floor(then.getTime() / 1000);
var now = Math.floor(Date.now() / 1000);
var t = now - then;
if (t <= 1) {
return "moments ago";
}
else if (t < 5) {
return Math.round(t) + " seconds ago";
}
else if (t < 60) {
return "about " + Math.round(t/10)*10 + " seconds ago";
}
t /= 60;
if (t < 60) {
t = Math.floor(t);
return t + " minute" + (t == 1 ? '' : 's') + " ago";
}
t /= 60;
if (t < 24) {
t = Math.floor(t);
return t + " hour" + (t == 1 ? '' : 's') + " ago";
}
t /= 24;
if (t < 7) {
t = Math.floor(t);
return t + " day" + (t == 1 ? '' : 's') + " ago";
}
t /= 7;
t = Math.floor(t);
return t + " week" + (t == 1 ? '' : 's') + " ago";
}
///////////////////// Protovis stuff goes here...
var visRunning = true;
var userNodes = {};
// TODO: we'll need to translate these if we want them to work for de, etc.
var types = [ "User", "Article", "Talk:", "Category:", "Wikipedia:", "File:", "Template:", "User:", "User talk:", "Portal:" ];
function updateVis(edit) {
if (!(edit.user in userNodes)) {
userNodes[edit.user] = {
nodeName: edit.user,
user: edit.user,
group: 0, // User Nodes
nodeIndex: nodes.length,
lastTouched: Date.now(),
x: randomX(),
y: randomY()
}
nodes.push(userNodes[edit.user]);
}
var userNode = userNodes[edit.user];
if (userNode) { userNode.lastTouched = Date.now(); }
var pos = userNode ? randomOffset(userNode) : randomOuter();
var group = 1; // normal Articles
// skip first two, they aren't prefixes
for (var i = 2; i < types.length; i++) {
if (edit.title.indexOf(types[i]) == 0) {
group = i;
break;
}
}
var node = {
nodeName: edit.title,
group: group, // TODO: color based on edit type (special, talk, bot, etc)
nodeIndex: nodes.length,
lastTouched: Date.now(),
x: pos.x,
y: pos.y
};
nodes.push(node)
links.push({ source: userNode.nodeIndex, target: node.nodeIndex, value: 5 });
// keep nodes to a manageable length, remove oldest one that isn't a type
while (nodes.length > 100) {
var sortedNodes = nodes.slice();
sortedNodes.sort(function(a,b) {
return a.lastTouched - b.lastTouched;
});
var dead = sortedNodes[0];
// remove dead node and correct node indexes:
nodes.splice(dead.nodeIndex, 1);
for (var i = dead.nodeIndex; i < nodes.length; i++) {
nodes[i].nodeIndex = i;
};
if (dead.user) {
delete userNodes[dead.user];
}
// decrement source and target index and remove invalid links
links = links.filter(function(link) {
if (link.source == dead.nodeIndex || link.target == dead.nodeIndex) {
return false;
}
if (link.source > dead.nodeIndex) {
link.source -= 1;
}
if (link.target > dead.nodeIndex) {
link.target -= 1;
}
return true;
});
}
if (force) {
force.reset();
vis.render();
}
}
function randomOffset(p) {
var a = Math.random() * 2 * Math.PI;
var r = Math.random() * 25;
return {
x: p.x + r*Math.cos(a),
y: p.y + r*Math.sin(a)
}
}
function randomOuter() {
var w = document.getElementById('vis').offsetWidth;
var h = document.getElementById('vis').offsetHeight;
var a = Math.random() * 2 * Math.PI;
var r = (0.5+Math.random()/2) * Math.min(w,h)/2;
return {
x: w/2 + (w/3)*Math.cos(a),
y: h/2 + (h/3)*Math.sin(a)
}
}
function randomX() {
var w = document.getElementById('vis').offsetWidth;
return w/2 + (2.0 * (Math.random() - 0.5)) * w/3;
}
function randomY() {
var h = document.getElementById('vis').offsetHeight;
return h/2 + (2.0 * (Math.random() - 0.5)) * h/3;
}
var force, vis;
var nodes = [];
var links = [];
function initVis() {
var container = document.getElementById('vis'),
colors = pv.Colors.category10();
vis = new pv.Panel()
.canvas('vis')
.width(function() { return container.offsetWidth })
.height(function() { return container.offsetHeight })
.fillStyle('rgba(0,0,0,0.01)')
.event("mousedown", pv.Behavior.pan().bound(true))
.event("mousewheel", pv.Behavior.zoom().bound(true));
force = vis.add(pv.Layout.Force)
.nodes(function() { return nodes })
.links(function() { return links })
.bound(true)
.springConstant(0.2)
.chargeConstant(-5)
.iterations(null); // continuous
force.link.add(pv.Line)
.strokeStyle('black')
.lineWidth(0.5);
force.node.add(pv.Dot)
.size(function(d) {
var ageMult = 1.0 - Math.min(1.0, (Date.now() - d.lastTouched) / 15000);
//var linkSize = Math.sqrt(100*d.linkDegree); //(d.type ? 100 : 10));
return 1.0 + (ageMult*25.0);// + (linkSize);
})
.fillStyle(function(d) { return d.fix ? "brown" : colors(d.group) })
.strokeStyle(function(d) { return d.user ? 'white' : null })
.lineWidth(1)
.title(function(d) { return d.nodeName })
.event("mousedown", pv.Behavior.drag())
.event("drag", force).anchor(function(d) { return d.user ? 'right' : 'left' }).add(pv.Label)
.visible(function(d) { return (Date.now() - d.lastTouched) < (d.user ? 5000 : 10000); })
.textStyle(function(d) { return d.user ? 'white' : colors(d.group).brighter() })
.text(function(d) {
return d.nodeName;
});
var reverseTypes = types.slice();
reverseTypes.reverse();
var legend = new pv.Panel()
.canvas('legend')
.width(function() { return container.offsetWidth })
.height(function() { return container.offsetHeight })
.add(pv.Dot)
.data(reverseTypes)
.bottom(function(d) { return 15 + this.index * 15 })
.size(15)
.left(15)
.fillStyle(function(d) { return colors(types.length - 1 - this.index) })
.strokeStyle(function(d) { return this.index == types.length - 1 ? 'white' : null })
.lineWidth(1)
.anchor("right").add(pv.Label)
.textAlign("left")
.text(function(d) { return d })
.textStyle(function(d) { return this.index == types.length - 1 ? 'white' : colors(types.length - 1 - this.index).brighter() });
legend.render();
vis.render();
var resizeTimer = 0;
window.onresize = function() {
if (resizeTimer) {
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function() {
vis.render();
}, 50);
}
}
function toggleVis() {
visRunning = !visRunning;
var link = document.getElementById('stop').getElementsByTagName('a')[0];
if (visRunning) {
force.iterations(null);
link.innerHTML = "stop hurting my ipad!"
}
else {
force.iterations(1);
link.innerHTML = "start it up again!"
}
force.reset();
vis.render();
return false; // for event handlers
}