This repository has been archived by the owner on Jun 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
gerard.js
512 lines (439 loc) · 15.4 KB
/
gerard.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
{% extends "home.html" %}
{% import "jsmacros.html" as js %}
{% block gerard %}
/* IRC live */
var onair = true;
var prevdate = '1970-01-01';
var searchval = '';
var htmlesc = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'\\\\': '\',
};
var escape_html = function(data) {
$.each(htmlesc, function(k, v) {
var re = new RegExp(k, 'g');
data = data.replace(re, v);
});
/* https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet */
return data;
}
var std_border_bottom = '1px solid black';
var hl_border_bottom = '1px solid #5090ff';
var _isimg = function(url) {
if (url.match(/\.(jpe?g|gif|png|bmp)$/i))
return true
return false
}
var mkmark = function(mark, repl, line) {
var rx = '(^|\\\s)' + mark + '([^' + mark + ']+)' + mark + '(\\\s|$)';
re = new RegExp(rx, 'g');
return line.replace(re, '$1<' + repl + '>' + '$2' + '</' + repl + '>$3')
}
var minimd = function(str) {
var mds = {
'`': 'code',
'_': 'em',
'\\\*': 'strong',
};
$.each(mds, function(k, v) {
str = mkmark(k, v, str);
});
return str;
}
/* generates a popover preview for images */
var rabbitify = function(url) {
var img = escape_html(escape_html(url));
img = '<img src=\'' + img + '\' width=\'200\'>';
var data = 'data-toggle="popover" data-content="' + img + '" ';
data += 'data-placement="auto"';
return data;
}
var url_exists = function(url) {
var exists = false;
$.ajax({
async: false,
url: url,
type: 'HEAD',
success: function() {
exists = true;
return false;
}
});
return exists;
}
var showrage = function(line) {
var larr = line.match(/(.*)\[img:([a-zA-Z0-9_-]+)\](.*)/);
if (larr && larr.length > 3) {
var imgext = ['png', 'gif', 'jpg'];
var baseurl = '{{ url_for("images", filename="") }}';
$.each(imgext, function() {
imgurl = baseurl + 'rage/' + larr[2] + '.' + this;
if (url_exists(imgurl)) {
line = larr[1];
line += ' <img src="' + encodeURIComponent(imgurl) + '" width="100"/>';
line += larr[3];
return true;
}
});
}
return line;
}
/* replaces line URLs with clickable links and apply minimal markdown*/
var decoline = function(source) {
/* minimal markdown */
var l = minimd(escape_html(source.line + ' '));
/* display rage faces if they exist */
l = showrage(l);
/* foreach URLs in line, make them a href */
$.each(source.urls, function() {
var eurl = escape_html(this);
var res = '<kbd><a href="' + eurl + '" target="_blank"';
/* if it is an image, make it a popover */
if (_isimg(this))
res += rabbitify(this)
res += '>' + eurl + '</a></kbd>';
/* only replace a complete url (like rhonrhon think it is)
* so match the last space also
*/
l = l.replace(eurl + ' ', res + ' ');
});
return l;
}
var mktweeturl = function(data) {
var text = encodeURIComponent('<' + data.nick + '> ' + data.line);
var via = 'GCUsquad';
var tweeturl = 'https://twitter.com/share?text=' + text;
tweeturl += '&via=' + via;
if ( data.tags ) {
tweeturl += '&hashtags=' + encodeURIComponent(data.tags.join(','));
}
return tweeturl;
}
/* process irc channel window */
var process_ircline = function(data, lastdate, cnt, pos) {
$.each(data, function() {
source = this._source;
/* do not refresh last line */
if (lastdate && source.fulldate == lastdate)
return true
/* timestamp */
var ircline = '<div ';
ircline += 'class="small {{ ircline_style["div"] }}" ';
ircline += 'id="' + source.fulldate + '">';
if (prevdate && source.date != prevdate) {
ircline += '<div class="newdate">';
ircline += '<a href="#" onclick="searchjson(';
ircline += '\'date:' + source.date + '\', \'.irclive\', false);';
ircline += 'return false;">';
ircline += source.date + ' ';
ircline += '<span class="glyphicon glyphicon-calendar"></span>';
ircline += '</div></a>';
}
{{ js.button('time', ircline_style) }}
{{ js.button('nick', ircline_style) }}
/* destination nicks */
{{ js.buttonlst('tonick', ircline_style) }}
/* real line */
ircline += '<span class="line">' + decoline(source) + '</span>';
/* tags */
{{ js.buttonlst('tags', ircline_style, 'tag') }}
ircline += '</div>';
if (pos == 'append')
$(cnt).append(ircline);
else
$(cnt).prepend(ircline);
prevdate = source.date;
});
}
/* process "links of the day" column */
var process_urlline = function(data, lastdate, cnt, pos) {
$.each(data, function() {
source = this._source;
if (lastdate && source['fulldate'] == lastdate)
return true;
var urlline = '';
var hasimg = false;
var hastags = false;
$.each(source.urls, function() {
var eurl = escape_html(this);
urlline += '<div class="small list-group-item urlline" ';
urlline += 'id="' + source.fulldate + '">';
urlline += '<a href="' + eurl + '" target="_blank" ';
/* URL is an image, popover is a preview */
if (_isimg(this)) {
urlline += rabbitify(this);
hasimg = true;
} else {
/* URL is not an image, popover is an abstract */
urlline += 'data-content="[' + source.time + '] ';
urlline += '<span class=\'label label-success bigger-label\'>';
/* Double escaping needed to avoid XSS in popovers */
urlline += escape_html(escape_html(source.nick));
urlline += '</span> ';
urlline += escape_html(escape_html(source.line)) + ' ';
if (source.tags.length > 0) {
hastags = true;
urlline += '<h5>';
$.each(source.tags, function() {
urlline += '<span class=\'label label-warning\'>';
urlline += escape_html(escape_html(this)) + ' ';
urlline += '<span class=\'glyphicon glyphicon-tag\'>';
urlline += '</span></span> ';
});
urlline += '</h5>';
}
urlline += '" ';
urlline += 'data-placement="auto" ';
urlline += 'data-toggle="popover"';
}
/* what is actually shown in LotD div */
if (hasimg)
urlline += '><span class="glyphicon glyphicon-film"></span> ';
else if (hastags)
urlline += '><span class="glyphicon glyphicon-tag"></span> ';
else
urlline += '><span class="glyphicon glyphicon-globe"></span> ';
eurl = eurl.replace(/^https?:\/\/(www\.)?/,'');
var maxlen = 30;
if (eurl.length > maxlen)
eurl = eurl.substr(0, maxlen - 1) + "…";
urlline += eurl + '</a></div>';
});
if (pos == 'append')
$(cnt).append(urlline);
else
$(cnt).prepend(urlline);
});
}
var _getratio = function(t) {
return $('.' + t + 'live').children('.' + t + 'line').length / {{ nlines }};
}
/**
* Returns and fills container 't' + 'live' with latest entries
*/
var _getjson = function(t, todate) {
var live = $('.' + t + 'live'); /* full div */
var lastdate;
var action;
var get_last = '{{ url_for("get_last") }}?';
get_last += 't=' + encodeURIComponent(t); /* type: irc or url */
if (todate) { /* todate was given, we're fetching previous results */
lastdate = $('.' + t + 'line').first().attr('id');
get_last += '&x=to';
action = 'prepend';
} else { /* normal call, fetch last entries */
lastdate = $('.' + t + 'line').last().attr('id');
action = 'append';
}
if (!lastdate) {/* first call, no lastdate yet */
lastdate = '';
this['sh_' + t] = 0; /* record type scroll height */
}
get_last += '&d=' + encodeURIComponent(lastdate);
var doscroll = false;
/* fetch scrollbar position */
var livepos = live.prop('scrollTop') + live.prop('offsetHeight');
/* at bottom, auto scroll to next results */
if (onair && livepos >= live.prop('scrollHeight'))
doscroll = true;
var fn = window['process_' + t + 'line']; /* build generic function */
$.getJSON(get_last, function(data) {
if (typeof fn === "function")
fn(data, lastdate, '.' + t + 'live', action);
});
/* autoscroll only if we're at the bottom (i.e. not scrolling) */
if (!lastdate || doscroll) {
/* autoscroll to bottom */
live.prop({ scrollTop: live.prop('scrollHeight') });
live.css('border-bottom', std_border_bottom);
} else if (this['sh_' + t] < live.prop('scrollHeight'))
live.css('border-bottom', hl_border_bottom);
/* proportional positionning if we're going back in history */
if (todate)
live.prop({ scrollTop: live.prop('scrollHeight') / _getratio(t) })
/* record last scrollHeight */
this['sh_' + t] = live.prop('scrollHeight');
}
/**
* Returns and fills container 'cnt' with query 'q', more is false on first
* query, true if we are to fetch next results
*/
var searchjson = function(q, cnt, more) {
/* stop updating IRC window, no more scrollback */
onair = false;
/* record the search for scroll down / _getheight */
searchval = q;
/* wipe old content */
if (!more)
$(cnt).empty();
var search = '{{ url_for("search") }}?q=' + encodeURIComponent(q);
if (more)
search += '&f=' + $(cnt).children('.ircline').length;
var total = 0;
$.getJSON(search, function(data) {
if (!data.hits)
data = { 'hits': [], 'total': 0 }
process_ircline(data.hits, undefined, cnt, 'append');
total = data.total;
});
/* change topic line */
$('#topic').html(total + ' résultats');
$('#backtolive').css('display', 'inline');
if (total > {{ nlines }} && more) {
var sh = $(cnt).prop('scrollHeight');
$(cnt).prop({ scrollTop: sh - (sh / _getratio('irc')) })
}
if (!total)
$(cnt).css('background-image',
'url({{ url_for("images", filename="trollface.png") }})');
else
$(cnt).css('background-image', 'none');
}
/**
* Refresh the 't' (type 'irc' or 'url') component
*/
var _refresh = function(t) {
_getjson(t, false);
/* must be refreshed for every new entry */
$('[data-toggle="popover"]').popover({
trigger: 'hover',
html: true,
container: 'body'
});
$('[data-toggle="tooltip"]').tooltip({
trigger: 'hover',
html: true,
container: 'body'
});
}
/**
* Get stab status from upstream nginx
*/
var _refresh_stats = function() {
var stats_url = '{{ url_for("status") }}';
var stats = 0;
$.getJSON(stats_url, function(data) {
stats = data.active_connections;
});
$('#stats').html(stats);
}
/**
* Get channel informations: topic, users, ops
*/
var _refresh_chaninfos = function() {
var chaninfos_url = '{{ url_for("chaninfos") }}';
var topic = '';
var users = [];
var ops = [];
$.getJSON(chaninfos_url, function(data) {
topic = data.topic;
users = data.users;
ops = data.ops;
});
var maxlen = 80;
var eol = '@@EOL@@';
var umark = '@@URL@@';
if (topic.length > maxlen) {
topic = [topic.slice(0, maxlen), eol, topic.slice(maxlen)].join('');
maxlen = false;
}
var re = new RegExp('(https?:\/\/[^\\\s]+)', 'g')
urls = topic.match(re);
topic = topic.replace(re, umark);
topic = escape_html(topic);
if (urls) {
$.each(urls, function() {
eurl = escape_html(this);
url = '<a href=\'' + eurl + '\'>' + eurl + '</a>';
topic = topic.replace(umark, url);
});
}
/* update topic tooltip */
$('#topic').attr('data-original-title', topic.replace(eol, ''));
/* topic was > maxlen, cut it and finish it with ... */
if (!maxlen) {
re = new RegExp(eol + '.*')
topic = topic.replace(re, '…')
}
/* display channel topic */
if (onair) {
$('#topic').html(topic);
$('#backtolive').css('display', 'none');
}
/* display actual IRC users */
$('#chaninfos').html(users.length);
/* refresh ircers (users) popover list */
$.each(users, function() {
i = ops.join(' ').indexOf(this);
if (i != -1)
users[i] = '<strong>@' + this + '</strong>';
});
var ircers = users.sort().join(', ');
$('#ircers').attr('data-content', ircers);
}
var _check_height = function(t) {
var live = $('.' + t + 'live'); /* full div */
live.scroll(function() {
var livepos = live.prop('scrollTop') + live.prop('offsetHeight');
/* user is at the bottom of div */
if (livepos >= live.prop('scrollHeight'))
if (onair)
live.css('border-bottom', std_border_bottom);
else
searchjson(searchval, '.irclive', true)
/* user is on top of div, load previous lines */
if (onair && live.prop('scrollTop') == 0)
_getjson(t, true);
});
}
var _async_ajax = function(b) {
$.ajaxSetup({
async: b
});
}
$(function() {
/* synchronous ajax queries mess up first display plus scrolling pos. */
_async_ajax(false)
/* load these two before main refresh so popovers are correctly updated */
_refresh_stats();
_refresh_chaninfos();
$.each(['irc', 'url'], function() {
_refresh(this);
_check_height(this);
});
/* main search */
var searchform = $('input[class="form-control"]');
searchform.keypress(function(event) {
if (event.which == 13) {
/* no date specified */
searchjson(searchform.val(), '.irclive', false);
return false;
};
});
/* windows users must have a special treatment. */
if (navigator.platform.match(/win(32|64|dows)/gi)) {
$('.irclive').css('font-family', 'Comic Sans MS');
}
/* escaped fragment, crawler hashes */
var hash = window.location.hash;
var ef = hash.match(/^#!([^=]+)=([^=]+)/);
if (hash && ef)
searchjson(ef[1] + ':' + ef[2], 'irc', false);
/* insert shameless ad on the IRC channel */
var ad = $('#adsense').html();
$('.irclive').append(ad);
$('.irclive').prop({ scrollTop: $('.irclive').prop('scrollHeight') });
/* set the timer to refresh data every 8 seconds */
var auto_refresh = setInterval(function() {
_refresh_stats();
_refresh_chaninfos();
_refresh('url');
if (onair)
_refresh('irc');
}, 8000);
});
{% endblock %}