-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.js
1091 lines (1031 loc) · 40.5 KB
/
server.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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var irc = require('irc');
var request = require('request');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var $ = require('cheerio');
var twitter = require('node-twitter');
var nodemailer = require('nodemailer');
var socialNetworkSearch = require('./social-network-search.js');
var wiki2html = require('./wiki2html.js');
var wikipedias = require('./wikipedias.js');
var illustrator = require('./mediagallery.js');
var env = require('node-env-file');
if (require('fs').existsSync(__dirname + '/.env')) {
env(__dirname + '/.env');
}
// verbous debug mode
var VERBOUS = true;
// really very verbous debug mode
var REALLY_VERBOUS = true;
// use WebSocket reporting
var USE_WEBSOCKETS = true;
// whether to monitor the 1,000,000+ articles Wikipedias
var MONITOR_SHORT_TAIL_WIKIPEDIAS = true;
// whether to monitor the 100,000+ articles Wikipedias
var MONITOR_LONG_TAIL_WIKIPEDIAS = true;
// whether to also monitor the << 100,000+ articles Wikipedias
var MONITOR_REALLY_LONG_TAIL_WIKIPEDIAS = true;
// whether to monitor the knowledge base Wikidata
var MONITOR_WIKIDATA = true;
// an article cluster is thrown out of the monitoring loop if its last edit is
// longer ago than SECONDS_SINCE_LAST_EDIT seconds
var SECONDS_SINCE_LAST_EDIT = 240;
// an article cluster may have at max SECONDS_BETWEEN_EDITS seconds in between
// edits in order to be regarded a breaking news candidate
var SECONDS_BETWEEN_EDITS = 60;
// an article cluster must have at least BREAKING_NEWS_THRESHOLD edits before it
// is considered a breaking news candidate
var BREAKING_NEWS_THRESHOLD = 5;
// an article cluster must be edited by at least NUMBER_OF_CONCURRENT_EDITORS
// concurrent editors before it is considered a breaking news candidate
var NUMBER_OF_CONCURRENT_EDITORS = 3;
// Wikipedia edit bots can account for many false positives, so usually we want
// to discard them
var DISCARD_WIKIPEDIA_BOTS = true;
// IRC details for the recent changes live updates
var IRC_SERVER = 'irc.wikimedia.org';
var IRC_NICK = 'wikipedia-live-monitor-' + Date.now();
var IRC_REAL_NAME_AND_CONTACT = 'Thomas Steiner (tomac@google.com)';
// required for Wikipedia API
var USER_AGENT = 'Wikipedia Live Monitor * IRC nick: ' + IRC_NICK + ' *' +
' Contact: tomac(a)google.com.';
// the maximum length of http://t.co links
var TWITTER_SHORT_URL_LENGTH = 23;
// if enabled, breaking news candidates will be tweeted
var TWEET_BREAKING_NEWS_CANDIDATES =
process.env.TWEET_BREAKING_NEWS_CANDIDATES.toLowerCase().trim() === 'false' ?
false : true;
// if enabled, breaking news candidates will be emailed
var EMAIL_BREAKING_NEWS_CANDIDATES =
process.env.EMAIL_BREAKING_NEWS_CANDIDATES.toLowerCase().trim() === 'false' ?
false : true;
var IP_V6 = /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/g;
var IP_V4 = /((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])/;
if (EMAIL_BREAKING_NEWS_CANDIDATES) {
// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: process.env.EMAIL_ADDRESS,
pass: process.env.EMAIL_PASSWORD
}
});
var recentEmailsBuffer = [];
}
if (TWEET_BREAKING_NEWS_CANDIDATES) {
var twit = new twitter.RestClient(
process.env.TWITTER_CONSUMER_KEY,
process.env.TWITTER_CONSUMER_SECRET,
process.env.TWITTER_ACCESS_TOKEN_KEY,
process.env.TWITTER_ACCESS_TOKEN_SECRET
);
var recentTweetsBuffer = [];
}
var IRC_CHANNELS = [];
var PROJECT = '.wikipedia';
if (MONITOR_SHORT_TAIL_WIKIPEDIAS) {
Object.keys(wikipedias.millionPlusLanguages).forEach(function(language) {
if (wikipedias.millionPlusLanguages[language]) {
IRC_CHANNELS.push('#' + language + PROJECT);
}
});
}
if (MONITOR_LONG_TAIL_WIKIPEDIAS) {
Object.keys(wikipedias.oneHundredThousandPlusLanguages).forEach(
function(language) {
if (wikipedias.oneHundredThousandPlusLanguages[language]) {
IRC_CHANNELS.push('#' + language + PROJECT);
}
});
}
if (MONITOR_REALLY_LONG_TAIL_WIKIPEDIAS) {
Object.keys(wikipedias.reallyLongTailWikipedias).forEach(function(language) {
if (wikipedias.reallyLongTailWikipedias[language]) {
IRC_CHANNELS.push('#' + language + PROJECT);
}
});
}
if (MONITOR_WIKIDATA) {
Object.keys(wikipedias.wikidata).forEach(function(language) {
if (wikipedias.wikidata[language]) {
IRC_CHANNELS.push('#' + language + PROJECT);
}
});
}
var client = new irc.Client(
IRC_SERVER,
IRC_NICK,
{
userName: IRC_NICK,
realName: IRC_REAL_NAME_AND_CONTACT,
floodProtection: true,
showErrors: true,
stripColors: true
}
);
client.addListener('registered', function() {
console.log('Connected to IRC server ' + IRC_SERVER);
// connect to IRC channels
IRC_CHANNELS.forEach(function(channel) {
console.log('Joining channel ' + channel);
client.join(channel);
});
});
// fired whenever the client connects to an IRC channel
client.addListener('join', function(channel, nick) {
console.log(nick + ' joined channel ' + channel);
});
// fired whenever someone parts a channel
client.addListener('part', function(channel, nick, reason) {
console.log('User ' + nick + ' has left ' + channel + ' (' + reason + ')');
});
// fired whenever someone quits the IRC server
client.addListener('quit', function(nick, reason, channels) {
console.log('User ' + nick + ' has quit ' + channels + ' (' + reason + ')');
});
// fired whenever someone sends a notice
client.addListener('notice', function(nick, to, text) {
console.log('Notice from ' + (nick === undefined? 'server' : nick) + ' to ' +
to + ': ' + text);
});
// fired whenever someone gets kicked from a channel
client.addListener('kick', function(channel, nick, by, reason) {
console.warn('User ' + (by === undefined? 'server' : by) + ' has kicked ' +
nick + ' from ' + channel + ' (' + reason + ')');
});
// fired whenever someone is killed from the IRC server
client.addListener('kill', function(nick, reason, channels) {
console.warn('User ' + nick + ' was killed from ' + channels + ' (' +
reason + ')');
});
// fired whenever the client encounters an error
client.addListener('error', function(message) {
console.warn('IRC error: ' + message);
});
// global objects, required to keep track of the currently monitored articles
// and article clusters for the different language versions
var articles = {};
var articleClusters = {};
var articleVersionsMap = {};
function parseMessage(message, to) {
// get the editor's username or IP address
// the IRC log format is as follows (with color codes removed):
// rc-pmtpa: [[Juniata River]] http://en.wikipedia.org/w/index.php?diff=
// 516269072&oldid=514659029 * Johanna-Hypatia * (+67) Category:Place names
// of Native American origin in Pennsylvania
var messageComponents = message.split(' * ');
var articleRegExp = /\[\[(.+?)\]\].+?$/;
var article = messageComponents[0].replace(articleRegExp, '$1');
// discard non-article namespaces, as listed here:
// http://www.mediawiki.org/wiki/Help:Namespaces
// this means only listening to messages without a ':' essentially
if (article.indexOf(':') !== -1) {
return false;
}
var editor = messageComponents[1];
// discard edits made by bots.
// bots are identified by a B flag, as documented here
// http://www.mediawiki.org/wiki/Help:Tracking_changes
// (the 'b' is actually uppercase in IRC)
//
// bots must identify themselves by prefixing or suffixing their
// username with 'bot'.
// http://en.wikipedia.org/wiki/Wikipedia:Bot_policy#Bot_accounts
var flagsAndDiffUrl =
messageComponents[0].replace('[[' + article + ']] ', '').split(' ');
var flags = flagsAndDiffUrl[0];
if (DISCARD_WIKIPEDIA_BOTS) {
if ((/B/.test(flags)) ||
(/\bbot/i.test(editor)) ||
(/bot\b/i.test(editor))) {
return;
}
}
// normalize article titles to follow the Wikipedia URLs
article = article.replace(/\s/g, '_');
// the language format follows the IRC room format: '#language.project'
var language = to.substring(1, to.indexOf('.'));
editor = language + ':' + editor;
// diff URL
var diffUrl = flagsAndDiffUrl[1];
if ((diffUrl) &&
(diffUrl.indexOf('diff') !== -1) &&
(diffUrl.indexOf('oldid') !== -1)) {
var toRev = diffUrl.replace(/.*\?diff=(\d+).*/, '$1');
var fromRev = diffUrl.replace(/.*&oldid=(\d+).*/, '$1');
if (language === 'wikidata') {
diffUrl = 'http://wikidata.org/w/api.php?action=compare&torev=' +
toRev + '&fromrev=' + fromRev + '&format=json';
} else {
diffUrl = 'http://' + language +
'.wikipedia.org/w/api.php?action=compare&torev=' + toRev +
'&fromrev=' + fromRev + '&format=json';
}
} else {
diffUrl = '';
}
// delta
var deltaAndCommentRegExp = /\(([+-]\d+)\)\s(.*?)$/;
var delta = messageComponents[2].replace(deltaAndCommentRegExp, '$1');
// comment
var comment = messageComponents[2].replace(deltaAndCommentRegExp, '$2');
// language cluster URL
var languageClusterUrl;
if (language === 'wikidata') {
languageClusterUrl = 'http://www.wikidata.org/w/api.php?' +
'action=wbgetentities&props=sitelinks&format=json&ids=' +
encodeURIComponent(article);
} else {
languageClusterUrl = 'http://' + language +
'.wikipedia.org/w/api.php?action=query&prop=langlinks' +
'&format=json&lllimit=500&titles=' + encodeURIComponent(article);
}
return {
article: article,
editor: editor,
language: language,
delta: delta,
comment: comment,
diffUrl: diffUrl,
languageClusterUrl: languageClusterUrl
};
}
function checkBreakingNewsConditions(article) {
// (1) breaking news threshold
var breakingNewsThresholdReached =
article.occurrences >= BREAKING_NEWS_THRESHOLD;
// (2) check interval distances between edits
// if something is suspected to be breaking news, all interval
// distances must be below a certain threshold
var intervals = article.intervals;
var allEditsInShortDistances = false;
var index = 0;
var intervalsLength = intervals.length;
if (intervalsLength > BREAKING_NEWS_THRESHOLD - 1) {
index = intervalsLength - BREAKING_NEWS_THRESHOLD + 1;
}
for (var i = index; i < intervalsLength; i++) {
if (intervals[i] <= SECONDS_BETWEEN_EDITS * 1000) {
allEditsInShortDistances = true;
} else {
allEditsInShortDistances = false;
break;
}
}
// (3) number of concurrent editors
var numberOfEditors = article.editors.length;
var numberOfEditorsReached =
numberOfEditors >= NUMBER_OF_CONCURRENT_EDITORS;
// if we have an article in more than one languge, check for the
// normal NUMBER_OF_CONCURRENT_EDITORS
if (Object.keys(article.languages).length > 1) {
numberOfEditorsReached =
numberOfEditors >= NUMBER_OF_CONCURRENT_EDITORS;
// else if we have an article in just one languge, require the
// triple NUMBER_OF_CONCURRENT_EDITORS
} else {
numberOfEditorsReached =
numberOfEditors >= 3 * NUMBER_OF_CONCURRENT_EDITORS;
}
return {
breakingNewsThresholdReached: breakingNewsThresholdReached,
allEditsInShortDistances: allEditsInShortDistances,
numberOfEditorsReached: numberOfEditorsReached
};
}
function monitorWikipedia() {
// fires whenever a new IRC message arrives on any of the IRC rooms
client.addListener('message', function(from, to, message) {
// this is the Wikipedia IRC bot that announces live changes
if (from !== 'rc-pmtpa') {
return;
}
var components = parseMessage(message, to);
if (!components) {
return;
}
var article = components.article;
var editor = components.editor;
var delta = components.delta;
var comment = components.comment;
var language = components.language;
var languageClusterUrl = components.languageClusterUrl;
var diffUrl = components.diffUrl;
var now = Date.now();
// get language references via the Wikipedia API
article = language + ':' + article;
request.get({
uri: languageClusterUrl,
headers: {'User-Agent': USER_AGENT}
}, function(error, response, body) {
getLanguageReferences(error, response, body, article);
});
// TODO
// get out-links to other articles mentioned in the current article
// http://en.wikipedia.org/w/api.php?action=query&prop=links&pllimit=500&format=json&titles=
// TODO
// get in-links to the current article
// http://en.wikipedia.org/w/api.php?action=query&list=backlinks&bllimit=500&format=json&bltitle=
// get the diff URL and check if we have notable or trivial changes
if (diffUrl) {
request.get({
uri: diffUrl,
headers: {'User-Agent': USER_AGENT}
}, function(error, response, body) {
getDiffUrl(error, response, body, article, now);
});
}
// new article
if (!articleVersionsMap[article]) {
// self-reference to detect repeatedly edited single-language version
// articles that do not have other language versions
articleVersionsMap[article] = article;
// store the first occurrence of the new article
articles[article] = {
timestamp: now,
occurrences: 1,
intervals: [],
editors: [editor],
languages: {},
versions: {},
changes: {}
};
articles[article].languages[language] = 1;
articles[article].changes[now] = {
diffUrl: diffUrl,
delta: delta,
language: language,
editor: editor,
comment: comment ? comment : ''
};
// reporting WebSockets
if (USE_WEBSOCKETS) {
io.sockets.emit('firstTimeSeen', {
article: article,
timestamp: new Date(articles[article].timestamp).toString(),
editors: [editor],
languages: articles[article].languages,
versions: articles[article].versions
});
}
// reporting console
if (VERBOUS && REALLY_VERBOUS) {
console.log('[ * ] First time seen: "' + article + '". ' +
'Timestamp: ' + new Date(articles[article].timestamp) + '. ' +
'Editors: ' + editor + '. ' +
'Languages: ' + JSON.stringify(articles[article].languages));
}
// existing article
} else {
var currentArticle = article;
if (article !== articleVersionsMap[article]) {
// reporting WebSockets
if (USE_WEBSOCKETS) {
io.sockets.emit('merging', {
current: article,
existing: articleVersionsMap[article],
timestamp: new Date(now).toString()
});
}
// reporting console
if (VERBOUS) {
console.log('[ ⚭ ] Merging ' + article + ' with ' +
articleVersionsMap[article]);
}
article = articleVersionsMap[article];
}
// update statistics of the article
if (articles[article]) {
articles[article].occurrences += 1;
articles[article].versions[currentArticle] = true;
articles[article].intervals.push(now - articles[article].timestamp);
articles[article].timestamp = now;
articles[article].changes[now] = {
diffUrl: diffUrl,
delta: delta,
language: language,
editor: editor,
comment: comment ? comment : ''
};
// we track editors by languages like so: lang:user. if the same user
// edits an article in different languages, she is logged as
// lang1:user and lang2:user, but we still consider them the same,
// and add them like so: lang1,lang2:user.
var editorPresent = false;
var presentEditorIndex = 0;
var currentEditor = editor.split(':')[1];
for (var i = 0, l = articles[article].editors.length; i < l; i++) {
if (currentEditor === articles[article].editors[i].split(':')[1]) {
editorPresent = true;
presentEditorIndex = i;
break;
}
}
if (!editorPresent) {
articles[article].editors.push(editor);
} else {
var currentLanguages =
articles[article].editors[presentEditorIndex].split(':')[0];
if (currentLanguages.indexOf(language) === -1) {
currentLanguages = language + ',' + currentLanguages;
}
articles[article].editors[presentEditorIndex] =
currentLanguages + ':' + currentEditor;
}
if (articles[article].languages[language]) {
articles[article].languages[language] += 1;
} else {
articles[article].languages[language] = 1;
}
// check the three breaking news conditions:
var breakingNewsConditions =
checkBreakingNewsConditions(articles[article]);
// reporting WebSockets
if (USE_WEBSOCKETS) {
io.sockets.emit('nTimesSeen', {
article: article,
occurrences: articles[article].occurrences,
timestamp: new Date(articles[article].timestamp).toString(),
editIntervals: articles[article].intervals,
editors: articles[article].editors,
languages: articles[article].languages,
versions: articles[article].versions,
changes: articles[article].changes,
conditions: {
breakingNewsThreshold:
breakingNewsConditions.breakingNewsThresholdReached,
secondsBetweenEdits:
breakingNewsConditions.allEditsInShortDistances,
numberOfConcurrentEditors:
breakingNewsConditions.numberOfEditorsReached
}
});
}
// reporting console
if (VERBOUS) {
console.log('[ ! ] ' + articles[article].occurrences + ' ' +
'times seen: "' + article + '". ' +
'Timestamp: ' + new Date(articles[article].timestamp) +
'. Edit intervals: ' + articles[article].intervals.toString()
.replace(/(\d+),?/g, '$1ms ').trim() + '. ' +
'Parallel editors: ' + articles[article].editors.length +
'. Editors: ' + articles[article].editors + '. ' +
'Languages: ' + JSON.stringify(articles[article].languages));
}
// check if all three breaking news conditions are fulfilled at once
if ((breakingNewsConditions.breakingNewsThresholdReached) &&
(breakingNewsConditions.allEditsInShortDistances) &&
(breakingNewsConditions.numberOfEditorsReached)) {
// search for all article titles in social networks
var searchTerms = {};
// use the article title as search term
searchTerms[article.split(':')[1].replace(/_/g, ' ')] = true;
for (var key in articles[article].versions) {
// use the article title as search term
var articleTitle = key.split(':')[1].replace(/_/g, ' ');
if (!searchTerms[articleTitle]) {
searchTerms[articleTitle] = true;
}
}
var wikipediaUrl = createWikipediaUrl(articleVersionsMap[article]);
illustrator(searchTerms, wikipediaUrl, function(mediaGalleryHtml) {
socialNetworkSearch(searchTerms, function(socialNetworksResults) {
if (USE_WEBSOCKETS) {
if (articles[article]) {
io.sockets.emit('breakingNewsCandidate', {
article: article,
occurrences: articles[article].occurrences,
timestamp: new Date(articles[article].timestamp).toString(),
editIntervals: articles[article].intervals,
editors: articles[article].editors,
languages: articles[article].languages,
versions: articles[article].versions,
changes: articles[article].changes,
conditions: {
breakingNewsThreshold:
breakingNewsConditions.breakingNewsThresholdReached,
secondsBetweenEdits:
breakingNewsConditions.allEditsInShortDistances,
numberOfConcurrentEditors:
breakingNewsConditions.numberOfEditorsReached
},
mediaGalleryHtml: mediaGalleryHtml,
socialNetworksResults: socialNetworksResults
});
if (TWEET_BREAKING_NEWS_CANDIDATES) {
// the actual breaking news article language version may
// vary, however, to avoid over-tweeting, tweet only
// once, i.e., look up the main article in the
// articleVersionsMap
tweet(
wikipediaUrl,
articles[article].occurrences,
articles[article].editors.length,
Object.keys(articles[article].languages).length,
socialNetworksResults);
}
if (EMAIL_BREAKING_NEWS_CANDIDATES) {
email(articleVersionsMap[article], wikipediaUrl,
socialNetworksResults);
}
// reporting console
if (VERBOUS) {
console.log('[ ★ ] Breaking news candidate: "' +
article + '". ' +
articles[article].occurrences + ' ' +
'times seen. ' +
'Timestamp: ' +
new Date(articles[article].timestamp) +
'. Edit intervals: ' +
articles[article].intervals.toString()
.replace(/(\d+),?/g, '$1ms ').trim() + '. ' +
'Number of editors: ' +
articles[article].editors.length + '. ' +
'Editors: ' + articles[article].editors + '. ' +
'Languages: ' +
JSON.stringify(articles[article].languages));
}
}
}
});
});
}
}
}
});
}
// retrieves the diff URL of an article and stores the cleaned diff text
function getDiffUrl(error, response, body, article, now) {
if (!error) {
var json;
try {
json = JSON.parse(body);
} catch(e) {
json = false;
}
if ((json && json.compare && json.compare['*']) &&
(articles[article] && articles[article].changes[now])) {
var parsedHtml = $.load(json.compare['*']);
var addedLines = parsedHtml('.diff-addedline');
var diffTexts = [];
var diffConcepts = [];
addedLines.each(function() {
var text = $(this).text().trim();
var concepts = extractWikiConcepts(text,
articles[article].changes[now].language);
if (concepts) {
diffConcepts.concat(concepts);
}
text = removeWikiNoise(text);
text = removeWikiMarkup(text);
if (text) {
diffTexts.push(text);
}
});
articles[article].changes[now].diffTexts = diffTexts;
articles[article].changes[now].namedEntities = diffConcepts;
}
} else {
console.warn('Wikipedia API error while getting diff text.' +
(response? ' Status Code: ' + response.statusCode : '') +
(error? ' Error message: ' + error : ''));
}
}
// removes HTML tags from text (like the PHP function with the same name)
function strip_tags (input, allowed) {
// making sure the allowed arg is a string containing only tags in lowercase
// (<a><b><c>)
allowed = (((allowed || '') + '').toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || []).join('');
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
// extracts Wikipedia concepts (i.e., links to other articles)
function extractWikiConcepts(text, language) {
var concepts = [];
text = text.replace(/\[\[(.*?)\]\]/g, function(m, l) {
var p = l.split(/\|/);
var link = p.shift();
if (link.match(/^Image:(.*)/)) {
return false;
}
if (link.indexOf(':') === -1) {
concepts.push(language + ':' + link.replace(/\s/g, '_'));
} else {
concepts.push(link.replace(/\s/g, '_'));
}
});
return concepts;
}
// removes noise from the diff text of article edits
function removeWikiNoise(text) {
// remove things like [[Kategorie:Moravske Toplice| Moravske Toplice]]
var namespaceNoiseRegEx = /\[\[.*?\:.*?\]\]/g;
// remove things like {{NewZealand-writer-stub}}
var commentNoiseRegEx = /\{\{.*?\}\}/g;
// remove things like align="center"
var htmlAttributeRegEx = /\w+\s*\=\s*\"\w+\"/g;
// remove things like {{
var openingCommentParenthesisRegEx = /\{\{/g;
// remove things like }}
var closingCommentParenthesisRegEx = /\}\}/g;
text = text.replace(namespaceNoiseRegEx, '')
.replace(commentNoiseRegEx, ' ')
.replace(htmlAttributeRegEx, ' ')
.replace(openingCommentParenthesisRegEx, ' ')
.replace(closingCommentParenthesisRegEx, ' ')
.replace(/\n/g, ' ')
.replace(/\s+/g, ' ')
.trim();
text = strip_tags(text);
return text;
}
// removes wiki markup from the diff text of article edits
function removeWikiMarkup(text) {
var tableMarkupRegEx = /\|/g;
text = strip_tags(wiki2html(text));
text = text.replace(tableMarkupRegEx, ' ')
.replace(/\[\[/g, ' ')
.replace(/\]\]/g, ' ')
.replace(/\s+/g, ' ')
.replace(/\s?=\s?/g, ' = ')
.trim();
return text;
}
// callback function for getting language references from the Wikipedia API
// for an article
function getLanguageReferences(error, response, body, article) {
// helper function to insert language versions
var insertArticle = function(language, title) {
if (((MONITOR_SHORT_TAIL_WIKIPEDIAS) &&
(wikipedias.millionPlusLanguages[language])) ||
((MONITOR_LONG_TAIL_WIKIPEDIAS) &&
(wikipedias.oneHundredThousandPlusLanguages[language])) ||
((MONITOR_REALLY_LONG_TAIL_WIKIPEDIAS) &&
(wikipedias.reallyLongTailWikipedias[language]))) {
var articleVersion = language + ':' + title;
articleClusters[article][articleVersion] = true;
articleVersionsMap[articleVersion] = article;
}
};
if (!error && response.statusCode == 200) {
var json;
try {
json = JSON.parse(body);
} catch(e) {
json = false;
}
if (json) {
var language = article.split(':')[0];
if (!articleClusters[article]) {
articleClusters[article] = {};
}
if (language === 'wikidata') {
var wikidataId = article.split(':')[1].toLowerCase();
if ((json.entities) &&
(json.entities[wikidataId]) &&
(json.entities[wikidataId].sitelinks)) {
var sitelinks = json.entities[wikidataId].sitelinks;
for (var languageWiki in sitelinks) {
var language = languageWiki.replace(/wiki$/, '');
var title = sitelinks[languageWiki].title.replace(/\s/g, '_');
insertArticle(language, title);
}
}
} else {
if (json.query && json.query.pages) {
var pages = json.query.pages;
for (var id in pages) {
var page = pages[id];
if (page.langlinks) {
page.langlinks.forEach(function(langLink) {
var language = langLink.lang;
var title = langLink['*'].replace(/\s/g, '_');
insertArticle(language, title);
});
}
}
}
}
}
} else {
console.warn('Wikipedia API error while getting language references.' +
(response? ' Status Code: ' + response.statusCode : '') +
(error? ' Error message: ' + error : ''));
}
}
// setting up the Web Socket-based communication with the front-end
if (USE_WEBSOCKETS) {
io.sockets.on('connection', function(socket) {
// send the default settings
socket.emit('defaultSettings', {
secondsSinceLastEdit: SECONDS_SINCE_LAST_EDIT,
secondsBetweenEdits: SECONDS_BETWEEN_EDITS,
breakingNewsThreshold: BREAKING_NEWS_THRESHOLD,
numberOfConcurrentEditors: NUMBER_OF_CONCURRENT_EDITORS
});
// react on settings changes
socket.on('secondsSinceLastEdit', function(data) {
SECONDS_SINCE_LAST_EDIT = data.value;
console.log('Setting SECONDS_SINCE_LAST_EDIT to: ' +
SECONDS_SINCE_LAST_EDIT);
});
socket.on('secondsBetweenEdits', function(data) {
SECONDS_BETWEEN_EDITS = data.value;
console.log('Setting SECONDS_BETWEEN_EDITS to: ' + SECONDS_BETWEEN_EDITS);
});
socket.on('breakingNewsThreshold', function(data) {
BREAKING_NEWS_THRESHOLD = data.value;
console.log('Setting BREAKING_NEWS_THRESHOLD to: ' +
BREAKING_NEWS_THRESHOLD);
});
socket.on('numberOfConcurrentEditors', function(data) {
NUMBER_OF_CONCURRENT_EDITORS = data.value;
console.log('Setting NUMBER_OF_CONCURRENT_EDITORS to: ' +
NUMBER_OF_CONCURRENT_EDITORS);
});
});
}
// clean-up function, called regularly like a garbage collector
function cleanUpMonitoringLoop() {
for (var key in articles) {
var now = Date.now();
if (now - articles[key].timestamp > SECONDS_SINCE_LAST_EDIT * 1000) {
delete articles[key];
for (var version in articleClusters[key]) {
delete articleVersionsMap[version];
}
delete articleClusters[key];
delete articleVersionsMap[key];
if (VERBOUS && REALLY_VERBOUS) {
console.log('[ † ] No more mentions: "' + key + '". ' +
'Article clusters left: ' +
Object.keys(articleClusters).length + '. ' +
'Mappings left: ' + Object.keys(articleVersionsMap).length);
}
}
}
if (USE_WEBSOCKETS) {
io.sockets.emit('stats', {
clustersLeft: Object.keys(articleClusters).length
});
}
}
function createWikipediaUrl(article) {
var components = article.split(':');
if (components[0] === 'wikidata') {
return 'http://' + components[0] + '.org/wiki/' +
encodeURIComponent(components[1]);
} else {
return 'http://' + components[0] + '.wikipedia.org/wiki/' +
encodeURIComponent(components[1]);
}
}
function email(article, wikipediaUrl, microposts) {
// if we have already emailed the current URL, don't email it again
if (recentEmailsBuffer.indexOf(wikipediaUrl) !== -1) {
console.log('Already emailed about ' + wikipediaUrl);
return;
}
// keep the recent emails buffer at most 10 elements long
recentEmailsBuffer.push(wikipediaUrl);
if (recentEmailsBuffer.length > 10) {
recentEmailsBuffer.shift();
}
var generateHtmlMail = function() {
var preg_quote = function(str, delimiter) {
// http://kevin.vanzonneveld.net
// + original by: booeyOH
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: preg_quote("$40");
// * returns 1: '\$40'
// * example 2: preg_quote("*RRRING* Hello?");
// * returns 2: '\*RRRING\* Hello\?'
// * example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
// * returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' +
(delimiter || '') + '-]', 'g'), '\\$&');
};
// converts a user name like en:Jon_Doe to a valid Wikipedia user profile
// link like so: http://en.wikipedia.org/wiki/User:Jon_Doe. Ignore
// anonymous users
var linkifyEditor = function(user) {
var components = user.split(':');
IP_V4.lastIndex = 0;
IP_V6.lastIndex = 0;
if (IP_V4.test(user) || IP_V6.test(user)) {
return '<a class="user">' + components[1] + '</a>';
}
return '<a class="user" href="http://' +
components[0].replace(/(\w+),.*/, '$1') +
'.wikipedia.org/wiki/User:' + components[1] + '">' + components[1] +
'</a>';
};
var imgUrl = 'https://raw.github.com/tomayac/wikipedia-irc/master/static/';
var html = '';
var image =
'<img src="' + imgUrl +
article.split(':')[0] + '.png">';
html += '<h1 style="font-size: 1.2em;">Breaking News Candidate<br><nobr>' +
image + ' <a href="' + wikipediaUrl + '">' +
decodeURIComponent(wikipediaUrl) + '</a></nobr></h1>';
html += '<h2 style="font-size: 1.0em;">All Language Versions</h2>';
if (Object.keys(articles[article].versions).length) {
html += '<ul>';
for (var version in articles[article].versions) {
var url = createWikipediaUrl(version);
html += '<li>' + '<nobr><img src="' + imgUrl + version.split(':')[0] +
'.png"> <a href="' + url + '">' + decodeURIComponent(url) + '</a>' +
'</nobr></li>';
}
html += '</ul>';
}
html += '<h2 style="font-size: 1.0em;">Last Edits</h2><ul>';
for (var timestamp in articles[article].changes) {
var change = articles[article].changes[timestamp];
html += '<li><nobr><img src="' + imgUrl + change.language + '.png"> ' +
linkifyEditor(change.editor) + ': ' +
'</nobr><span style="font-style: italic; font-size: 0.8em;">' +
(change.comment ? change.comment : 'N/A') + '</span> ' +
'(<a href="' + change.diffUrl + '"><span style="' +
(change.delta.indexOf('+') === -1 ? 'color:red;' : 'color:green;') +
'">' + change.delta + '</span></a>) ';
if (change.diffTexts) {
html += '<ul>';
change.diffTexts.forEach(function(diffText) {
html += '<li><span style="font-style: italic; font-size: 0.8em; ' +
'color: gray;">' + diffText + '</span>';
});
html += '</ul>';
}
}
html += '</ul>';
var socialHtml = '';
if (microposts) {
var now = Date.now();
for (var term in microposts) {
// only append the term if microposts exist. need to iterate over all
// networks and check the freshness. ugly, but works.
var resultsExistForTerm = false;
for (var network in microposts[term]) {
if (Array.isArray(microposts[term][network])) {
microposts[term][network].forEach(function(item) {
// not older than 1h: 1 * 60 * 60 * 1000 = 3600000
if (now - item.timestamp < 3600000) {
resultsExistForTerm = true;
}
});
}
}
if (resultsExistForTerm) {
socialHtml += '<li><b>' + term + '</b>';
}
for (var network in microposts[term]) {
if (Array.isArray(microposts[term][network])) {
microposts[term][network].forEach(function(item) {
// not older than 1h: 1 * 60 * 60 * 1000 = 3600000
if (now - item.timestamp < 3600000) {
var micropost = item.micropost;
if (micropost.length > 280) {
micropost = micropost.substring(0, 280) + ' […]';
}
socialHtml += '<br/><img style="width: 16px; height: 16px; ' +
'border-radius: 5px; vertical-align: middle;" src="' +
item.avatar + '"/> ' +
'<img style="width: 16px; height: 16px; ' +
'border-radius: 5px; vertical-align: middle;" src="' +
imgUrl + network.toLowerCase() + '.png"/> <small> ' +
'<a href="' + item.profileLink + '">' +
item.user + '</a> (<a href="' + item.deepLink + '">' +
new Date(item.timestamp).toString().substring(0,24) +
'</span></a>): ' + micropost.replace(
new RegExp('(' + preg_quote(term) + ')', 'gi'),
'<span style="background-color: yellow;">$1</span>') +
'</small>';
}
});
}
}
if (resultsExistForTerm) {
socialHtml += '</li>';
}
}
}
if (socialHtml) {
html += '<h2 style="font-size: 1.0em;">Social Network Coverage</h2><ul>' +
socialHtml + '</ul>';
}
return html;
};
// setup e-mail data with unicode symbols
var mailOptions = {
from: 'Wikipedia Live Monitor <' + process.env.EMAIL_ADDRESS + '>',
to: process.env.EMAIL_RECEIVER,
subject: 'Breaking News Candidate: ' + decodeURIComponent(wikipediaUrl),
generateTextFromHTML: true,
forceEmbeddedImages: true,
html: generateHtmlMail()
};
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
console.warn(error);
} else {
console.log('Message sent: ' + response.message);
// https://groups.google.com/forum/feed/wikipedialivemonitor/msgs/atom.xml?num=15
}