This repository has been archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
master.js
8629 lines (7154 loc) · 300 KB
/
master.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
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/*global exports*/
// some sort of pseudo constructor
exports.Command = function (cmd) {
var bot = this;
cmd.name = cmd.name.toLowerCase();
cmd.thisArg = cmd.thisArg || cmd;
cmd.permissions = cmd.permissions || {};
cmd.permissions.use = cmd.permissions.use || 'ALL';
cmd.permissions.del = cmd.permissions.del || 'NONE';
cmd.description = cmd.description || '';
cmd.creator = cmd.creator || 'God';
// make canUse and canDel
['Use', 'Del'].forEach(function (perm) {
var low = perm.toLowerCase();
cmd['can' + perm] = function (usrid) {
var canDo = this.permissions[low];
if (canDo === 'ALL') {
return true;
}
else if (canDo === 'NONE') {
return false;
}
else if (bot.isOwner(usrid)) {
return true;
}
return canDo.indexOf(usrid) > -1;
};
});
cmd.exec = function () {
return this.fun.apply(this.thisArg, arguments);
};
cmd.del = function () {
bot.info.forgotten += 1;
delete bot.commands[cmd.name];
bot.commandDictionary.trie.del(cmd.name);
};
return cmd;
};
// a normally priviliged command which can be executed if enough people use it
exports.CommunityCommand = function (command, req) {
var bot = this;
var cmd = this.Command(command),
used = {},
oldExecute = cmd.exec,
oldCanUse = cmd.canUse;
var pendingMessage = command.pendingMessage ||
'Already registered; still need {0} more';
console.log(command.pendingMessage, pendingMessage);
req = req || 2;
cmd.canUse = function () {
return true;
};
cmd.exec = function (msg) {
var err = register(msg.get('user_id'));
if (err) {
bot.log(err);
return err;
}
used = {};
return oldExecute.apply(cmd, arguments);
};
return cmd;
// once again, a switched return statement: truthy means a message, falsy
// means to go on ahead
function register (usrid) {
if (oldCanUse.call(cmd, usrid)) {
return false;
}
clean();
var count = Object.keys(used).length,
needed = req - count;
bot.log(used, count, req);
if (usrid in used) {
return 'Already registered; still need {0} more'.supplant(needed);
}
used[usrid] = new Date();
needed -= 1;
if (needed > 0) {
return pendingMessage.supplant(needed);
}
bot.log('should execute');
// huzzah!
return false;
}
function clean () {
var tenMinsAgo = new Date();
tenMinsAgo.setMinutes(tenMinsAgo.getMinutes() - 10);
Object.keys(used).reduce(rm, used);
function rm (ret, key) {
if (ret[key] < tenMinsAgo) {
delete ret[key];
}
return ret;
}
}
};
},{}],2:[function(require,module,exports){
/*global module, require*/
var IO = window.IO = module.exports = {
// event handling
events: {},
preventDefault: false,
// register for an event
register: function (name, fun, thisArg) {
if (!this.events[name]) {
this.events[name] = [];
}
this.events[name].push({
fun: fun,
thisArg: thisArg,
args: Array.prototype.slice.call(arguments, 3)
});
return this;
},
unregister: function (name, fun) {
if (!this.events[name]) {
return this;
}
this.events[name] = this.events[name].filter(function (obj) {
return obj.fun !== fun;
});
return this;
},
// fire event!
fire: function (name) {
this.preventDefault = false;
if (!this.events[name]) {
return;
}
var args = Array.prototype.slice.call(arguments, 1),
that = this;
this.events[name].forEach(fireEvent);
function fireEvent(evt) {
var call = evt.fun.apply(evt.thisArg, evt.args.concat(args));
that.preventDefault = call === false;
}
},
urlstringify: (function () {
// simple types, for which toString does the job
// used in singularStringify
var simplies = { number: true, string: true, boolean: true };
var singularStringify = function (thing) {
if (typeof thing in simplies) {
return encodeURIComponent(thing.toString());
}
return '';
};
var arrayStringify = function (key, array) {
key = singularStringify(key);
return array.map(function (val) {
return pair(key, val, true);
}).join('&');
};
// returns a key=value pair. pass in dontStringifyKey so that, well, the
// key won't be stringified (used in arrayStringify)
var pair = function (key, val, dontStringifyKey) {
if (!dontStringifyKey) {
key = singularStringify(key);
}
return key + '=' + singularStringify(val);
};
return function (obj) {
return Object.keys(obj).map(function (key) {
var val = obj[key];
if (Array.isArray(val)) {
return arrayStringify(key, val);
}
else {
return pair(key, val);
}
}).join('&');
};
}()),
loadScript: function (url, cb) {
var script = document.createElement('script');
script.src = url;
script.onload = cb;
document.head.appendChild(script);
}
};
// turns some html tags into markdown. a major assumption is that the input is
// properly sanitised - that is, all <, &, etc entered by the user got turned
// into html entities.
IO.htmlToMarkdown = (function () {
// A string value is the delimiter (what replaces the tag)
var markdown = {
i: '*',
b: '**',
strike: '---',
code: '`',
a: function ($0, $1, text) {
var href = /href="([^"]+?)"/.exec($0);
if (!href) {
return $0;
}
return '[' + text + '](' + href[1] + ')';
}
};
var htmlRe = /<(\S+)[^\>]*>([^<]+)<\/\1>/g;
return function (html) {
var delim;
return html.replace(htmlRe, decodeHtml);
function decodeHtml ($0, tag, text) {
if (!markdown.hasOwnProperty(tag)) {
return $0;
}
delim = markdown[tag];
return delim.apply ?
markdown[tag].apply(markdown, arguments) :
delim + text + delim;
}
};
}());
IO.decodehtmlEntities = (function () {
var entities = require('static/htmlEntities.json');
/*
& -all entities start with &
(
# -charcode entities also have a #
x? -hex charcodes
)?
[\w;] -now the entity (alphanumeric, separated by ;)
+? -capture em until there aint no more (don't get the trailing ;)
; -trailing ;
*/
var entityRegex = /&(#x?)?[\w;]+?;/g;
var replaceEntities = function (entities) {
// remove the & and split into each separate entity
return entities.slice(1).split(';').map(decodeEntity).join('');
};
var decodeEntity = function (entity) {
if (!entity) {
return '';
}
// starts with a #, it's charcode
if (entity[0] === '#') {
return decodeCharcodeEntity(entity);
}
if (!entities.hasOwnProperty(entity)) {
// I hate this so. so. so much. it's just wrong.
return '&' + entity +';';
}
return entities[entity];
};
var decodeCharcodeEntity = function (entity) {
// remove the # prefix
entity = entity.slice(1);
var cc;
// hex entities
if (entity[0] === 'x') {
cc = parseInt(entity.slice(1), 16);
}
// decimal entities
else {
cc = parseInt(entity, 10);
}
return String.fromCharCode(cc);
};
return function (html) {
return html.replace(entityRegex, replaceEntities);
};
}());
// build IO.in and IO.out
['in', 'out'].forEach(function (dir) {
var fullName = dir + 'put';
IO[dir] = {
buffer: [],
receive: function (obj) {
IO.fire('receive' + fullName, obj);
if (IO.preventDefault) {
return this;
}
this.buffer.push(obj);
return this;
},
// unload the next item in the buffer
tick: function () {
if (this.buffer.length) {
IO.fire(fullName, this.buffer.shift());
}
return this;
},
// unload everything in the buffer
flush: function () {
IO.fire('before' + fullName);
if (!this.buffer.length) {
return this;
}
while (this.buffer.length) {
this.tick();
}
IO.fire('after' + fullName);
this.buffer = [];
return this;
}
};
});
IO.relativeUrlToAbsolute = function (url) {
// the anchor's href *property* will always be absolute, unlike the href
// *attribute*
var a = document.createElement('a');
a.setAttribute('href', url);
return a.href;
};
IO.injectScript = function (url) {
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
return script;
};
IO.xhr = function (params) {
// merge in the defaults
params = Object.merge({
method: 'GET',
headers: {},
complete: function (){}
}, params);
params.headers = Object.merge({
'Content-Type': 'application/x-www-form-urlencoded'
}, params.headers);
// if the data is an object, and not a fakey String object, dress it up
if (typeof params.data === 'object' && !params.data.charAt) {
params.data = IO.urlstringify(params.data);
}
if (params.method === 'GET') {
params.url += '?' + params.data;
}
var xhr = new XMLHttpRequest();
xhr.open(params.method, params.url);
if (params.document) {
xhr.responseType = 'document';
}
xhr.addEventListener('load', function () {
params.complete.call(
params.thisArg, xhr.response, xhr
);
});
Object.iterate(params.headers, xhr.setRequestHeader.bind(xhr));
xhr.send(params.data);
return xhr;
};
IO.jsonp = function (opts) {
opts.data = opts.data || {};
opts.jsonpName = opts.jsonpName || 'jsonp';
var script = document.createElement('script'),
semiRandom;
do {
semiRandom = 'IO' + (Date.now() * Math.ceil(Math.random()));
} while (window[semiRandom]);
// this is the callback function, called from the "jsonp file"
window[semiRandom] = function () {
opts.fun.apply(opts.thisArg, arguments);
// cleanup
delete window[semiRandom];
script.parentNode.removeChild(script);
};
// add the jsonp parameter to the data we're sending
opts.data[opts.jsonpName] = semiRandom;
// start preparing the url to be sent
if (opts.url.indexOf('?') === -1) {
opts.url += '?';
}
// append the data to be sent, in string form, to the url
opts.url += '&' + this.urlstringify(opts.data);
script.onerror = opts.error;
script.src = opts.url;
document.head.appendChild(script);
};
// generic, pre-made call to be used inside commands
IO.jsonp.google = function (query, cb) {
IO.jsonp({
url: 'http://ajax.googleapis.com/ajax/services/search/web',
jsonpName: 'callback',
data: {
v: '1.0',
q: query
},
fun: cb
});
};
IO.normalizeUnderscoreProperties = function (obj) {
Object.iterate(obj, function (key, val) {
key = key.replace(/_([A-z])/g, function (_, $1) {
return $1.toUpperCase();
});
// lulz what am I doing
delete obj[key];
obj[key] = val;
});
return obj;
};
},{"static/htmlEntities.json":56}],3:[function(require,module,exports){
/*global exports*/
exports.Message = function (text, msgObj) {
var bot = this;
// "casting" to object so that it can be extended with cool stuff and
// still be treated like a string
var ret = Object(text);
ret.content = text;
var rawSend = function (text) {
bot.adapter.out.add(text, msgObj.room_id);
};
var deliciousObject = {
send: rawSend,
reply: function (resp, userName) {
var prefix = bot.adapter.reply(userName || msgObj.user_name);
rawSend(prefix + ' ' + resp);
},
directreply: function (resp) {
var prefix = bot.adapter.directreply(msgObj.message_id);
rawSend(prefix + ' ' + resp);
},
// parse() parses the original message
// parse( true ) also turns every match result to a Message
// parse( msgToParse ) parses msgToParse
// parse( msgToParse, true ) combination of the above
parse: function (msg, map) {
// parse( true )
if (Boolean(msg) === msg) {
map = msg;
msg = text;
}
var parsed = bot.parseCommandArgs(msg || text);
// parse( msgToParse )
if (!map) {
return parsed;
}
// parse( msgToParse, true )
return parsed.map(function (part) {
return bot.Message(part, msgObj);
});
},
// execute a regexp against the text, saving it inside the object
exec: function (regexp) {
var match = regexp.exec(text);
this.matches = match || [];
return match;
},
findUserId: bot.users.findUserId,
findUsername: bot.users.findUsername,
codify: bot.adapter.codify.bind(bot.adapter),
escape: bot.adapter.escape.bind(bot.adapter),
link: bot.adapter.link.bind(bot.adapter),
stringifyGiantArray: function (giantArray) {
function partition (list, maxSize) {
var size = 0, last = [];
var ret = list.reduce(function partition (ret, item) {
// +1 for comma, +1 for space
var len = item.length + 2;
if (size + len > maxSize) {
ret.push(last);
last = [];
size = 0;
}
last.push(item);
size += len;
return ret;
}, []);
if (last.length) {
ret.push(last);
}
return ret;
}
// 500 is the max, compensate for user reply
var maxSize = 499 - bot.adapter.reply(this.get('user_name')).length,
partitioned = partition(giantArray, maxSize);
return partitioned.invoke('join', ', ').join('\n');
},
// retrieve a value from the original message object, or if no argument
// provided, the msgObj itself
get: function (what) {
if (!what) {
return msgObj;
}
return msgObj[what];
},
set: function (what, val) {
msgObj[what] = val;
return msgObj[what];
}
};
Object.iterate(deliciousObject, function (key, prop) {
ret[key] = prop;
});
return ret;
};
},{}],4:[function(require,module,exports){
module.exports = function (bot) {
require("plugins/STOP.js")(bot);
require("plugins/afk.js")(bot);
require("plugins/backup.js")(bot);
require("plugins/ban.js")(bot);
require("plugins/clap.js")(bot);
require("plugins/converter.js")(bot);
require("plugins/cowsay.js")(bot);
require("plugins/define.js")(bot);
require("plugins/doge.js")(bot);
require("plugins/firefly.js")(bot);
require("plugins/google.js")(bot);
require("plugins/hangman.js")(bot);
require("plugins/imdb.js")(bot);
require("plugins/jquery.js")(bot);
require("plugins/juicebox.js")(bot);
require("plugins/learn.js")(bot);
require("plugins/life.js")(bot);
require("plugins/mdn.js")(bot);
require("plugins/meme.js")(bot);
require("plugins/msdn.js")(bot);
require("plugins/mustache.js")(bot);
require("plugins/nudge.js")(bot);
require("plugins/quote.js")(bot);
require("plugins/spec.js")(bot);
require("plugins/stat.js")(bot);
require("plugins/substitution.js")(bot);
require("plugins/summon.js")(bot);
require("plugins/undo.js")(bot);
require("plugins/unformatted-code.js")(bot);
require("plugins/unonebox.js")(bot);
require("plugins/urban.js")(bot);
require("plugins/vendetta.js")(bot);
require("plugins/weasel.js")(bot);
require("plugins/weather.js")(bot);
require("plugins/welcome.js")(bot);
require("plugins/wiki.js")(bot);
require("plugins/xkcd.js")(bot);
require("plugins/youtube.js")(bot);
require("plugins/zalgo.js")(bot);
};
},{"plugins/STOP.js":17,"plugins/afk.js":18,"plugins/backup.js":19,"plugins/ban.js":20,"plugins/clap.js":21,"plugins/converter.js":22,"plugins/cowsay.js":23,"plugins/define.js":24,"plugins/doge.js":25,"plugins/firefly.js":26,"plugins/google.js":27,"plugins/hangman.js":28,"plugins/imdb.js":29,"plugins/jquery.js":30,"plugins/juicebox.js":31,"plugins/learn.js":32,"plugins/life.js":33,"plugins/mdn.js":34,"plugins/meme.js":35,"plugins/msdn.js":36,"plugins/mustache.js":37,"plugins/nudge.js":38,"plugins/quote.js":39,"plugins/spec.js":40,"plugins/stat.js":41,"plugins/substitution.js":42,"plugins/summon.js":43,"plugins/undo.js":44,"plugins/unformatted-code.js":45,"plugins/unonebox.js":46,"plugins/urban.js":47,"plugins/vendetta.js":48,"plugins/weasel.js":49,"plugins/weather.js":50,"plugins/welcome.js":51,"plugins/wiki.js":52,"plugins/xkcd.js":53,"plugins/youtube.js":54,"plugins/zalgo.js":55}],5:[function(require,module,exports){
// follows is an explanation of how SO's chat does things. you may want to skip
// this gigantuous comment.
/*
Note: This may be outdated next year, tomorrow, never, or in 4 minutes. We
are leeching off a disinterested 3rd party, and knowledge of how to poke
around requests/websockets is required to correctly maintain everything.
Generally, the client gets input from a websocket connected to SO's server,
grabbing events as they come in (new message, edits, room invites, whatever).
However, output (sending a message, editing, basically creating these events) is
not handled via this socket, but via separate http requests. One should note
that if/when the socket fails for any reason, the chat resorts to long polling.
First, a note on authentication. Apparently, the chat uses two things to
decide who you are. The first is, quite obviously, cookies. The second is an
elusive thing called the "fkey". It's given to us by the server inside an input
called (you guessed it) "fkey", and its value is a 32 character string. Maybe
its the result of running a checksum of something, maybe it's the first 32 chars
of a sha512, who knows. But it is used, since you can view chat while not being
logged in, and you have to provide it in all your requests.
Now to the actual meat.
Connecting to the input websocket is done in two steps, of which the first
is obtaining the link to the second. We make a request containing our room id
to /ws-auth (e.g. http://chat.stackoverflow.com/ws-auth), and we receive a JSON
object containing a url property (or something else if there was an error):
Request:
POST http://chat.stackoverflow.com/ws-auth
Content-Length: 47
Content-Type: application/x-www-form-urlencoded
Content: roomid=17&fkey=01234567890123456789012345678901
Response:
Content-Type: application/json; charset=utf-8
Content: {"url":"wss://chat.sockets.stackexchange.com/events/17/..."}
We parse the response, and connect to the websocket at the specified URL. Note
that the websocket URL accepts an `l` query parameter
(...another32CharLongStringBlahBlaah?l=someNumber). It's a number, I'm not sure
what it's supposed to represent exactly, but omitting it brings a lot of history
messages in the first frame, and setting it to a really high value brings no
messages, so we opt to the latter (?l=99999999 or something like that. also note
that it doesn't appear to be a "since message id" parameter, but I may be wrong)
Okay, we've got a connection to the web socket. How does a frame look like?
The simplest one, containing no events, looks like this:
{"r17" : {}}
Just a simple object with the keys being the room's were connected to, each id
prefixed with an "r". But sometimes, even if your room(s) has no traffic, you
may get something like this:
{"r17" : {
"t" : 23531002,
"d" : 3
}}
Again, I have no clue what these mean. I think `d` is short for `delta`, and
maybe `t` is a form of internal timestamp or counter or...I don't know. However,
remember this `t` value for when we discuss polling - it is used there. It does
however seem to be related to how many messages were sent which are not in this
room - so if you're listening to room 17, and someone posted a mesage on room 42
then you'd get a `d` of 1, and the `t` value may be updated by 1. Or maybe not.
The `t` values don't seem to be consistently increasing, or decreasing, or
following any pattern I could recognise.
Anyway! What does a message look like?
{"r1" : {
"e" : [{
"event_type" : 1,
"time_stamp" : 1379405022,
"content" : "test",
"id" : 23531402,
"user_id" : 617762,
"user_name" : "Zirak",
"room_id" : 1,
"room_name" : "Sandbox",
"message_id" : 11832153
}],
"t": 23531402,
"d": 1
}}
We receive an array of events under the property `e` of the respective room.
Each event, called inside the bot a `msgObj` (message object), contains several
interesting properties, which may change according to what kind of event it is.
You can determine the type of the event by checking...drum roll...the event_type
field. 1 is new message, 2 is edit, 3 is user-join, 4 is user-leave, and there
are many others. Also note that pinging a user may add some properties, replying
to a message adds some more, and so forth.
Once we have this array, we simply iterate over it, and decide what we want to
do based on what event it is. But at the end, the adapter's job is to do one
thing - call IO.fire, and pass the torch onwards.
[insert magic about polling. I don't have the web console in front of me, so I
can't stimulate requests]
Now, output! Sending a message is a simple http request, containing the text
and the magical fkey. In the following example, we send a new message to room 1
containing just the word "butts":
Request:
POST http://chat.stackoverflow.com/chats/1/messages/new
text=butts&fkey=01234567890123456789012345678901
Response:
{"id":11832651,"time":1379406464}
And...that's it. Pretty simple. Most of the requests endpoints are like that.
*/
/*global location, WebSocket, setTimeout, module, require*/
/*global fkey, CHAT*/
'use strict';
var IO = require('./IO');
var linkTemplate = '[{text}]({url})';
var adapter = {
// the following two only used in the adapter; you can change & drop at will
roomid: null,
fkey: null,
// used in commands calling the SO API
site: null,
// our user id
userid: null,
maxLineLength: 500,
// not a necessary function, used in here to set some variables
init: function () {
var fkey = document.getElementById('fkey');
if (!fkey) {
console.error('adapter could not find fkey; aborting');
return;
}
this.fkey = fkey.value;
this.roomid = Number(/\d+/.exec(location)[0]);
this.site = this.getCurrentSite();
this.userid = CHAT.CURRENT_USER_ID;
this.in.init();
this.out.init();
},
getCurrentSite: function () {
var site = /chat\.(\w+)/.exec(location)[1];
if (site !== 'stackexchange') {
return site;
}
var siteRoomsLink = document.getElementById('siterooms').href;
// #170. thanks to @patricknc4pk for the original fix.
site = /host=(.+?)\./.exec(siteRoomsLink)[1];
return site;
},
// a pretty crucial function. accepts the msgObj we know nothing about,
// and returns an object with these properties:
// user_name, user_id, room_id, content
// and any other properties, as the abstraction sees fit
// since the bot was designed around the SO chat message object, in this
// case, we simply do nothing
transform: function (msgObj) {
return msgObj;
},
// escape characters meaningful to the chat, such as parentheses
// full list of escaped characters: `*_()[]
escape: function (msg) {
return msg.replace(/([`\*_\(\)\[\]])/g, '\\$1');
},
// receives a username, and returns a string recognized as a reply to the
// user
reply: function (usrname) {
return '@' + usrname.replace(/\s/g, '');
},
// receives a msgid, returns a string recognized as a reply to the specific
// message
directreply: function (msgid) {
return ':' + msgid;
},
// receives text and turns it into a codified version
// codified is ambiguous for a simple reason: it means nicely-aligned and
// mono-spaced. in SO chat, it handles it for us nicely; in others, more
// clever methods may need to be taken
codify: function (msg) {
var tab = ' ',
spacified = msg.replace('\t', tab),
lines = spacified.split(/[\r\n]/g);
if (lines.length === 1) {
return '`' + lines[0] + '`';
}
return lines.map(function (line) {
return tab + line;
}).join('\n');
},
// receives a url and text to display, returns a recognizable link
link: function (text, url) {
return linkTemplate.supplant({
text: this.escape(text),
url: url
});
},
moveMessage: function (msgid, fromRoom, toRoom, cb) {
IO.xhr({
method: 'POST',
url: '/admin/movePosts/' + fromRoom,
data: {
fkey: adapter.fkey,
to: toRoom,
ids: msgid
},
finish: cb || function () {}
});
}
};
// the input is not used by the bot directly, so you can implement it however
// you like
var input = {
// used in the SO chat requests, dunno exactly what for, but guessing it's
// the latest id or something like that. could also be the time last
// sent, which is why I called it times at the beginning. or something.
times: {},
firstPoll: true,
interval: 5000,
init: function (roomid) {
var that = this,
// TODO: this is fucking yucky.
providedRoomid = arguments.length > 0;
roomid = roomid || adapter.roomid;
IO.xhr({
url: '/ws-auth',
data: fkey({
roomid: roomid
}),
method: 'POST',
complete: finish
});
function finish (resp) {
resp = JSON.parse(resp);
console.log(resp);
that.openSocket(resp.url, providedRoomid);
}
},
initialPoll: function () {
console.log('adapter: initial poll');
var roomid = adapter.roomid,
that = this;
IO.xhr({
url: '/chats/' + roomid + '/events/',
data: fkey({
since: 0,
mode: 'Messages',
msgCount: 0
}),
method: 'POST',
complete: finish
});
function finish (resp) {
resp = JSON.parse(resp);
console.log(resp);
that.times['r' + roomid] = resp.time;
that.firstPoll = false;
}
},
openSocket: function (url, discard) {
// chat sends an l query string parameter. seems to be the same as the
// since xhr parameter, but I didn't know what that was either so...
// putting in 0 got the last shitload of messages, so what does a high
// number do? (spoiler: it "works")
var socket = new WebSocket(url + '?l=99999999999');
if (discard) {
socket.onmessage = function () {
socket.close();
};
}
else {
this.socket = socket;
socket.onmessage = this.ondata.bind(this);
socket.onclose = this.socketFail.bind(this);
}
},
ondata: function (messageEvent) {
this.pollComplete(messageEvent.data);
},
poll: function () {
if (this.firstPoll) {
this.initialPoll();
return;
}
var that = this;
IO.xhr({
url: '/events',
data: fkey(that.times),
method: 'POST',
complete: that.pollComplete,
thisArg: that
});
},
pollComplete: function (resp) {
if (!resp) {
return;
}
resp = JSON.parse(resp);
// each key will be in the form of rROOMID