jquery.signalR-2.4.0.js 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119
  1. /* jquery.signalR.core.js */
  2. /*global window:false */
  3. /*!
  4. * ASP.NET SignalR JavaScript Library 2.4.0
  5. * http://signalr.net/
  6. *
  7. * Copyright (c) .NET Foundation. All rights reserved.
  8. * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  9. *
  10. */
  11. /// <reference path="Scripts/jquery-1.6.4.js" />
  12. /// <reference path="jquery.signalR.version.js" />
  13. (function ($, window, undefined) {
  14. var resources = {
  15. nojQuery: "jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.",
  16. noTransportOnInit: "No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.",
  17. errorOnNegotiate: "Error during negotiation request.",
  18. stoppedWhileLoading: "The connection was stopped during page load.",
  19. stoppedWhileNegotiating: "The connection was stopped during the negotiate request.",
  20. errorParsingNegotiateResponse: "Error parsing negotiate response.",
  21. errorRedirectionExceedsLimit: "Negotiate redirection limit exceeded.",
  22. errorDuringStartRequest: "Error during start request. Stopping the connection.",
  23. errorFromServer: "Error message received from the server: '{0}'.",
  24. stoppedDuringStartRequest: "The connection was stopped during the start request.",
  25. errorParsingStartResponse: "Error parsing start response: '{0}'. Stopping the connection.",
  26. invalidStartResponse: "Invalid start response: '{0}'. Stopping the connection.",
  27. protocolIncompatible: "You are using a version of the client that isn't compatible with the server. Client version {0}, server version {1}.",
  28. aspnetCoreSignalrServer: "Detected a connection attempt to an ASP.NET Core SignalR Server. This client only supports connecting to an ASP.NET SignalR Server. See https://aka.ms/signalr-core-differences for details.",
  29. sendFailed: "Send failed.",
  30. parseFailed: "Failed at parsing response: {0}",
  31. longPollFailed: "Long polling request failed.",
  32. eventSourceFailedToConnect: "EventSource failed to connect.",
  33. eventSourceError: "Error raised by EventSource",
  34. webSocketClosed: "WebSocket closed.",
  35. pingServerFailedInvalidResponse: "Invalid ping response when pinging server: '{0}'.",
  36. pingServerFailed: "Failed to ping server.",
  37. pingServerFailedStatusCode: "Failed to ping server. Server responded with status code {0}, stopping the connection.",
  38. pingServerFailedParse: "Failed to parse ping server response, stopping the connection.",
  39. noConnectionTransport: "Connection is in an invalid state, there is no transport active.",
  40. webSocketsInvalidState: "The Web Socket transport is in an invalid state, transitioning into reconnecting.",
  41. reconnectTimeout: "Couldn't reconnect within the configured timeout of {0} ms, disconnecting.",
  42. reconnectWindowTimeout: "The client has been inactive since {0} and it has exceeded the inactivity timeout of {1} ms. Stopping the connection.",
  43. jsonpNotSupportedWithAccessToken: "The JSONP protocol does not support connections that require a Bearer token to connect, such as the Azure SignalR Service."
  44. };
  45. if (typeof ($) !== "function") {
  46. // no jQuery!
  47. throw new Error(resources.nojQuery);
  48. }
  49. var signalR,
  50. _connection,
  51. _pageLoaded = (window.document.readyState === "complete"),
  52. _pageWindow = $(window),
  53. _negotiateAbortText = "__Negotiate Aborted__",
  54. events = {
  55. onStart: "onStart",
  56. onStarting: "onStarting",
  57. onReceived: "onReceived",
  58. onError: "onError",
  59. onConnectionSlow: "onConnectionSlow",
  60. onReconnecting: "onReconnecting",
  61. onReconnect: "onReconnect",
  62. onStateChanged: "onStateChanged",
  63. onDisconnect: "onDisconnect"
  64. },
  65. ajaxDefaults = {
  66. processData: true,
  67. timeout: null,
  68. async: true,
  69. global: false,
  70. cache: false
  71. },
  72. log = function (msg, logging) {
  73. if (logging === false) {
  74. return;
  75. }
  76. var m;
  77. if (typeof (window.console) === "undefined") {
  78. return;
  79. }
  80. m = "[" + new Date().toTimeString() + "] SignalR: " + msg;
  81. if (window.console.debug) {
  82. window.console.debug(m);
  83. } else if (window.console.log) {
  84. window.console.log(m);
  85. }
  86. },
  87. changeState = function (connection, expectedState, newState) {
  88. if (expectedState === connection.state) {
  89. connection.state = newState;
  90. $(connection).triggerHandler(events.onStateChanged, [{ oldState: expectedState, newState: newState }]);
  91. return true;
  92. }
  93. return false;
  94. },
  95. isDisconnecting = function (connection) {
  96. return connection.state === signalR.connectionState.disconnected;
  97. },
  98. supportsKeepAlive = function (connection) {
  99. return connection._.keepAliveData.activated &&
  100. connection.transport.supportsKeepAlive(connection);
  101. },
  102. configureStopReconnectingTimeout = function (connection) {
  103. var stopReconnectingTimeout,
  104. onReconnectTimeout;
  105. // Check if this connection has already been configured to stop reconnecting after a specified timeout.
  106. // Without this check if a connection is stopped then started events will be bound multiple times.
  107. if (!connection._.configuredStopReconnectingTimeout) {
  108. onReconnectTimeout = function (connection) {
  109. var message = signalR._.format(signalR.resources.reconnectTimeout, connection.disconnectTimeout);
  110. connection.log(message);
  111. $(connection).triggerHandler(events.onError, [signalR._.error(message, /* source */ "TimeoutException")]);
  112. connection.stop(/* async */ false, /* notifyServer */ false);
  113. };
  114. connection.reconnecting(function () {
  115. var connection = this;
  116. // Guard against state changing in a previous user defined even handler
  117. if (connection.state === signalR.connectionState.reconnecting) {
  118. stopReconnectingTimeout = window.setTimeout(function () { onReconnectTimeout(connection); }, connection.disconnectTimeout);
  119. }
  120. });
  121. connection.stateChanged(function (data) {
  122. if (data.oldState === signalR.connectionState.reconnecting) {
  123. // Clear the pending reconnect timeout check
  124. window.clearTimeout(stopReconnectingTimeout);
  125. }
  126. });
  127. connection._.configuredStopReconnectingTimeout = true;
  128. }
  129. };
  130. signalR = function (url, qs, logging) {
  131. /// <summary>Creates a new SignalR connection for the given url</summary>
  132. /// <param name="url" type="String">The URL of the long polling endpoint</param>
  133. /// <param name="qs" type="Object">
  134. /// [Optional] Custom querystring parameters to add to the connection URL.
  135. /// If an object, every non-function member will be added to the querystring.
  136. /// If a string, it's added to the QS as specified.
  137. /// </param>
  138. /// <param name="logging" type="Boolean">
  139. /// [Optional] A flag indicating whether connection logging is enabled to the browser
  140. /// console/log. Defaults to false.
  141. /// </param>
  142. return new signalR.fn.init(url, qs, logging);
  143. };
  144. signalR._ = {
  145. defaultContentType: "application/x-www-form-urlencoded; charset=UTF-8",
  146. ieVersion: (function () {
  147. var version,
  148. matches;
  149. if (window.navigator.appName === 'Microsoft Internet Explorer') {
  150. // Check if the user agent has the pattern "MSIE (one or more numbers).(one or more numbers)";
  151. matches = /MSIE ([0-9]+\.[0-9]+)/.exec(window.navigator.userAgent);
  152. if (matches) {
  153. version = window.parseFloat(matches[1]);
  154. }
  155. }
  156. // undefined value means not IE
  157. return version;
  158. })(),
  159. error: function (message, source, context) {
  160. var e = new Error(message);
  161. e.source = source;
  162. if (typeof context !== "undefined") {
  163. e.context = context;
  164. }
  165. return e;
  166. },
  167. transportError: function (message, transport, source, context) {
  168. var e = this.error(message, source, context);
  169. e.transport = transport ? transport.name : undefined;
  170. return e;
  171. },
  172. format: function () {
  173. /// <summary>Usage: format("Hi {0}, you are {1}!", "Foo", 100) </summary>
  174. var s = arguments[0];
  175. for (var i = 0; i < arguments.length - 1; i++) {
  176. s = s.replace("{" + i + "}", arguments[i + 1]);
  177. }
  178. return s;
  179. },
  180. firefoxMajorVersion: function (userAgent) {
  181. // Firefox user agents: http://useragentstring.com/pages/Firefox/
  182. var matches = userAgent.match(/Firefox\/(\d+)/);
  183. if (!matches || !matches.length || matches.length < 2) {
  184. return 0;
  185. }
  186. return parseInt(matches[1], 10 /* radix */);
  187. },
  188. configurePingInterval: function (connection) {
  189. var config = connection._.config,
  190. onFail = function (error) {
  191. $(connection).triggerHandler(events.onError, [error]);
  192. };
  193. if (config && !connection._.pingIntervalId && config.pingInterval) {
  194. connection._.pingIntervalId = window.setInterval(function () {
  195. signalR.transports._logic.pingServer(connection).fail(onFail);
  196. }, config.pingInterval);
  197. }
  198. }
  199. };
  200. signalR.events = events;
  201. signalR.resources = resources;
  202. signalR.ajaxDefaults = ajaxDefaults;
  203. signalR.changeState = changeState;
  204. signalR.isDisconnecting = isDisconnecting;
  205. signalR.connectionState = {
  206. connecting: 0,
  207. connected: 1,
  208. reconnecting: 2,
  209. disconnected: 4
  210. };
  211. signalR.hub = {
  212. start: function () {
  213. // This will get replaced with the real hub connection start method when hubs is referenced correctly
  214. throw new Error("SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/js'></script>.");
  215. }
  216. };
  217. // .on() was added in version 1.7.0, .load() was removed in version 3.0.0 so we fallback to .load() if .on() does
  218. // not exist to not break existing applications
  219. if (typeof _pageWindow.on == "function") {
  220. _pageWindow.on("load", function () { _pageLoaded = true; });
  221. }
  222. else {
  223. _pageWindow.load(function () { _pageLoaded = true; });
  224. }
  225. function validateTransport(requestedTransport, connection) {
  226. /// <summary>Validates the requested transport by cross checking it with the pre-defined signalR.transports</summary>
  227. /// <param name="requestedTransport" type="Object">The designated transports that the user has specified.</param>
  228. /// <param name="connection" type="signalR">The connection that will be using the requested transports. Used for logging purposes.</param>
  229. /// <returns type="Object" />
  230. if ($.isArray(requestedTransport)) {
  231. // Go through transport array and remove an "invalid" tranports
  232. for (var i = requestedTransport.length - 1; i >= 0; i--) {
  233. var transport = requestedTransport[i];
  234. if ($.type(transport) !== "string" || !signalR.transports[transport]) {
  235. connection.log("Invalid transport: " + transport + ", removing it from the transports list.");
  236. requestedTransport.splice(i, 1);
  237. }
  238. }
  239. // Verify we still have transports left, if we dont then we have invalid transports
  240. if (requestedTransport.length === 0) {
  241. connection.log("No transports remain within the specified transport array.");
  242. requestedTransport = null;
  243. }
  244. } else if (!signalR.transports[requestedTransport] && requestedTransport !== "auto") {
  245. connection.log("Invalid transport: " + requestedTransport.toString() + ".");
  246. requestedTransport = null;
  247. } else if (requestedTransport === "auto" && signalR._.ieVersion <= 8) {
  248. // If we're doing an auto transport and we're IE8 then force longPolling, #1764
  249. return ["longPolling"];
  250. }
  251. return requestedTransport;
  252. }
  253. function getDefaultPort(protocol) {
  254. if (protocol === "http:") {
  255. return 80;
  256. } else if (protocol === "https:") {
  257. return 443;
  258. }
  259. }
  260. function addDefaultPort(protocol, url) {
  261. // Remove ports from url. We have to check if there's a / or end of line
  262. // following the port in order to avoid removing ports such as 8080.
  263. if (url.match(/:\d+$/)) {
  264. return url;
  265. } else {
  266. return url + ":" + getDefaultPort(protocol);
  267. }
  268. }
  269. function ConnectingMessageBuffer(connection, drainCallback) {
  270. var that = this,
  271. buffer = [];
  272. that.tryBuffer = function (message) {
  273. if (connection.state === $.signalR.connectionState.connecting) {
  274. buffer.push(message);
  275. return true;
  276. }
  277. return false;
  278. };
  279. that.drain = function () {
  280. // Ensure that the connection is connected when we drain (do not want to drain while a connection is not active)
  281. if (connection.state === $.signalR.connectionState.connected) {
  282. while (buffer.length > 0) {
  283. drainCallback(buffer.shift());
  284. }
  285. }
  286. };
  287. that.clear = function () {
  288. buffer = [];
  289. };
  290. }
  291. signalR.fn = signalR.prototype = {
  292. init: function (url, qs, logging) {
  293. var $connection = $(this);
  294. this.url = url;
  295. this.qs = qs;
  296. this.lastError = null;
  297. this._ = {
  298. keepAliveData: {},
  299. connectingMessageBuffer: new ConnectingMessageBuffer(this, function (message) {
  300. $connection.triggerHandler(events.onReceived, [message]);
  301. }),
  302. lastMessageAt: new Date().getTime(),
  303. lastActiveAt: new Date().getTime(),
  304. beatInterval: 5000, // Default value, will only be overridden if keep alive is enabled,
  305. beatHandle: null,
  306. totalTransportConnectTimeout: 0 // This will be the sum of the TransportConnectTimeout sent in response to negotiate and connection.transportConnectTimeout
  307. };
  308. if (typeof (logging) === "boolean") {
  309. this.logging = logging;
  310. }
  311. },
  312. _parseResponse: function (response) {
  313. var that = this;
  314. if (!response) {
  315. return response;
  316. } else if (typeof response === "string") {
  317. return that.json.parse(response);
  318. } else {
  319. return response;
  320. }
  321. },
  322. _originalJson: window.JSON,
  323. json: window.JSON,
  324. isCrossDomain: function (url, against) {
  325. /// <summary>Checks if url is cross domain</summary>
  326. /// <param name="url" type="String">The base URL</param>
  327. /// <param name="against" type="Object">
  328. /// An optional argument to compare the URL against, if not specified it will be set to window.location.
  329. /// If specified it must contain a protocol and a host property.
  330. /// </param>
  331. var link;
  332. url = $.trim(url);
  333. against = against || window.location;
  334. if (url.indexOf("http") !== 0) {
  335. return false;
  336. }
  337. // Create an anchor tag.
  338. link = window.document.createElement("a");
  339. link.href = url;
  340. // When checking for cross domain we have to special case port 80 because the window.location will remove the
  341. return link.protocol + addDefaultPort(link.protocol, link.host) !== against.protocol + addDefaultPort(against.protocol, against.host);
  342. },
  343. ajaxDataType: "text",
  344. contentType: "application/json; charset=UTF-8",
  345. logging: false,
  346. state: signalR.connectionState.disconnected,
  347. clientProtocol: "2.0",
  348. // We want to support older servers since the 2.0 change is to support redirection results, which isn't
  349. // really breaking in the protocol. So if a user updates their client to 2.0 protocol version there's
  350. // no reason they can't still connect to a 1.5 server.
  351. supportedProtocols: ["1.5", "2.0"],
  352. reconnectDelay: 2000,
  353. transportConnectTimeout: 0,
  354. disconnectTimeout: 30000, // This should be set by the server in response to the negotiate request (30s default)
  355. reconnectWindow: 30000, // This should be set by the server in response to the negotiate request
  356. keepAliveWarnAt: 2 / 3, // Warn user of slow connection if we breach the X% mark of the keep alive timeout
  357. start: function (options, callback) {
  358. /// <summary>Starts the connection</summary>
  359. /// <param name="options" type="Object">Options map</param>
  360. /// <param name="callback" type="Function">A callback function to execute when the connection has started</param>
  361. var connection = this,
  362. config = {
  363. pingInterval: 300000,
  364. waitForPageLoad: true,
  365. transport: "auto",
  366. jsonp: false
  367. },
  368. initialize,
  369. deferred = connection._deferral || $.Deferred(), // Check to see if there is a pre-existing deferral that's being built on, if so we want to keep using it
  370. parser = window.document.createElement("a"),
  371. setConnectionUrl = function (connection, url) {
  372. if (connection.url === url && connection.baseUrl) {
  373. // when the url related properties are already set
  374. return;
  375. }
  376. connection.url = url;
  377. // Resolve the full url
  378. parser.href = connection.url;
  379. if (!parser.protocol || parser.protocol === ":") {
  380. connection.protocol = window.document.location.protocol;
  381. connection.host = parser.host || window.document.location.host;
  382. } else {
  383. connection.protocol = parser.protocol;
  384. connection.host = parser.host;
  385. }
  386. connection.baseUrl = connection.protocol + "//" + connection.host;
  387. // Set the websocket protocol
  388. connection.wsProtocol = connection.protocol === "https:" ? "wss://" : "ws://";
  389. // If the url is protocol relative, prepend the current windows protocol to the url.
  390. if (connection.url.indexOf("//") === 0) {
  391. connection.url = window.location.protocol + connection.url;
  392. connection.log("Protocol relative URL detected, normalizing it to '" + connection.url + "'.");
  393. }
  394. if (connection.isCrossDomain(connection.url)) {
  395. connection.log("Auto detected cross domain url.");
  396. if (config.transport === "auto") {
  397. // Cross-domain does not support foreverFrame
  398. config.transport = ["webSockets", "serverSentEvents", "longPolling"];
  399. }
  400. if (typeof connection.withCredentials === "undefined") {
  401. connection.withCredentials = true;
  402. }
  403. // Determine if jsonp is the only choice for negotiation, ajaxSend and ajaxAbort.
  404. // i.e. if the browser doesn't supports CORS
  405. // If it is, ignore any preference to the contrary, and switch to jsonp.
  406. if (!$.support.cors) {
  407. connection.ajaxDataType = "jsonp";
  408. connection.log("Using jsonp because this browser doesn't support CORS.");
  409. }
  410. connection.contentType = signalR._.defaultContentType;
  411. }
  412. };
  413. connection.lastError = null;
  414. // Persist the deferral so that if start is called multiple times the same deferral is used.
  415. connection._deferral = deferred;
  416. if (!connection.json) {
  417. // no JSON!
  418. throw new Error("SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.");
  419. }
  420. if ($.type(options) === "function") {
  421. // Support calling with single callback parameter
  422. callback = options;
  423. } else if ($.type(options) === "object") {
  424. $.extend(config, options);
  425. if ($.type(config.callback) === "function") {
  426. callback = config.callback;
  427. }
  428. }
  429. config.transport = validateTransport(config.transport, connection);
  430. // If the transport is invalid throw an error and abort start
  431. if (!config.transport) {
  432. throw new Error("SignalR: Invalid transport(s) specified, aborting start.");
  433. }
  434. connection._.config = config;
  435. // Check to see if start is being called prior to page load
  436. // If waitForPageLoad is true we then want to re-direct function call to the window load event
  437. if (!_pageLoaded && config.waitForPageLoad === true) {
  438. connection._.deferredStartHandler = function () {
  439. connection.start(options, callback);
  440. };
  441. _pageWindow.bind("load", connection._.deferredStartHandler);
  442. return deferred.promise();
  443. }
  444. // If we're already connecting just return the same deferral as the original connection start
  445. if (connection.state === signalR.connectionState.connecting) {
  446. return deferred.promise();
  447. } else if (changeState(connection,
  448. signalR.connectionState.disconnected,
  449. signalR.connectionState.connecting) === false) {
  450. // We're not connecting so try and transition into connecting.
  451. // If we fail to transition then we're either in connected or reconnecting.
  452. deferred.resolve(connection);
  453. return deferred.promise();
  454. }
  455. configureStopReconnectingTimeout(connection);
  456. // If jsonp with no/auto transport is specified, then set the transport to long polling
  457. // since that is the only transport for which jsonp really makes sense.
  458. // Some developers might actually choose to specify jsonp for same origin requests
  459. // as demonstrated by Issue #623.
  460. if (config.transport === "auto" && config.jsonp === true) {
  461. config.transport = "longPolling";
  462. }
  463. connection.withCredentials = config.withCredentials;
  464. setConnectionUrl(connection, connection.url);
  465. // Save the original url so that we can reset it when we stop and restart the connection
  466. connection._originalUrl = connection.url;
  467. connection.ajaxDataType = config.jsonp ? "jsonp" : "text";
  468. $(connection).bind(events.onStart, function (e, data) {
  469. if ($.type(callback) === "function") {
  470. callback.call(connection);
  471. }
  472. deferred.resolve(connection);
  473. });
  474. connection._.initHandler = signalR.transports._logic.initHandler(connection);
  475. initialize = function (transports, index) {
  476. var noTransportError = signalR._.error(resources.noTransportOnInit);
  477. index = index || 0;
  478. if (index >= transports.length) {
  479. if (index === 0) {
  480. connection.log("No transports supported by the server were selected.");
  481. } else if (index === 1) {
  482. connection.log("No fallback transports were selected.");
  483. } else {
  484. connection.log("Fallback transports exhausted.");
  485. }
  486. // No transport initialized successfully
  487. $(connection).triggerHandler(events.onError, [noTransportError]);
  488. deferred.reject(noTransportError);
  489. // Stop the connection if it has connected and move it into the disconnected state
  490. connection.stop();
  491. return;
  492. }
  493. // The connection was aborted
  494. if (connection.state === signalR.connectionState.disconnected) {
  495. return;
  496. }
  497. var transportName = transports[index],
  498. transport = signalR.transports[transportName],
  499. onFallback = function () {
  500. initialize(transports, index + 1);
  501. };
  502. connection.transport = transport;
  503. try {
  504. connection._.initHandler.start(transport, function () { // success
  505. // Firefox 11+ doesn't allow sync XHR withCredentials: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#withCredentials
  506. var isFirefox11OrGreater = signalR._.firefoxMajorVersion(window.navigator.userAgent) >= 11,
  507. asyncAbort = true;
  508. connection.log("The start request succeeded. Transitioning to the connected state.");
  509. if (supportsKeepAlive(connection)) {
  510. signalR.transports._logic.monitorKeepAlive(connection);
  511. }
  512. signalR.transports._logic.startHeartbeat(connection);
  513. // Used to ensure low activity clients maintain their authentication.
  514. // Must be configured once a transport has been decided to perform valid ping requests.
  515. signalR._.configurePingInterval(connection);
  516. if (!changeState(connection,
  517. signalR.connectionState.connecting,
  518. signalR.connectionState.connected)) {
  519. connection.log("WARNING! The connection was not in the connecting state.");
  520. }
  521. // Drain any incoming buffered messages (messages that came in prior to connect)
  522. connection._.connectingMessageBuffer.drain();
  523. $(connection).triggerHandler(events.onStart);
  524. // wire the stop handler for when the user leaves the page
  525. _pageWindow.bind("unload", function () {
  526. connection.log("Window unloading, stopping the connection.");
  527. connection.stop(asyncAbort);
  528. });
  529. if (isFirefox11OrGreater) {
  530. // Firefox does not fire cross-domain XHRs in the normal unload handler on tab close.
  531. // #2400
  532. _pageWindow.bind("beforeunload", function () {
  533. // If connection.stop() runs runs in beforeunload and fails, it will also fail
  534. // in unload unless connection.stop() runs after a timeout.
  535. window.setTimeout(function () {
  536. connection.stop(asyncAbort);
  537. }, 0);
  538. });
  539. }
  540. }, onFallback);
  541. }
  542. catch (error) {
  543. connection.log(transport.name + " transport threw '" + error.message + "' when attempting to start.");
  544. onFallback();
  545. }
  546. };
  547. var url = connection.url + "/negotiate",
  548. onFailed = function (error, connection) {
  549. var err = signalR._.error(resources.errorOnNegotiate, error, connection._.negotiateRequest);
  550. $(connection).triggerHandler(events.onError, err);
  551. deferred.reject(err);
  552. // Stop the connection if negotiate failed
  553. connection.stop();
  554. };
  555. $(connection).triggerHandler(events.onStarting);
  556. url = signalR.transports._logic.prepareQueryString(connection, url);
  557. connection.log("Negotiating with '" + url + "'.");
  558. // Save the ajax negotiate request object so we can abort it if stop is called while the request is in flight.
  559. connection._.negotiateRequest = function () {
  560. var res,
  561. redirects = 0,
  562. MAX_REDIRECTS = 100,
  563. keepAliveData,
  564. protocolError,
  565. transports = [],
  566. supportedTransports = [],
  567. negotiate = function (connection, onSuccess) {
  568. var url = signalR.transports._logic.prepareQueryString(connection, connection.url + "/negotiate");
  569. connection.log("Negotiating with '" + url + "'.");
  570. var options = {
  571. url: url,
  572. error: function (error, statusText) {
  573. // We don't want to cause any errors if we're aborting our own negotiate request.
  574. if (statusText !== _negotiateAbortText) {
  575. onFailed(error, connection);
  576. } else {
  577. // This rejection will noop if the deferred has already been resolved or rejected.
  578. deferred.reject(signalR._.error(resources.stoppedWhileNegotiating, null /* error */, connection._.negotiateRequest));
  579. }
  580. },
  581. success: onSuccess
  582. };
  583. if (connection.accessToken) {
  584. options.headers = { "Authorization": "Bearer " + connection.accessToken };
  585. }
  586. return signalR.transports._logic.ajax(connection, options);
  587. },
  588. callback = function (result) {
  589. try {
  590. res = connection._parseResponse(result);
  591. } catch (error) {
  592. onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);
  593. return;
  594. }
  595. // Check if the server is an ASP.NET Core app
  596. if (res.availableTransports) {
  597. protocolError = signalR._.error(resources.aspnetCoreSignalrServer);
  598. $(connection).triggerHandler(events.onError, [protocolError]);
  599. deferred.reject(protocolError);
  600. return;
  601. }
  602. if (!res.ProtocolVersion || (connection.supportedProtocols.indexOf(res.ProtocolVersion) === -1)) {
  603. protocolError = signalR._.error(signalR._.format(resources.protocolIncompatible, connection.clientProtocol, res.ProtocolVersion));
  604. $(connection).triggerHandler(events.onError, [protocolError]);
  605. deferred.reject(protocolError);
  606. return;
  607. }
  608. // Check for a redirect response (which must have a ProtocolVersion of 2.0)
  609. if (res.ProtocolVersion === "2.0") {
  610. if (res.Error) {
  611. protocolError = signalR._.error(signalR._.format(resources.errorFromServer, res.Error));
  612. $(connection).triggerHandler(events.onError, [protocolError]);
  613. deferred.reject(protocolError);
  614. return;
  615. }
  616. else if (res.RedirectUrl) {
  617. if (redirects === MAX_REDIRECTS) {
  618. onFailed(signalR._.error(resources.errorRedirectionExceedsLimit), connection);
  619. return;
  620. }
  621. if (config.transport === "auto") {
  622. // Redirected connections do not support foreverFrame
  623. config.transport = ["webSockets", "serverSentEvents", "longPolling"];
  624. }
  625. connection.log("Received redirect to: " + res.RedirectUrl);
  626. connection.accessToken = res.AccessToken;
  627. setConnectionUrl(connection, res.RedirectUrl);
  628. if (connection.ajaxDataType === "jsonp" && connection.accessToken) {
  629. onFailed(signalR._.error(resources.jsonpNotSupportedWithAccessToken), connection);
  630. return;
  631. }
  632. redirects++;
  633. negotiate(connection, callback);
  634. return;
  635. }
  636. }
  637. keepAliveData = connection._.keepAliveData;
  638. connection.appRelativeUrl = res.Url;
  639. connection.id = res.ConnectionId;
  640. connection.token = res.ConnectionToken;
  641. connection.webSocketServerUrl = res.WebSocketServerUrl;
  642. // The long poll timeout is the ConnectionTimeout plus 10 seconds
  643. connection._.pollTimeout = res.ConnectionTimeout * 1000 + 10000; // in ms
  644. // Once the server has labeled the PersistentConnection as Disconnected, we should stop attempting to reconnect
  645. // after res.DisconnectTimeout seconds.
  646. connection.disconnectTimeout = res.DisconnectTimeout * 1000; // in ms
  647. // Add the TransportConnectTimeout from the response to the transportConnectTimeout from the client to calculate the total timeout
  648. connection._.totalTransportConnectTimeout = connection.transportConnectTimeout + res.TransportConnectTimeout * 1000;
  649. // If we have a keep alive
  650. if (res.KeepAliveTimeout) {
  651. // Register the keep alive data as activated
  652. keepAliveData.activated = true;
  653. // Timeout to designate when to force the connection into reconnecting converted to milliseconds
  654. keepAliveData.timeout = res.KeepAliveTimeout * 1000;
  655. // Timeout to designate when to warn the developer that the connection may be dead or is not responding.
  656. keepAliveData.timeoutWarning = keepAliveData.timeout * connection.keepAliveWarnAt;
  657. // Instantiate the frequency in which we check the keep alive. It must be short in order to not miss/pick up any changes
  658. connection._.beatInterval = (keepAliveData.timeout - keepAliveData.timeoutWarning) / 3;
  659. } else {
  660. keepAliveData.activated = false;
  661. }
  662. connection.reconnectWindow = connection.disconnectTimeout + (keepAliveData.timeout || 0);
  663. $.each(signalR.transports, function (key) {
  664. if ((key.indexOf("_") === 0) || (key === "webSockets" && !res.TryWebSockets)) {
  665. return true;
  666. }
  667. supportedTransports.push(key);
  668. });
  669. if ($.isArray(config.transport)) {
  670. $.each(config.transport, function (_, transport) {
  671. if ($.inArray(transport, supportedTransports) >= 0) {
  672. transports.push(transport);
  673. }
  674. });
  675. } else if (config.transport === "auto") {
  676. transports = supportedTransports;
  677. } else if ($.inArray(config.transport, supportedTransports) >= 0) {
  678. transports.push(config.transport);
  679. }
  680. initialize(transports);
  681. };
  682. return negotiate(connection, callback);
  683. }();
  684. return deferred.promise();
  685. },
  686. starting: function (callback) {
  687. /// <summary>Adds a callback that will be invoked before anything is sent over the connection</summary>
  688. /// <param name="callback" type="Function">A callback function to execute before the connection is fully instantiated.</param>
  689. /// <returns type="signalR" />
  690. var connection = this;
  691. $(connection).bind(events.onStarting, function (e, data) {
  692. callback.call(connection);
  693. });
  694. return connection;
  695. },
  696. send: function (data) {
  697. /// <summary>Sends data over the connection</summary>
  698. /// <param name="data" type="String">The data to send over the connection</param>
  699. /// <returns type="signalR" />
  700. var connection = this;
  701. if (connection.state === signalR.connectionState.disconnected) {
  702. // Connection hasn't been started yet
  703. throw new Error("SignalR: Connection must be started before data can be sent. Call .start() before .send()");
  704. }
  705. if (connection.state === signalR.connectionState.connecting) {
  706. // Connection hasn't been started yet
  707. throw new Error("SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.");
  708. }
  709. connection.transport.send(connection, data);
  710. // REVIEW: Should we return deferred here?
  711. return connection;
  712. },
  713. received: function (callback) {
  714. /// <summary>Adds a callback that will be invoked after anything is received over the connection</summary>
  715. /// <param name="callback" type="Function">A callback function to execute when any data is received on the connection</param>
  716. /// <returns type="signalR" />
  717. var connection = this;
  718. $(connection).bind(events.onReceived, function (e, data) {
  719. callback.call(connection, data);
  720. });
  721. return connection;
  722. },
  723. stateChanged: function (callback) {
  724. /// <summary>Adds a callback that will be invoked when the connection state changes</summary>
  725. /// <param name="callback" type="Function">A callback function to execute when the connection state changes</param>
  726. /// <returns type="signalR" />
  727. var connection = this;
  728. $(connection).bind(events.onStateChanged, function (e, data) {
  729. callback.call(connection, data);
  730. });
  731. return connection;
  732. },
  733. error: function (callback) {
  734. /// <summary>Adds a callback that will be invoked after an error occurs with the connection</summary>
  735. /// <param name="callback" type="Function">A callback function to execute when an error occurs on the connection</param>
  736. /// <returns type="signalR" />
  737. var connection = this;
  738. $(connection).bind(events.onError, function (e, errorData, sendData) {
  739. connection.lastError = errorData;
  740. // In practice 'errorData' is the SignalR built error object.
  741. // In practice 'sendData' is undefined for all error events except those triggered by
  742. // 'ajaxSend' and 'webSockets.send'.'sendData' is the original send payload.
  743. callback.call(connection, errorData, sendData);
  744. });
  745. return connection;
  746. },
  747. disconnected: function (callback) {
  748. /// <summary>Adds a callback that will be invoked when the client disconnects</summary>
  749. /// <param name="callback" type="Function">A callback function to execute when the connection is broken</param>
  750. /// <returns type="signalR" />
  751. var connection = this;
  752. $(connection).bind(events.onDisconnect, function (e, data) {
  753. callback.call(connection);
  754. });
  755. return connection;
  756. },
  757. connectionSlow: function (callback) {
  758. /// <summary>Adds a callback that will be invoked when the client detects a slow connection</summary>
  759. /// <param name="callback" type="Function">A callback function to execute when the connection is slow</param>
  760. /// <returns type="signalR" />
  761. var connection = this;
  762. $(connection).bind(events.onConnectionSlow, function (e, data) {
  763. callback.call(connection);
  764. });
  765. return connection;
  766. },
  767. reconnecting: function (callback) {
  768. /// <summary>Adds a callback that will be invoked when the underlying transport begins reconnecting</summary>
  769. /// <param name="callback" type="Function">A callback function to execute when the connection enters a reconnecting state</param>
  770. /// <returns type="signalR" />
  771. var connection = this;
  772. $(connection).bind(events.onReconnecting, function (e, data) {
  773. callback.call(connection);
  774. });
  775. return connection;
  776. },
  777. reconnected: function (callback) {
  778. /// <summary>Adds a callback that will be invoked when the underlying transport reconnects</summary>
  779. /// <param name="callback" type="Function">A callback function to execute when the connection is restored</param>
  780. /// <returns type="signalR" />
  781. var connection = this;
  782. $(connection).bind(events.onReconnect, function (e, data) {
  783. callback.call(connection);
  784. });
  785. return connection;
  786. },
  787. stop: function (async, notifyServer) {
  788. /// <summary>Stops listening</summary>
  789. /// <param name="async" type="Boolean">Whether or not to asynchronously abort the connection</param>
  790. /// <param name="notifyServer" type="Boolean">Whether we want to notify the server that we are aborting the connection</param>
  791. /// <returns type="signalR" />
  792. var connection = this,
  793. // Save deferral because this is always cleaned up
  794. deferral = connection._deferral;
  795. // Verify that we've bound a load event.
  796. if (connection._.deferredStartHandler) {
  797. // Unbind the event.
  798. _pageWindow.unbind("load", connection._.deferredStartHandler);
  799. }
  800. // Always clean up private non-timeout based state.
  801. delete connection._.config;
  802. delete connection._.deferredStartHandler;
  803. // This needs to be checked despite the connection state because a connection start can be deferred until page load.
  804. // If we've deferred the start due to a page load we need to unbind the "onLoad" -> start event.
  805. if (!_pageLoaded && (!connection._.config || connection._.config.waitForPageLoad === true)) {
  806. connection.log("Stopping connection prior to negotiate.");
  807. // If we have a deferral we should reject it
  808. if (deferral) {
  809. deferral.reject(signalR._.error(resources.stoppedWhileLoading));
  810. }
  811. // Short-circuit because the start has not been fully started.
  812. return;
  813. }
  814. if (connection.state === signalR.connectionState.disconnected) {
  815. return;
  816. }
  817. connection.log("Stopping connection.");
  818. // Clear this no matter what
  819. window.clearTimeout(connection._.beatHandle);
  820. window.clearInterval(connection._.pingIntervalId);
  821. if (connection.transport) {
  822. connection.transport.stop(connection);
  823. if (notifyServer !== false) {
  824. connection.transport.abort(connection, async);
  825. }
  826. if (supportsKeepAlive(connection)) {
  827. signalR.transports._logic.stopMonitoringKeepAlive(connection);
  828. }
  829. connection.transport = null;
  830. }
  831. if (connection._.negotiateRequest) {
  832. // If the negotiation request has already completed this will noop.
  833. connection._.negotiateRequest.abort(_negotiateAbortText);
  834. delete connection._.negotiateRequest;
  835. }
  836. // Ensure that initHandler.stop() is called before connection._deferral is deleted
  837. if (connection._.initHandler) {
  838. connection._.initHandler.stop();
  839. }
  840. delete connection._deferral;
  841. delete connection.messageId;
  842. delete connection.groupsToken;
  843. delete connection.id;
  844. delete connection._.pingIntervalId;
  845. delete connection._.lastMessageAt;
  846. delete connection._.lastActiveAt;
  847. // Clear out our message buffer
  848. connection._.connectingMessageBuffer.clear();
  849. // Clean up this event
  850. $(connection).unbind(events.onStart);
  851. // Reset the URL and clear the access token
  852. delete connection.accessToken;
  853. connection.url = connection._originalUrl;
  854. // Trigger the disconnect event
  855. changeState(connection, connection.state, signalR.connectionState.disconnected);
  856. $(connection).triggerHandler(events.onDisconnect);
  857. return connection;
  858. },
  859. log: function (msg) {
  860. log(msg, this.logging);
  861. }
  862. };
  863. signalR.fn.init.prototype = signalR.fn;
  864. signalR.noConflict = function () {
  865. /// <summary>Reinstates the original value of $.connection and returns the signalR object for manual assignment</summary>
  866. /// <returns type="signalR" />
  867. if ($.connection === signalR) {
  868. $.connection = _connection;
  869. }
  870. return signalR;
  871. };
  872. if ($.connection) {
  873. _connection = $.connection;
  874. }
  875. $.connection = $.signalR = signalR;
  876. }(window.jQuery, window));
  877. /* jquery.signalR.transports.common.js */
  878. // Copyright (c) .NET Foundation. All rights reserved.
  879. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  880. /*global window:false */
  881. /// <reference path="jquery.signalR.core.js" />
  882. (function ($, window, undefined) {
  883. var signalR = $.signalR,
  884. events = $.signalR.events,
  885. changeState = $.signalR.changeState,
  886. startAbortText = "__Start Aborted__",
  887. transportLogic;
  888. signalR.transports = {};
  889. function beat(connection) {
  890. if (connection._.keepAliveData.monitoring) {
  891. checkIfAlive(connection);
  892. }
  893. // Ensure that we successfully marked active before continuing the heartbeat.
  894. if (transportLogic.markActive(connection)) {
  895. connection._.beatHandle = window.setTimeout(function () {
  896. beat(connection);
  897. }, connection._.beatInterval);
  898. }
  899. }
  900. function checkIfAlive(connection) {
  901. var keepAliveData = connection._.keepAliveData,
  902. timeElapsed;
  903. // Only check if we're connected
  904. if (connection.state === signalR.connectionState.connected) {
  905. timeElapsed = new Date().getTime() - connection._.lastMessageAt;
  906. // Check if the keep alive has completely timed out
  907. if (timeElapsed >= keepAliveData.timeout) {
  908. connection.log("Keep alive timed out. Notifying transport that connection has been lost.");
  909. // Notify transport that the connection has been lost
  910. connection.transport.lostConnection(connection);
  911. } else if (timeElapsed >= keepAliveData.timeoutWarning) {
  912. // This is to assure that the user only gets a single warning
  913. if (!keepAliveData.userNotified) {
  914. connection.log("Keep alive has been missed, connection may be dead/slow.");
  915. $(connection).triggerHandler(events.onConnectionSlow);
  916. keepAliveData.userNotified = true;
  917. }
  918. } else {
  919. keepAliveData.userNotified = false;
  920. }
  921. }
  922. }
  923. function getAjaxUrl(connection, path) {
  924. var url = connection.url + path;
  925. if (connection.transport) {
  926. url += "?transport=" + connection.transport.name;
  927. }
  928. return transportLogic.prepareQueryString(connection, url);
  929. }
  930. function InitHandler(connection) {
  931. this.connection = connection;
  932. this.startRequested = false;
  933. this.startCompleted = false;
  934. this.connectionStopped = false;
  935. }
  936. InitHandler.prototype = {
  937. start: function (transport, onSuccess, onFallback) {
  938. var that = this,
  939. connection = that.connection,
  940. failCalled = false;
  941. if (that.startRequested || that.connectionStopped) {
  942. connection.log("WARNING! " + transport.name + " transport cannot be started. Initialization ongoing or completed.");
  943. return;
  944. }
  945. connection.log(transport.name + " transport starting.");
  946. transport.start(connection, function () {
  947. if (!failCalled) {
  948. that.initReceived(transport, onSuccess);
  949. }
  950. }, function (error) {
  951. // Don't allow the same transport to cause onFallback to be called twice
  952. if (!failCalled) {
  953. failCalled = true;
  954. that.transportFailed(transport, error, onFallback);
  955. }
  956. // Returns true if the transport should stop;
  957. // false if it should attempt to reconnect
  958. return !that.startCompleted || that.connectionStopped;
  959. });
  960. that.transportTimeoutHandle = window.setTimeout(function () {
  961. if (!failCalled) {
  962. failCalled = true;
  963. connection.log(transport.name + " transport timed out when trying to connect.");
  964. that.transportFailed(transport, undefined, onFallback);
  965. }
  966. }, connection._.totalTransportConnectTimeout);
  967. },
  968. stop: function () {
  969. this.connectionStopped = true;
  970. window.clearTimeout(this.transportTimeoutHandle);
  971. signalR.transports._logic.tryAbortStartRequest(this.connection);
  972. },
  973. initReceived: function (transport, onSuccess) {
  974. var that = this,
  975. connection = that.connection;
  976. if (that.startRequested) {
  977. connection.log("WARNING! The client received multiple init messages.");
  978. return;
  979. }
  980. if (that.connectionStopped) {
  981. return;
  982. }
  983. that.startRequested = true;
  984. window.clearTimeout(that.transportTimeoutHandle);
  985. connection.log(transport.name + " transport connected. Initiating start request.");
  986. signalR.transports._logic.ajaxStart(connection, function () {
  987. that.startCompleted = true;
  988. onSuccess();
  989. });
  990. },
  991. transportFailed: function (transport, error, onFallback) {
  992. var connection = this.connection,
  993. deferred = connection._deferral,
  994. wrappedError;
  995. if (this.connectionStopped) {
  996. return;
  997. }
  998. window.clearTimeout(this.transportTimeoutHandle);
  999. if (!this.startRequested) {
  1000. transport.stop(connection);
  1001. connection.log(transport.name + " transport failed to connect. Attempting to fall back.");
  1002. onFallback();
  1003. } else if (!this.startCompleted) {
  1004. // Do not attempt to fall back if a start request is ongoing during a transport failure.
  1005. // Instead, trigger an error and stop the connection.
  1006. wrappedError = signalR._.error(signalR.resources.errorDuringStartRequest, error);
  1007. connection.log(transport.name + " transport failed during the start request. Stopping the connection.");
  1008. $(connection).triggerHandler(events.onError, [wrappedError]);
  1009. if (deferred) {
  1010. deferred.reject(wrappedError);
  1011. }
  1012. connection.stop();
  1013. } else {
  1014. // The start request has completed, but the connection has not stopped.
  1015. // No need to do anything here. The transport should attempt its normal reconnect logic.
  1016. }
  1017. }
  1018. };
  1019. transportLogic = signalR.transports._logic = {
  1020. ajax: function (connection, options) {
  1021. return $.ajax(
  1022. $.extend(/*deep copy*/ true, {}, $.signalR.ajaxDefaults, {
  1023. type: "GET",
  1024. data: {},
  1025. xhrFields: { withCredentials: connection.withCredentials },
  1026. contentType: connection.contentType,
  1027. dataType: connection.ajaxDataType
  1028. }, options));
  1029. },
  1030. pingServer: function (connection) {
  1031. /// <summary>Pings the server</summary>
  1032. /// <param name="connection" type="signalr">Connection associated with the server ping</param>
  1033. /// <returns type="signalR" />
  1034. var url,
  1035. xhr,
  1036. deferral = $.Deferred();
  1037. if (connection.transport) {
  1038. url = connection.url + "/ping";
  1039. url = transportLogic.addQs(url, connection.qs);
  1040. xhr = transportLogic.ajax(connection, {
  1041. url: url,
  1042. headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
  1043. success: function (result) {
  1044. var data;
  1045. try {
  1046. data = connection._parseResponse(result);
  1047. }
  1048. catch (error) {
  1049. deferral.reject(
  1050. signalR._.transportError(
  1051. signalR.resources.pingServerFailedParse,
  1052. connection.transport,
  1053. error,
  1054. xhr
  1055. )
  1056. );
  1057. connection.stop();
  1058. return;
  1059. }
  1060. if (data.Response === "pong") {
  1061. deferral.resolve();
  1062. }
  1063. else {
  1064. deferral.reject(
  1065. signalR._.transportError(
  1066. signalR._.format(signalR.resources.pingServerFailedInvalidResponse, result),
  1067. connection.transport,
  1068. null /* error */,
  1069. xhr
  1070. )
  1071. );
  1072. }
  1073. },
  1074. error: function (error) {
  1075. if (error.status === 401 || error.status === 403) {
  1076. deferral.reject(
  1077. signalR._.transportError(
  1078. signalR._.format(signalR.resources.pingServerFailedStatusCode, error.status),
  1079. connection.transport,
  1080. error,
  1081. xhr
  1082. )
  1083. );
  1084. connection.stop();
  1085. }
  1086. else {
  1087. deferral.reject(
  1088. signalR._.transportError(
  1089. signalR.resources.pingServerFailed,
  1090. connection.transport,
  1091. error,
  1092. xhr
  1093. )
  1094. );
  1095. }
  1096. }
  1097. });
  1098. }
  1099. else {
  1100. deferral.reject(
  1101. signalR._.transportError(
  1102. signalR.resources.noConnectionTransport,
  1103. connection.transport
  1104. )
  1105. );
  1106. }
  1107. return deferral.promise();
  1108. },
  1109. prepareQueryString: function (connection, url) {
  1110. var preparedUrl;
  1111. // Use addQs to start since it handles the ?/& prefix for us
  1112. preparedUrl = transportLogic.addQs(url, "clientProtocol=" + connection.clientProtocol);
  1113. // Add the user-specified query string params if any
  1114. preparedUrl = transportLogic.addQs(preparedUrl, connection.qs);
  1115. if (connection.token) {
  1116. preparedUrl += "&connectionToken=" + window.encodeURIComponent(connection.token);
  1117. }
  1118. if (connection.data) {
  1119. preparedUrl += "&connectionData=" + window.encodeURIComponent(connection.data);
  1120. }
  1121. return preparedUrl;
  1122. },
  1123. addQs: function (url, qs) {
  1124. var appender = url.indexOf("?") !== -1 ? "&" : "?",
  1125. firstChar;
  1126. if (!qs) {
  1127. return url;
  1128. }
  1129. if (typeof (qs) === "object") {
  1130. return url + appender + $.param(qs);
  1131. }
  1132. if (typeof (qs) === "string") {
  1133. firstChar = qs.charAt(0);
  1134. if (firstChar === "?" || firstChar === "&") {
  1135. appender = "";
  1136. }
  1137. return url + appender + qs;
  1138. }
  1139. throw new Error("Query string property must be either a string or object.");
  1140. },
  1141. // BUG #2953: The url needs to be same otherwise it will cause a memory leak
  1142. getUrl: function (connection, transport, reconnecting, poll, ajaxPost) {
  1143. /// <summary>Gets the url for making a GET based connect request</summary>
  1144. var baseUrl = transport === "webSockets" ? "" : connection.baseUrl,
  1145. url = baseUrl + connection.appRelativeUrl,
  1146. qs = "transport=" + transport;
  1147. if (!ajaxPost && connection.groupsToken) {
  1148. qs += "&groupsToken=" + window.encodeURIComponent(connection.groupsToken);
  1149. }
  1150. if (!reconnecting) {
  1151. url += "/connect";
  1152. } else {
  1153. if (poll) {
  1154. // longPolling transport specific
  1155. url += "/poll";
  1156. } else {
  1157. url += "/reconnect";
  1158. }
  1159. if (!ajaxPost && connection.messageId) {
  1160. qs += "&messageId=" + window.encodeURIComponent(connection.messageId);
  1161. }
  1162. }
  1163. url += "?" + qs;
  1164. url = transportLogic.prepareQueryString(connection, url);
  1165. // With sse or ws, access_token in request header is not supported
  1166. if (connection.transport && connection.accessToken) {
  1167. if (connection.transport.name === "serverSentEvents" || connection.transport.name === "webSockets") {
  1168. url += "&access_token=" + window.encodeURIComponent(connection.accessToken);
  1169. }
  1170. }
  1171. if (!ajaxPost) {
  1172. url += "&tid=" + Math.floor(Math.random() * 11);
  1173. }
  1174. return url;
  1175. },
  1176. maximizePersistentResponse: function (minPersistentResponse) {
  1177. return {
  1178. MessageId: minPersistentResponse.C,
  1179. Messages: minPersistentResponse.M,
  1180. Initialized: typeof (minPersistentResponse.S) !== "undefined" ? true : false,
  1181. ShouldReconnect: typeof (minPersistentResponse.T) !== "undefined" ? true : false,
  1182. LongPollDelay: minPersistentResponse.L,
  1183. GroupsToken: minPersistentResponse.G,
  1184. Error: minPersistentResponse.E
  1185. };
  1186. },
  1187. updateGroups: function (connection, groupsToken) {
  1188. if (groupsToken) {
  1189. connection.groupsToken = groupsToken;
  1190. }
  1191. },
  1192. stringifySend: function (connection, message) {
  1193. if (typeof (message) === "string" || typeof (message) === "undefined" || message === null) {
  1194. return message;
  1195. }
  1196. return connection.json.stringify(message);
  1197. },
  1198. ajaxSend: function (connection, data) {
  1199. var payload = transportLogic.stringifySend(connection, data),
  1200. url = getAjaxUrl(connection, "/send"),
  1201. xhr,
  1202. onFail = function (error, connection) {
  1203. $(connection).triggerHandler(events.onError, [signalR._.transportError(signalR.resources.sendFailed, connection.transport, error, xhr), data]);
  1204. };
  1205. xhr = transportLogic.ajax(connection, {
  1206. url: url,
  1207. type: connection.ajaxDataType === "jsonp" ? "GET" : "POST",
  1208. contentType: signalR._.defaultContentType,
  1209. headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
  1210. data: {
  1211. data: payload
  1212. },
  1213. success: function (result) {
  1214. var res;
  1215. if (result) {
  1216. try {
  1217. res = connection._parseResponse(result);
  1218. }
  1219. catch (error) {
  1220. onFail(error, connection);
  1221. connection.stop();
  1222. return;
  1223. }
  1224. transportLogic.triggerReceived(connection, res);
  1225. }
  1226. },
  1227. error: function (error, textStatus) {
  1228. if (textStatus === "abort" || textStatus === "parsererror") {
  1229. // The parsererror happens for sends that don't return any data, and hence
  1230. // don't write the jsonp callback to the response. This is harder to fix on the server
  1231. // so just hack around it on the client for now.
  1232. return;
  1233. }
  1234. onFail(error, connection);
  1235. }
  1236. });
  1237. return xhr;
  1238. },
  1239. ajaxAbort: function (connection, async) {
  1240. if (typeof (connection.transport) === "undefined") {
  1241. return;
  1242. }
  1243. // Async by default unless explicitly overidden
  1244. async = typeof async === "undefined" ? true : async;
  1245. var url = getAjaxUrl(connection, "/abort");
  1246. transportLogic.ajax(connection, {
  1247. url: url,
  1248. async: async,
  1249. timeout: 1000,
  1250. type: "POST",
  1251. headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
  1252. dataType: "text" // We don't want to use JSONP here even when JSONP is enabled
  1253. });
  1254. connection.log("Fired ajax abort async = " + async + ".");
  1255. },
  1256. ajaxStart: function (connection, onSuccess) {
  1257. var rejectDeferred = function (error) {
  1258. var deferred = connection._deferral;
  1259. if (deferred) {
  1260. deferred.reject(error);
  1261. }
  1262. },
  1263. triggerStartError = function (error) {
  1264. connection.log("The start request failed. Stopping the connection.");
  1265. $(connection).triggerHandler(events.onError, [error]);
  1266. rejectDeferred(error);
  1267. connection.stop();
  1268. };
  1269. connection._.startRequest = transportLogic.ajax(connection, {
  1270. url: getAjaxUrl(connection, "/start"),
  1271. headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
  1272. success: function (result, statusText, xhr) {
  1273. var data;
  1274. try {
  1275. data = connection._parseResponse(result);
  1276. } catch (error) {
  1277. triggerStartError(signalR._.error(
  1278. signalR._.format(signalR.resources.errorParsingStartResponse, result),
  1279. error, xhr));
  1280. return;
  1281. }
  1282. if (data.Response === "started") {
  1283. onSuccess();
  1284. } else {
  1285. triggerStartError(signalR._.error(
  1286. signalR._.format(signalR.resources.invalidStartResponse, result),
  1287. null /* error */, xhr));
  1288. }
  1289. },
  1290. error: function (xhr, statusText, error) {
  1291. if (statusText !== startAbortText) {
  1292. triggerStartError(signalR._.error(
  1293. signalR.resources.errorDuringStartRequest,
  1294. error, xhr));
  1295. } else {
  1296. // Stop has been called, no need to trigger the error handler
  1297. // or stop the connection again with onStartError
  1298. connection.log("The start request aborted because connection.stop() was called.");
  1299. rejectDeferred(signalR._.error(
  1300. signalR.resources.stoppedDuringStartRequest,
  1301. null /* error */, xhr));
  1302. }
  1303. }
  1304. });
  1305. },
  1306. tryAbortStartRequest: function (connection) {
  1307. if (connection._.startRequest) {
  1308. // If the start request has already completed this will noop.
  1309. connection._.startRequest.abort(startAbortText);
  1310. delete connection._.startRequest;
  1311. }
  1312. },
  1313. tryInitialize: function (connection, persistentResponse, onInitialized) {
  1314. if (persistentResponse.Initialized && onInitialized) {
  1315. onInitialized();
  1316. } else if (persistentResponse.Initialized) {
  1317. connection.log("WARNING! The client received an init message after reconnecting.");
  1318. }
  1319. },
  1320. triggerReceived: function (connection, data) {
  1321. if (!connection._.connectingMessageBuffer.tryBuffer(data)) {
  1322. $(connection).triggerHandler(events.onReceived, [data]);
  1323. }
  1324. },
  1325. processMessages: function (connection, minData, onInitialized) {
  1326. var data;
  1327. if(minData && (typeof minData.I !== "undefined")) {
  1328. // This is a response to a message the client sent
  1329. transportLogic.triggerReceived(connection, minData);
  1330. return;
  1331. }
  1332. // Update the last message time stamp
  1333. transportLogic.markLastMessage(connection);
  1334. if (minData) {
  1335. // This is a message send directly to the client
  1336. data = transportLogic.maximizePersistentResponse(minData);
  1337. if(data.Error) {
  1338. // This is a global error, stop the connection.
  1339. connection.log("Received an error message from the server: " + minData.E);
  1340. $(connection).triggerHandler(signalR.events.onError, [signalR._.error(minData.E, /* source */ "ServerError")]);
  1341. connection.stop(/* async */ false, /* notifyServer */ false);
  1342. }
  1343. transportLogic.updateGroups(connection, data.GroupsToken);
  1344. if (data.MessageId) {
  1345. connection.messageId = data.MessageId;
  1346. }
  1347. if (data.Messages) {
  1348. $.each(data.Messages, function (index, message) {
  1349. transportLogic.triggerReceived(connection, message);
  1350. });
  1351. transportLogic.tryInitialize(connection, data, onInitialized);
  1352. }
  1353. }
  1354. },
  1355. monitorKeepAlive: function (connection) {
  1356. var keepAliveData = connection._.keepAliveData;
  1357. // If we haven't initiated the keep alive timeouts then we need to
  1358. if (!keepAliveData.monitoring) {
  1359. keepAliveData.monitoring = true;
  1360. transportLogic.markLastMessage(connection);
  1361. // Save the function so we can unbind it on stop
  1362. connection._.keepAliveData.reconnectKeepAliveUpdate = function () {
  1363. // Mark a new message so that keep alive doesn't time out connections
  1364. transportLogic.markLastMessage(connection);
  1365. };
  1366. // Update Keep alive on reconnect
  1367. $(connection).bind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate);
  1368. connection.log("Now monitoring keep alive with a warning timeout of " + keepAliveData.timeoutWarning + ", keep alive timeout of " + keepAliveData.timeout + " and disconnecting timeout of " + connection.disconnectTimeout);
  1369. } else {
  1370. connection.log("Tried to monitor keep alive but it's already being monitored.");
  1371. }
  1372. },
  1373. stopMonitoringKeepAlive: function (connection) {
  1374. var keepAliveData = connection._.keepAliveData;
  1375. // Only attempt to stop the keep alive monitoring if its being monitored
  1376. if (keepAliveData.monitoring) {
  1377. // Stop monitoring
  1378. keepAliveData.monitoring = false;
  1379. // Remove the updateKeepAlive function from the reconnect event
  1380. $(connection).unbind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate);
  1381. // Clear all the keep alive data
  1382. connection._.keepAliveData = {};
  1383. connection.log("Stopping the monitoring of the keep alive.");
  1384. }
  1385. },
  1386. startHeartbeat: function (connection) {
  1387. connection._.lastActiveAt = new Date().getTime();
  1388. beat(connection);
  1389. },
  1390. markLastMessage: function (connection) {
  1391. connection._.lastMessageAt = new Date().getTime();
  1392. },
  1393. markActive: function (connection) {
  1394. if (transportLogic.verifyLastActive(connection)) {
  1395. connection._.lastActiveAt = new Date().getTime();
  1396. return true;
  1397. }
  1398. return false;
  1399. },
  1400. isConnectedOrReconnecting: function (connection) {
  1401. return connection.state === signalR.connectionState.connected ||
  1402. connection.state === signalR.connectionState.reconnecting;
  1403. },
  1404. ensureReconnectingState: function (connection) {
  1405. if (changeState(connection,
  1406. signalR.connectionState.connected,
  1407. signalR.connectionState.reconnecting) === true) {
  1408. $(connection).triggerHandler(events.onReconnecting);
  1409. }
  1410. return connection.state === signalR.connectionState.reconnecting;
  1411. },
  1412. clearReconnectTimeout: function (connection) {
  1413. if (connection && connection._.reconnectTimeout) {
  1414. window.clearTimeout(connection._.reconnectTimeout);
  1415. delete connection._.reconnectTimeout;
  1416. }
  1417. },
  1418. verifyLastActive: function (connection) {
  1419. if (new Date().getTime() - connection._.lastActiveAt >= connection.reconnectWindow) {
  1420. var message = signalR._.format(signalR.resources.reconnectWindowTimeout, new Date(connection._.lastActiveAt), connection.reconnectWindow);
  1421. connection.log(message);
  1422. $(connection).triggerHandler(events.onError, [signalR._.error(message, /* source */ "TimeoutException")]);
  1423. connection.stop(/* async */ false, /* notifyServer */ false);
  1424. return false;
  1425. }
  1426. return true;
  1427. },
  1428. reconnect: function (connection, transportName) {
  1429. var transport = signalR.transports[transportName];
  1430. // We should only set a reconnectTimeout if we are currently connected
  1431. // and a reconnectTimeout isn't already set.
  1432. if (transportLogic.isConnectedOrReconnecting(connection) && !connection._.reconnectTimeout) {
  1433. // Need to verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration.
  1434. if (!transportLogic.verifyLastActive(connection)) {
  1435. return;
  1436. }
  1437. connection._.reconnectTimeout = window.setTimeout(function () {
  1438. if (!transportLogic.verifyLastActive(connection)) {
  1439. return;
  1440. }
  1441. transport.stop(connection);
  1442. if (transportLogic.ensureReconnectingState(connection)) {
  1443. connection.log(transportName + " reconnecting.");
  1444. transport.start(connection);
  1445. }
  1446. }, connection.reconnectDelay);
  1447. }
  1448. },
  1449. handleParseFailure: function (connection, result, error, onFailed, context) {
  1450. var wrappedError = signalR._.transportError(
  1451. signalR._.format(signalR.resources.parseFailed, result),
  1452. connection.transport,
  1453. error,
  1454. context);
  1455. // If we're in the initialization phase trigger onFailed, otherwise stop the connection.
  1456. if (onFailed && onFailed(wrappedError)) {
  1457. connection.log("Failed to parse server response while attempting to connect.");
  1458. } else {
  1459. $(connection).triggerHandler(events.onError, [wrappedError]);
  1460. connection.stop();
  1461. }
  1462. },
  1463. initHandler: function (connection) {
  1464. return new InitHandler(connection);
  1465. },
  1466. foreverFrame: {
  1467. count: 0,
  1468. connections: {}
  1469. }
  1470. };
  1471. }(window.jQuery, window));
  1472. /* jquery.signalR.transports.webSockets.js */
  1473. // Copyright (c) .NET Foundation. All rights reserved.
  1474. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  1475. /*global window:false */
  1476. /// <reference path="jquery.signalR.transports.common.js" />
  1477. (function ($, window, undefined) {
  1478. var signalR = $.signalR,
  1479. events = $.signalR.events,
  1480. changeState = $.signalR.changeState,
  1481. transportLogic = signalR.transports._logic;
  1482. signalR.transports.webSockets = {
  1483. name: "webSockets",
  1484. supportsKeepAlive: function () {
  1485. return true;
  1486. },
  1487. send: function (connection, data) {
  1488. var payload = transportLogic.stringifySend(connection, data);
  1489. try {
  1490. connection.socket.send(payload);
  1491. } catch (ex) {
  1492. $(connection).triggerHandler(events.onError,
  1493. [signalR._.transportError(
  1494. signalR.resources.webSocketsInvalidState,
  1495. connection.transport,
  1496. ex,
  1497. connection.socket
  1498. ),
  1499. data]);
  1500. }
  1501. },
  1502. start: function (connection, onSuccess, onFailed) {
  1503. var url,
  1504. opened = false,
  1505. that = this,
  1506. reconnecting = !onSuccess,
  1507. $connection = $(connection);
  1508. if (!window.WebSocket) {
  1509. onFailed();
  1510. return;
  1511. }
  1512. if (!connection.socket) {
  1513. if (connection.webSocketServerUrl) {
  1514. url = connection.webSocketServerUrl;
  1515. } else {
  1516. url = connection.wsProtocol + connection.host;
  1517. }
  1518. url += transportLogic.getUrl(connection, this.name, reconnecting);
  1519. connection.log("Connecting to websocket endpoint '" + url + "'.");
  1520. connection.socket = new window.WebSocket(url);
  1521. connection.socket.onopen = function () {
  1522. opened = true;
  1523. connection.log("Websocket opened.");
  1524. transportLogic.clearReconnectTimeout(connection);
  1525. if (changeState(connection,
  1526. signalR.connectionState.reconnecting,
  1527. signalR.connectionState.connected) === true) {
  1528. $connection.triggerHandler(events.onReconnect);
  1529. }
  1530. };
  1531. connection.socket.onclose = function (event) {
  1532. var error;
  1533. // Only handle a socket close if the close is from the current socket.
  1534. // Sometimes on disconnect the server will push down an onclose event
  1535. // to an expired socket.
  1536. if (this === connection.socket) {
  1537. if (opened && typeof event.wasClean !== "undefined" && event.wasClean === false) {
  1538. // Ideally this would use the websocket.onerror handler (rather than checking wasClean in onclose) but
  1539. // I found in some circumstances Chrome won't call onerror. This implementation seems to work on all browsers.
  1540. error = signalR._.transportError(
  1541. signalR.resources.webSocketClosed,
  1542. connection.transport,
  1543. event);
  1544. connection.log("Unclean disconnect from websocket: " + (event.reason || "[no reason given]."));
  1545. } else {
  1546. connection.log("Websocket closed.");
  1547. }
  1548. if (!onFailed || !onFailed(error)) {
  1549. if (error) {
  1550. $(connection).triggerHandler(events.onError, [error]);
  1551. }
  1552. that.reconnect(connection);
  1553. }
  1554. }
  1555. };
  1556. connection.socket.onmessage = function (event) {
  1557. var data;
  1558. try {
  1559. data = connection._parseResponse(event.data);
  1560. }
  1561. catch (error) {
  1562. transportLogic.handleParseFailure(connection, event.data, error, onFailed, event);
  1563. return;
  1564. }
  1565. if (data) {
  1566. transportLogic.processMessages(connection, data, onSuccess);
  1567. }
  1568. };
  1569. }
  1570. },
  1571. reconnect: function (connection) {
  1572. transportLogic.reconnect(connection, this.name);
  1573. },
  1574. lostConnection: function (connection) {
  1575. this.reconnect(connection);
  1576. },
  1577. stop: function (connection) {
  1578. // Don't trigger a reconnect after stopping
  1579. transportLogic.clearReconnectTimeout(connection);
  1580. if (connection.socket) {
  1581. connection.log("Closing the Websocket.");
  1582. connection.socket.close();
  1583. connection.socket = null;
  1584. }
  1585. },
  1586. abort: function (connection, async) {
  1587. transportLogic.ajaxAbort(connection, async);
  1588. }
  1589. };
  1590. }(window.jQuery, window));
  1591. /* jquery.signalR.transports.serverSentEvents.js */
  1592. // Copyright (c) .NET Foundation. All rights reserved.
  1593. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  1594. /*global window:false */
  1595. /// <reference path="jquery.signalR.transports.common.js" />
  1596. (function ($, window, undefined) {
  1597. var signalR = $.signalR,
  1598. events = $.signalR.events,
  1599. changeState = $.signalR.changeState,
  1600. transportLogic = signalR.transports._logic,
  1601. clearReconnectAttemptTimeout = function (connection) {
  1602. window.clearTimeout(connection._.reconnectAttemptTimeoutHandle);
  1603. delete connection._.reconnectAttemptTimeoutHandle;
  1604. };
  1605. signalR.transports.serverSentEvents = {
  1606. name: "serverSentEvents",
  1607. supportsKeepAlive: function () {
  1608. return true;
  1609. },
  1610. timeOut: 3000,
  1611. start: function (connection, onSuccess, onFailed) {
  1612. var that = this,
  1613. opened = false,
  1614. $connection = $(connection),
  1615. reconnecting = !onSuccess,
  1616. url;
  1617. if (connection.eventSource) {
  1618. connection.log("The connection already has an event source. Stopping it.");
  1619. connection.stop();
  1620. }
  1621. if (!window.EventSource) {
  1622. if (onFailed) {
  1623. connection.log("This browser doesn't support SSE.");
  1624. onFailed();
  1625. }
  1626. return;
  1627. }
  1628. url = transportLogic.getUrl(connection, this.name, reconnecting);
  1629. try {
  1630. connection.log("Attempting to connect to SSE endpoint '" + url + "'.");
  1631. connection.eventSource = new window.EventSource(url, { withCredentials: connection.withCredentials });
  1632. }
  1633. catch (e) {
  1634. connection.log("EventSource failed trying to connect with error " + e.Message + ".");
  1635. if (onFailed) {
  1636. // The connection failed, call the failed callback
  1637. onFailed();
  1638. } else {
  1639. $connection.triggerHandler(events.onError, [signalR._.transportError(signalR.resources.eventSourceFailedToConnect, connection.transport, e)]);
  1640. if (reconnecting) {
  1641. // If we were reconnecting, rather than doing initial connect, then try reconnect again
  1642. that.reconnect(connection);
  1643. }
  1644. }
  1645. return;
  1646. }
  1647. if (reconnecting) {
  1648. connection._.reconnectAttemptTimeoutHandle = window.setTimeout(function () {
  1649. if (opened === false) {
  1650. // If we're reconnecting and the event source is attempting to connect,
  1651. // don't keep retrying. This causes duplicate connections to spawn.
  1652. if (connection.eventSource.readyState !== window.EventSource.OPEN) {
  1653. // If we were reconnecting, rather than doing initial connect, then try reconnect again
  1654. that.reconnect(connection);
  1655. }
  1656. }
  1657. },
  1658. that.timeOut);
  1659. }
  1660. connection.eventSource.addEventListener("open", function (e) {
  1661. connection.log("EventSource connected.");
  1662. clearReconnectAttemptTimeout(connection);
  1663. transportLogic.clearReconnectTimeout(connection);
  1664. if (opened === false) {
  1665. opened = true;
  1666. if (changeState(connection,
  1667. signalR.connectionState.reconnecting,
  1668. signalR.connectionState.connected) === true) {
  1669. $connection.triggerHandler(events.onReconnect);
  1670. }
  1671. }
  1672. }, false);
  1673. connection.eventSource.addEventListener("message", function (e) {
  1674. var res;
  1675. // process messages
  1676. if (e.data === "initialized") {
  1677. return;
  1678. }
  1679. try {
  1680. res = connection._parseResponse(e.data);
  1681. }
  1682. catch (error) {
  1683. transportLogic.handleParseFailure(connection, e.data, error, onFailed, e);
  1684. return;
  1685. }
  1686. transportLogic.processMessages(connection, res, onSuccess);
  1687. }, false);
  1688. connection.eventSource.addEventListener("error", function (e) {
  1689. var error = signalR._.transportError(
  1690. signalR.resources.eventSourceError,
  1691. connection.transport,
  1692. e);
  1693. // Only handle an error if the error is from the current Event Source.
  1694. // Sometimes on disconnect the server will push down an error event
  1695. // to an expired Event Source.
  1696. if (this !== connection.eventSource) {
  1697. return;
  1698. }
  1699. if (onFailed && onFailed(error)) {
  1700. return;
  1701. }
  1702. connection.log("EventSource readyState: " + connection.eventSource.readyState + ".");
  1703. if (e.eventPhase === window.EventSource.CLOSED) {
  1704. // We don't use the EventSource's native reconnect function as it
  1705. // doesn't allow us to change the URL when reconnecting. We need
  1706. // to change the URL to not include the /connect suffix, and pass
  1707. // the last message id we received.
  1708. connection.log("EventSource reconnecting due to the server connection ending.");
  1709. that.reconnect(connection);
  1710. } else {
  1711. // connection error
  1712. connection.log("EventSource error.");
  1713. $connection.triggerHandler(events.onError, [error]);
  1714. }
  1715. }, false);
  1716. },
  1717. reconnect: function (connection) {
  1718. transportLogic.reconnect(connection, this.name);
  1719. },
  1720. lostConnection: function (connection) {
  1721. this.reconnect(connection);
  1722. },
  1723. send: function (connection, data) {
  1724. transportLogic.ajaxSend(connection, data);
  1725. },
  1726. stop: function (connection) {
  1727. // Don't trigger a reconnect after stopping
  1728. clearReconnectAttemptTimeout(connection);
  1729. transportLogic.clearReconnectTimeout(connection);
  1730. if (connection && connection.eventSource) {
  1731. connection.log("EventSource calling close().");
  1732. connection.eventSource.close();
  1733. connection.eventSource = null;
  1734. delete connection.eventSource;
  1735. }
  1736. },
  1737. abort: function (connection, async) {
  1738. transportLogic.ajaxAbort(connection, async);
  1739. }
  1740. };
  1741. }(window.jQuery, window));
  1742. /* jquery.signalR.transports.foreverFrame.js */
  1743. // Copyright (c) .NET Foundation. All rights reserved.
  1744. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  1745. /*global window:false */
  1746. /// <reference path="jquery.signalR.transports.common.js" />
  1747. (function ($, window, undefined) {
  1748. var signalR = $.signalR,
  1749. events = $.signalR.events,
  1750. changeState = $.signalR.changeState,
  1751. transportLogic = signalR.transports._logic,
  1752. createFrame = function () {
  1753. var frame = window.document.createElement("iframe");
  1754. frame.setAttribute("style", "position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;");
  1755. return frame;
  1756. },
  1757. // Used to prevent infinite loading icon spins in older versions of ie
  1758. // We build this object inside a closure so we don't pollute the rest of
  1759. // the foreverFrame transport with unnecessary functions/utilities.
  1760. loadPreventer = (function () {
  1761. var loadingFixIntervalId = null,
  1762. loadingFixInterval = 1000,
  1763. attachedTo = 0;
  1764. return {
  1765. prevent: function () {
  1766. // Prevent additional iframe removal procedures from newer browsers
  1767. if (signalR._.ieVersion <= 8) {
  1768. // We only ever want to set the interval one time, so on the first attachedTo
  1769. if (attachedTo === 0) {
  1770. // Create and destroy iframe every 3 seconds to prevent loading icon, super hacky
  1771. loadingFixIntervalId = window.setInterval(function () {
  1772. var tempFrame = createFrame();
  1773. window.document.body.appendChild(tempFrame);
  1774. window.document.body.removeChild(tempFrame);
  1775. tempFrame = null;
  1776. }, loadingFixInterval);
  1777. }
  1778. attachedTo++;
  1779. }
  1780. },
  1781. cancel: function () {
  1782. // Only clear the interval if there's only one more object that the loadPreventer is attachedTo
  1783. if (attachedTo === 1) {
  1784. window.clearInterval(loadingFixIntervalId);
  1785. }
  1786. if (attachedTo > 0) {
  1787. attachedTo--;
  1788. }
  1789. }
  1790. };
  1791. })();
  1792. signalR.transports.foreverFrame = {
  1793. name: "foreverFrame",
  1794. supportsKeepAlive: function () {
  1795. return true;
  1796. },
  1797. // Added as a value here so we can create tests to verify functionality
  1798. iframeClearThreshold: 50,
  1799. start: function (connection, onSuccess, onFailed) {
  1800. if (connection.accessToken) {
  1801. if (onFailed) {
  1802. connection.log("Forever Frame does not support connections that require a Bearer token to connect, such as the Azure SignalR Service.");
  1803. onFailed();
  1804. }
  1805. return;
  1806. }
  1807. var that = this,
  1808. frameId = (transportLogic.foreverFrame.count += 1),
  1809. url,
  1810. frame = createFrame(),
  1811. frameLoadHandler = function () {
  1812. connection.log("Forever frame iframe finished loading and is no longer receiving messages.");
  1813. if (!onFailed || !onFailed()) {
  1814. that.reconnect(connection);
  1815. }
  1816. };
  1817. if (window.EventSource) {
  1818. // If the browser supports SSE, don't use Forever Frame
  1819. if (onFailed) {
  1820. connection.log("Forever Frame is not supported by SignalR on browsers with SSE support.");
  1821. onFailed();
  1822. }
  1823. return;
  1824. }
  1825. frame.setAttribute("data-signalr-connection-id", connection.id);
  1826. // Start preventing loading icon
  1827. // This will only perform work if the loadPreventer is not attached to another connection.
  1828. loadPreventer.prevent();
  1829. // Build the url
  1830. url = transportLogic.getUrl(connection, this.name);
  1831. url += "&frameId=" + frameId;
  1832. // add frame to the document prior to setting URL to avoid caching issues.
  1833. window.document.documentElement.appendChild(frame);
  1834. connection.log("Binding to iframe's load event.");
  1835. if (frame.addEventListener) {
  1836. frame.addEventListener("load", frameLoadHandler, false);
  1837. } else if (frame.attachEvent) {
  1838. frame.attachEvent("onload", frameLoadHandler);
  1839. }
  1840. frame.src = url;
  1841. transportLogic.foreverFrame.connections[frameId] = connection;
  1842. connection.frame = frame;
  1843. connection.frameId = frameId;
  1844. if (onSuccess) {
  1845. connection.onSuccess = function () {
  1846. connection.log("Iframe transport started.");
  1847. onSuccess();
  1848. };
  1849. }
  1850. },
  1851. reconnect: function (connection) {
  1852. var that = this;
  1853. // Need to verify connection state and verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration.
  1854. if (transportLogic.isConnectedOrReconnecting(connection) && transportLogic.verifyLastActive(connection)) {
  1855. window.setTimeout(function () {
  1856. // Verify that we're ok to reconnect.
  1857. if (!transportLogic.verifyLastActive(connection)) {
  1858. return;
  1859. }
  1860. if (connection.frame && transportLogic.ensureReconnectingState(connection)) {
  1861. var frame = connection.frame,
  1862. src = transportLogic.getUrl(connection, that.name, true) + "&frameId=" + connection.frameId;
  1863. connection.log("Updating iframe src to '" + src + "'.");
  1864. frame.src = src;
  1865. }
  1866. }, connection.reconnectDelay);
  1867. }
  1868. },
  1869. lostConnection: function (connection) {
  1870. this.reconnect(connection);
  1871. },
  1872. send: function (connection, data) {
  1873. transportLogic.ajaxSend(connection, data);
  1874. },
  1875. receive: function (connection, data) {
  1876. var cw,
  1877. body,
  1878. response;
  1879. if (connection.json !== connection._originalJson) {
  1880. // If there's a custom JSON parser configured then serialize the object
  1881. // using the original (browser) JSON parser and then deserialize it using
  1882. // the custom parser (connection._parseResponse does that). This is so we
  1883. // can easily send the response from the server as "raw" JSON but still
  1884. // support custom JSON deserialization in the browser.
  1885. data = connection._originalJson.stringify(data);
  1886. }
  1887. response = connection._parseResponse(data);
  1888. transportLogic.processMessages(connection, response, connection.onSuccess);
  1889. // Protect against connection stopping from a callback trigger within the processMessages above.
  1890. if (connection.state === $.signalR.connectionState.connected) {
  1891. // Delete the script & div elements
  1892. connection.frameMessageCount = (connection.frameMessageCount || 0) + 1;
  1893. if (connection.frameMessageCount > signalR.transports.foreverFrame.iframeClearThreshold) {
  1894. connection.frameMessageCount = 0;
  1895. cw = connection.frame.contentWindow || connection.frame.contentDocument;
  1896. if (cw && cw.document && cw.document.body) {
  1897. body = cw.document.body;
  1898. // Remove all the child elements from the iframe's body to conserver memory
  1899. while (body.firstChild) {
  1900. body.removeChild(body.firstChild);
  1901. }
  1902. }
  1903. }
  1904. }
  1905. },
  1906. stop: function (connection) {
  1907. var cw = null;
  1908. // Stop attempting to prevent loading icon
  1909. loadPreventer.cancel();
  1910. if (connection.frame) {
  1911. if (connection.frame.stop) {
  1912. connection.frame.stop();
  1913. } else {
  1914. try {
  1915. cw = connection.frame.contentWindow || connection.frame.contentDocument;
  1916. if (cw.document && cw.document.execCommand) {
  1917. cw.document.execCommand("Stop");
  1918. }
  1919. }
  1920. catch (e) {
  1921. connection.log("Error occurred when stopping foreverFrame transport. Message = " + e.message + ".");
  1922. }
  1923. }
  1924. // Ensure the iframe is where we left it
  1925. if (connection.frame.parentNode === window.document.documentElement) {
  1926. window.document.documentElement.removeChild(connection.frame);
  1927. }
  1928. delete transportLogic.foreverFrame.connections[connection.frameId];
  1929. connection.frame = null;
  1930. connection.frameId = null;
  1931. delete connection.frame;
  1932. delete connection.frameId;
  1933. delete connection.onSuccess;
  1934. delete connection.frameMessageCount;
  1935. connection.log("Stopping forever frame.");
  1936. }
  1937. },
  1938. abort: function (connection, async) {
  1939. transportLogic.ajaxAbort(connection, async);
  1940. },
  1941. getConnection: function (id) {
  1942. return transportLogic.foreverFrame.connections[id];
  1943. },
  1944. started: function (connection) {
  1945. if (changeState(connection,
  1946. signalR.connectionState.reconnecting,
  1947. signalR.connectionState.connected) === true) {
  1948. $(connection).triggerHandler(events.onReconnect);
  1949. }
  1950. }
  1951. };
  1952. }(window.jQuery, window));
  1953. /* jquery.signalR.transports.longPolling.js */
  1954. // Copyright (c) .NET Foundation. All rights reserved.
  1955. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  1956. /*global window:false */
  1957. /// <reference path="jquery.signalR.transports.common.js" />
  1958. (function ($, window, undefined) {
  1959. var signalR = $.signalR,
  1960. events = $.signalR.events,
  1961. changeState = $.signalR.changeState,
  1962. isDisconnecting = $.signalR.isDisconnecting,
  1963. transportLogic = signalR.transports._logic;
  1964. signalR.transports.longPolling = {
  1965. name: "longPolling",
  1966. supportsKeepAlive: function () {
  1967. return false;
  1968. },
  1969. reconnectDelay: 3000,
  1970. start: function (connection, onSuccess, onFailed) {
  1971. /// <summary>Starts the long polling connection</summary>
  1972. /// <param name="connection" type="signalR">The SignalR connection to start</param>
  1973. var that = this,
  1974. fireConnect = function () {
  1975. fireConnect = $.noop;
  1976. connection.log("LongPolling connected.");
  1977. if (onSuccess) {
  1978. onSuccess();
  1979. } else {
  1980. connection.log("WARNING! The client received an init message after reconnecting.");
  1981. }
  1982. },
  1983. tryFailConnect = function (error) {
  1984. if (onFailed(error)) {
  1985. connection.log("LongPolling failed to connect.");
  1986. return true;
  1987. }
  1988. return false;
  1989. },
  1990. privateData = connection._,
  1991. reconnectErrors = 0,
  1992. fireReconnected = function (instance) {
  1993. window.clearTimeout(privateData.reconnectTimeoutId);
  1994. privateData.reconnectTimeoutId = null;
  1995. if (changeState(instance,
  1996. signalR.connectionState.reconnecting,
  1997. signalR.connectionState.connected) === true) {
  1998. // Successfully reconnected!
  1999. instance.log("Raising the reconnect event");
  2000. $(instance).triggerHandler(events.onReconnect);
  2001. }
  2002. },
  2003. // 1 hour
  2004. maxFireReconnectedTimeout = 3600000;
  2005. if (connection.pollXhr) {
  2006. connection.log("Polling xhr requests already exists, aborting.");
  2007. connection.stop();
  2008. }
  2009. connection.messageId = null;
  2010. privateData.reconnectTimeoutId = null;
  2011. privateData.pollTimeoutId = window.setTimeout(function () {
  2012. (function poll(instance, raiseReconnect) {
  2013. var messageId = instance.messageId,
  2014. connect = (messageId === null),
  2015. reconnecting = !connect,
  2016. polling = !raiseReconnect,
  2017. url = transportLogic.getUrl(instance, that.name, reconnecting, polling, true /* use Post for longPolling */),
  2018. postData = {};
  2019. if (instance.messageId) {
  2020. postData.messageId = instance.messageId;
  2021. }
  2022. if (instance.groupsToken) {
  2023. postData.groupsToken = instance.groupsToken;
  2024. }
  2025. // If we've disconnected during the time we've tried to re-instantiate the poll then stop.
  2026. if (isDisconnecting(instance) === true) {
  2027. return;
  2028. }
  2029. connection.log("Opening long polling request to '" + url + "'.");
  2030. instance.pollXhr = transportLogic.ajax(connection, {
  2031. xhrFields: {
  2032. onprogress: function () {
  2033. transportLogic.markLastMessage(connection);
  2034. }
  2035. },
  2036. url: url,
  2037. type: "POST",
  2038. contentType: signalR._.defaultContentType,
  2039. data: postData,
  2040. timeout: connection._.pollTimeout,
  2041. headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
  2042. success: function (result) {
  2043. var minData,
  2044. delay = 0,
  2045. data,
  2046. shouldReconnect;
  2047. connection.log("Long poll complete.");
  2048. // Reset our reconnect errors so if we transition into a reconnecting state again we trigger
  2049. // reconnected quickly
  2050. reconnectErrors = 0;
  2051. try {
  2052. // Remove any keep-alives from the beginning of the result
  2053. minData = connection._parseResponse(result);
  2054. }
  2055. catch (error) {
  2056. transportLogic.handleParseFailure(instance, result, error, tryFailConnect, instance.pollXhr);
  2057. return;
  2058. }
  2059. // If there's currently a timeout to trigger reconnect, fire it now before processing messages
  2060. if (privateData.reconnectTimeoutId !== null) {
  2061. fireReconnected(instance);
  2062. }
  2063. if (minData) {
  2064. data = transportLogic.maximizePersistentResponse(minData);
  2065. }
  2066. transportLogic.processMessages(instance, minData, fireConnect);
  2067. if (data &&
  2068. $.type(data.LongPollDelay) === "number") {
  2069. delay = data.LongPollDelay;
  2070. }
  2071. if (isDisconnecting(instance) === true) {
  2072. return;
  2073. }
  2074. shouldReconnect = data && data.ShouldReconnect;
  2075. if (shouldReconnect) {
  2076. // Transition into the reconnecting state
  2077. // If this fails then that means that the user transitioned the connection into a invalid state in processMessages.
  2078. if (!transportLogic.ensureReconnectingState(instance)) {
  2079. return;
  2080. }
  2081. }
  2082. // We never want to pass a raiseReconnect flag after a successful poll. This is handled via the error function
  2083. if (delay > 0) {
  2084. privateData.pollTimeoutId = window.setTimeout(function () {
  2085. poll(instance, shouldReconnect);
  2086. }, delay);
  2087. } else {
  2088. poll(instance, shouldReconnect);
  2089. }
  2090. },
  2091. error: function (data, textStatus) {
  2092. var error = signalR._.transportError(signalR.resources.longPollFailed, connection.transport, data, instance.pollXhr);
  2093. // Stop trying to trigger reconnect, connection is in an error state
  2094. // If we're not in the reconnect state this will noop
  2095. window.clearTimeout(privateData.reconnectTimeoutId);
  2096. privateData.reconnectTimeoutId = null;
  2097. if (textStatus === "abort") {
  2098. connection.log("Aborted xhr request.");
  2099. return;
  2100. }
  2101. if (!tryFailConnect(error)) {
  2102. // Increment our reconnect errors, we assume all errors to be reconnect errors
  2103. // In the case that it's our first error this will cause Reconnect to be fired
  2104. // after 1 second due to reconnectErrors being = 1.
  2105. reconnectErrors++;
  2106. if (connection.state !== signalR.connectionState.reconnecting) {
  2107. connection.log("An error occurred using longPolling. Status = " + textStatus + ". Response = " + data.responseText + ".");
  2108. $(instance).triggerHandler(events.onError, [error]);
  2109. }
  2110. // We check the state here to verify that we're not in an invalid state prior to verifying Reconnect.
  2111. // If we're not in connected or reconnecting then the next ensureReconnectingState check will fail and will return.
  2112. // Therefore we don't want to change that failure code path.
  2113. if ((connection.state === signalR.connectionState.connected ||
  2114. connection.state === signalR.connectionState.reconnecting) &&
  2115. !transportLogic.verifyLastActive(connection)) {
  2116. return;
  2117. }
  2118. // Transition into the reconnecting state
  2119. // If this fails then that means that the user transitioned the connection into the disconnected or connecting state within the above error handler trigger.
  2120. if (!transportLogic.ensureReconnectingState(instance)) {
  2121. return;
  2122. }
  2123. // Call poll with the raiseReconnect flag as true after the reconnect delay
  2124. privateData.pollTimeoutId = window.setTimeout(function () {
  2125. poll(instance, true);
  2126. }, that.reconnectDelay);
  2127. }
  2128. }
  2129. });
  2130. // This will only ever pass after an error has occurred via the poll ajax procedure.
  2131. if (reconnecting && raiseReconnect === true) {
  2132. // We wait to reconnect depending on how many times we've failed to reconnect.
  2133. // This is essentially a heuristic that will exponentially increase in wait time before
  2134. // triggering reconnected. This depends on the "error" handler of Poll to cancel this
  2135. // timeout if it triggers before the Reconnected event fires.
  2136. // The Math.min at the end is to ensure that the reconnect timeout does not overflow.
  2137. privateData.reconnectTimeoutId = window.setTimeout(function () { fireReconnected(instance); }, Math.min(1000 * (Math.pow(2, reconnectErrors) - 1), maxFireReconnectedTimeout));
  2138. }
  2139. }(connection));
  2140. }, 250); // Have to delay initial poll so Chrome doesn't show loader spinner in tab
  2141. },
  2142. lostConnection: function (connection) {
  2143. if (connection.pollXhr) {
  2144. connection.pollXhr.abort("lostConnection");
  2145. }
  2146. },
  2147. send: function (connection, data) {
  2148. transportLogic.ajaxSend(connection, data);
  2149. },
  2150. stop: function (connection) {
  2151. /// <summary>Stops the long polling connection</summary>
  2152. /// <param name="connection" type="signalR">The SignalR connection to stop</param>
  2153. window.clearTimeout(connection._.pollTimeoutId);
  2154. window.clearTimeout(connection._.reconnectTimeoutId);
  2155. delete connection._.pollTimeoutId;
  2156. delete connection._.reconnectTimeoutId;
  2157. if (connection.pollXhr) {
  2158. connection.pollXhr.abort();
  2159. connection.pollXhr = null;
  2160. delete connection.pollXhr;
  2161. }
  2162. },
  2163. abort: function (connection, async) {
  2164. transportLogic.ajaxAbort(connection, async);
  2165. }
  2166. };
  2167. }(window.jQuery, window));
  2168. /* jquery.signalR.hubs.js */
  2169. // Copyright (c) .NET Foundation. All rights reserved.
  2170. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  2171. /*global window:false */
  2172. /// <reference path="jquery.signalR.core.js" />
  2173. (function ($, window, undefined) {
  2174. var nextGuid = 0;
  2175. var eventNamespace = ".hubProxy",
  2176. signalR = $.signalR;
  2177. function makeEventName(event) {
  2178. return event + eventNamespace;
  2179. }
  2180. // Equivalent to Array.prototype.map
  2181. function map(arr, fun, thisp) {
  2182. var i,
  2183. length = arr.length,
  2184. result = [];
  2185. for (i = 0; i < length; i += 1) {
  2186. if (arr.hasOwnProperty(i)) {
  2187. result[i] = fun.call(thisp, arr[i], i, arr);
  2188. }
  2189. }
  2190. return result;
  2191. }
  2192. function getArgValue(a) {
  2193. return $.isFunction(a) ? null : ($.type(a) === "undefined" ? null : a);
  2194. }
  2195. function hasMembers(obj) {
  2196. for (var key in obj) {
  2197. // If we have any properties in our callback map then we have callbacks and can exit the loop via return
  2198. if (obj.hasOwnProperty(key)) {
  2199. return true;
  2200. }
  2201. }
  2202. return false;
  2203. }
  2204. function clearInvocationCallbacks(connection, error) {
  2205. /// <param name="connection" type="hubConnection" />
  2206. var callbacks = connection._.invocationCallbacks,
  2207. callback;
  2208. if (hasMembers(callbacks)) {
  2209. connection.log("Clearing hub invocation callbacks with error: " + error + ".");
  2210. }
  2211. // Reset the callback cache now as we have a local var referencing it
  2212. connection._.invocationCallbackId = 0;
  2213. delete connection._.invocationCallbacks;
  2214. connection._.invocationCallbacks = {};
  2215. // Loop over the callbacks and invoke them.
  2216. // We do this using a local var reference and *after* we've cleared the cache
  2217. // so that if a fail callback itself tries to invoke another method we don't
  2218. // end up with its callback in the list we're looping over.
  2219. for (var callbackId in callbacks) {
  2220. callback = callbacks[callbackId];
  2221. callback.method.call(callback.scope, { E: error });
  2222. }
  2223. }
  2224. // hubProxy
  2225. function hubProxy(hubConnection, hubName) {
  2226. /// <summary>
  2227. /// Creates a new proxy object for the given hub connection that can be used to invoke
  2228. /// methods on server hubs and handle client method invocation requests from the server.
  2229. /// </summary>
  2230. return new hubProxy.fn.init(hubConnection, hubName);
  2231. }
  2232. hubProxy.fn = hubProxy.prototype = {
  2233. init: function (connection, hubName) {
  2234. this.state = {};
  2235. this.connection = connection;
  2236. this.hubName = hubName;
  2237. this._ = {
  2238. callbackMap: {}
  2239. };
  2240. },
  2241. constructor: hubProxy,
  2242. hasSubscriptions: function () {
  2243. return hasMembers(this._.callbackMap);
  2244. },
  2245. on: function (eventName, callback, callbackIdentity) {
  2246. /// <summary>Wires up a callback to be invoked when a invocation request is received from the server hub.</summary>
  2247. /// <param name="eventName" type="String">The name of the hub event to register the callback for.</param>
  2248. /// <param name="callback" type="Function">The callback to be invoked.</param>
  2249. /// <param name="callbackIdentity" type="Object">An optional object to use as the "identity" for the callback when checking if the handler has already been registered. Defaults to the value of 'callback' if not provided.</param>
  2250. var that = this,
  2251. callbackMap = that._.callbackMap;
  2252. // We need the third "identity" argument because the registerHubProxies call made by signalr/js wraps the user-provided callback in a custom wrapper which breaks the identity comparison.
  2253. // callbackIdentity allows the caller of `on` to provide a separate object to use as the "identity". `registerHubProxies` uses the original user callback as this identity object.
  2254. callbackIdentity = callbackIdentity || callback;
  2255. // Assign a global ID to the identity object. This tags the object so we can detect the same object when it comes back.
  2256. if(!callbackIdentity._signalRGuid) {
  2257. callbackIdentity._signalRGuid = nextGuid++;
  2258. }
  2259. // Normalize the event name to lowercase
  2260. eventName = eventName.toLowerCase();
  2261. // If there is not an event registered for this callback yet we want to create its event space in the callback map.
  2262. var callbackSpace = callbackMap[eventName];
  2263. if (!callbackSpace) {
  2264. callbackSpace = [];
  2265. callbackMap[eventName] = callbackSpace;
  2266. }
  2267. // Check if there's already a registration
  2268. var registration;
  2269. for (var i = 0; i < callbackSpace.length; i++) {
  2270. if (callbackSpace[i].guid === callbackIdentity._signalRGuid) {
  2271. registration = callbackSpace[i];
  2272. }
  2273. }
  2274. // Create a registration if there isn't one already
  2275. if (!registration) {
  2276. registration = {
  2277. guid: callbackIdentity._signalRGuid,
  2278. eventHandlers: []
  2279. };
  2280. callbackMap[eventName].push(registration);
  2281. }
  2282. var handler = function (e, data) {
  2283. callback.apply(that, data);
  2284. };
  2285. registration.eventHandlers.push(handler);
  2286. $(that).bind(makeEventName(eventName), handler);
  2287. return that;
  2288. },
  2289. off: function (eventName, callback, callbackIdentity) {
  2290. /// <summary>Removes the callback invocation request from the server hub for the given event name.</summary>
  2291. /// <param name="eventName" type="String">The name of the hub event to unregister the callback for.</param>
  2292. /// <param name="callback" type="Function">The callback to be removed.</param>
  2293. /// <param name="callbackIdentity" type="Object">An optional object to use as the "identity" when looking up the callback. Corresponds to the same parameter provided to 'on'. Defaults to the value of 'callback' if not provided.</param>
  2294. var that = this,
  2295. callbackMap = that._.callbackMap,
  2296. callbackSpace;
  2297. callbackIdentity = callbackIdentity || callback;
  2298. // Normalize the event name to lowercase
  2299. eventName = eventName.toLowerCase();
  2300. callbackSpace = callbackMap[eventName];
  2301. // Verify that there is an event space to unbind
  2302. if (callbackSpace) {
  2303. if (callback) {
  2304. // Find the callback registration
  2305. var callbackRegistration;
  2306. var callbackIndex;
  2307. for (var i = 0; i < callbackSpace.length; i++) {
  2308. if (callbackSpace[i].guid === callbackIdentity._signalRGuid) {
  2309. callbackIndex = i;
  2310. callbackRegistration = callbackSpace[i];
  2311. }
  2312. }
  2313. // Only unbind if there's an event bound with eventName and a callback with the specified callback
  2314. if (callbackRegistration) {
  2315. // Unbind all event handlers associated with the registration.
  2316. for (var j = 0; j < callbackRegistration.eventHandlers.length; j++) {
  2317. $(that).unbind(makeEventName(eventName), callbackRegistration.eventHandlers[j]);
  2318. }
  2319. // Remove the registration from the list
  2320. callbackSpace.splice(i, 1);
  2321. // Check if there are any registrations left, if not we need to destroy it.
  2322. if (callbackSpace.length === 0) {
  2323. delete callbackMap[eventName];
  2324. }
  2325. }
  2326. } else if (!callback) { // Check if we're removing the whole event and we didn't error because of an invalid callback
  2327. $(that).unbind(makeEventName(eventName));
  2328. delete callbackMap[eventName];
  2329. }
  2330. }
  2331. return that;
  2332. },
  2333. invoke: function (methodName) {
  2334. /// <summary>Invokes a server hub method with the given arguments.</summary>
  2335. /// <param name="methodName" type="String">The name of the server hub method.</param>
  2336. var that = this,
  2337. connection = that.connection,
  2338. args = $.makeArray(arguments).slice(1),
  2339. argValues = map(args, getArgValue),
  2340. data = { H: that.hubName, M: methodName, A: argValues, I: connection._.invocationCallbackId },
  2341. d = $.Deferred(),
  2342. callback = function (minResult) {
  2343. var result = that._maximizeHubResponse(minResult),
  2344. source,
  2345. error;
  2346. // Update the hub state
  2347. $.extend(that.state, result.State);
  2348. if (result.Progress) {
  2349. if (d.notifyWith) {
  2350. // Progress is only supported in jQuery 1.7+
  2351. d.notifyWith(that, [result.Progress.Data]);
  2352. } else if (!connection._.progressjQueryVersionLogged) {
  2353. connection.log("A hub method invocation progress update was received but the version of jQuery in use (" + $.prototype.jquery + ") does not support progress updates. Upgrade to jQuery 1.7+ to receive progress notifications.");
  2354. connection._.progressjQueryVersionLogged = true;
  2355. }
  2356. } else if (result.Error) {
  2357. // Server hub method threw an exception, log it & reject the deferred
  2358. if (result.StackTrace) {
  2359. connection.log(result.Error + "\n" + result.StackTrace + ".");
  2360. }
  2361. // result.ErrorData is only set if a HubException was thrown
  2362. source = result.IsHubException ? "HubException" : "Exception";
  2363. error = signalR._.error(result.Error, source);
  2364. error.data = result.ErrorData;
  2365. connection.log(that.hubName + "." + methodName + " failed to execute. Error: " + error.message);
  2366. d.rejectWith(that, [error]);
  2367. } else {
  2368. // Server invocation succeeded, resolve the deferred
  2369. connection.log("Invoked " + that.hubName + "." + methodName);
  2370. d.resolveWith(that, [result.Result]);
  2371. }
  2372. };
  2373. connection._.invocationCallbacks[connection._.invocationCallbackId.toString()] = { scope: that, method: callback };
  2374. connection._.invocationCallbackId += 1;
  2375. if (!$.isEmptyObject(that.state)) {
  2376. data.S = that.state;
  2377. }
  2378. connection.log("Invoking " + that.hubName + "." + methodName);
  2379. connection.send(data);
  2380. return d.promise();
  2381. },
  2382. _maximizeHubResponse: function (minHubResponse) {
  2383. return {
  2384. State: minHubResponse.S,
  2385. Result: minHubResponse.R,
  2386. Progress: minHubResponse.P ? {
  2387. Id: minHubResponse.P.I,
  2388. Data: minHubResponse.P.D
  2389. } : null,
  2390. Id: minHubResponse.I,
  2391. IsHubException: minHubResponse.H,
  2392. Error: minHubResponse.E,
  2393. StackTrace: minHubResponse.T,
  2394. ErrorData: minHubResponse.D
  2395. };
  2396. }
  2397. };
  2398. hubProxy.fn.init.prototype = hubProxy.fn;
  2399. // hubConnection
  2400. function hubConnection(url, options) {
  2401. /// <summary>Creates a new hub connection.</summary>
  2402. /// <param name="url" type="String">[Optional] The hub route url, defaults to "/signalr".</param>
  2403. /// <param name="options" type="Object">[Optional] Settings to use when creating the hubConnection.</param>
  2404. var settings = {
  2405. qs: null,
  2406. logging: false,
  2407. useDefaultPath: true
  2408. };
  2409. $.extend(settings, options);
  2410. if (!url || settings.useDefaultPath) {
  2411. url = (url || "") + "/signalr";
  2412. }
  2413. return new hubConnection.fn.init(url, settings);
  2414. }
  2415. hubConnection.fn = hubConnection.prototype = $.connection();
  2416. hubConnection.fn.init = function (url, options) {
  2417. var settings = {
  2418. qs: null,
  2419. logging: false,
  2420. useDefaultPath: true
  2421. },
  2422. connection = this;
  2423. $.extend(settings, options);
  2424. // Call the base constructor
  2425. $.signalR.fn.init.call(connection, url, settings.qs, settings.logging);
  2426. // Object to store hub proxies for this connection
  2427. connection.proxies = {};
  2428. connection._.invocationCallbackId = 0;
  2429. connection._.invocationCallbacks = {};
  2430. // Wire up the received handler
  2431. connection.received(function (minData) {
  2432. var data, proxy, dataCallbackId, callback, hubName, eventName;
  2433. if (!minData) {
  2434. return;
  2435. }
  2436. // We have to handle progress updates first in order to ensure old clients that receive
  2437. // progress updates enter the return value branch and then no-op when they can't find
  2438. // the callback in the map (because the minData.I value will not be a valid callback ID)
  2439. // Process progress notification
  2440. if (typeof (minData.P) !== "undefined") {
  2441. dataCallbackId = minData.P.I.toString();
  2442. callback = connection._.invocationCallbacks[dataCallbackId];
  2443. if (callback) {
  2444. callback.method.call(callback.scope, minData);
  2445. }
  2446. } else if (typeof (minData.I) !== "undefined") {
  2447. // We received the return value from a server method invocation, look up callback by id and call it
  2448. dataCallbackId = minData.I.toString();
  2449. callback = connection._.invocationCallbacks[dataCallbackId];
  2450. if (callback) {
  2451. // Delete the callback from the proxy
  2452. connection._.invocationCallbacks[dataCallbackId] = null;
  2453. delete connection._.invocationCallbacks[dataCallbackId];
  2454. // Invoke the callback
  2455. callback.method.call(callback.scope, minData);
  2456. }
  2457. } else {
  2458. data = this._maximizeClientHubInvocation(minData);
  2459. // We received a client invocation request, i.e. broadcast from server hub
  2460. connection.log("Triggering client hub event '" + data.Method + "' on hub '" + data.Hub + "'.");
  2461. // Normalize the names to lowercase
  2462. hubName = data.Hub.toLowerCase();
  2463. eventName = data.Method.toLowerCase();
  2464. // Trigger the local invocation event
  2465. proxy = this.proxies[hubName];
  2466. // Update the hub state
  2467. $.extend(proxy.state, data.State);
  2468. $(proxy).triggerHandler(makeEventName(eventName), [data.Args]);
  2469. }
  2470. });
  2471. connection.error(function (errData, origData) {
  2472. var callbackId, callback;
  2473. if (!origData) {
  2474. // No original data passed so this is not a send error
  2475. return;
  2476. }
  2477. callbackId = origData.I;
  2478. callback = connection._.invocationCallbacks[callbackId];
  2479. // Verify that there is a callback bound (could have been cleared)
  2480. if (callback) {
  2481. // Delete the callback
  2482. connection._.invocationCallbacks[callbackId] = null;
  2483. delete connection._.invocationCallbacks[callbackId];
  2484. // Invoke the callback with an error to reject the promise
  2485. callback.method.call(callback.scope, { E: errData });
  2486. }
  2487. });
  2488. connection.reconnecting(function () {
  2489. if (connection.transport && connection.transport.name === "webSockets") {
  2490. clearInvocationCallbacks(connection, "Connection started reconnecting before invocation result was received.");
  2491. }
  2492. });
  2493. connection.disconnected(function () {
  2494. clearInvocationCallbacks(connection, "Connection was disconnected before invocation result was received.");
  2495. });
  2496. };
  2497. hubConnection.fn._maximizeClientHubInvocation = function (minClientHubInvocation) {
  2498. return {
  2499. Hub: minClientHubInvocation.H,
  2500. Method: minClientHubInvocation.M,
  2501. Args: minClientHubInvocation.A,
  2502. State: minClientHubInvocation.S
  2503. };
  2504. };
  2505. hubConnection.fn._registerSubscribedHubs = function () {
  2506. /// <summary>
  2507. /// Sets the starting event to loop through the known hubs and register any new hubs
  2508. /// that have been added to the proxy.
  2509. /// </summary>
  2510. var connection = this;
  2511. if (!connection._subscribedToHubs) {
  2512. connection._subscribedToHubs = true;
  2513. connection.starting(function () {
  2514. // Set the connection's data object with all the hub proxies with active subscriptions.
  2515. // These proxies will receive notifications from the server.
  2516. var subscribedHubs = [];
  2517. $.each(connection.proxies, function (key) {
  2518. if (this.hasSubscriptions()) {
  2519. subscribedHubs.push({ name: key });
  2520. connection.log("Client subscribed to hub '" + key + "'.");
  2521. }
  2522. });
  2523. if (subscribedHubs.length === 0) {
  2524. connection.log("No hubs have been subscribed to. The client will not receive data from hubs. To fix, declare at least one client side function prior to connection start for each hub you wish to subscribe to.");
  2525. }
  2526. connection.data = connection.json.stringify(subscribedHubs);
  2527. });
  2528. }
  2529. };
  2530. hubConnection.fn.createHubProxy = function (hubName) {
  2531. /// <summary>
  2532. /// Creates a new proxy object for the given hub connection that can be used to invoke
  2533. /// methods on server hubs and handle client method invocation requests from the server.
  2534. /// </summary>
  2535. /// <param name="hubName" type="String">
  2536. /// The name of the hub on the server to create the proxy for.
  2537. /// </param>
  2538. // Normalize the name to lowercase
  2539. hubName = hubName.toLowerCase();
  2540. var proxy = this.proxies[hubName];
  2541. if (!proxy) {
  2542. proxy = hubProxy(this, hubName);
  2543. this.proxies[hubName] = proxy;
  2544. }
  2545. this._registerSubscribedHubs();
  2546. return proxy;
  2547. };
  2548. hubConnection.fn.init.prototype = hubConnection.fn;
  2549. $.hubConnection = hubConnection;
  2550. }(window.jQuery, window));
  2551. /* jquery.signalR.version.js */
  2552. // Copyright (c) .NET Foundation. All rights reserved.
  2553. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  2554. /*global window:false */
  2555. /// <reference path="jquery.signalR.core.js" />
  2556. (function ($, undefined) {
  2557. // This will be modified by the build script
  2558. $.signalR.version = "2.4.0";
  2559. }(window.jQuery));