This repository has been archived by the owner on Aug 5, 2020. It is now read-only.
forked from Zirak/SO-ChatBot
/
IO.js
394 lines (316 loc) · 8.6 KB
/
IO.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
var IO = window.IO = {
//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; //will be filled in the following line
//#build static/htmlEntities.js
/*
& -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;
}
var i = this.buffer.length;
while( i --> 0 ) {
this.tick();
}
IO.fire( 'after' + fullName );
this.buffer = [];
return this;
}
};
});
//a very incomplete circular-buffer implementation, used for the bored responses
IO.CBuffer = function ( size ) {
var ret = {
items : [],
pos : 0,
size : size
};
ret.add = function ( item ) {
if ( this.pos === size ) {
this.pos = 0;
}
this.items[ this.pos ] = item;
this.pos += 1;
};
ret.contains = function ( item ) {
return this.items.indexOf( item ) > -1;
};
return ret;
};
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 );
}
var xhr = new XMLHttpRequest();
xhr.open( params.method, params.url );
xhr.addEventListener( 'readystatechange', function () {
if ( xhr.readyState === 4 ) {
params.complete.call(
params.thisArg, xhr.responseText, xhr
);
}
});
Object.iterate( params.headers, function ( header, value ) {
xhr.setRequestHeader( header, value );
});
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.jsonp.image = function ( query, cb, number ) {
IO.jsonp({
url : 'https://www.googleapis.com/customsearch/v1',
jsonpName : 'callback',
data : {
q : query,
searchType: "image",
key: 'AIzaSyAHOOk144Q4ZQyRA0rxlmC8iZduc31Dnbo',
cx: '009867671278203221224:g1mxqhphcsk',
num: number,
safe: 'high'
},
fun : cb
});
};