forked from pubnub/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplatform.js
More file actions
490 lines (415 loc) · 13 KB
/
platform.js
File metadata and controls
490 lines (415 loc) · 13 KB
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
/* =-====================================================================-= */
/* =-====================================================================-= */
/* =-========================= UTIL =============================-= */
/* =-====================================================================-= */
/* =-====================================================================-= */
window['PUBNUB'] || (function() {
/**
* UTIL LOCALS
*/
var SWF = 'https://pubnub.a.ssl.fastly.net/pubnub.swf'
, ASYNC = 'async'
, UA = navigator.userAgent
, PNSDK = 'PubNub-JS-' + PLATFORM + '/' + VERSION
, XORIGN = UA.indexOf('MSIE 6') == -1;
/**
* CONSOLE COMPATIBILITY
*/
window.console || (window.console=window.console||{});
console.log || (
console.log =
console.error =
((window.opera||{}).postError||function(){})
);
/**
* LOCAL STORAGE OR COOKIE
*/
var db = (function(){
var ls = window['localStorage'];
return {
'get' : function(key) {
try {
if (ls) return ls.getItem(key);
if (document.cookie.indexOf(key) == -1) return null;
return ((document.cookie||'').match(
RegExp(key+'=([^;]+)')
)||[])[1] || null;
} catch(e) { return }
},
'set' : function( key, value ) {
try {
if (ls) return ls.setItem( key, value ) && 0;
document.cookie = key + '=' + value +
'; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/';
} catch(e) { return }
}
};
})();
function get_hmac_SHA256(data,key) {
var hash = CryptoJS['HmacSHA256'](data, key);
return hash.toString(CryptoJS['enc']['Base64']);
}
/**
* $
* =
* var div = $('divid');
*/
function $(id) { return document.getElementById(id) }
/**
* ERROR
* =====
* error('message');
*/
function error(message) { console['error'](message) }
/**
* SEARCH
* ======
* var elements = search('a div span');
*/
function search( elements, start) {
var list = [];
each( elements.split(/\s+/), function(el) {
each( (start || document).getElementsByTagName(el), function(node) {
list.push(node);
} );
});
return list;
}
function search_old(a) {
var list = [];
each( a.split(/\s+/), function(el) {
each( (document).getElementsByTagName(el), function(node) {
list.push(node);
},1 );
}, 1);
return list;
}
/**
* BIND
* ====
* bind( 'keydown', search('a')[0], function(element) {
* ...
* } );
*/
function bind( type, el, fun ) {
each( type.split(','), function(etype) {
var rapfun = function(e) {
if (!e) e = window.event;
if (!fun(e)) {
e.cancelBubble = true;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
}
};
if ( el.addEventListener ) el.addEventListener( etype, rapfun, false );
else if ( el.attachEvent ) el.attachEvent( 'on' + etype, rapfun );
else el[ 'on' + etype ] = rapfun;
} );
}
/**
* UNBIND
* ======
* unbind( 'keydown', search('a')[0] );
*/
function unbind( type, el, fun ) {
if ( el.removeEventListener ) el.removeEventListener( type, false );
else if ( el.detachEvent ) el.detachEvent( 'on' + type, false );
else el[ 'on' + type ] = null;
}
/**
* HEAD
* ====
* head().appendChild(elm);
*/
function head() { return search_old('head')[0] }
/**
* ATTR
* ====
* var attribute = attr( node, 'attribute' );
*/
function attr( node, attribute, value ) {
if (value) node.setAttribute( attribute, value );
else return node && node.getAttribute && node.getAttribute(attribute);
}
/**
* CSS
* ===
* var obj = create('div');
*/
function css( element, styles ) {
for (var style in styles) if (styles.hasOwnProperty(style))
try {element.style[style] = styles[style] + (
'|width|height|top|left|'.indexOf(style) > 0 &&
typeof styles[style] == 'number'
? 'px' : ''
)}catch(e){}
}
/**
* CREATE
* ======
* var obj = create('div');
*/
function create(element) { return document.createElement(element) }
/**
* jsonp_cb
* ========
* var callback = jsonp_cb();
*/
function jsonp_cb() { return XORIGN || FDomainRequest() ? 0 : unique() }
/**
* EVENTS
* ======
* PUBNUB.events.bind( 'you-stepped-on-flower', function(message) {
* // Do Stuff with message
* } );
*
* PUBNUB.events.fire( 'you-stepped-on-flower', "message-data" );
* PUBNUB.events.fire( 'you-stepped-on-flower', {message:"data"} );
* PUBNUB.events.fire( 'you-stepped-on-flower', [1,2,3] );
*
*/
var events = {
'list' : {},
'unbind' : function( name ) { events.list[name] = [] },
'bind' : function( name, fun ) {
(events.list[name] = events.list[name] || []).push(fun);
},
'fire' : function( name, data ) {
each(
events.list[name] || [],
function(fun) { fun(data) }
);
}
};
/**
* XDR Cross Domain Request
* ========================
* xdr({
* url : ['http://www.blah.com/url'],
* success : function(response) {},
* fail : function() {}
* });
*/
function xdr( setup ) {
if (XORIGN || FDomainRequest()) return ajax(setup);
var script = create('script')
, callback = setup.callback
, id = unique()
, finished = 0
, xhrtme = setup.timeout || DEF_TIMEOUT
, timer = timeout( function(){done(1)}, xhrtme )
, fail = setup.fail || function(){}
, data = setup.data || {}
, success = setup.success || function(){}
, append = function() { head().appendChild(script) }
, done = function( failed, response ) {
if (finished) return;
finished = 1;
script.onerror = null;
clearTimeout(timer);
(failed || !response) || success(response);
timeout( function() {
failed && fail();
var s = $(id)
, p = s && s.parentNode;
p && p.removeChild(s);
}, SECOND );
};
window[callback] = function(response) {
done( 0, response );
};
if (!setup.blocking) script[ASYNC] = ASYNC;
script.onerror = function() { done(1) };
data['pnsdk'] = PNSDK;
script.src = build_url( setup.url, data );
attr( script, 'id', id );
append();
return done;
}
/**
* CORS XHR Request
* ================
* xdr({
* url : ['http://www.blah.com/url'],
* success : function(response) {},
* fail : function() {}
* });
*/
function ajax( setup ) {
var xhr, response
, finished = function() {
if (loaded) return;
loaded = 1;
clearTimeout(timer);
try { response = JSON['parse'](xhr.responseText); }
catch (r) { return done(1); }
complete = 1;
success(response);
}
, complete = 0
, loaded = 0
, xhrtme = setup.timeout || DEF_TIMEOUT
, timer = timeout( function(){done(1)}, xhrtme )
, fail = setup.fail || function(){}
, data = setup.data || {}
, success = setup.success || function(){}
, async = ( typeof(setup.blocking) === 'undefined' )
, done = function(failed,response) {
if (complete) return;
complete = 1;
clearTimeout(timer);
if (xhr) {
xhr.onerror = xhr.onload = null;
xhr.abort && xhr.abort();
xhr = null;
}
failed && fail(response);
};
// Send
try {
xhr = FDomainRequest() ||
window.XDomainRequest &&
new XDomainRequest() ||
new XMLHttpRequest();
xhr.onerror = xhr.onabort = function(){ done(1, xhr.responseText || { "error" : "Network Connection Error"}) };
xhr.onload = xhr.onloadend = finished;
xhr.onreadystatechange = function() {
if (xhr && xhr.readyState == 4) {
switch(xhr.status) {
case 401:
case 402:
case 403:
try {
response = JSON['parse'](xhr.responseText);
done(1,response);
}
catch (r) { return done(1, xhr.responseText); }
break;
default:
break;
}
}
}
if (async) xhr.timeout = xhrtme;
data['pnsdk'] = PNSDK;
var url = build_url(setup.url,data);
xhr.open( 'GET', url, async );
xhr.send();
}
catch(eee) {
done(0);
XORIGN = 0;
return xdr(setup);
}
// Return 'done'
return done;
}
// Test Connection State
function _is_online() {
if (!('onLine' in navigator)) return 1;
return navigator['onLine'];
}
/* =-====================================================================-= */
/* =-====================================================================-= */
/* =-========================= PUBNUB ===========================-= */
/* =-====================================================================-= */
/* =-====================================================================-= */
var PDIV = $('pubnub') || 0
, CREATE_PUBNUB = function(setup) {
// Force JSONP if requested from user.
if (setup['jsonp']) XORIGN = 0;
var SUBSCRIBE_KEY = setup['subscribe_key'] || ''
, KEEPALIVE = (+setup['keepalive'] || DEF_KEEPALIVE) * SECOND
, UUID = setup['uuid'] || db['get'](SUBSCRIBE_KEY+'uuid')||'';
var leave_on_unload = setup['leave_on_unload'] || 0;
setup['xdr'] = xdr;
setup['db'] = db;
setup['error'] = setup['error'] || error;
setup['_is_online'] = _is_online;
setup['jsonp_cb'] = jsonp_cb;
setup['PNSDK'] = PNSDK;
setup['hmac_SHA256']= get_hmac_SHA256;
setup['crypto_obj'] = crypto_obj();
var SELF = function(setup) {
return CREATE_PUBNUB(setup);
};
var PN = PN_API(setup);
for (var prop in PN) {
if (PN.hasOwnProperty(prop)) {
SELF[prop] = PN[prop];
}
}
SELF['css'] = css;
SELF['$'] = $;
SELF['create'] = create;
SELF['bind'] = bind;
SELF['head'] = head;
SELF['search'] = search;
SELF['attr'] = attr;
SELF['events'] = events;
SELF['init'] = SELF;
// Add Leave Functions
bind( 'beforeunload', window, function() {
if (leave_on_unload) SELF['each-channel'](function(ch){ SELF['LEAVE']( ch.name, 0 ) });
return true;
} );
// Return without Testing
if (setup['notest']) return SELF;
bind( 'offline', window, SELF['offline'] );
bind( 'offline', document, SELF['offline'] );
// Return PUBNUB Socket Object
return SELF;
};
CREATE_PUBNUB['init'] = CREATE_PUBNUB;
// Bind for PUBNUB Readiness to Subscribe
if (document.readyState === 'complete') {
timeout( ready, 0 );
}
else {
bind( 'load', window, function(){ timeout( ready, 0 ) } );
}
var pdiv = PDIV || {};
// CREATE A PUBNUB GLOBAL OBJECT
PUBNUB = CREATE_PUBNUB({
'notest' : 1,
'publish_key' : attr( pdiv, 'pub-key' ),
'subscribe_key' : attr( pdiv, 'sub-key' ),
'ssl' : !document.location.href.indexOf('https') ||
attr( pdiv, 'ssl' ) == 'on',
'origin' : attr( pdiv, 'origin' ),
'uuid' : attr( pdiv, 'uuid' )
});
// jQuery Interface
window['jQuery'] && (window['jQuery']['PUBNUB'] = CREATE_PUBNUB);
// For Modern JS + Testling.js - http://testling.com/
typeof(module) !== 'undefined' && (module['exports'] = PUBNUB) && ready();
var pubnubs = $('pubnubs') || 0;
// LEAVE NOW IF NO PDIV.
if (!PDIV) return;
// PUBNUB Flash Socket
css( PDIV, { 'position' : 'absolute', 'top' : -SECOND } );
if ('opera' in window || attr( PDIV, 'flash' )) PDIV['innerHTML'] =
'<object id=pubnubs data=' + SWF +
'><param name=movie value=' + SWF +
'><param name=allowscriptaccess value=always></object>';
// Create Interface for Opera Flash
PUBNUB['rdx'] = function( id, data ) {
if (!data) return FDomainRequest[id]['onerror']();
FDomainRequest[id]['responseText'] = unescape(data);
FDomainRequest[id]['onload']();
};
function FDomainRequest() {
if (!pubnubs || !pubnubs['get']) return 0;
var fdomainrequest = {
'id' : FDomainRequest['id']++,
'send' : function() {},
'abort' : function() { fdomainrequest['id'] = {} },
'open' : function( method, url ) {
FDomainRequest[fdomainrequest['id']] = fdomainrequest;
pubnubs['get']( fdomainrequest['id'], url );
}
};
return fdomainrequest;
}
FDomainRequest['id'] = SECOND;
})();