jquery.signalR-2.4.1.js 136 KB

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