socket.io.js 99 KB

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