PageRenderTime 68ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/javascripts/socket.io.js

https://github.com/timstephenson/Dal.io
JavaScript | 3779 lines | 2842 code | 327 blank | 610 comment | 219 complexity | 029c6542c73e125a2557b4a2e39c3856 MD5 | raw file
  1. /*! Socket.IO.js build:0.9.2, development. Copyright(c) 2011 LearnBoost <dev@learnboost.com> MIT Licensed */
  2. /**
  3. * socket.io
  4. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  5. * MIT Licensed
  6. */
  7. (function (exports, global) {
  8. /**
  9. * IO namespace.
  10. *
  11. * @namespace
  12. */
  13. var io = exports;
  14. /**
  15. * Socket.IO version
  16. *
  17. * @api public
  18. */
  19. io.version = '0.9.2';
  20. /**
  21. * Protocol implemented.
  22. *
  23. * @api public
  24. */
  25. io.protocol = 1;
  26. /**
  27. * Available transports, these will be populated with the available transports
  28. *
  29. * @api public
  30. */
  31. io.transports = [];
  32. /**
  33. * Keep track of jsonp callbacks.
  34. *
  35. * @api private
  36. */
  37. io.j = [];
  38. /**
  39. * Keep track of our io.Sockets
  40. *
  41. * @api private
  42. */
  43. io.sockets = {};
  44. /**
  45. * Manages connections to hosts.
  46. *
  47. * @param {String} uri
  48. * @Param {Boolean} force creation of new socket (defaults to false)
  49. * @api public
  50. */
  51. io.connect = function (host, details) {
  52. var uri = io.util.parseUri(host)
  53. , uuri
  54. , socket;
  55. if (global && global.location) {
  56. uri.protocol = uri.protocol || global.location.protocol.slice(0, -1);
  57. uri.host = uri.host || (global.document
  58. ? global.document.domain : global.location.hostname);
  59. uri.port = uri.port || global.location.port;
  60. }
  61. uuri = io.util.uniqueUri(uri);
  62. var options = {
  63. host: uri.host
  64. , secure: 'https' == uri.protocol
  65. , port: uri.port || ('https' == uri.protocol ? 443 : 80)
  66. , query: uri.query || ''
  67. };
  68. io.util.merge(options, details);
  69. if (options['force new connection'] || !io.sockets[uuri]) {
  70. socket = new io.Socket(options);
  71. }
  72. if (!options['force new connection'] && socket) {
  73. io.sockets[uuri] = socket;
  74. }
  75. socket = socket || io.sockets[uuri];
  76. // if path is different from '' or /
  77. return socket.of(uri.path.length > 1 ? uri.path : '');
  78. };
  79. })('object' === typeof module ? module.exports : (this.io = {}), this);
  80. /**
  81. * socket.io
  82. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  83. * MIT Licensed
  84. */
  85. (function (exports, global) {
  86. /**
  87. * Utilities namespace.
  88. *
  89. * @namespace
  90. */
  91. var util = exports.util = {};
  92. /**
  93. * Parses an URI
  94. *
  95. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  96. * @api public
  97. */
  98. var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  99. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
  100. 'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
  101. 'anchor'];
  102. util.parseUri = function (str) {
  103. var m = re.exec(str || '')
  104. , uri = {}
  105. , i = 14;
  106. while (i--) {
  107. uri[parts[i]] = m[i] || '';
  108. }
  109. return uri;
  110. };
  111. /**
  112. * Produces a unique url that identifies a Socket.IO connection.
  113. *
  114. * @param {Object} uri
  115. * @api public
  116. */
  117. util.uniqueUri = function (uri) {
  118. var protocol = uri.protocol
  119. , host = uri.host
  120. , port = uri.port;
  121. if ('document' in global) {
  122. host = host || document.domain;
  123. port = port || (protocol == 'https'
  124. && document.location.protocol !== 'https:' ? 443 : document.location.port);
  125. } else {
  126. host = host || 'localhost';
  127. if (!port && protocol == 'https') {
  128. port = 443;
  129. }
  130. }
  131. return (protocol || 'http') + '://' + host + ':' + (port || 80);
  132. };
  133. /**
  134. * Mergest 2 query strings in to once unique query string
  135. *
  136. * @param {String} base
  137. * @param {String} addition
  138. * @api public
  139. */
  140. util.query = function (base, addition) {
  141. var query = util.chunkQuery(base || '')
  142. , components = [];
  143. util.merge(query, util.chunkQuery(addition || ''));
  144. for (var part in query) {
  145. if (query.hasOwnProperty(part)) {
  146. components.push(part + '=' + query[part]);
  147. }
  148. }
  149. return components.length ? '?' + components.join('&') : '';
  150. };
  151. /**
  152. * Transforms a querystring in to an object
  153. *
  154. * @param {String} qs
  155. * @api public
  156. */
  157. util.chunkQuery = function (qs) {
  158. var query = {}
  159. , params = qs.split('&')
  160. , i = 0
  161. , l = params.length
  162. , kv;
  163. for (; i < l; ++i) {
  164. kv = params[i].split('=');
  165. if (kv[0]) {
  166. query[kv[0]] = kv[1];
  167. }
  168. }
  169. return query;
  170. };
  171. /**
  172. * Executes the given function when the page is loaded.
  173. *
  174. * io.util.load(function () { console.log('page loaded'); });
  175. *
  176. * @param {Function} fn
  177. * @api public
  178. */
  179. var pageLoaded = false;
  180. util.load = function (fn) {
  181. if ('document' in global && document.readyState === 'complete' || pageLoaded) {
  182. return fn();
  183. }
  184. util.on(global, 'load', fn, false);
  185. };
  186. /**
  187. * Adds an event.
  188. *
  189. * @api private
  190. */
  191. util.on = function (element, event, fn, capture) {
  192. if (element.attachEvent) {
  193. element.attachEvent('on' + event, fn);
  194. } else if (element.addEventListener) {
  195. element.addEventListener(event, fn, capture);
  196. }
  197. };
  198. /**
  199. * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
  200. *
  201. * @param {Boolean} [xdomain] Create a request that can be used cross domain.
  202. * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
  203. * @api private
  204. */
  205. util.request = function (xdomain) {
  206. if (xdomain && 'undefined' != typeof XDomainRequest) {
  207. return new XDomainRequest();
  208. }
  209. if ('undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
  210. return new XMLHttpRequest();
  211. }
  212. if (!xdomain) {
  213. try {
  214. return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP');
  215. } catch(e) { }
  216. }
  217. return null;
  218. };
  219. /**
  220. * XHR based transport constructor.
  221. *
  222. * @constructor
  223. * @api public
  224. */
  225. /**
  226. * Change the internal pageLoaded value.
  227. */
  228. if ('undefined' != typeof window) {
  229. util.load(function () {
  230. pageLoaded = true;
  231. });
  232. }
  233. /**
  234. * Defers a function to ensure a spinner is not displayed by the browser
  235. *
  236. * @param {Function} fn
  237. * @api public
  238. */
  239. util.defer = function (fn) {
  240. if (!util.ua.webkit || 'undefined' != typeof importScripts) {
  241. return fn();
  242. }
  243. util.load(function () {
  244. setTimeout(fn, 100);
  245. });
  246. };
  247. /**
  248. * Merges two objects.
  249. *
  250. * @api public
  251. */
  252. util.merge = function merge (target, additional, deep, lastseen) {
  253. var seen = lastseen || []
  254. , depth = typeof deep == 'undefined' ? 2 : deep
  255. , prop;
  256. for (prop in additional) {
  257. if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
  258. if (typeof target[prop] !== 'object' || !depth) {
  259. target[prop] = additional[prop];
  260. seen.push(additional[prop]);
  261. } else {
  262. util.merge(target[prop], additional[prop], depth - 1, seen);
  263. }
  264. }
  265. }
  266. return target;
  267. };
  268. /**
  269. * Merges prototypes from objects
  270. *
  271. * @api public
  272. */
  273. util.mixin = function (ctor, ctor2) {
  274. util.merge(ctor.prototype, ctor2.prototype);
  275. };
  276. /**
  277. * Shortcut for prototypical and static inheritance.
  278. *
  279. * @api private
  280. */
  281. util.inherit = function (ctor, ctor2) {
  282. function f() {};
  283. f.prototype = ctor2.prototype;
  284. ctor.prototype = new f;
  285. };
  286. /**
  287. * Checks if the given object is an Array.
  288. *
  289. * io.util.isArray([]); // true
  290. * io.util.isArray({}); // false
  291. *
  292. * @param Object obj
  293. * @api public
  294. */
  295. util.isArray = Array.isArray || function (obj) {
  296. return Object.prototype.toString.call(obj) === '[object Array]';
  297. };
  298. /**
  299. * Intersects values of two arrays into a third
  300. *
  301. * @api public
  302. */
  303. util.intersect = function (arr, arr2) {
  304. var ret = []
  305. , longest = arr.length > arr2.length ? arr : arr2
  306. , shortest = arr.length > arr2.length ? arr2 : arr;
  307. for (var i = 0, l = shortest.length; i < l; i++) {
  308. if (~util.indexOf(longest, shortest[i]))
  309. ret.push(shortest[i]);
  310. }
  311. return ret;
  312. }
  313. /**
  314. * Array indexOf compatibility.
  315. *
  316. * @see bit.ly/a5Dxa2
  317. * @api public
  318. */
  319. util.indexOf = function (arr, o, i) {
  320. for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
  321. i < j && arr[i] !== o; i++) {}
  322. return j <= i ? -1 : i;
  323. };
  324. /**
  325. * Converts enumerables to array.
  326. *
  327. * @api public
  328. */
  329. util.toArray = function (enu) {
  330. var arr = [];
  331. for (var i = 0, l = enu.length; i < l; i++)
  332. arr.push(enu[i]);
  333. return arr;
  334. };
  335. /**
  336. * UA / engines detection namespace.
  337. *
  338. * @namespace
  339. */
  340. util.ua = {};
  341. /**
  342. * Whether the UA supports CORS for XHR.
  343. *
  344. * @api public
  345. */
  346. util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () {
  347. try {
  348. var a = new XMLHttpRequest();
  349. } catch (e) {
  350. return false;
  351. }
  352. return a.withCredentials != undefined;
  353. })();
  354. /**
  355. * Detect webkit.
  356. *
  357. * @api public
  358. */
  359. util.ua.webkit = 'undefined' != typeof navigator
  360. && /webkit/i.test(navigator.userAgent);
  361. })('undefined' != typeof io ? io : module.exports, this);
  362. /**
  363. * socket.io
  364. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  365. * MIT Licensed
  366. */
  367. (function (exports, io) {
  368. /**
  369. * Expose constructor.
  370. */
  371. exports.EventEmitter = EventEmitter;
  372. /**
  373. * Event emitter constructor.
  374. *
  375. * @api public.
  376. */
  377. function EventEmitter () {};
  378. /**
  379. * Adds a listener
  380. *
  381. * @api public
  382. */
  383. EventEmitter.prototype.on = function (name, fn) {
  384. if (!this.$events) {
  385. this.$events = {};
  386. }
  387. if (!this.$events[name]) {
  388. this.$events[name] = fn;
  389. } else if (io.util.isArray(this.$events[name])) {
  390. this.$events[name].push(fn);
  391. } else {
  392. this.$events[name] = [this.$events[name], fn];
  393. }
  394. return this;
  395. };
  396. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  397. /**
  398. * Adds a volatile listener.
  399. *
  400. * @api public
  401. */
  402. EventEmitter.prototype.once = function (name, fn) {
  403. var self = this;
  404. function on () {
  405. self.removeListener(name, on);
  406. fn.apply(this, arguments);
  407. };
  408. on.listener = fn;
  409. this.on(name, on);
  410. return this;
  411. };
  412. /**
  413. * Removes a listener.
  414. *
  415. * @api public
  416. */
  417. EventEmitter.prototype.removeListener = function (name, fn) {
  418. if (this.$events && this.$events[name]) {
  419. var list = this.$events[name];
  420. if (io.util.isArray(list)) {
  421. var pos = -1;
  422. for (var i = 0, l = list.length; i < l; i++) {
  423. if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
  424. pos = i;
  425. break;
  426. }
  427. }
  428. if (pos < 0) {
  429. return this;
  430. }
  431. list.splice(pos, 1);
  432. if (!list.length) {
  433. delete this.$events[name];
  434. }
  435. } else if (list === fn || (list.listener && list.listener === fn)) {
  436. delete this.$events[name];
  437. }
  438. }
  439. return this;
  440. };
  441. /**
  442. * Removes all listeners for an event.
  443. *
  444. * @api public
  445. */
  446. EventEmitter.prototype.removeAllListeners = function (name) {
  447. // TODO: enable this when node 0.5 is stable
  448. //if (name === undefined) {
  449. //this.$events = {};
  450. //return this;
  451. //}
  452. if (this.$events && this.$events[name]) {
  453. this.$events[name] = null;
  454. }
  455. return this;
  456. };
  457. /**
  458. * Gets all listeners for a certain event.
  459. *
  460. * @api publci
  461. */
  462. EventEmitter.prototype.listeners = function (name) {
  463. if (!this.$events) {
  464. this.$events = {};
  465. }
  466. if (!this.$events[name]) {
  467. this.$events[name] = [];
  468. }
  469. if (!io.util.isArray(this.$events[name])) {
  470. this.$events[name] = [this.$events[name]];
  471. }
  472. return this.$events[name];
  473. };
  474. /**
  475. * Emits an event.
  476. *
  477. * @api public
  478. */
  479. EventEmitter.prototype.emit = function (name) {
  480. if (!this.$events) {
  481. return false;
  482. }
  483. var handler = this.$events[name];
  484. if (!handler) {
  485. return false;
  486. }
  487. var args = Array.prototype.slice.call(arguments, 1);
  488. if ('function' == typeof handler) {
  489. handler.apply(this, args);
  490. } else if (io.util.isArray(handler)) {
  491. var listeners = handler.slice();
  492. for (var i = 0, l = listeners.length; i < l; i++) {
  493. listeners[i].apply(this, args);
  494. }
  495. } else {
  496. return false;
  497. }
  498. return true;
  499. };
  500. })(
  501. 'undefined' != typeof io ? io : module.exports
  502. , 'undefined' != typeof io ? io : module.parent.exports
  503. );
  504. /**
  505. * socket.io
  506. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  507. * MIT Licensed
  508. */
  509. /**
  510. * Based on JSON2 (http://www.JSON.org/js.html).
  511. */
  512. (function (exports, nativeJSON) {
  513. "use strict";
  514. // use native JSON if it's available
  515. if (nativeJSON && nativeJSON.parse){
  516. return exports.JSON = {
  517. parse: nativeJSON.parse
  518. , stringify: nativeJSON.stringify
  519. }
  520. }
  521. var JSON = exports.JSON = {};
  522. function f(n) {
  523. // Format integers to have at least two digits.
  524. return n < 10 ? '0' + n : n;
  525. }
  526. function date(d, key) {
  527. return isFinite(d.valueOf()) ?
  528. d.getUTCFullYear() + '-' +
  529. f(d.getUTCMonth() + 1) + '-' +
  530. f(d.getUTCDate()) + 'T' +
  531. f(d.getUTCHours()) + ':' +
  532. f(d.getUTCMinutes()) + ':' +
  533. f(d.getUTCSeconds()) + 'Z' : null;
  534. };
  535. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  536. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  537. gap,
  538. indent,
  539. meta = { // table of character substitutions
  540. '\b': '\\b',
  541. '\t': '\\t',
  542. '\n': '\\n',
  543. '\f': '\\f',
  544. '\r': '\\r',
  545. '"' : '\\"',
  546. '\\': '\\\\'
  547. },
  548. rep;
  549. function quote(string) {
  550. // If the string contains no control characters, no quote characters, and no
  551. // backslash characters, then we can safely slap some quotes around it.
  552. // Otherwise we must also replace the offending characters with safe escape
  553. // sequences.
  554. escapable.lastIndex = 0;
  555. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  556. var c = meta[a];
  557. return typeof c === 'string' ? c :
  558. '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  559. }) + '"' : '"' + string + '"';
  560. }
  561. function str(key, holder) {
  562. // Produce a string from holder[key].
  563. var i, // The loop counter.
  564. k, // The member key.
  565. v, // The member value.
  566. length,
  567. mind = gap,
  568. partial,
  569. value = holder[key];
  570. // If the value has a toJSON method, call it to obtain a replacement value.
  571. if (value instanceof Date) {
  572. value = date(key);
  573. }
  574. // If we were called with a replacer function, then call the replacer to
  575. // obtain a replacement value.
  576. if (typeof rep === 'function') {
  577. value = rep.call(holder, key, value);
  578. }
  579. // What happens next depends on the value's type.
  580. switch (typeof value) {
  581. case 'string':
  582. return quote(value);
  583. case 'number':
  584. // JSON numbers must be finite. Encode non-finite numbers as null.
  585. return isFinite(value) ? String(value) : 'null';
  586. case 'boolean':
  587. case 'null':
  588. // If the value is a boolean or null, convert it to a string. Note:
  589. // typeof null does not produce 'null'. The case is included here in
  590. // the remote chance that this gets fixed someday.
  591. return String(value);
  592. // If the type is 'object', we might be dealing with an object or an array or
  593. // null.
  594. case 'object':
  595. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  596. // so watch out for that case.
  597. if (!value) {
  598. return 'null';
  599. }
  600. // Make an array to hold the partial results of stringifying this object value.
  601. gap += indent;
  602. partial = [];
  603. // Is the value an array?
  604. if (Object.prototype.toString.apply(value) === '[object Array]') {
  605. // The value is an array. Stringify every element. Use null as a placeholder
  606. // for non-JSON values.
  607. length = value.length;
  608. for (i = 0; i < length; i += 1) {
  609. partial[i] = str(i, value) || 'null';
  610. }
  611. // Join all of the elements together, separated with commas, and wrap them in
  612. // brackets.
  613. v = partial.length === 0 ? '[]' : gap ?
  614. '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
  615. '[' + partial.join(',') + ']';
  616. gap = mind;
  617. return v;
  618. }
  619. // If the replacer is an array, use it to select the members to be stringified.
  620. if (rep && typeof rep === 'object') {
  621. length = rep.length;
  622. for (i = 0; i < length; i += 1) {
  623. if (typeof rep[i] === 'string') {
  624. k = rep[i];
  625. v = str(k, value);
  626. if (v) {
  627. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  628. }
  629. }
  630. }
  631. } else {
  632. // Otherwise, iterate through all of the keys in the object.
  633. for (k in value) {
  634. if (Object.prototype.hasOwnProperty.call(value, k)) {
  635. v = str(k, value);
  636. if (v) {
  637. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  638. }
  639. }
  640. }
  641. }
  642. // Join all of the member texts together, separated with commas,
  643. // and wrap them in braces.
  644. v = partial.length === 0 ? '{}' : gap ?
  645. '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
  646. '{' + partial.join(',') + '}';
  647. gap = mind;
  648. return v;
  649. }
  650. }
  651. // If the JSON object does not yet have a stringify method, give it one.
  652. JSON.stringify = function (value, replacer, space) {
  653. // The stringify method takes a value and an optional replacer, and an optional
  654. // space parameter, and returns a JSON text. The replacer can be a function
  655. // that can replace values, or an array of strings that will select the keys.
  656. // A default replacer method can be provided. Use of the space parameter can
  657. // produce text that is more easily readable.
  658. var i;
  659. gap = '';
  660. indent = '';
  661. // If the space parameter is a number, make an indent string containing that
  662. // many spaces.
  663. if (typeof space === 'number') {
  664. for (i = 0; i < space; i += 1) {
  665. indent += ' ';
  666. }
  667. // If the space parameter is a string, it will be used as the indent string.
  668. } else if (typeof space === 'string') {
  669. indent = space;
  670. }
  671. // If there is a replacer, it must be a function or an array.
  672. // Otherwise, throw an error.
  673. rep = replacer;
  674. if (replacer && typeof replacer !== 'function' &&
  675. (typeof replacer !== 'object' ||
  676. typeof replacer.length !== 'number')) {
  677. throw new Error('JSON.stringify');
  678. }
  679. // Make a fake root object containing our value under the key of ''.
  680. // Return the result of stringifying the value.
  681. return str('', {'': value});
  682. };
  683. // If the JSON object does not yet have a parse method, give it one.
  684. JSON.parse = function (text, reviver) {
  685. // The parse method takes a text and an optional reviver function, and returns
  686. // a JavaScript value if the text is a valid JSON text.
  687. var j;
  688. function walk(holder, key) {
  689. // The walk method is used to recursively walk the resulting structure so
  690. // that modifications can be made.
  691. var k, v, value = holder[key];
  692. if (value && typeof value === 'object') {
  693. for (k in value) {
  694. if (Object.prototype.hasOwnProperty.call(value, k)) {
  695. v = walk(value, k);
  696. if (v !== undefined) {
  697. value[k] = v;
  698. } else {
  699. delete value[k];
  700. }
  701. }
  702. }
  703. }
  704. return reviver.call(holder, key, value);
  705. }
  706. // Parsing happens in four stages. In the first stage, we replace certain
  707. // Unicode characters with escape sequences. JavaScript handles many characters
  708. // incorrectly, either silently deleting them, or treating them as line endings.
  709. text = String(text);
  710. cx.lastIndex = 0;
  711. if (cx.test(text)) {
  712. text = text.replace(cx, function (a) {
  713. return '\\u' +
  714. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  715. });
  716. }
  717. // In the second stage, we run the text against regular expressions that look
  718. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  719. // because they can cause invocation, and '=' because it can cause mutation.
  720. // But just to be safe, we want to reject all unexpected forms.
  721. // We split the second stage into 4 regexp operations in order to work around
  722. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  723. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  724. // replace all simple value tokens with ']' characters. Third, we delete all
  725. // open brackets that follow a colon or comma or that begin the text. Finally,
  726. // we look to see that the remaining characters are only whitespace or ']' or
  727. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  728. if (/^[\],:{}\s]*$/
  729. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  730. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  731. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  732. // In the third stage we use the eval function to compile the text into a
  733. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  734. // in JavaScript: it can begin a block or an object literal. We wrap the text
  735. // in parens to eliminate the ambiguity.
  736. j = eval('(' + text + ')');
  737. // In the optional fourth stage, we recursively walk the new structure, passing
  738. // each name/value pair to a reviver function for possible transformation.
  739. return typeof reviver === 'function' ?
  740. walk({'': j}, '') : j;
  741. }
  742. // If the text is not JSON parseable, then a SyntaxError is thrown.
  743. throw new SyntaxError('JSON.parse');
  744. };
  745. })(
  746. 'undefined' != typeof io ? io : module.exports
  747. , typeof JSON !== 'undefined' ? JSON : undefined
  748. );
  749. /**
  750. * socket.io
  751. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  752. * MIT Licensed
  753. */
  754. (function (exports, io) {
  755. /**
  756. * Parser namespace.
  757. *
  758. * @namespace
  759. */
  760. var parser = exports.parser = {};
  761. /**
  762. * Packet types.
  763. */
  764. var packets = parser.packets = [
  765. 'disconnect'
  766. , 'connect'
  767. , 'heartbeat'
  768. , 'message'
  769. , 'json'
  770. , 'event'
  771. , 'ack'
  772. , 'error'
  773. , 'noop'
  774. ];
  775. /**
  776. * Errors reasons.
  777. */
  778. var reasons = parser.reasons = [
  779. 'transport not supported'
  780. , 'client not handshaken'
  781. , 'unauthorized'
  782. ];
  783. /**
  784. * Errors advice.
  785. */
  786. var advice = parser.advice = [
  787. 'reconnect'
  788. ];
  789. /**
  790. * Shortcuts.
  791. */
  792. var JSON = io.JSON
  793. , indexOf = io.util.indexOf;
  794. /**
  795. * Encodes a packet.
  796. *
  797. * @api private
  798. */
  799. parser.encodePacket = function (packet) {
  800. var type = indexOf(packets, packet.type)
  801. , id = packet.id || ''
  802. , endpoint = packet.endpoint || ''
  803. , ack = packet.ack
  804. , data = null;
  805. switch (packet.type) {
  806. case 'error':
  807. var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
  808. , adv = packet.advice ? indexOf(advice, packet.advice) : '';
  809. if (reason !== '' || adv !== '')
  810. data = reason + (adv !== '' ? ('+' + adv) : '');
  811. break;
  812. case 'message':
  813. if (packet.data !== '')
  814. data = packet.data;
  815. break;
  816. case 'event':
  817. var ev = { name: packet.name };
  818. if (packet.args && packet.args.length) {
  819. ev.args = packet.args;
  820. }
  821. data = JSON.stringify(ev);
  822. break;
  823. case 'json':
  824. data = JSON.stringify(packet.data);
  825. break;
  826. case 'connect':
  827. if (packet.qs)
  828. data = packet.qs;
  829. break;
  830. case 'ack':
  831. data = packet.ackId
  832. + (packet.args && packet.args.length
  833. ? '+' + JSON.stringify(packet.args) : '');
  834. break;
  835. }
  836. // construct packet with required fragments
  837. var encoded = [
  838. type
  839. , id + (ack == 'data' ? '+' : '')
  840. , endpoint
  841. ];
  842. // data fragment is optional
  843. if (data !== null && data !== undefined)
  844. encoded.push(data);
  845. return encoded.join(':');
  846. };
  847. /**
  848. * Encodes multiple messages (payload).
  849. *
  850. * @param {Array} messages
  851. * @api private
  852. */
  853. parser.encodePayload = function (packets) {
  854. var decoded = '';
  855. if (packets.length == 1)
  856. return packets[0];
  857. for (var i = 0, l = packets.length; i < l; i++) {
  858. var packet = packets[i];
  859. decoded += '\ufffd' + packet.length + '\ufffd' + packets[i];
  860. }
  861. return decoded;
  862. };
  863. /**
  864. * Decodes a packet
  865. *
  866. * @api private
  867. */
  868. var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
  869. parser.decodePacket = function (data) {
  870. var pieces = data.match(regexp);
  871. if (!pieces) return {};
  872. var id = pieces[2] || ''
  873. , data = pieces[5] || ''
  874. , packet = {
  875. type: packets[pieces[1]]
  876. , endpoint: pieces[4] || ''
  877. };
  878. // whether we need to acknowledge the packet
  879. if (id) {
  880. packet.id = id;
  881. if (pieces[3])
  882. packet.ack = 'data';
  883. else
  884. packet.ack = true;
  885. }
  886. // handle different packet types
  887. switch (packet.type) {
  888. case 'error':
  889. var pieces = data.split('+');
  890. packet.reason = reasons[pieces[0]] || '';
  891. packet.advice = advice[pieces[1]] || '';
  892. break;
  893. case 'message':
  894. packet.data = data || '';
  895. break;
  896. case 'event':
  897. try {
  898. var opts = JSON.parse(data);
  899. packet.name = opts.name;
  900. packet.args = opts.args;
  901. } catch (e) { }
  902. packet.args = packet.args || [];
  903. break;
  904. case 'json':
  905. try {
  906. packet.data = JSON.parse(data);
  907. } catch (e) { }
  908. break;
  909. case 'connect':
  910. packet.qs = data || '';
  911. break;
  912. case 'ack':
  913. var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
  914. if (pieces) {
  915. packet.ackId = pieces[1];
  916. packet.args = [];
  917. if (pieces[3]) {
  918. try {
  919. packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
  920. } catch (e) { }
  921. }
  922. }
  923. break;
  924. case 'disconnect':
  925. case 'heartbeat':
  926. break;
  927. };
  928. return packet;
  929. };
  930. /**
  931. * Decodes data payload. Detects multiple messages
  932. *
  933. * @return {Array} messages
  934. * @api public
  935. */
  936. parser.decodePayload = function (data) {
  937. // IE doesn't like data[i] for unicode chars, charAt works fine
  938. if (data.charAt(0) == '\ufffd') {
  939. var ret = [];
  940. for (var i = 1, length = ''; i < data.length; i++) {
  941. if (data.charAt(i) == '\ufffd') {
  942. ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
  943. i += Number(length) + 1;
  944. length = '';
  945. } else {
  946. length += data.charAt(i);
  947. }
  948. }
  949. return ret;
  950. } else {
  951. return [parser.decodePacket(data)];
  952. }
  953. };
  954. })(
  955. 'undefined' != typeof io ? io : module.exports
  956. , 'undefined' != typeof io ? io : module.parent.exports
  957. );
  958. /**
  959. * socket.io
  960. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  961. * MIT Licensed
  962. */
  963. (function (exports, io) {
  964. /**
  965. * Expose constructor.
  966. */
  967. exports.Transport = Transport;
  968. /**
  969. * This is the transport template for all supported transport methods.
  970. *
  971. * @constructor
  972. * @api public
  973. */
  974. function Transport (socket, sessid) {
  975. this.socket = socket;
  976. this.sessid = sessid;
  977. };
  978. /**
  979. * Apply EventEmitter mixin.
  980. */
  981. io.util.mixin(Transport, io.EventEmitter);
  982. /**
  983. * Handles the response from the server. When a new response is received
  984. * it will automatically update the timeout, decode the message and
  985. * forwards the response to the onMessage function for further processing.
  986. *
  987. * @param {String} data Response from the server.
  988. * @api private
  989. */
  990. Transport.prototype.onData = function (data) {
  991. this.clearCloseTimeout();
  992. // If the connection in currently open (or in a reopening state) reset the close
  993. // timeout since we have just received data. This check is necessary so
  994. // that we don't reset the timeout on an explicitly disconnected connection.
  995. if (this.socket.connected || this.socket.connecting || this.socket.reconnecting) {
  996. this.setCloseTimeout();
  997. }
  998. if (data !== '') {
  999. // todo: we should only do decodePayload for xhr transports
  1000. var msgs = io.parser.decodePayload(data);
  1001. if (msgs && msgs.length) {
  1002. for (var i = 0, l = msgs.length; i < l; i++) {
  1003. this.onPacket(msgs[i]);
  1004. }
  1005. }
  1006. }
  1007. return this;
  1008. };
  1009. /**
  1010. * Handles packets.
  1011. *
  1012. * @api private
  1013. */
  1014. Transport.prototype.onPacket = function (packet) {
  1015. this.socket.setHeartbeatTimeout();
  1016. if (packet.type == 'heartbeat') {
  1017. return this.onHeartbeat();
  1018. }
  1019. if (packet.type == 'connect' && packet.endpoint == '') {
  1020. this.onConnect();
  1021. }
  1022. this.socket.onPacket(packet);
  1023. return this;
  1024. };
  1025. /**
  1026. * Sets close timeout
  1027. *
  1028. * @api private
  1029. */
  1030. Transport.prototype.setCloseTimeout = function () {
  1031. if (!this.closeTimeout) {
  1032. var self = this;
  1033. this.closeTimeout = setTimeout(function () {
  1034. self.onDisconnect();
  1035. }, this.socket.closeTimeout);
  1036. }
  1037. };
  1038. /**
  1039. * Called when transport disconnects.
  1040. *
  1041. * @api private
  1042. */
  1043. Transport.prototype.onDisconnect = function () {
  1044. if (this.close && this.open) this.close();
  1045. this.clearTimeouts();
  1046. this.socket.onDisconnect();
  1047. return this;
  1048. };
  1049. /**
  1050. * Called when transport connects
  1051. *
  1052. * @api private
  1053. */
  1054. Transport.prototype.onConnect = function () {
  1055. this.socket.onConnect();
  1056. return this;
  1057. }
  1058. /**
  1059. * Clears close timeout
  1060. *
  1061. * @api private
  1062. */
  1063. Transport.prototype.clearCloseTimeout = function () {
  1064. if (this.closeTimeout) {
  1065. clearTimeout(this.closeTimeout);
  1066. this.closeTimeout = null;
  1067. }
  1068. };
  1069. /**
  1070. * Clear timeouts
  1071. *
  1072. * @api private
  1073. */
  1074. Transport.prototype.clearTimeouts = function () {
  1075. this.clearCloseTimeout();
  1076. if (this.reopenTimeout) {
  1077. clearTimeout(this.reopenTimeout);
  1078. }
  1079. };
  1080. /**
  1081. * Sends a packet
  1082. *
  1083. * @param {Object} packet object.
  1084. * @api private
  1085. */
  1086. Transport.prototype.packet = function (packet) {
  1087. this.send(io.parser.encodePacket(packet));
  1088. };
  1089. /**
  1090. * Send the received heartbeat message back to server. So the server
  1091. * knows we are still connected.
  1092. *
  1093. * @param {String} heartbeat Heartbeat response from the server.
  1094. * @api private
  1095. */
  1096. Transport.prototype.onHeartbeat = function (heartbeat) {
  1097. this.packet({ type: 'heartbeat' });
  1098. };
  1099. /**
  1100. * Called when the transport opens.
  1101. *
  1102. * @api private
  1103. */
  1104. Transport.prototype.onOpen = function () {
  1105. this.open = true;
  1106. this.clearCloseTimeout();
  1107. this.socket.onOpen();
  1108. };
  1109. /**
  1110. * Notifies the base when the connection with the Socket.IO server
  1111. * has been disconnected.
  1112. *
  1113. * @api private
  1114. */
  1115. Transport.prototype.onClose = function () {
  1116. var self = this;
  1117. /* FIXME: reopen delay causing a infinit loop
  1118. this.reopenTimeout = setTimeout(function () {
  1119. self.open();
  1120. }, this.socket.options['reopen delay']);*/
  1121. this.open = false;
  1122. this.socket.onClose();
  1123. this.onDisconnect();
  1124. };
  1125. /**
  1126. * Generates a connection url based on the Socket.IO URL Protocol.
  1127. * See <https://github.com/learnboost/socket.io-node/> for more details.
  1128. *
  1129. * @returns {String} Connection url
  1130. * @api private
  1131. */
  1132. Transport.prototype.prepareUrl = function () {
  1133. var options = this.socket.options;
  1134. return this.scheme() + '://'
  1135. + options.host + ':' + options.port + '/'
  1136. + options.resource + '/' + io.protocol
  1137. + '/' + this.name + '/' + this.sessid;
  1138. };
  1139. /**
  1140. * Checks if the transport is ready to start a connection.
  1141. *
  1142. * @param {Socket} socket The socket instance that needs a transport
  1143. * @param {Function} fn The callback
  1144. * @api private
  1145. */
  1146. Transport.prototype.ready = function (socket, fn) {
  1147. fn.call(this);
  1148. };
  1149. })(
  1150. 'undefined' != typeof io ? io : module.exports
  1151. , 'undefined' != typeof io ? io : module.parent.exports
  1152. );
  1153. /**
  1154. * socket.io
  1155. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1156. * MIT Licensed
  1157. */
  1158. (function (exports, io, global) {
  1159. /**
  1160. * Expose constructor.
  1161. */
  1162. exports.Socket = Socket;
  1163. /**
  1164. * Create a new `Socket.IO client` which can establish a persistent
  1165. * connection with a Socket.IO enabled server.
  1166. *
  1167. * @api public
  1168. */
  1169. function Socket (options) {
  1170. this.options = {
  1171. port: 80
  1172. , secure: false
  1173. , document: 'document' in global ? document : false
  1174. , resource: 'socket.io'
  1175. , transports: io.transports
  1176. , 'connect timeout': 10000
  1177. , 'try multiple transports': true
  1178. , 'reconnect': true
  1179. , 'reconnection delay': 500
  1180. , 'reconnection limit': Infinity
  1181. , 'reopen delay': 3000
  1182. , 'max reconnection attempts': 10
  1183. , 'sync disconnect on unload': true
  1184. , 'auto connect': true
  1185. , 'flash policy port': 10843
  1186. };
  1187. io.util.merge(this.options, options);
  1188. this.connected = false;
  1189. this.open = false;
  1190. this.connecting = false;
  1191. this.reconnecting = false;
  1192. this.namespaces = {};
  1193. this.buffer = [];
  1194. this.doBuffer = false;
  1195. if (this.options['sync disconnect on unload'] &&
  1196. (!this.isXDomain() || io.util.ua.hasCORS)) {
  1197. var self = this;
  1198. io.util.on(global, 'beforeunload', function () {
  1199. self.disconnectSync();
  1200. }, false);
  1201. }
  1202. if (this.options['auto connect']) {
  1203. this.connect();
  1204. }
  1205. };
  1206. /**
  1207. * Apply EventEmitter mixin.
  1208. */
  1209. io.util.mixin(Socket, io.EventEmitter);
  1210. /**
  1211. * Returns a namespace listener/emitter for this socket
  1212. *
  1213. * @api public
  1214. */
  1215. Socket.prototype.of = function (name) {
  1216. if (!this.namespaces[name]) {
  1217. this.namespaces[name] = new io.SocketNamespace(this, name);
  1218. if (name !== '') {
  1219. this.namespaces[name].packet({ type: 'connect' });
  1220. }
  1221. }
  1222. return this.namespaces[name];
  1223. };
  1224. /**
  1225. * Emits the given event to the Socket and all namespaces
  1226. *
  1227. * @api private
  1228. */
  1229. Socket.prototype.publish = function () {
  1230. this.emit.apply(this, arguments);
  1231. var nsp;
  1232. for (var i in this.namespaces) {
  1233. if (this.namespaces.hasOwnProperty(i)) {
  1234. nsp = this.of(i);
  1235. nsp.$emit.apply(nsp, arguments);
  1236. }
  1237. }
  1238. };
  1239. /**
  1240. * Performs the handshake
  1241. *
  1242. * @api private
  1243. */
  1244. function empty () { };
  1245. Socket.prototype.handshake = function (fn) {
  1246. var self = this
  1247. , options = this.options;
  1248. function complete (data) {
  1249. if (data instanceof Error) {
  1250. self.onError(data.message);
  1251. } else {
  1252. fn.apply(null, data.split(':'));
  1253. }
  1254. };
  1255. var url = [
  1256. 'http' + (options.secure ? 's' : '') + ':/'
  1257. , options.host + ':' + options.port
  1258. , options.resource
  1259. , io.protocol
  1260. , io.util.query(this.options.query, 't=' + +new Date)
  1261. ].join('/');
  1262. if (this.isXDomain() && !io.util.ua.hasCORS) {
  1263. var insertAt = document.getElementsByTagName('script')[0]
  1264. , script = document.createElement('script');
  1265. script.src = url + '&jsonp=' + io.j.length;
  1266. insertAt.parentNode.insertBefore(script, insertAt);
  1267. io.j.push(function (data) {
  1268. complete(data);
  1269. script.parentNode.removeChild(script);
  1270. });
  1271. } else {
  1272. var xhr = io.util.request();
  1273. xhr.open('GET', url, true);
  1274. xhr.withCredentials = true;
  1275. xhr.onreadystatechange = function () {
  1276. if (xhr.readyState == 4) {
  1277. xhr.onreadystatechange = empty;
  1278. if (xhr.status == 200) {
  1279. complete(xhr.responseText);
  1280. } else {
  1281. !self.reconnecting && self.onError(xhr.responseText);
  1282. }
  1283. }
  1284. };
  1285. xhr.send(null);
  1286. }
  1287. };
  1288. /**
  1289. * Find an available transport based on the options supplied in the constructor.
  1290. *
  1291. * @api private
  1292. */
  1293. Socket.prototype.getTransport = function (override) {
  1294. var transports = override || this.transports, match;
  1295. for (var i = 0, transport; transport = transports[i]; i++) {
  1296. if (io.Transport[transport]
  1297. && io.Transport[transport].check(this)
  1298. && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) {
  1299. return new io.Transport[transport](this, this.sessionid);
  1300. }
  1301. }
  1302. return null;
  1303. };
  1304. /**
  1305. * Connects to the server.
  1306. *
  1307. * @param {Function} [fn] Callback.
  1308. * @returns {io.Socket}
  1309. * @api public
  1310. */
  1311. Socket.prototype.connect = function (fn) {
  1312. if (this.connecting) {
  1313. return this;
  1314. }
  1315. var self = this;
  1316. this.handshake(function (sid, heartbeat, close, transports) {
  1317. self.sessionid = sid;
  1318. self.closeTimeout = close * 1000;
  1319. self.heartbeatTimeout = heartbeat * 1000;
  1320. self.transports = io.util.intersect(
  1321. transports.split(',')
  1322. , self.options.transports
  1323. );
  1324. self.setHeartbeatTimeout();
  1325. function connect (transports){
  1326. if (self.transport) self.transport.clearTimeouts();
  1327. self.transport = self.getTransport(transports);
  1328. if (!self.transport) return self.publish('connect_failed');
  1329. // once the transport is ready
  1330. self.transport.ready(self, function () {
  1331. self.connecting = true;
  1332. self.publish('connecting', self.transport.name);
  1333. self.transport.open();
  1334. if (self.options['connect timeout']) {
  1335. self.connectTimeoutTimer = setTimeout(function () {
  1336. if (!self.connected) {
  1337. self.connecting = false;
  1338. if (self.options['try multiple transports']) {
  1339. if (!self.remainingTransports) {
  1340. self.remainingTransports = self.transports.slice(0);
  1341. }
  1342. var remaining = self.remainingTransports;
  1343. while (remaining.length > 0 && remaining.splice(0,1)[0] !=
  1344. self.transport.name) {}
  1345. if (remaining.length){
  1346. connect(remaining);
  1347. } else {
  1348. self.publish('connect_failed');
  1349. }
  1350. }
  1351. }
  1352. }, self.options['connect timeout']);
  1353. }
  1354. });
  1355. }
  1356. connect(self.options.transports);
  1357. self.once('connect', function (){
  1358. clearTimeout(self.connectTimeoutTimer);
  1359. fn && typeof fn == 'function' && fn();
  1360. });
  1361. });
  1362. return this;
  1363. };
  1364. /**
  1365. * Clears and sets a new heartbeat timeout using the value given by the
  1366. * server during the handshake.
  1367. *
  1368. * @api private
  1369. */
  1370. Socket.prototype.setHeartbeatTimeout = function () {
  1371. clearTimeout(this.heartbeatTimeoutTimer);
  1372. var self = this;
  1373. this.heartbeatTimeoutTimer = setTimeout(function () {
  1374. self.transport.onClose();
  1375. }, this.heartbeatTimeout);
  1376. };
  1377. /**
  1378. * Sends a message.
  1379. *
  1380. * @param {Object} data packet.
  1381. * @returns {io.Socket}
  1382. * @api public
  1383. */
  1384. Socket.prototype.packet = function (data) {
  1385. if (this.connected && !this.doBuffer) {
  1386. this.transport.packet(data);
  1387. } else {
  1388. this.buffer.push(data);
  1389. }
  1390. return this;
  1391. };
  1392. /**
  1393. * Sets buffer state
  1394. *
  1395. * @api private
  1396. */
  1397. Socket.prototype.setBuffer = function (v) {
  1398. this.doBuffer = v;
  1399. if (!v && this.connected && this.buffer.length) {
  1400. this.transport.payload(this.buffer);
  1401. this.buffer = [];
  1402. }
  1403. };
  1404. /**
  1405. * Disconnect the established connect.
  1406. *
  1407. * @returns {io.Socket}
  1408. * @api public
  1409. */
  1410. Socket.prototype.disconnect = function () {
  1411. if (this.connected || this.connecting) {
  1412. if (this.open) {
  1413. this.of('').packet({ type: 'disconnect' });
  1414. }
  1415. // handle disconnection immediately
  1416. this.onDisconnect('booted');
  1417. }
  1418. return this;
  1419. };
  1420. /**
  1421. * Disconnects the socket with a sync XHR.
  1422. *
  1423. * @api private
  1424. */
  1425. Socket.prototype.disconnectSync = function () {
  1426. // ensure disconnection
  1427. var xhr = io.util.request()
  1428. , uri = this.resource + '/' + io.protocol + '/' + this.sessionid;
  1429. xhr.open('GET', uri, true);
  1430. // handle disconnection immediately
  1431. this.onDisconnect('booted');
  1432. };
  1433. /**
  1434. * Check if we need to use cross domain enabled transports. Cross domain would
  1435. * be a different port or different domain name.
  1436. *
  1437. * @returns {Boolean}
  1438. * @api private
  1439. */
  1440. Socket.prototype.isXDomain = function () {
  1441. var port = global.location.port ||
  1442. ('https:' == global.location.protocol ? 443 : 80);
  1443. return this.options.host !== global.location.hostname
  1444. || this.options.port != port;
  1445. };
  1446. /**
  1447. * Called upon handshake.
  1448. *
  1449. * @api private
  1450. */
  1451. Socket.prototype.onConnect = function () {
  1452. if (!this.connected) {
  1453. this.connected = true;
  1454. this.connecting = false;
  1455. if (!this.doBuffer) {
  1456. // make sure to flush the buffer
  1457. this.setBuffer(false);
  1458. }
  1459. this.emit('connect');
  1460. }
  1461. };
  1462. /**
  1463. * Called when the transport opens
  1464. *
  1465. * @api private
  1466. */
  1467. Socket.prototype.onOpen = function () {
  1468. this.open = true;
  1469. };
  1470. /**
  1471. * Called when the transport closes.
  1472. *
  1473. * @api private
  1474. */
  1475. Socket.prototype.onClose = function () {
  1476. this.open = false;
  1477. clearTimeout(this.heartbeatTimeoutTimer);
  1478. };
  1479. /**
  1480. * Called when the transport first opens a connection
  1481. *
  1482. * @param text
  1483. */
  1484. Socket.prototype.onPacket = function (packet) {
  1485. this.of(packet.endpoint).onPacket(packet);
  1486. };
  1487. /**
  1488. * Handles an error.
  1489. *
  1490. * @api private
  1491. */
  1492. Socket.prototype.onError = function (err) {
  1493. if (err && err.advice) {
  1494. if (err.advice === 'reconnect' && (this.connected || this.connecting)) {
  1495. this.disconnect();
  1496. if (this.options.reconnect) {
  1497. this.reconnect();
  1498. }
  1499. }
  1500. }
  1501. this.publish('error', err && err.reason ? err.reason : err);
  1502. };
  1503. /**
  1504. * Called when the transport disconnects.
  1505. *
  1506. * @api private
  1507. */
  1508. Socket.prototype.onDisconnect = function (reason) {
  1509. var wasConnected = this.connected
  1510. , wasConnecting = this.connecting;
  1511. this.connected = false;
  1512. this.connecting = false;
  1513. this.open = false;
  1514. if (wasConnected || wasConnecting) {
  1515. this.transport.close();
  1516. this.transport.clearTimeouts();
  1517. if (wasConnected) {
  1518. this.publish('disconnect', reason);
  1519. if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
  1520. this.reconnect();
  1521. }
  1522. }
  1523. }
  1524. };
  1525. /**
  1526. * Called upon reconnection.
  1527. *
  1528. * @api private
  1529. */
  1530. Socket.prototype.reconnect = function () {
  1531. this.reconnecting = true;
  1532. this.reconnectionAttempts = 0;
  1533. this.reconnectionDelay = this.options['reconnection delay'];
  1534. var self = this
  1535. , maxAttempts = this.options['max reconnection attempts']
  1536. , tryMultiple = this.options['try multiple transports']
  1537. , limit = this.options['reconnection limit'];
  1538. function reset () {
  1539. if (self.connected) {
  1540. for (var i in self.namespaces) {
  1541. if (self.namespaces.hasOwnProperty(i) && '' !== i) {
  1542. self.namespaces[i].packet({ type: 'connect' });
  1543. }
  1544. }
  1545. self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
  1546. }
  1547. clearTimeout(self.reconnectionTimer);
  1548. self.removeListener('connect_failed', maybeReconnect);
  1549. self.removeListener('connect', maybeReconnect);
  1550. self.reconnecting = false;
  1551. delete self.reconnectionAttempts;
  1552. delete self.reconnectionDelay;
  1553. delete self.reconnectionTimer;
  1554. delete self.redoTransports;
  1555. self.options['try multiple transports'] = tryMultiple;
  1556. };
  1557. function maybeReconnect () {
  1558. if (!self.reconnecting) {
  1559. return;
  1560. }
  1561. if (self.connected) {
  1562. return reset();
  1563. };
  1564. if (self.connecting && self.reconnecting) {
  1565. return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
  1566. }
  1567. if (self.reconnectionAttempts++ >= maxAttempts) {
  1568. if (!self.redoTransports) {
  1569. self.on('connect_failed', maybeReconnect);
  1570. self.options['try multiple transports'] = true;
  1571. self.transport = self.getTransport();
  1572. self.redoTransports = true;
  1573. self.connect();
  1574. } else {
  1575. self.publish('reconnect_failed');
  1576. reset();
  1577. }
  1578. } else {
  1579. if (self.reconnectionDelay < limit) {
  1580. self.reconnectionDelay *= 2; // exponential back off
  1581. }
  1582. self.connect();
  1583. self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
  1584. self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
  1585. }
  1586. };
  1587. this.options['try multiple transports'] = false;
  1588. this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
  1589. this.on('connect', maybeReconnect);
  1590. };
  1591. })(
  1592. 'undefined' != typeof io ? io : module.exports
  1593. , 'undefined' != typeof io ? io : module.parent.exports
  1594. , this
  1595. );
  1596. /**
  1597. * socket.io
  1598. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1599. * MIT Licensed
  1600. */
  1601. (function (exports, io) {
  1602. /**
  1603. * Expose constructor.
  1604. */
  1605. exports.SocketNamespace = SocketNamespace;
  1606. /**
  1607. * Socket namespace constructor.
  1608. *
  1609. * @constructor
  1610. * @api public
  1611. */
  1612. function SocketNamespace (socket, name) {
  1613. this.socket = socket;
  1614. this.name = name || '';
  1615. this.flags = {};
  1616. this.json = new Flag(this, 'json');
  1617. this.ackPackets = 0;
  1618. this.acks = {};
  1619. };
  1620. /**
  1621. * Apply EventEmitter mixin.
  1622. */
  1623. io.util.mixin(SocketNamespace, io.EventEmitter);
  1624. /**
  1625. * Copies emit since we override it
  1626. *
  1627. * @api private
  1628. */
  1629. SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
  1630. /**
  1631. * Creates a new namespace, by proxying the request to the socket. This
  1632. * allows us to use the synax as we do on the server.
  1633. *
  1634. * @api public
  1635. */
  1636. SocketNamespace.prototype.of = function () {
  1637. return this.socket.of.apply(this.socket, arguments);
  1638. };
  1639. /**
  1640. * Sends a packet.
  1641. *
  1642. * @api private
  1643. */
  1644. SocketNamespace.prototype.packet = function (packet) {
  1645. packet.endpoint = this.name;
  1646. this.socket.packet(packet);
  1647. this.flags = {};
  1648. return this;
  1649. };
  1650. /**
  1651. * Sends a message
  1652. *
  1653. * @api public
  1654. */
  1655. SocketNamespace.prototype.send = function (data, fn) {
  1656. var packet = {
  1657. type: this.flags.json ? 'json' : 'message'
  1658. , data: data
  1659. };
  1660. if ('function' == typeof fn) {
  1661. packet.id = ++this.ackPackets;
  1662. packet.ack = true;
  1663. this.acks[packet.id] = fn;
  1664. }
  1665. return this.packet(packet);
  1666. };
  1667. /**
  1668. * Emits an event
  1669. *
  1670. * @api public
  1671. */
  1672. SocketNamespace.prototype.emit = function (name) {
  1673. var args = Array.prototype.slice.call(arguments, 1)
  1674. , lastArg = args[args.length - 1]
  1675. , packet = {
  1676. type: 'event'
  1677. , name: name
  1678. };
  1679. if ('function' == typeof lastArg) {
  1680. packet.id = ++this.ackPackets;
  1681. packet.ack = 'data';
  1682. this.acks[packet.id] = lastArg;
  1683. args = args.slice(0, args.length - 1);
  1684. }
  1685. packet.args = args;
  1686. return this.packet(packet);
  1687. };
  1688. /**
  1689. * Disconnects the namespace
  1690. *
  1691. * @api private
  1692. */
  1693. SocketNamespace.prototype.disconnect = function () {
  1694. if (this.name === '') {
  1695. this.socket.disconnect();
  1696. } else {
  1697. this.packet({ type: 'disconnect' });
  1698. this.$emit('disconnect');
  1699. }
  1700. return this;
  1701. };
  1702. /**
  1703. * Handles a packet
  1704. *
  1705. * @api private
  1706. */
  1707. SocketNamespace.prototype.onPacket = function (packet) {
  1708. var self = this;
  1709. function ack () {
  1710. self.packet({
  1711. type: 'ack'
  1712. , args: io.util.toArray(arguments)
  1713. , ackId: packet.id
  1714. });
  1715. };
  1716. switch (packet.type) {
  1717. case 'connect':
  1718. this.$emit('connect');
  1719. break;
  1720. case 'disconnect':
  1721. if (this.name === '') {
  1722. this.socket.onDisconnect(packet.reason || 'booted');
  1723. } else {
  1724. this.$emit('disconnect', packet.reason);
  1725. }
  1726. break;
  1727. case 'message':
  1728. case 'json':
  1729. var params = ['message', packet.data];
  1730. if (packet.ack == 'data') {
  1731. params.push(ack);
  1732. } else if (packet.ack) {
  1733. this.packet({ type: 'ack', ackId: packet.id });
  1734. }
  1735. this.$emit.apply(this, params);
  1736. break;
  1737. case 'event':
  1738. var params = [packet.name].concat(packet.args);
  1739. if (packet.ack == 'data')
  1740. params.push(ack);
  1741. this.$emit.apply(this, params);
  1742. break;
  1743. case 'ack':
  1744. if (this.acks[packet.ackId]) {
  1745. this.acks[packet.ackId].apply(this, packet.args);
  1746. delete this.acks[packet.ackId];
  1747. }
  1748. break;
  1749. case 'error':
  1750. if (packet.advice){
  1751. this.socket.onError(packet);
  1752. } else {
  1753. if (packet.reason == 'unauthorized') {
  1754. this.$emit('connect_failed', packet.reason);
  1755. } else {
  1756. this.$emit('error', packet.reason);
  1757. }
  1758. }
  1759. break;
  1760. }
  1761. };
  1762. /**
  1763. * Flag interface.
  1764. *
  1765. * @api private
  1766. */
  1767. function Flag (nsp, name) {
  1768. this.namespace = nsp;
  1769. this.name = name;
  1770. };
  1771. /**
  1772. * Send a message
  1773. *
  1774. * @api public
  1775. */
  1776. Flag.prototype.send = function () {
  1777. this.namespace.flags[this.name] = true;
  1778. this.namespace.send.apply(this.namespace, arguments);
  1779. };
  1780. /**
  1781. * Emit an event
  1782. *
  1783. * @api public
  1784. */
  1785. Flag.prototype.emit = function () {
  1786. this.namespace.flags[this.name] = true;
  1787. this.namespace.emit.apply(this.namespace, arguments);
  1788. };
  1789. })(
  1790. 'undefined' != typeof io ? io : module.exports
  1791. , 'undefined' != typeof io ? io : module.parent.exports
  1792. );
  1793. /**
  1794. * socket.io
  1795. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1796. * MIT Licensed
  1797. */
  1798. (function (exports, io, global) {
  1799. /**
  1800. * Expose constructor.
  1801. */
  1802. exports.websocket = WS;
  1803. /**
  1804. * The WebSocket transport uses the HTML5 WebSocket API to establish an
  1805. * persistent connection with the Socket.IO server. This transport will also
  1806. * be inherited by the FlashSocket fallback as it provides a API compatible
  1807. * polyfill for the WebSockets.
  1808. *
  1809. * @constructor
  1810. * @extends {io.Transport}
  1811. * @api public
  1812. */
  1813. function WS (socket) {
  1814. io.Transport.apply(this, arguments);
  1815. };
  1816. /**
  1817. * Inherits from Transport.
  1818. */
  1819. io.util.inherit(WS, io.Transport);
  1820. /**
  1821. * Transport name
  1822. *
  1823. * @api public
  1824. */
  1825. WS.prototype.name = 'websocket';
  1826. /**
  1827. * Initializes a new `WebSocket` connection with the Socket.IO server. We attach
  1828. * all the appropriate listeners to handle the responses from the server.
  1829. *
  1830. * @returns {Transport}
  1831. * @api public
  1832. */
  1833. WS.prototype.open = function () {
  1834. var query = io.util.query(this.socket.options.query)
  1835. , self = this
  1836. , Socket
  1837. if (!Socket) {
  1838. Socket = global.MozWebSocket || global.WebSocket;
  1839. }
  1840. this.websocket = new Socket(this.prepareUrl() + query);
  1841. this.websocket.onopen = function () {
  1842. self.onOpen();
  1843. self.socket.setBuffer(false);
  1844. };
  1845. this.websocket.onmessage = function (ev) {
  1846. self.onData(ev.data);
  1847. };
  1848. this.websocket.onclose = function () {
  1849. self.onClose();
  1850. self.socket.setBuffer(true);
  1851. };
  1852. this.websocket.onerror = function (e) {
  1853. self.onError(e);
  1854. };
  1855. return this;
  1856. };
  1857. /**
  1858. * Send a message to the Socket.IO server. The message will automatically be
  1859. * encoded in the correct message format.
  1860. *
  1861. * @returns {Transport}
  1862. * @api public
  1863. */
  1864. WS.prototype.send = function (data) {
  1865. this.websocket.send(data);
  1866. return this;
  1867. };
  1868. /**
  1869. * Payload
  1870. *
  1871. * @api private
  1872. */
  1873. WS.prototype.payload = function (arr) {
  1874. for (var i = 0, l = arr.length; i < l; i++) {
  1875. this.packet(arr[i]);
  1876. }
  1877. return this;
  1878. };
  1879. /**
  1880. * Disconnect the established `WebSocket` connection.
  1881. *
  1882. * @returns {Transport}
  1883. * @api public
  1884. */
  1885. WS.prototype.close = function () {
  1886. this.websocket.close();
  1887. return this;
  1888. };
  1889. /**
  1890. * Handle the errors that `WebSocket` might be giving when we
  1891. * are attempting to connect or send messages.
  1892. *
  1893. * @param {Error} e The error.
  1894. * @api private
  1895. */
  1896. WS.prototype.onError = function (e) {
  1897. this.socket.onError(e);
  1898. };
  1899. /**
  1900. * Returns the appropriate scheme for the URI generation.
  1901. *
  1902. * @api private
  1903. */
  1904. WS.prototype.scheme = function () {
  1905. return this.socket.options.secure ? 'wss' : 'ws';
  1906. };
  1907. /**
  1908. * Checks if the browser has support for native `WebSockets` and that
  1909. * it's not the polyfill created for the FlashSocket transport.
  1910. *
  1911. * @return {Boolean}
  1912. * @api public
  1913. */
  1914. WS.check = function () {
  1915. return ('WebSocket' in global && !('__addTask' in WebSocket))
  1916. || 'MozWebSocket' in global;
  1917. };
  1918. /**
  1919. * Check if the `WebSocket` transport support cross domain communications.
  1920. *
  1921. * @returns {Boolean}
  1922. * @api public
  1923. */
  1924. WS.xdomainCheck = function () {
  1925. return true;
  1926. };
  1927. /**
  1928. * Add the transport to your public io.transports array.
  1929. *
  1930. * @api private
  1931. */
  1932. io.transports.push('websocket');
  1933. })(
  1934. 'undefined' != typeof io ? io.Transport : module.exports
  1935. , 'undefined' != typeof io ? io : module.parent.exports
  1936. , this
  1937. );
  1938. /**
  1939. * socket.io
  1940. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1941. * MIT Licensed
  1942. */
  1943. (function (exports, io) {
  1944. /**
  1945. * Expose constructor.
  1946. */
  1947. exports.flashsocket = Flashsocket;
  1948. /**
  1949. * The FlashSocket transport. This is a API wrapper for the HTML5 WebSocket
  1950. * specification. It uses a .swf file to communicate with the server. If you want
  1951. * to serve the .swf file from a other server than where the Socket.IO script is
  1952. * coming from you need to use the insecure version of the .swf. More information
  1953. * about this can be found on the github page.
  1954. *
  1955. * @constructor
  1956. * @extends {io.Transport.websocket}
  1957. * @api public
  1958. */
  1959. function Flashsocket () {
  1960. io.Transport.websocket.apply(this, arguments);
  1961. };
  1962. /**
  1963. * Inherits from Transport.
  1964. */
  1965. io.util.inherit(Flashsocket, io.Transport.websocket);
  1966. /**
  1967. * Transport name
  1968. *
  1969. * @api public
  1970. */
  1971. Flashsocket.prototype.name = 'flashsocket';
  1972. /**
  1973. * Disconnect the established `FlashSocket` connection. This is done by adding a
  1974. * new task to the FlashSocket. The rest will be handled off by the `WebSocket`
  1975. * transport.
  1976. *
  1977. * @returns {Transport}
  1978. * @api public
  1979. */
  1980. Flashsocket.prototype.open = function () {
  1981. var self = this
  1982. , args = arguments;
  1983. WebSocket.__addTask(function () {
  1984. io.Transport.websocket.prototype.open.apply(self, args);
  1985. });
  1986. return this;
  1987. };
  1988. /**
  1989. * Sends a message to the Socket.IO server. This is done by adding a new
  1990. * task to the FlashSocket. The rest will be handled off by the `WebSocket`
  1991. * transport.
  1992. *
  1993. * @returns {Transport}
  1994. * @api public
  1995. */
  1996. Flashsocket.prototype.send = function () {
  1997. var self = this, args = arguments;
  1998. WebSocket.__addTask(function () {
  1999. io.Transport.websocket.prototype.send.apply(self, args);
  2000. });
  2001. return this;
  2002. };
  2003. /**
  2004. * Disconnects the established `FlashSocket` connection.
  2005. *
  2006. * @returns {Transport}
  2007. * @api public
  2008. */
  2009. Flashsocket.prototype.close = function () {
  2010. WebSocket.__tasks.length = 0;
  2011. io.Transport.websocket.prototype.close.call(this);
  2012. return this;
  2013. };
  2014. /**
  2015. * The WebSocket fall back needs to append the flash container to the body
  2016. * element, so we need to make sure we have access to it. Or defer the call
  2017. * until we are sure there is a body element.
  2018. *
  2019. * @param {Socket} socket The socket instance that needs a transport
  2020. * @param {Function} fn The callback
  2021. * @api private
  2022. */
  2023. Flashsocket.prototype.ready = function (socket, fn) {
  2024. function init () {
  2025. var options = socket.options
  2026. , port = options['flash policy port']
  2027. , path = [
  2028. 'http' + (options.secure ? 's' : '') + ':/'
  2029. , options.host + ':' + options.port
  2030. , options.resource
  2031. , 'static/flashsocket'
  2032. , 'WebSocketMain' + (socket.isXDomain() ? 'Insecure' : '') + '.swf'
  2033. ];
  2034. // Only start downloading the swf file when the checked that this browser
  2035. // actually supports it
  2036. if (!Flashsocket.loaded) {
  2037. if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined') {
  2038. // Set the correct file based on the XDomain settings
  2039. WEB_SOCKET_SWF_LOCATION = path.join('/');
  2040. }
  2041. if (port !== 843) {
  2042. WebSocket.loadFlashPolicyFile('xmlsocket://' + options.host + ':' + port);
  2043. }
  2044. WebSocket.__initialize();
  2045. Flashsocket.loaded = true;
  2046. }
  2047. fn.call(self);
  2048. }
  2049. var self = this;
  2050. if (document.body) return init();
  2051. io.util.load(init);
  2052. };
  2053. /**
  2054. * Check if the FlashSocket transport is supported as it requires that the Adobe
  2055. * Flash Player plug-in version `10.0.0` or greater is installed. And also check if
  2056. * the polyfill is correctly loaded.
  2057. *
  2058. * @returns {Boolean}
  2059. * @api public
  2060. */
  2061. Flashsocket.check = function () {
  2062. if (
  2063. typeof WebSocket == 'undefined'
  2064. || !('__initialize' in WebSocket) || !swfobject
  2065. ) return false;
  2066. return swfobject.getFlashPlayerVersion().major >= 10;
  2067. };
  2068. /**
  2069. * Check if the FlashSocket transport can be used as cross domain / cross origin
  2070. * transport. Because we can't see which type (secure or insecure) of .swf is used
  2071. * we will just return true.
  2072. *
  2073. * @returns {Boolean}
  2074. * @api public
  2075. */
  2076. Flashsocket.xdomainCheck = function () {
  2077. return true;
  2078. };
  2079. /**
  2080. * Disable AUTO_INITIALIZATION
  2081. */
  2082. if (typeof window != 'undefined') {
  2083. WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true;
  2084. }
  2085. /**
  2086. * Add the transport to your public io.transports array.
  2087. *
  2088. * @api private
  2089. */
  2090. io.transports.push('flashsocket');
  2091. })(
  2092. 'undefined' != typeof io ? io.Transport : module.exports
  2093. , 'undefined' != typeof io ? io : module.parent.exports
  2094. );
  2095. /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
  2096. is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  2097. */
  2098. if ('undefined' != typeof window) {
  2099. var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O[(['Active'].concat('Object').join('X'))]!=D){try{var ad=new window[(['Active'].concat('Object').join('X'))](W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?(['Active'].concat('').join('X')):"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
  2100. }
  2101. // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
  2102. // License: New BSD License
  2103. // Reference: http://dev.w3.org/html5/websockets/
  2104. // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
  2105. (function() {
  2106. if ('undefined' == typeof window || window.WebSocket) return;
  2107. var console = window.console;
  2108. if (!console || !console.log || !console.error) {
  2109. console = {log: function(){ }, error: function(){ }};
  2110. }
  2111. if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
  2112. console.error("Flash Player >= 10.0.0 is required.");
  2113. return;
  2114. }
  2115. if (location.protocol == "file:") {
  2116. console.error(
  2117. "WARNING: web-socket-js doesn't work in file:///... URL " +
  2118. "unless you set Flash Security Settings properly. " +
  2119. "Open the page via Web server i.e. http://...");
  2120. }
  2121. /**
  2122. * This class represents a faux web socket.
  2123. * @param {string} url
  2124. * @param {array or string} protocols
  2125. * @param {string} proxyHost
  2126. * @param {int} proxyPort
  2127. * @param {string} headers
  2128. */
  2129. WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
  2130. var self = this;
  2131. self.__id = WebSocket.__nextId++;
  2132. WebSocket.__instances[self.__id] = self;
  2133. self.readyState = WebSocket.CONNECTING;
  2134. self.bufferedAmount = 0;
  2135. self.__events = {};
  2136. if (!protocols) {
  2137. protocols = [];
  2138. } else if (typeof protocols == "string") {
  2139. protocols = [protocols];
  2140. }
  2141. // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
  2142. // Otherwise, when onopen fires immediately, onopen is called before it is set.
  2143. setTimeout(function() {
  2144. WebSocket.__addTask(function() {
  2145. WebSocket.__flash.create(
  2146. self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
  2147. });
  2148. }, 0);
  2149. };
  2150. /**
  2151. * Send data to the web socket.
  2152. * @param {string} data The data to send to the socket.
  2153. * @return {boolean} True for success, false for failure.
  2154. */
  2155. WebSocket.prototype.send = function(data) {
  2156. if (this.readyState == WebSocket.CONNECTING) {
  2157. throw "INVALID_STATE_ERR: Web Socket connection has not been established";
  2158. }
  2159. // We use encodeURIComponent() here, because FABridge doesn't work if
  2160. // the argument includes some characters. We don't use escape() here
  2161. // because of this:
  2162. // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
  2163. // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
  2164. // preserve all Unicode characters either e.g. "\uffff" in Firefox.
  2165. // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
  2166. // additional testing.
  2167. var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
  2168. if (result < 0) { // success
  2169. return true;
  2170. } else {
  2171. this.bufferedAmount += result;
  2172. return false;
  2173. }
  2174. };
  2175. /**
  2176. * Close this web socket gracefully.
  2177. */
  2178. WebSocket.prototype.close = function() {
  2179. if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
  2180. return;
  2181. }
  2182. this.readyState = WebSocket.CLOSING;
  2183. WebSocket.__flash.close(this.__id);
  2184. };
  2185. /**
  2186. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  2187. *
  2188. * @param {string} type
  2189. * @param {function} listener
  2190. * @param {boolean} useCapture
  2191. * @return void
  2192. */
  2193. WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
  2194. if (!(type in this.__events)) {
  2195. this.__events[type] = [];
  2196. }
  2197. this.__events[type].push(listener);
  2198. };
  2199. /**
  2200. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  2201. *
  2202. * @param {string} type
  2203. * @param {function} listener
  2204. * @param {boolean} useCapture
  2205. * @return void
  2206. */
  2207. WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
  2208. if (!(type in this.__events)) return;
  2209. var events = this.__events[type];
  2210. for (var i = events.length - 1; i >= 0; --i) {
  2211. if (events[i] === listener) {
  2212. events.splice(i, 1);
  2213. break;
  2214. }
  2215. }
  2216. };
  2217. /**
  2218. * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
  2219. *
  2220. * @param {Event} event
  2221. * @return void
  2222. */
  2223. WebSocket.prototype.dispatchEvent = function(event) {
  2224. var events = this.__events[event.type] || [];
  2225. for (var i = 0; i < events.length; ++i) {
  2226. events[i](event);
  2227. }
  2228. var handler = this["on" + event.type];
  2229. if (handler) handler(event);
  2230. };
  2231. /**
  2232. * Handles an event from Flash.
  2233. * @param {Object} flashEvent
  2234. */
  2235. WebSocket.prototype.__handleEvent = function(flashEvent) {
  2236. if ("readyState" in flashEvent) {
  2237. this.readyState = flashEvent.readyState;
  2238. }
  2239. if ("protocol" in flashEvent) {
  2240. this.protocol = flashEvent.protocol;
  2241. }
  2242. var jsEvent;
  2243. if (flashEvent.type == "open" || flashEvent.type == "error") {
  2244. jsEvent = this.__createSimpleEvent(flashEvent.type);
  2245. } else if (flashEvent.type == "close") {
  2246. // TODO implement jsEvent.wasClean
  2247. jsEvent = this.__createSimpleEvent("close");
  2248. } else if (flashEvent.type == "message") {
  2249. var data = decodeURIComponent(flashEvent.message);
  2250. jsEvent = this.__createMessageEvent("message", data);
  2251. } else {
  2252. throw "unknown event type: " + flashEvent.type;
  2253. }
  2254. this.dispatchEvent(jsEvent);
  2255. };
  2256. WebSocket.prototype.__createSimpleEvent = function(type) {
  2257. if (document.createEvent && window.Event) {
  2258. var event = document.createEvent("Event");
  2259. event.initEvent(type, false, false);
  2260. return event;
  2261. } else {
  2262. return {type: type, bubbles: false, cancelable: false};
  2263. }
  2264. };
  2265. WebSocket.prototype.__createMessageEvent = function(type, data) {
  2266. if (document.createEvent && window.MessageEvent && !window.opera) {
  2267. var event = document.createEvent("MessageEvent");
  2268. event.initMessageEvent("message", false, false, data, null, null, window, null);
  2269. return event;
  2270. } else {
  2271. // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
  2272. return {type: type, data: data, bubbles: false, cancelable: false};
  2273. }
  2274. };
  2275. /**
  2276. * Define the WebSocket readyState enumeration.
  2277. */
  2278. WebSocket.CONNECTING = 0;
  2279. WebSocket.OPEN = 1;
  2280. WebSocket.CLOSING = 2;
  2281. WebSocket.CLOSED = 3;
  2282. WebSocket.__flash = null;
  2283. WebSocket.__instances = {};
  2284. WebSocket.__tasks = [];
  2285. WebSocket.__nextId = 0;
  2286. /**
  2287. * Load a new flash security policy file.
  2288. * @param {string} url
  2289. */
  2290. WebSocket.loadFlashPolicyFile = function(url){
  2291. WebSocket.__addTask(function() {
  2292. WebSocket.__flash.loadManualPolicyFile(url);
  2293. });
  2294. };
  2295. /**
  2296. * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
  2297. */
  2298. WebSocket.__initialize = function() {
  2299. if (WebSocket.__flash) return;
  2300. if (WebSocket.__swfLocation) {
  2301. // For backword compatibility.
  2302. window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
  2303. }
  2304. if (!window.WEB_SOCKET_SWF_LOCATION) {
  2305. console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
  2306. return;
  2307. }
  2308. var container = document.createElement("div");
  2309. container.id = "webSocketContainer";
  2310. // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
  2311. // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
  2312. // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
  2313. // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
  2314. // the best we can do as far as we know now.
  2315. container.style.position = "absolute";
  2316. if (WebSocket.__isFlashLite()) {
  2317. container.style.left = "0px";
  2318. container.style.top = "0px";
  2319. } else {
  2320. container.style.left = "-100px";
  2321. container.style.top = "-100px";
  2322. }
  2323. var holder = document.createElement("div");
  2324. holder.id = "webSocketFlash";
  2325. container.appendChild(holder);
  2326. document.body.appendChild(container);
  2327. // See this article for hasPriority:
  2328. // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
  2329. swfobject.embedSWF(
  2330. WEB_SOCKET_SWF_LOCATION,
  2331. "webSocketFlash",
  2332. "1" /* width */,
  2333. "1" /* height */,
  2334. "10.0.0" /* SWF version */,
  2335. null,
  2336. null,
  2337. {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
  2338. null,
  2339. function(e) {
  2340. if (!e.success) {
  2341. console.error("[WebSocket] swfobject.embedSWF failed");
  2342. }
  2343. });
  2344. };
  2345. /**
  2346. * Called by Flash to notify JS that it's fully loaded and ready
  2347. * for communication.
  2348. */
  2349. WebSocket.__onFlashInitialized = function() {
  2350. // We need to set a timeout here to avoid round-trip calls
  2351. // to flash during the initialization process.
  2352. setTimeout(function() {
  2353. WebSocket.__flash = document.getElementById("webSocketFlash");
  2354. WebSocket.__flash.setCallerUrl(location.href);
  2355. WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
  2356. for (var i = 0; i < WebSocket.__tasks.length; ++i) {
  2357. WebSocket.__tasks[i]();
  2358. }
  2359. WebSocket.__tasks = [];
  2360. }, 0);
  2361. };
  2362. /**
  2363. * Called by Flash to notify WebSockets events are fired.
  2364. */
  2365. WebSocket.__onFlashEvent = function() {
  2366. setTimeout(function() {
  2367. try {
  2368. // Gets events using receiveEvents() instead of getting it from event object
  2369. // of Flash event. This is to make sure to keep message order.
  2370. // It seems sometimes Flash events don't arrive in the same order as they are sent.
  2371. var events = WebSocket.__flash.receiveEvents();
  2372. for (var i = 0; i < events.length; ++i) {
  2373. WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
  2374. }
  2375. } catch (e) {
  2376. console.error(e);
  2377. }
  2378. }, 0);
  2379. return true;
  2380. };
  2381. // Called by Flash.
  2382. WebSocket.__log = function(message) {
  2383. console.log(decodeURIComponent(message));
  2384. };
  2385. // Called by Flash.
  2386. WebSocket.__error = function(message) {
  2387. console.error(decodeURIComponent(message));
  2388. };
  2389. WebSocket.__addTask = function(task) {
  2390. if (WebSocket.__flash) {
  2391. task();
  2392. } else {
  2393. WebSocket.__tasks.push(task);
  2394. }
  2395. };
  2396. /**
  2397. * Test if the browser is running flash lite.
  2398. * @return {boolean} True if flash lite is running, false otherwise.
  2399. */
  2400. WebSocket.__isFlashLite = function() {
  2401. if (!window.navigator || !window.navigator.mimeTypes) {
  2402. return false;
  2403. }
  2404. var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
  2405. if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
  2406. return false;
  2407. }
  2408. return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  2409. };
  2410. if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
  2411. if (window.addEventListener) {
  2412. window.addEventListener("load", function(){
  2413. WebSocket.__initialize();
  2414. }, false);
  2415. } else {
  2416. window.attachEvent("onload", function(){
  2417. WebSocket.__initialize();
  2418. });
  2419. }
  2420. }
  2421. })();
  2422. /**
  2423. * socket.io
  2424. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2425. * MIT Licensed
  2426. */
  2427. (function (exports, io, global) {
  2428. /**
  2429. * Expose constructor.
  2430. *
  2431. * @api public
  2432. */
  2433. exports.XHR = XHR;
  2434. /**
  2435. * XHR constructor
  2436. *
  2437. * @costructor
  2438. * @api public
  2439. */
  2440. function XHR (socket) {
  2441. if (!socket) return;
  2442. io.Transport.apply(this, arguments);
  2443. this.sendBuffer = [];
  2444. };
  2445. /**
  2446. * Inherits from Transport.
  2447. */
  2448. io.util.inherit(XHR, io.Transport);
  2449. /**
  2450. * Establish a connection
  2451. *
  2452. * @returns {Transport}
  2453. * @api public
  2454. */
  2455. XHR.prototype.open = function () {
  2456. this.socket.setBuffer(false);
  2457. this.onOpen();
  2458. this.get();
  2459. // we need to make sure the request succeeds since we have no indication
  2460. // whether the request opened or not until it succeeded.
  2461. this.setCloseTimeout();
  2462. return this;
  2463. };
  2464. /**
  2465. * Check if we need to send data to the Socket.IO server, if we have data in our
  2466. * buffer we encode it and forward it to the `post` method.
  2467. *
  2468. * @api private
  2469. */
  2470. XHR.prototype.payload = function (payload) {
  2471. var msgs = [];
  2472. for (var i = 0, l = payload.length; i < l; i++) {
  2473. msgs.push(io.parser.encodePacket(payload[i]));
  2474. }
  2475. this.send(io.parser.encodePayload(msgs));
  2476. };
  2477. /**
  2478. * Send data to the Socket.IO server.
  2479. *
  2480. * @param data The message
  2481. * @returns {Transport}
  2482. * @api public
  2483. */
  2484. XHR.prototype.send = function (data) {
  2485. this.post(data);
  2486. return this;
  2487. };
  2488. /**
  2489. * Posts a encoded message to the Socket.IO server.
  2490. *
  2491. * @param {String} data A encoded message.
  2492. * @api private
  2493. */
  2494. function empty () { };
  2495. XHR.prototype.post = function (data) {
  2496. var self = this;
  2497. this.socket.setBuffer(true);
  2498. function stateChange () {
  2499. if (this.readyState == 4) {
  2500. this.onreadystatechange = empty;
  2501. self.posting = false;
  2502. if (this.status == 200){
  2503. self.socket.setBuffer(false);
  2504. } else {
  2505. self.onClose();
  2506. }
  2507. }
  2508. }
  2509. function onload () {
  2510. this.onload = empty;
  2511. self.socket.setBuffer(false);
  2512. };
  2513. this.sendXHR = this.request('POST');
  2514. if (global.XDomainRequest && this.sendXHR instanceof XDomainRequest) {
  2515. this.sendXHR.onload = this.sendXHR.onerror = onload;
  2516. } else {
  2517. this.sendXHR.onreadystatechange = stateChange;
  2518. }
  2519. this.sendXHR.send(data);
  2520. };
  2521. /**
  2522. * Disconnects the established `XHR` connection.
  2523. *
  2524. * @returns {Transport}
  2525. * @api public
  2526. */
  2527. XHR.prototype.close = function () {
  2528. this.onClose();
  2529. return this;
  2530. };
  2531. /**
  2532. * Generates a configured XHR request
  2533. *
  2534. * @param {String} url The url that needs to be requested.
  2535. * @param {String} method The method the request should use.
  2536. * @returns {XMLHttpRequest}
  2537. * @api private
  2538. */
  2539. XHR.prototype.request = function (method) {
  2540. var req = io.util.request(this.socket.isXDomain())
  2541. , query = io.util.query(this.socket.options.query, 't=' + +new Date);
  2542. req.open(method || 'GET', this.prepareUrl() + query, true);
  2543. if (method == 'POST') {
  2544. try {
  2545. if (req.setRequestHeader) {
  2546. req.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  2547. } else {
  2548. // XDomainRequest
  2549. req.contentType = 'text/plain';
  2550. }
  2551. } catch (e) {}
  2552. }
  2553. return req;
  2554. };
  2555. /**
  2556. * Returns the scheme to use for the transport URLs.
  2557. *
  2558. * @api private
  2559. */
  2560. XHR.prototype.scheme = function () {
  2561. return this.socket.options.secure ? 'https' : 'http';
  2562. };
  2563. /**
  2564. * Check if the XHR transports are supported
  2565. *
  2566. * @param {Boolean} xdomain Check if we support cross domain requests.
  2567. * @returns {Boolean}
  2568. * @api public
  2569. */
  2570. XHR.check = function (socket, xdomain) {
  2571. try {
  2572. if (io.util.request(xdomain)) {
  2573. return true;
  2574. }
  2575. } catch(e) {}
  2576. return false;
  2577. };
  2578. /**
  2579. * Check if the XHR transport supports corss domain requests.
  2580. *
  2581. * @returns {Boolean}
  2582. * @api public
  2583. */
  2584. XHR.xdomainCheck = function () {
  2585. return XHR.check(null, true);
  2586. };
  2587. })(
  2588. 'undefined' != typeof io ? io.Transport : module.exports
  2589. , 'undefined' != typeof io ? io : module.parent.exports
  2590. , this
  2591. );
  2592. /**
  2593. * socket.io
  2594. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2595. * MIT Licensed
  2596. */
  2597. (function (exports, io) {
  2598. /**
  2599. * Expose constructor.
  2600. */
  2601. exports.htmlfile = HTMLFile;
  2602. /**
  2603. * The HTMLFile transport creates a `forever iframe` based transport
  2604. * for Internet Explorer. Regular forever iframe implementations will
  2605. * continuously trigger the browsers buzy indicators. If the forever iframe
  2606. * is created inside a `htmlfile` these indicators will not be trigged.
  2607. *
  2608. * @constructor
  2609. * @extends {io.Transport.XHR}
  2610. * @api public
  2611. */
  2612. function HTMLFile (socket) {
  2613. io.Transport.XHR.apply(this, arguments);
  2614. };
  2615. /**
  2616. * Inherits from XHR transport.
  2617. */
  2618. io.util.inherit(HTMLFile, io.Transport.XHR);
  2619. /**
  2620. * Transport name
  2621. *
  2622. * @api public
  2623. */
  2624. HTMLFile.prototype.name = 'htmlfile';
  2625. /**
  2626. * Creates a new Ac...eX `htmlfile` with a forever loading iframe
  2627. * that can be used to listen to messages. Inside the generated
  2628. * `htmlfile` a reference will be made to the HTMLFile transport.
  2629. *
  2630. * @api private
  2631. */
  2632. HTMLFile.prototype.get = function () {
  2633. this.doc = new window[(['Active'].concat('Object').join('X'))]('htmlfile');
  2634. this.doc.open();
  2635. this.doc.write('<html></html>');
  2636. this.doc.close();
  2637. this.doc.parentWindow.s = this;
  2638. var iframeC = this.doc.createElement('div');
  2639. iframeC.className = 'socketio';
  2640. this.doc.body.appendChild(iframeC);
  2641. this.iframe = this.doc.createElement('iframe');
  2642. iframeC.appendChild(this.iframe);
  2643. var self = this
  2644. , query = io.util.query(this.socket.options.query, 't='+ +new Date);
  2645. this.iframe.src = this.prepareUrl() + query;
  2646. io.util.on(window, 'unload', function () {
  2647. self.destroy();
  2648. });
  2649. };
  2650. /**
  2651. * The Socket.IO server will write script tags inside the forever
  2652. * iframe, this function will be used as callback for the incoming
  2653. * information.
  2654. *
  2655. * @param {String} data The message
  2656. * @param {document} doc Reference to the context
  2657. * @api private
  2658. */
  2659. HTMLFile.prototype._ = function (data, doc) {
  2660. this.onData(data);
  2661. try {
  2662. var script = doc.getElementsByTagName('script')[0];
  2663. script.parentNode.removeChild(script);
  2664. } catch (e) { }
  2665. };
  2666. /**
  2667. * Destroy the established connection, iframe and `htmlfile`.
  2668. * And calls the `CollectGarbage` function of Internet Explorer
  2669. * to release the memory.
  2670. *
  2671. * @api private
  2672. */
  2673. HTMLFile.prototype.destroy = function () {
  2674. if (this.iframe){
  2675. try {
  2676. this.iframe.src = 'about:blank';
  2677. } catch(e){}
  2678. this.doc = null;
  2679. this.iframe.parentNode.removeChild(this.iframe);
  2680. this.iframe = null;
  2681. CollectGarbage();
  2682. }
  2683. };
  2684. /**
  2685. * Disconnects the established connection.
  2686. *
  2687. * @returns {Transport} Chaining.
  2688. * @api public
  2689. */
  2690. HTMLFile.prototype.close = function () {
  2691. this.destroy();
  2692. return io.Transport.XHR.prototype.close.call(this);
  2693. };
  2694. /**
  2695. * Checks if the browser supports this transport. The browser
  2696. * must have an `Ac...eXObject` implementation.
  2697. *
  2698. * @return {Boolean}
  2699. * @api public
  2700. */
  2701. HTMLFile.check = function () {
  2702. if (typeof window != "undefined" && (['Active'].concat('Object').join('X')) in window){
  2703. try {
  2704. var a = new window[(['Active'].concat('Object').join('X'))]('htmlfile');
  2705. return a && io.Transport.XHR.check();
  2706. } catch(e){}
  2707. }
  2708. return false;
  2709. };
  2710. /**
  2711. * Check if cross domain requests are supported.
  2712. *
  2713. * @returns {Boolean}
  2714. * @api public
  2715. */
  2716. HTMLFile.xdomainCheck = function () {
  2717. // we can probably do handling for sub-domains, we should
  2718. // test that it's cross domain but a subdomain here
  2719. return false;
  2720. };
  2721. /**
  2722. * Add the transport to your public io.transports array.
  2723. *
  2724. * @api private
  2725. */
  2726. io.transports.push('htmlfile');
  2727. })(
  2728. 'undefined' != typeof io ? io.Transport : module.exports
  2729. , 'undefined' != typeof io ? io : module.parent.exports
  2730. );
  2731. /**
  2732. * socket.io
  2733. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2734. * MIT Licensed
  2735. */
  2736. (function (exports, io, global) {
  2737. /**
  2738. * Expose constructor.
  2739. */
  2740. exports['xhr-polling'] = XHRPolling;
  2741. /**
  2742. * The XHR-polling transport uses long polling XHR requests to create a
  2743. * "persistent" connection with the server.
  2744. *
  2745. * @constructor
  2746. * @api public
  2747. */
  2748. function XHRPolling () {
  2749. io.Transport.XHR.apply(this, arguments);
  2750. };
  2751. /**
  2752. * Inherits from XHR transport.
  2753. */
  2754. io.util.inherit(XHRPolling, io.Transport.XHR);
  2755. /**
  2756. * Merge the properties from XHR transport
  2757. */
  2758. io.util.merge(XHRPolling, io.Transport.XHR);
  2759. /**
  2760. * Transport name
  2761. *
  2762. * @api public
  2763. */
  2764. XHRPolling.prototype.name = 'xhr-polling';
  2765. /**
  2766. * Establish a connection, for iPhone and Android this will be done once the page
  2767. * is loaded.
  2768. *
  2769. * @returns {Transport} Chaining.
  2770. * @api public
  2771. */
  2772. XHRPolling.prototype.open = function () {
  2773. var self = this;
  2774. io.Transport.XHR.prototype.open.call(self);
  2775. return false;
  2776. };
  2777. /**
  2778. * Starts a XHR request to wait for incoming messages.
  2779. *
  2780. * @api private
  2781. */
  2782. function empty () {};
  2783. XHRPolling.prototype.get = function () {
  2784. if (!this.open) return;
  2785. var self = this;
  2786. function stateChange () {
  2787. if (this.readyState == 4) {
  2788. this.onreadystatechange = empty;
  2789. if (this.status == 200) {
  2790. self.onData(this.responseText);
  2791. self.get();
  2792. } else {
  2793. self.onClose();
  2794. }
  2795. }
  2796. };
  2797. function onload () {
  2798. this.onload = empty;
  2799. this.onerror = empty;
  2800. self.onData(this.responseText);
  2801. self.get();
  2802. };
  2803. function onerror () {
  2804. self.onClose();
  2805. };
  2806. this.xhr = this.request();
  2807. if (global.XDomainRequest && this.xhr instanceof XDomainRequest) {
  2808. this.xhr.onload = onload;
  2809. this.xhr.onerror = onerror;
  2810. } else {
  2811. this.xhr.onreadystatechange = stateChange;
  2812. }
  2813. this.xhr.send(null);
  2814. };
  2815. /**
  2816. * Handle the unclean close behavior.
  2817. *
  2818. * @api private
  2819. */
  2820. XHRPolling.prototype.onClose = function () {
  2821. io.Transport.XHR.prototype.onClose.call(this);
  2822. if (this.xhr) {
  2823. this.xhr.onreadystatechange = this.xhr.onload = this.xhr.onerror = empty;
  2824. try {
  2825. this.xhr.abort();
  2826. } catch(e){}
  2827. this.xhr = null;
  2828. }
  2829. };
  2830. /**
  2831. * Webkit based browsers show a infinit spinner when you start a XHR request
  2832. * before the browsers onload event is called so we need to defer opening of
  2833. * the transport until the onload event is called. Wrapping the cb in our
  2834. * defer method solve this.
  2835. *
  2836. * @param {Socket} socket The socket instance that needs a transport
  2837. * @param {Function} fn The callback
  2838. * @api private
  2839. */
  2840. XHRPolling.prototype.ready = function (socket, fn) {
  2841. var self = this;
  2842. io.util.defer(function () {
  2843. fn.call(self);
  2844. });
  2845. };
  2846. /**
  2847. * Add the transport to your public io.transports array.
  2848. *
  2849. * @api private
  2850. */
  2851. io.transports.push('xhr-polling');
  2852. })(
  2853. 'undefined' != typeof io ? io.Transport : module.exports
  2854. , 'undefined' != typeof io ? io : module.parent.exports
  2855. , this
  2856. );
  2857. /**
  2858. * socket.io
  2859. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  2860. * MIT Licensed
  2861. */
  2862. (function (exports, io, global) {
  2863. /**
  2864. * There is a way to hide the loading indicator in Firefox. If you create and
  2865. * remove a iframe it will stop showing the current loading indicator.
  2866. * Unfortunately we can't feature detect that and UA sniffing is evil.
  2867. *
  2868. * @api private
  2869. */
  2870. var indicator = global.document && "MozAppearance" in
  2871. global.document.documentElement.style;
  2872. /**
  2873. * Expose constructor.
  2874. */
  2875. exports['jsonp-polling'] = JSONPPolling;
  2876. /**
  2877. * The JSONP transport creates an persistent connection by dynamically
  2878. * inserting a script tag in the page. This script tag will receive the
  2879. * information of the Socket.IO server. When new information is received
  2880. * it creates a new script tag for the new data stream.
  2881. *
  2882. * @constructor
  2883. * @extends {io.Transport.xhr-polling}
  2884. * @api public
  2885. */
  2886. function JSONPPolling (socket) {
  2887. io.Transport['xhr-polling'].apply(this, arguments);
  2888. this.index = io.j.length;
  2889. var self = this;
  2890. io.j.push(function (msg) {
  2891. self._(msg);
  2892. });
  2893. };
  2894. /**
  2895. * Inherits from XHR polling transport.
  2896. */
  2897. io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
  2898. /**
  2899. * Transport name
  2900. *
  2901. * @api public
  2902. */
  2903. JSONPPolling.prototype.name = 'jsonp-polling';
  2904. /**
  2905. * Posts a encoded message to the Socket.IO server using an iframe.
  2906. * The iframe is used because script tags can create POST based requests.
  2907. * The iframe is positioned outside of the view so the user does not
  2908. * notice it's existence.
  2909. *
  2910. * @param {String} data A encoded message.
  2911. * @api private
  2912. */
  2913. JSONPPolling.prototype.post = function (data) {
  2914. var self = this
  2915. , query = io.util.query(
  2916. this.socket.options.query
  2917. , 't='+ (+new Date) + '&i=' + this.index
  2918. );
  2919. if (!this.form) {
  2920. var form = document.createElement('form')
  2921. , area = document.createElement('textarea')
  2922. , id = this.iframeId = 'socketio_iframe_' + this.index
  2923. , iframe;
  2924. form.className = 'socketio';
  2925. form.style.position = 'absolute';
  2926. form.style.top = '-1000px';
  2927. form.style.left = '-1000px';
  2928. form.target = id;
  2929. form.method = 'POST';
  2930. form.setAttribute('accept-charset', 'utf-8');
  2931. area.name = 'd';
  2932. form.appendChild(area);
  2933. document.body.appendChild(form);
  2934. this.form = form;
  2935. this.area = area;
  2936. }
  2937. this.form.action = this.prepareUrl() + query;
  2938. function complete () {
  2939. initIframe();
  2940. self.socket.setBuffer(false);
  2941. };
  2942. function initIframe () {
  2943. if (self.iframe) {
  2944. self.form.removeChild(self.iframe);
  2945. }
  2946. try {
  2947. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2948. iframe = document.createElement('<iframe name="'+ self.iframeId +'">');
  2949. } catch (e) {
  2950. iframe = document.createElement('iframe');
  2951. iframe.name = self.iframeId;
  2952. }
  2953. iframe.id = self.iframeId;
  2954. self.form.appendChild(iframe);
  2955. self.iframe = iframe;
  2956. };
  2957. initIframe();
  2958. // we temporarily stringify until we figure out how to prevent
  2959. // browsers from turning `\n` into `\r\n` in form inputs
  2960. this.area.value = io.JSON.stringify(data);
  2961. try {
  2962. this.form.submit();
  2963. } catch(e) {}
  2964. if (this.iframe.attachEvent) {
  2965. iframe.onreadystatechange = function () {
  2966. if (self.iframe.readyState == 'complete') {
  2967. complete();
  2968. }
  2969. };
  2970. } else {
  2971. this.iframe.onload = complete;
  2972. }
  2973. this.socket.setBuffer(true);
  2974. };
  2975. /**
  2976. * Creates a new JSONP poll that can be used to listen
  2977. * for messages from the Socket.IO server.
  2978. *
  2979. * @api private
  2980. */
  2981. JSONPPolling.prototype.get = function () {
  2982. var self = this
  2983. , script = document.createElement('script')
  2984. , query = io.util.query(
  2985. this.socket.options.query
  2986. , 't='+ (+new Date) + '&i=' + this.index
  2987. );
  2988. if (this.script) {
  2989. this.script.parentNode.removeChild(this.script);
  2990. this.script = null;
  2991. }
  2992. script.async = true;
  2993. script.src = this.prepareUrl() + query;
  2994. script.onerror = function () {
  2995. self.onClose();
  2996. };
  2997. var insertAt = document.getElementsByTagName('script')[0]
  2998. insertAt.parentNode.insertBefore(script, insertAt);
  2999. this.script = script;
  3000. if (indicator) {
  3001. setTimeout(function () {
  3002. var iframe = document.createElement('iframe');
  3003. document.body.appendChild(iframe);
  3004. document.body.removeChild(iframe);
  3005. }, 100);
  3006. }
  3007. };
  3008. /**
  3009. * Callback function for the incoming message stream from the Socket.IO server.
  3010. *
  3011. * @param {String} data The message
  3012. * @api private
  3013. */
  3014. JSONPPolling.prototype._ = function (msg) {
  3015. this.onData(msg);
  3016. if (this.open) {
  3017. this.get();
  3018. }
  3019. return this;
  3020. };
  3021. /**
  3022. * The indicator hack only works after onload
  3023. *
  3024. * @param {Socket} socket The socket instance that needs a transport
  3025. * @param {Function} fn The callback
  3026. * @api private
  3027. */
  3028. JSONPPolling.prototype.ready = function (socket, fn) {
  3029. var self = this;
  3030. if (!indicator) return fn.call(this);
  3031. io.util.load(function () {
  3032. fn.call(self);
  3033. });
  3034. };
  3035. /**
  3036. * Checks if browser supports this transport.
  3037. *
  3038. * @return {Boolean}
  3039. * @api public
  3040. */
  3041. JSONPPolling.check = function () {
  3042. return 'document' in global;
  3043. };
  3044. /**
  3045. * Check if cross domain requests are supported
  3046. *
  3047. * @returns {Boolean}
  3048. * @api public
  3049. */
  3050. JSONPPolling.xdomainCheck = function () {
  3051. return true;
  3052. };
  3053. /**
  3054. * Add the transport to your public io.transports array.
  3055. *
  3056. * @api private
  3057. */
  3058. io.transports.push('jsonp-polling');
  3059. })(
  3060. 'undefined' != typeof io ? io.Transport : module.exports
  3061. , 'undefined' != typeof io ? io : module.parent.exports
  3062. , this
  3063. );