Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

2957 linhas
121 KiB

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