diff --git a/CWASP Razor Edition/Program.cs b/CWASP Razor Edition/Program.cs
index 2ffb015..da60326 100644
--- a/CWASP Razor Edition/Program.cs
+++ b/CWASP Razor Edition/Program.cs
@@ -2,6 +2,7 @@
using Microsoft.Extensions.DependencyInjection;
using CWASP_Razor_Edition.Data;
using CWASP_Razor_Edition.Models;
+using CWASP_Razor_Edition.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
@@ -9,6 +10,7 @@
builder.Services.AddDbContext(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("CWASPdbconnection") ?? throw new InvalidOperationException("Connection string 'CWASPdbconnection' not found.")));
builder.Services.AddApplicationInsightsTelemetry();
+builder.Services.AddSignalR().AddAzureSignalR();
var app = builder.Build();
@@ -37,5 +39,6 @@
app.UseAuthorization();
app.MapRazorPages();
+app.MapHub("/indexHub");
app.Run();
diff --git a/CWASP Razor Edition/Properties/ServiceDependencies/local/signalr1.arm.json b/CWASP Razor Edition/Properties/ServiceDependencies/local/signalr1.arm.json
new file mode 100644
index 0000000..58137d2
--- /dev/null
+++ b/CWASP Razor Edition/Properties/ServiceDependencies/local/signalr1.arm.json
@@ -0,0 +1,71 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "resourceGroupName": {
+ "type": "string",
+ "defaultValue": "CWASP-AppService",
+ "metadata": {
+ "_parameterType": "resourceGroup",
+ "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking."
+ }
+ },
+ "resourceGroupLocation": {
+ "type": "string",
+ "defaultValue": "eastus",
+ "metadata": {
+ "_parameterType": "location",
+ "description": "Location of the resource group. Resource groups could have different location than resources."
+ }
+ },
+ "resourceLocation": {
+ "type": "string",
+ "defaultValue": "[parameters('resourceGroupLocation')]",
+ "metadata": {
+ "_parameterType": "location",
+ "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there."
+ }
+ }
+ },
+ "resources": [
+ {
+ "type": "Microsoft.Resources/resourceGroups",
+ "name": "[parameters('resourceGroupName')]",
+ "location": "[parameters('resourceGroupLocation')]",
+ "apiVersion": "2019-10-01"
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat('CWASP-SignalR-Service', subscription().subscriptionId)))]",
+ "resourceGroup": "[parameters('resourceGroupName')]",
+ "apiVersion": "2019-10-01",
+ "dependsOn": [
+ "[parameters('resourceGroupName')]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "resources": [
+ {
+ "sku": {
+ "name": "Free_F1",
+ "tier": "Free",
+ "size": "F1",
+ "capacity": 1
+ },
+ "location": "[parameters('resourceLocation')]",
+ "name": "CWASP-SignalR-Service",
+ "type": "Microsoft.SignalRService/SignalR",
+ "apiVersion": "2018-10-01"
+ }
+ ]
+ }
+ }
+ }
+ ],
+ "metadata": {
+ "_dependencyType": "signalr.azure"
+ }
+}
\ No newline at end of file
diff --git a/CWASP Razor Edition/Properties/launchSettings.json b/CWASP Razor Edition/Properties/launchSettings.json
index 0306b3e..257d2c8 100644
--- a/CWASP Razor Edition/Properties/launchSettings.json
+++ b/CWASP Razor Edition/Properties/launchSettings.json
@@ -15,7 +15,8 @@
"launchBrowser": true,
"applicationUrl": "http://localhost:5095",
"environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.Azure.SignalR"
}
},
"https": {
@@ -24,15 +25,17 @@
"launchBrowser": true,
"applicationUrl": "https://localhost:7229;http://localhost:5095",
"environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.Azure.SignalR"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.Azure.SignalR"
}
}
}
-}
+}
\ No newline at end of file
diff --git a/CWASP Razor Edition/Properties/serviceDependencies.json b/CWASP Razor Edition/Properties/serviceDependencies.json
index 05a9707..11f1469 100644
--- a/CWASP Razor Edition/Properties/serviceDependencies.json
+++ b/CWASP Razor Edition/Properties/serviceDependencies.json
@@ -9,6 +9,11 @@
"type": "appInsights",
"connectionId": "APPLICATIONINSIGHTS_CONNECTION_STRING",
"dynamicId": null
+ },
+ "signalr1": {
+ "type": "signalr",
+ "connectionId": "Azure:SignalR:ConnectionString",
+ "dynamicId": null
}
}
}
\ No newline at end of file
diff --git a/CWASP Razor Edition/Properties/serviceDependencies.local.json b/CWASP Razor Edition/Properties/serviceDependencies.local.json
index 96b9096..081c2be 100644
--- a/CWASP Razor Edition/Properties/serviceDependencies.local.json
+++ b/CWASP Razor Edition/Properties/serviceDependencies.local.json
@@ -10,6 +10,14 @@
"type": "appInsights.azure",
"connectionId": "APPLICATIONINSIGHTS_CONNECTION_STRING",
"dynamicId": null
+ },
+ "signalr1": {
+ "serviceConnectorResourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroupName')]/providers/Microsoft.ServiceLinker/locations/eastus/connectors/AzureSignalRConnectionString_B403A73EB6",
+ "secretStore": "LocalSecretsFile",
+ "resourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroupName')]/providers/Microsoft.SignalRService/SignalR/CWASP-SignalR-Service",
+ "type": "signalr.azure",
+ "connectionId": "Azure:SignalR:ConnectionString",
+ "dynamicId": null
}
}
}
\ No newline at end of file
diff --git a/CWASP Razor Edition/libman.json b/CWASP Razor Edition/libman.json
index 3642968..cfb8f5e 100644
--- a/CWASP Razor Edition/libman.json
+++ b/CWASP Razor Edition/libman.json
@@ -9,6 +9,14 @@
"dist/browser/signalr.js",
"dist/browser/signalr.min.js"
]
+ },
+ {
+ "library": "signalr@2.4.3",
+ "destination": "wwwroot/lib/signalr/",
+ "files": [
+ "jquery.signalR.js",
+ "jquery.signalR.min.js"
+ ]
}
]
}
\ No newline at end of file
diff --git a/CWASP Razor Edition/wwwroot/js/Create.js b/CWASP Razor Edition/wwwroot/js/Create.js
new file mode 100644
index 0000000..ef72be4
--- /dev/null
+++ b/CWASP Razor Edition/wwwroot/js/Create.js
@@ -0,0 +1,12 @@
+"use strict";
+
+var connection = new signalR.HubConnectionBuilder().withUrl("/indexHub").build();
+
+document.getElementById("createButton").addEventListener("click", function (event) {
+ // Tell the SignalR hub to invoke the "RefreshDatabaseView" function.
+ connection.invoke("RefreshDatabaseView").catch(function (err) {
+ return console.error(err.toString());
+ });
+
+ console.log("SignalR detected an event.");
+});
\ No newline at end of file
diff --git a/CWASP Razor Edition/wwwroot/js/Index.js b/CWASP Razor Edition/wwwroot/js/Index.js
new file mode 100644
index 0000000..43231e6
--- /dev/null
+++ b/CWASP Razor Edition/wwwroot/js/Index.js
@@ -0,0 +1,9 @@
+"use strict";
+
+var connection = new signalR.HubConnectionBuilder().withUrl("/indexHub").build();
+
+// Run function when told to by the SignalR hub.
+connection.on("RefreshDatabaseView", function () {
+ // Refresh the page to display updated data.
+ window.location.reload();
+});
\ No newline at end of file
diff --git a/CWASP Razor Edition/wwwroot/js/site.js b/CWASP Razor Edition/wwwroot/js/site.js
deleted file mode 100644
index 0937657..0000000
--- a/CWASP Razor Edition/wwwroot/js/site.js
+++ /dev/null
@@ -1,4 +0,0 @@
-// Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
-// for details on configuring this project to bundle and minify static web assets.
-
-// Write your JavaScript code.
diff --git a/CWASP Razor Edition/wwwroot/lib/signalr/jquery.signalR.js b/CWASP Razor Edition/wwwroot/lib/signalr/jquery.signalR.js
new file mode 100644
index 0000000..85fef39
--- /dev/null
+++ b/CWASP Razor Edition/wwwroot/lib/signalr/jquery.signalR.js
@@ -0,0 +1,3174 @@
+/* jquery.signalR.core.js */
+/*global window:false */
+/*!
+ * ASP.NET SignalR JavaScript Library 2.4.3
+ * http://signalr.net/
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+ *
+ */
+
+//
+//
+(function ($, window, undefined) {
+
+ var resources = {
+ nojQuery: "jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.",
+ noTransportOnInit: "No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.",
+ errorOnNegotiate: "Error during negotiation request.",
+ stoppedWhileLoading: "The connection was stopped during page load.",
+ stoppedWhileNegotiating: "The connection was stopped during the negotiate request.",
+ errorParsingNegotiateResponse: "Error parsing negotiate response.",
+ errorRedirectionExceedsLimit: "Negotiate redirection limit exceeded.",
+ errorDuringStartRequest: "Error during start request. Stopping the connection.",
+ errorFromServer: "Error message received from the server: '{0}'.",
+ stoppedDuringStartRequest: "The connection was stopped during the start request.",
+ errorParsingStartResponse: "Error parsing start response: '{0}'. Stopping the connection.",
+ invalidStartResponse: "Invalid start response: '{0}'. Stopping the connection.",
+ protocolIncompatible: "You are using a version of the client that isn't compatible with the server. Client version {0}, server version {1}.",
+ aspnetCoreSignalrServer: "Detected a connection attempt to an ASP.NET Core SignalR Server. This client only supports connecting to an ASP.NET SignalR Server. See https://aka.ms/signalr-core-differences for details.",
+ sendFailed: "Send failed.",
+ parseFailed: "Failed at parsing response: {0}",
+ longPollFailed: "Long polling request failed.",
+ eventSourceFailedToConnect: "EventSource failed to connect.",
+ eventSourceError: "Error raised by EventSource",
+ webSocketClosed: "WebSocket closed.",
+ pingServerFailedInvalidResponse: "Invalid ping response when pinging server: '{0}'.",
+ pingServerFailed: "Failed to ping server.",
+ pingServerFailedStatusCode: "Failed to ping server. Server responded with status code {0}, stopping the connection.",
+ pingServerFailedParse: "Failed to parse ping server response, stopping the connection.",
+ noConnectionTransport: "Connection is in an invalid state, there is no transport active.",
+ webSocketsInvalidState: "The Web Socket transport is in an invalid state, transitioning into reconnecting.",
+ reconnectTimeout: "Couldn't reconnect within the configured timeout of {0} ms, disconnecting.",
+ reconnectWindowTimeout: "The client has been inactive since {0} and it has exceeded the inactivity timeout of {1} ms. Stopping the connection.",
+ jsonpNotSupportedWithAccessToken: "The JSONP protocol does not support connections that require a Bearer token to connect, such as the Azure SignalR Service."
+ };
+
+ if (typeof ($) !== "function") {
+ // no jQuery!
+ throw new Error(resources.nojQuery);
+ }
+
+ var signalR,
+ _connection,
+ _pageLoaded = (window.document.readyState === "complete"),
+ _pageWindow = $(window),
+ _negotiateAbortText = "__Negotiate Aborted__",
+ events = {
+ onStart: "onStart",
+ onStarting: "onStarting",
+ onReceived: "onReceived",
+ onError: "onError",
+ onConnectionSlow: "onConnectionSlow",
+ onReconnecting: "onReconnecting",
+ onReconnect: "onReconnect",
+ onStateChanged: "onStateChanged",
+ onDisconnect: "onDisconnect"
+ },
+ ajaxDefaults = {
+ processData: true,
+ timeout: null,
+ async: true,
+ global: false,
+ cache: false
+ },
+ log = function (msg, logging) {
+ if (logging === false) {
+ return;
+ }
+ var m;
+ if (typeof (window.console) === "undefined") {
+ return;
+ }
+ m = "[" + new Date().toTimeString() + "] SignalR: " + msg;
+ if (window.console.debug) {
+ window.console.debug(m);
+ } else if (window.console.log) {
+ window.console.log(m);
+ }
+ },
+
+ changeState = function (connection, expectedState, newState) {
+ if (expectedState === connection.state) {
+ connection.state = newState;
+
+ $(connection).triggerHandler(events.onStateChanged, [{ oldState: expectedState, newState: newState }]);
+ return true;
+ }
+
+ return false;
+ },
+
+ isDisconnecting = function (connection) {
+ return connection.state === signalR.connectionState.disconnected;
+ },
+
+ supportsKeepAlive = function (connection) {
+ return connection._.keepAliveData.activated &&
+ connection.transport.supportsKeepAlive(connection);
+ },
+
+ configureStopReconnectingTimeout = function (connection) {
+ var stopReconnectingTimeout,
+ onReconnectTimeout;
+
+ // Check if this connection has already been configured to stop reconnecting after a specified timeout.
+ // Without this check if a connection is stopped then started events will be bound multiple times.
+ if (!connection._.configuredStopReconnectingTimeout) {
+ onReconnectTimeout = function (connection) {
+ var message = signalR._.format(signalR.resources.reconnectTimeout, connection.disconnectTimeout);
+ connection.log(message);
+ $(connection).triggerHandler(events.onError, [signalR._.error(message, /* source */ "TimeoutException")]);
+ connection.stop(/* async */ false, /* notifyServer */ false);
+ };
+
+ connection.reconnecting(function () {
+ var connection = this;
+
+ // Guard against state changing in a previous user defined even handler
+ if (connection.state === signalR.connectionState.reconnecting) {
+ stopReconnectingTimeout = window.setTimeout(function () { onReconnectTimeout(connection); }, connection.disconnectTimeout);
+ }
+ });
+
+ connection.stateChanged(function (data) {
+ if (data.oldState === signalR.connectionState.reconnecting) {
+ // Clear the pending reconnect timeout check
+ window.clearTimeout(stopReconnectingTimeout);
+ }
+ });
+
+ connection._.configuredStopReconnectingTimeout = true;
+ }
+ };
+
+ signalR = function (url, qs, logging) {
+ /// Creates a new SignalR connection for the given url
+ /// The URL of the long polling endpoint
+ ///
+ /// [Optional] Custom querystring parameters to add to the connection URL.
+ /// If an object, every non-function member will be added to the querystring.
+ /// If a string, it's added to the QS as specified.
+ ///
+ ///
+ /// [Optional] A flag indicating whether connection logging is enabled to the browser
+ /// console/log. Defaults to false.
+ ///
+
+ return new signalR.fn.init(url, qs, logging);
+ };
+
+ signalR._ = {
+ defaultContentType: "application/x-www-form-urlencoded; charset=UTF-8",
+
+ ieVersion: (function () {
+ var version,
+ matches;
+
+ if (window.navigator.userAgentData.platform === 'Microsoft Internet Explorer') {
+ // Check if the user agent has the pattern "MSIE (one or more numbers).(one or more numbers)";
+ matches = /MSIE ([0-9]+\.[0-9]+)/.exec(window.navigator.userAgent);
+
+ if (matches) {
+ version = window.parseFloat(matches[1]);
+ }
+ }
+
+ // undefined value means not IE
+ return version;
+ })(),
+
+ error: function (message, source, context) {
+ var e = new Error(message);
+ e.source = source;
+
+ if (typeof context !== "undefined") {
+ e.context = context;
+ }
+
+ return e;
+ },
+
+ transportError: function (message, transport, source, context) {
+ var e = this.error(message, source, context);
+ e.transport = transport ? transport.name : undefined;
+ return e;
+ },
+
+ format: function () {
+ /// Usage: format("Hi {0}, you are {1}!", "Foo", 100)
+ var s = arguments[0];
+ for (var i = 0; i < arguments.length - 1; i++) {
+ s = s.replace("{" + i + "}", arguments[i + 1]);
+ }
+ return s;
+ },
+
+ firefoxMajorVersion: function (userAgent) {
+ // Firefox user agents: http://useragentstring.com/pages/Firefox/
+ var matches = userAgent.match(/Firefox\/(\d+)/);
+ if (!matches || !matches.length || matches.length < 2) {
+ return 0;
+ }
+ return parseInt(matches[1], 10 /* radix */);
+ },
+
+ configurePingInterval: function (connection) {
+ var config = connection._.config,
+ onFail = function (error) {
+ $(connection).triggerHandler(events.onError, [error]);
+ };
+
+ if (config && !connection._.pingIntervalId && config.pingInterval) {
+ connection._.pingIntervalId = window.setInterval(function () {
+ signalR.transports._logic.pingServer(connection).fail(onFail);
+ }, config.pingInterval);
+ }
+ }
+ };
+
+ signalR.events = events;
+
+ signalR.resources = resources;
+
+ signalR.ajaxDefaults = ajaxDefaults;
+
+ signalR.changeState = changeState;
+
+ signalR.isDisconnecting = isDisconnecting;
+
+ signalR.connectionState = {
+ connecting: 0,
+ connected: 1,
+ reconnecting: 2,
+ disconnected: 4
+ };
+
+ signalR.hub = {
+ start: function () {
+ // This will get replaced with the real hub connection start method when hubs is referenced correctly
+ throw new Error("SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. .");
+ }
+ };
+
+ // .on() was added in version 1.7.0, .load() was removed in version 3.0.0 so we fallback to .load() if .on() does
+ // not exist to not break existing applications
+ if (typeof _pageWindow.on === "function") {
+ _pageWindow.on("load", function () { _pageLoaded = true; });
+ }
+ else {
+ _pageWindow.load(function () { _pageLoaded = true; });
+ }
+
+ function validateTransport(requestedTransport, connection) {
+ /// Validates the requested transport by cross checking it with the pre-defined signalR.transports
+ /// The designated transports that the user has specified.
+ /// The connection that will be using the requested transports. Used for logging purposes.
+ ///
+
+ if ($.isArray(requestedTransport)) {
+ // Go through transport array and remove an "invalid" tranports
+ for (var i = requestedTransport.length - 1; i >= 0; i--) {
+ var transport = requestedTransport[i];
+ if ($.type(transport) !== "string" || !signalR.transports[transport]) {
+ connection.log("Invalid transport: " + transport + ", removing it from the transports list.");
+ requestedTransport.splice(i, 1);
+ }
+ }
+
+ // Verify we still have transports left, if we dont then we have invalid transports
+ if (requestedTransport.length === 0) {
+ connection.log("No transports remain within the specified transport array.");
+ requestedTransport = null;
+ }
+ } else if (!signalR.transports[requestedTransport] && requestedTransport !== "auto") {
+ connection.log("Invalid transport: " + requestedTransport.toString() + ".");
+ requestedTransport = null;
+ } else if (requestedTransport === "auto" && signalR._.ieVersion <= 8) {
+ // If we're doing an auto transport and we're IE8 then force longPolling, #1764
+ return ["longPolling"];
+
+ }
+
+ return requestedTransport;
+ }
+
+ function getDefaultPort(protocol) {
+ if (protocol === "http:") {
+ return 80;
+ } else if (protocol === "https:") {
+ return 443;
+ }
+ }
+
+ function addDefaultPort(protocol, url) {
+ // Remove ports from url. We have to check if there's a / or end of line
+ // following the port in order to avoid removing ports such as 8080.
+ if (url.match(/:\d+$/)) {
+ return url;
+ } else {
+ return url + ":" + getDefaultPort(protocol);
+ }
+ }
+
+ function ConnectingMessageBuffer(connection, drainCallback) {
+ var that = this,
+ buffer = [];
+
+ that.tryBuffer = function (message) {
+ if (connection.state === $.signalR.connectionState.connecting) {
+ buffer.push(message);
+
+ return true;
+ }
+
+ return false;
+ };
+
+ that.drain = function () {
+ // Ensure that the connection is connected when we drain (do not want to drain while a connection is not active)
+ if (connection.state === $.signalR.connectionState.connected) {
+ while (buffer.length > 0) {
+ drainCallback(buffer.shift());
+ }
+ }
+ };
+
+ that.clear = function () {
+ buffer = [];
+ };
+ }
+
+ signalR.fn = signalR.prototype = {
+ init: function (url, qs, logging) {
+ var $connection = $(this);
+
+ this.url = url;
+ this.qs = qs;
+ this.lastError = null;
+ this._ = {
+ keepAliveData: {},
+ connectingMessageBuffer: new ConnectingMessageBuffer(this, function (message) {
+ $connection.triggerHandler(events.onReceived, [message]);
+ }),
+ lastMessageAt: new Date().getTime(),
+ lastActiveAt: new Date().getTime(),
+ beatInterval: 5000, // Default value, will only be overridden if keep alive is enabled,
+ beatHandle: null,
+ totalTransportConnectTimeout: 0, // This will be the sum of the TransportConnectTimeout sent in response to negotiate and connection.transportConnectTimeout
+ redirectQs: null
+ };
+ if (typeof (logging) === "boolean") {
+ this.logging = logging;
+ }
+ },
+
+ _parseResponse: function (response) {
+ var that = this;
+
+ if (!response) {
+ return response;
+ } else if (typeof response === "string") {
+ return that.json.parse(response);
+ } else {
+ return response;
+ }
+ },
+
+ _originalJson: window.JSON,
+
+ json: window.JSON,
+
+ isCrossDomain: function (url, against) {
+ /// Checks if url is cross domain
+ /// The base URL
+ ///
+ /// An optional argument to compare the URL against, if not specified it will be set to window.location.
+ /// If specified it must contain a protocol and a host property.
+ ///
+ var link;
+
+ url = $.trim(url);
+
+ against = against || window.location;
+
+ if (url.indexOf("http") !== 0) {
+ return false;
+ }
+
+ // Create an anchor tag.
+ link = window.document.createElement("a");
+ link.href = url;
+
+ // When checking for cross domain we have to special case port 80 because the window.location will remove the
+ return link.protocol + addDefaultPort(link.protocol, link.host) !== against.protocol + addDefaultPort(against.protocol, against.host);
+ },
+
+ ajaxDataType: "text",
+
+ contentType: "application/json; charset=UTF-8",
+
+ logging: false,
+
+ state: signalR.connectionState.disconnected,
+
+ clientProtocol: "2.1",
+
+ // We want to support older servers since the 2.0 change is to support redirection results, which isn't
+ // really breaking in the protocol. So if a user updates their client to 2.0 protocol version there's
+ // no reason they can't still connect to a 1.5 server. The 2.1 protocol is sent by the client so the SignalR
+ // service knows the client will use they query string returned via the RedirectUrl for subsequent requests.
+ // It doesn't matter whether the server reflects back 2.1 or continues using 2.0 as the protocol version.
+ supportedProtocols: ["1.5", "2.0", "2.1"],
+
+ negotiateRedirectSupportedProtocols: ["2.0", "2.1"],
+
+ reconnectDelay: 2000,
+
+ transportConnectTimeout: 0,
+
+ disconnectTimeout: 30000, // This should be set by the server in response to the negotiate request (30s default)
+
+ reconnectWindow: 30000, // This should be set by the server in response to the negotiate request
+
+ keepAliveWarnAt: 2 / 3, // Warn user of slow connection if we breach the X% mark of the keep alive timeout
+
+ start: function (options, callback) {
+ /// Starts the connection
+ /// Options map
+ /// A callback function to execute when the connection has started
+ var connection = this,
+ config = {
+ pingInterval: 300000,
+ waitForPageLoad: true,
+ transport: "auto",
+ jsonp: false
+ },
+ initialize,
+ 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
+ parser = window.document.createElement("a"),
+ setConnectionUrl = function (connection, url) {
+ if (connection.url === url && connection.baseUrl) {
+ // when the url related properties are already set
+ return;
+ }
+
+ connection.url = url;
+
+ // Resolve the full url
+ parser.href = connection.url;
+ if (!parser.protocol || parser.protocol === ":") {
+ connection.protocol = window.document.location.protocol;
+ connection.host = parser.host || window.document.location.host;
+ } else {
+ connection.protocol = parser.protocol;
+ connection.host = parser.host;
+ }
+
+ connection.baseUrl = connection.protocol + "//" + connection.host;
+
+ // Set the websocket protocol
+ connection.wsProtocol = connection.protocol === "https:" ? "wss://" : "ws://";
+
+ // If the url is protocol relative, prepend the current windows protocol to the url.
+ if (connection.url.indexOf("//") === 0) {
+ connection.url = window.location.protocol + connection.url;
+ connection.log("Protocol relative URL detected, normalizing it to '" + connection.url + "'.");
+ }
+
+ if (connection.isCrossDomain(connection.url)) {
+ connection.log("Auto detected cross domain url.");
+
+ if (config.transport === "auto") {
+ // Cross-domain does not support foreverFrame
+ config.transport = ["webSockets", "serverSentEvents", "longPolling"];
+ }
+
+ if (typeof connection.withCredentials === "undefined") {
+ connection.withCredentials = true;
+ }
+
+ // Determine if jsonp is the only choice for negotiation, ajaxSend and ajaxAbort.
+ // i.e. if the browser doesn't supports CORS
+ // If it is, ignore any preference to the contrary, and switch to jsonp.
+ if (!$.support.cors) {
+ connection.ajaxDataType = "jsonp";
+ connection.log("Using jsonp because this browser doesn't support CORS.");
+ }
+
+ connection.contentType = signalR._.defaultContentType;
+ }
+ };
+
+ connection.lastError = null;
+
+ // Persist the deferral so that if start is called multiple times the same deferral is used.
+ connection._deferral = deferred;
+
+ if (!connection.json) {
+ // no JSON!
+ 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.");
+ }
+
+ if ($.type(options) === "function") {
+ // Support calling with single callback parameter
+ callback = options;
+ } else if ($.type(options) === "object") {
+ $.extend(config, options);
+ if ($.type(config.callback) === "function") {
+ callback = config.callback;
+ }
+ }
+
+ config.transport = validateTransport(config.transport, connection);
+
+ // If the transport is invalid throw an error and abort start
+ if (!config.transport) {
+ throw new Error("SignalR: Invalid transport(s) specified, aborting start.");
+ }
+
+ connection._.config = config;
+
+ // Check to see if start is being called prior to page load
+ // If waitForPageLoad is true we then want to re-direct function call to the window load event
+ if (!_pageLoaded && config.waitForPageLoad === true) {
+ connection._.deferredStartHandler = function () {
+ connection.start(options, callback);
+ };
+ _pageWindow.bind("load", connection._.deferredStartHandler);
+
+ return deferred.promise();
+ }
+
+ // If we're already connecting just return the same deferral as the original connection start
+ if (connection.state === signalR.connectionState.connecting) {
+ return deferred.promise();
+ } else if (changeState(connection,
+ signalR.connectionState.disconnected,
+ signalR.connectionState.connecting) === false) {
+ // We're not connecting so try and transition into connecting.
+ // If we fail to transition then we're either in connected or reconnecting.
+
+ deferred.resolve(connection);
+ return deferred.promise();
+ }
+
+ configureStopReconnectingTimeout(connection);
+
+ // If jsonp with no/auto transport is specified, then set the transport to long polling
+ // since that is the only transport for which jsonp really makes sense.
+ // Some developers might actually choose to specify jsonp for same origin requests
+ // as demonstrated by Issue #623.
+ if (config.transport === "auto" && config.jsonp === true) {
+ config.transport = "longPolling";
+ }
+
+ connection.withCredentials = config.withCredentials;
+
+ // Save the original url so that we can reset it when we stop and restart the connection
+ connection._originalUrl = connection.url;
+
+ connection.ajaxDataType = config.jsonp ? "jsonp" : "text";
+
+ setConnectionUrl(connection, connection.url);
+
+ $(connection).bind(events.onStart, function (e, data) {
+ if ($.type(callback) === "function") {
+ callback.call(connection);
+ }
+ deferred.resolve(connection);
+ });
+
+ connection._.initHandler = signalR.transports._logic.initHandler(connection);
+
+ initialize = function (transports, index) {
+ var noTransportError = signalR._.error(resources.noTransportOnInit);
+
+ index = index || 0;
+ if (index >= transports.length) {
+ if (index === 0) {
+ connection.log("No transports supported by the server were selected.");
+ } else if (index === 1) {
+ connection.log("No fallback transports were selected.");
+ } else {
+ connection.log("Fallback transports exhausted.");
+ }
+
+ // No transport initialized successfully
+ $(connection).triggerHandler(events.onError, [noTransportError]);
+ deferred.reject(noTransportError);
+ // Stop the connection if it has connected and move it into the disconnected state
+ connection.stop();
+ return;
+ }
+
+ // The connection was aborted
+ if (connection.state === signalR.connectionState.disconnected) {
+ return;
+ }
+
+ var transportName = transports[index],
+ transport = signalR.transports[transportName],
+ onFallback = function () {
+ initialize(transports, index + 1);
+ };
+
+ connection.transport = transport;
+
+ try {
+ connection._.initHandler.start(transport, function () { // success
+ // Firefox 11+ doesn't allow sync XHR withCredentials: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#withCredentials
+ var isFirefox11OrGreater = signalR._.firefoxMajorVersion(window.navigator.userAgent) >= 11,
+ asyncAbort = true;
+
+ connection.log("The start request succeeded. Transitioning to the connected state.");
+
+ if (supportsKeepAlive(connection)) {
+ signalR.transports._logic.monitorKeepAlive(connection);
+ }
+
+ if (connection._.keepAliveData.activated) {
+ signalR.transports._logic.startHeartbeat(connection);
+ }
+
+ // Used to ensure low activity clients maintain their authentication.
+ // Must be configured once a transport has been decided to perform valid ping requests.
+ signalR._.configurePingInterval(connection);
+
+ if (!changeState(connection,
+ signalR.connectionState.connecting,
+ signalR.connectionState.connected)) {
+ connection.log("WARNING! The connection was not in the connecting state.");
+ }
+
+ // Drain any incoming buffered messages (messages that came in prior to connect)
+ connection._.connectingMessageBuffer.drain();
+
+ $(connection).triggerHandler(events.onStart);
+
+ // wire the stop handler for when the user leaves the page
+ _pageWindow.bind("unload", function () {
+ connection.log("Window unloading, stopping the connection.");
+
+ connection.stop(asyncAbort);
+ });
+
+ if (isFirefox11OrGreater) {
+ // Firefox does not fire cross-domain XHRs in the normal unload handler on tab close.
+ // #2400
+ _pageWindow.bind("beforeunload", function () {
+ // If connection.stop() runs runs in beforeunload and fails, it will also fail
+ // in unload unless connection.stop() runs after a timeout.
+ window.setTimeout(function () {
+ connection.stop(asyncAbort);
+ }, 0);
+ });
+ }
+ }, onFallback);
+ }
+ catch (error) {
+ connection.log(transport.name + " transport threw '" + error.message + "' when attempting to start.");
+ onFallback();
+ }
+ };
+
+ var url = connection.url + "/negotiate",
+ onFailed = function (error, connection) {
+ var err = signalR._.error(resources.errorOnNegotiate, error, connection._.negotiateRequest);
+
+ $(connection).triggerHandler(events.onError, err);
+ deferred.reject(err);
+ // Stop the connection if negotiate failed
+ connection.stop();
+ };
+
+ $(connection).triggerHandler(events.onStarting);
+
+ url = signalR.transports._logic.prepareQueryString(connection, url);
+
+ connection.log("Negotiating with '" + url + "'.");
+
+ // Save the ajax negotiate request object so we can abort it if stop is called while the request is in flight.
+ connection._.negotiateRequest = function () {
+ var res,
+ redirects = 0,
+ MAX_REDIRECTS = 100,
+ keepAliveData,
+ protocolError,
+ transports = [],
+ supportedTransports = [],
+ negotiate = function (connection, onSuccess) {
+ var url = signalR.transports._logic.prepareQueryString(connection, connection.url + "/negotiate");
+ connection.log("Negotiating with '" + url + "'.");
+ var options = {
+ url: url,
+ error: function (error, statusText) {
+ // We don't want to cause any errors if we're aborting our own negotiate request.
+ if (statusText !== _negotiateAbortText) {
+ onFailed(error, connection);
+ } else {
+ // This rejection will noop if the deferred has already been resolved or rejected.
+ deferred.reject(signalR._.error(resources.stoppedWhileNegotiating, null /* error */, connection._.negotiateRequest));
+ }
+ },
+ success: onSuccess
+ };
+
+ if (connection.accessToken) {
+ options.headers = { "Authorization": "Bearer " + connection.accessToken };
+ }
+
+ return signalR.transports._logic.ajax(connection, options);
+ },
+ callback = function (result) {
+ try {
+ res = connection._parseResponse(result);
+ } catch (error) {
+ onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);
+ return;
+ }
+
+ // Check if the server is an ASP.NET Core app
+ if (res.availableTransports) {
+ protocolError = signalR._.error(resources.aspnetCoreSignalrServer);
+ $(connection).triggerHandler(events.onError, [protocolError]);
+ deferred.reject(protocolError);
+ return;
+ }
+
+ if (!res.ProtocolVersion || (connection.supportedProtocols.indexOf(res.ProtocolVersion) === -1)) {
+ protocolError = signalR._.error(signalR._.format(resources.protocolIncompatible, connection.clientProtocol, res.ProtocolVersion));
+ $(connection).triggerHandler(events.onError, [protocolError]);
+ deferred.reject(protocolError);
+
+ return;
+ }
+
+ // Check for a redirect response (which must have a ProtocolVersion of 2.0 or greater)
+ // ProtocolVersion 2.1 is the highest supported by the client, so we can just check for 2.0 or 2.1 for now
+ // instead of trying to do proper version string comparison in JavaScript.
+ if (connection.negotiateRedirectSupportedProtocols.indexOf(res.ProtocolVersion) !== -1) {
+ if (res.Error) {
+ protocolError = signalR._.error(signalR._.format(resources.errorFromServer, res.Error));
+ $(connection).triggerHandler(events.onError, [protocolError]);
+ deferred.reject(protocolError);
+ return;
+ }
+ else if (res.RedirectUrl) {
+ if (redirects === MAX_REDIRECTS) {
+ onFailed(signalR._.error(resources.errorRedirectionExceedsLimit), connection);
+ return;
+ }
+
+ if (config.transport === "auto") {
+ // Redirected connections do not support foreverFrame
+ config.transport = ["webSockets", "serverSentEvents", "longPolling"];
+ }
+
+ connection.log("Received redirect to: " + res.RedirectUrl);
+ connection.accessToken = res.AccessToken;
+
+ var splitUrlAndQs = res.RedirectUrl.split("?", 2);
+ setConnectionUrl(connection, splitUrlAndQs[0]);
+
+ // Update redirectQs with query string from only the most recent RedirectUrl.
+ connection._.redirectQs = splitUrlAndQs.length === 2 ? splitUrlAndQs[1] : null;
+
+ if (connection.ajaxDataType === "jsonp" && connection.accessToken) {
+ onFailed(signalR._.error(resources.jsonpNotSupportedWithAccessToken), connection);
+ return;
+ }
+
+ redirects++;
+ negotiate(connection, callback);
+ return;
+ }
+ }
+
+ keepAliveData = connection._.keepAliveData;
+ connection.appRelativeUrl = res.Url;
+ connection.id = res.ConnectionId;
+ connection.token = res.ConnectionToken;
+ connection.webSocketServerUrl = res.WebSocketServerUrl;
+
+ // The long poll timeout is the ConnectionTimeout plus 10 seconds
+ connection._.pollTimeout = res.ConnectionTimeout * 1000 + 10000; // in ms
+
+ // Once the server has labeled the PersistentConnection as Disconnected, we should stop attempting to reconnect
+ // after res.DisconnectTimeout seconds.
+ connection.disconnectTimeout = res.DisconnectTimeout * 1000; // in ms
+
+ // Add the TransportConnectTimeout from the response to the transportConnectTimeout from the client to calculate the total timeout
+ connection._.totalTransportConnectTimeout = connection.transportConnectTimeout + res.TransportConnectTimeout * 1000;
+
+ // If we have a keep alive
+ if (res.KeepAliveTimeout) {
+ // Register the keep alive data as activated
+ keepAliveData.activated = true;
+
+ // Timeout to designate when to force the connection into reconnecting converted to milliseconds
+ keepAliveData.timeout = res.KeepAliveTimeout * 1000;
+
+ // Timeout to designate when to warn the developer that the connection may be dead or is not responding.
+ keepAliveData.timeoutWarning = keepAliveData.timeout * connection.keepAliveWarnAt;
+
+ // Instantiate the frequency in which we check the keep alive. It must be short in order to not miss/pick up any changes
+ connection._.beatInterval = (keepAliveData.timeout - keepAliveData.timeoutWarning) / 3;
+ } else {
+ keepAliveData.activated = false;
+ }
+
+ connection.reconnectWindow = connection.disconnectTimeout + (keepAliveData.timeout || 0);
+
+ $.each(signalR.transports, function (key) {
+ if ((key.indexOf("_") === 0) || (key === "webSockets" && !res.TryWebSockets)) {
+ return true;
+ }
+ supportedTransports.push(key);
+ });
+
+ if ($.isArray(config.transport)) {
+ $.each(config.transport, function (_, transport) {
+ if ($.inArray(transport, supportedTransports) >= 0) {
+ transports.push(transport);
+ }
+ });
+ } else if (config.transport === "auto") {
+ transports = supportedTransports;
+ } else if ($.inArray(config.transport, supportedTransports) >= 0) {
+ transports.push(config.transport);
+ }
+
+ initialize(transports);
+ };
+
+ return negotiate(connection, callback);
+ }();
+
+ return deferred.promise();
+ },
+
+ starting: function (callback) {
+ /// Adds a callback that will be invoked before anything is sent over the connection
+ /// A callback function to execute before the connection is fully instantiated.
+ ///
+ var connection = this;
+ $(connection).bind(events.onStarting, function (e, data) {
+ callback.call(connection);
+ });
+ return connection;
+ },
+
+ send: function (data) {
+ /// Sends data over the connection
+ /// The data to send over the connection
+ ///
+ var connection = this;
+
+ if (connection.state === signalR.connectionState.disconnected) {
+ // Connection hasn't been started yet
+ throw new Error("SignalR: Connection must be started before data can be sent. Call .start() before .send()");
+ }
+
+ if (connection.state === signalR.connectionState.connecting) {
+ // Connection hasn't been started yet
+ throw new Error("SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.");
+ }
+
+ connection.transport.send(connection, data);
+ // REVIEW: Should we return deferred here?
+ return connection;
+ },
+
+ received: function (callback) {
+ /// Adds a callback that will be invoked after anything is received over the connection
+ /// A callback function to execute when any data is received on the connection
+ ///
+ var connection = this;
+ $(connection).bind(events.onReceived, function (e, data) {
+ callback.call(connection, data);
+ });
+ return connection;
+ },
+
+ stateChanged: function (callback) {
+ /// Adds a callback that will be invoked when the connection state changes
+ /// A callback function to execute when the connection state changes
+ ///
+ var connection = this;
+ $(connection).bind(events.onStateChanged, function (e, data) {
+ callback.call(connection, data);
+ });
+ return connection;
+ },
+
+ error: function (callback) {
+ /// Adds a callback that will be invoked after an error occurs with the connection
+ /// A callback function to execute when an error occurs on the connection
+ ///
+ var connection = this;
+ $(connection).bind(events.onError, function (e, errorData, sendData) {
+ connection.lastError = errorData;
+ // In practice 'errorData' is the SignalR built error object.
+ // In practice 'sendData' is undefined for all error events except those triggered by
+ // 'ajaxSend' and 'webSockets.send'.'sendData' is the original send payload.
+ callback.call(connection, errorData, sendData);
+ });
+ return connection;
+ },
+
+ disconnected: function (callback) {
+ /// Adds a callback that will be invoked when the client disconnects
+ /// A callback function to execute when the connection is broken
+ ///
+ var connection = this;
+ $(connection).bind(events.onDisconnect, function (e, data) {
+ callback.call(connection);
+ });
+ return connection;
+ },
+
+ connectionSlow: function (callback) {
+ /// Adds a callback that will be invoked when the client detects a slow connection
+ /// A callback function to execute when the connection is slow
+ ///
+ var connection = this;
+ $(connection).bind(events.onConnectionSlow, function (e, data) {
+ callback.call(connection);
+ });
+
+ return connection;
+ },
+
+ reconnecting: function (callback) {
+ /// Adds a callback that will be invoked when the underlying transport begins reconnecting
+ /// A callback function to execute when the connection enters a reconnecting state
+ ///
+ var connection = this;
+ $(connection).bind(events.onReconnecting, function (e, data) {
+ callback.call(connection);
+ });
+ return connection;
+ },
+
+ reconnected: function (callback) {
+ /// Adds a callback that will be invoked when the underlying transport reconnects
+ /// A callback function to execute when the connection is restored
+ ///
+ var connection = this;
+ $(connection).bind(events.onReconnect, function (e, data) {
+ callback.call(connection);
+ });
+ return connection;
+ },
+
+ stop: function (async, notifyServer) {
+ /// Stops listening
+ /// Whether or not to asynchronously abort the connection
+ /// Whether we want to notify the server that we are aborting the connection
+ ///
+ var connection = this,
+ // Save deferral because this is always cleaned up
+ deferral = connection._deferral;
+
+ // Verify that we've bound a load event.
+ if (connection._.deferredStartHandler) {
+ // Unbind the event.
+ _pageWindow.unbind("load", connection._.deferredStartHandler);
+ }
+
+ // Always clean up private non-timeout based state.
+ delete connection._.config;
+ delete connection._.deferredStartHandler;
+
+ // This needs to be checked despite the connection state because a connection start can be deferred until page load.
+ // If we've deferred the start due to a page load we need to unbind the "onLoad" -> start event.
+ if (!_pageLoaded && (!connection._.config || connection._.config.waitForPageLoad === true)) {
+ connection.log("Stopping connection prior to negotiate.");
+
+ // If we have a deferral we should reject it
+ if (deferral) {
+ deferral.reject(signalR._.error(resources.stoppedWhileLoading));
+ }
+
+ // Short-circuit because the start has not been fully started.
+ return;
+ }
+
+ if (connection.state === signalR.connectionState.disconnected) {
+ return;
+ }
+
+ connection.log("Stopping connection.");
+
+ // Clear this no matter what
+ window.clearTimeout(connection._.beatHandle);
+ window.clearInterval(connection._.pingIntervalId);
+
+ if (connection.transport) {
+ connection.transport.stop(connection);
+
+ if (notifyServer !== false) {
+ connection.transport.abort(connection, async);
+ }
+
+ if (supportsKeepAlive(connection)) {
+ signalR.transports._logic.stopMonitoringKeepAlive(connection);
+ }
+
+ connection.transport = null;
+ }
+
+ if (connection._.negotiateRequest) {
+ // If the negotiation request has already completed this will noop.
+ connection._.negotiateRequest.abort(_negotiateAbortText);
+ delete connection._.negotiateRequest;
+ }
+
+ // Ensure that initHandler.stop() is called before connection._deferral is deleted
+ if (connection._.initHandler) {
+ connection._.initHandler.stop();
+ }
+
+ delete connection._deferral;
+ delete connection.messageId;
+ delete connection.groupsToken;
+ delete connection.id;
+ delete connection._.pingIntervalId;
+ delete connection._.lastMessageAt;
+ delete connection._.lastActiveAt;
+
+ // Clear out our message buffer
+ connection._.connectingMessageBuffer.clear();
+
+ // Clean up this event
+ $(connection).unbind(events.onStart);
+
+ // Reset the URL and clear the access token
+ delete connection.accessToken;
+ delete connection.protocol;
+ delete connection.host;
+ delete connection.baseUrl;
+ delete connection.wsProtocol;
+ delete connection.contentType;
+ connection.url = connection._originalUrl;
+ connection._.redirectQs = null;
+
+ // Trigger the disconnect event
+ changeState(connection, connection.state, signalR.connectionState.disconnected);
+ $(connection).triggerHandler(events.onDisconnect);
+
+ return connection;
+ },
+
+ log: function (msg) {
+ log(msg, this.logging);
+ }
+ };
+
+ signalR.fn.init.prototype = signalR.fn;
+
+ signalR.noConflict = function () {
+ /// Reinstates the original value of $.connection and returns the signalR object for manual assignment
+ ///
+ if ($.connection === signalR) {
+ $.connection = _connection;
+ }
+ return signalR;
+ };
+
+ if ($.connection) {
+ _connection = $.connection;
+ }
+
+ $.connection = $.signalR = signalR;
+
+}(window.jQuery, window));
+/* jquery.signalR.transports.common.js */
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+/*global window:false */
+///
+
+(function ($, window, undefined) {
+
+ var signalR = $.signalR,
+ events = $.signalR.events,
+ changeState = $.signalR.changeState,
+ startAbortText = "__Start Aborted__",
+ transportLogic;
+
+ signalR.transports = {};
+
+ function beat(connection) {
+ if (connection._.keepAliveData.monitoring) {
+ checkIfAlive(connection);
+ }
+
+ // Ensure that we successfully marked active before continuing the heartbeat.
+ if (transportLogic.markActive(connection)) {
+ connection._.beatHandle = window.setTimeout(function () {
+ beat(connection);
+ }, connection._.beatInterval);
+ }
+ }
+
+ function checkIfAlive(connection) {
+ var keepAliveData = connection._.keepAliveData,
+ timeElapsed;
+
+ // Only check if we're connected
+ if (connection.state === signalR.connectionState.connected) {
+ timeElapsed = new Date().getTime() - connection._.lastMessageAt;
+
+ // Check if the keep alive has completely timed out
+ if (timeElapsed >= keepAliveData.timeout) {
+ connection.log("Keep alive timed out. Notifying transport that connection has been lost.");
+
+ // Notify transport that the connection has been lost
+ connection.transport.lostConnection(connection);
+ } else if (timeElapsed >= keepAliveData.timeoutWarning) {
+ // This is to assure that the user only gets a single warning
+ if (!keepAliveData.userNotified) {
+ connection.log("Keep alive has been missed, connection may be dead/slow.");
+ $(connection).triggerHandler(events.onConnectionSlow);
+ keepAliveData.userNotified = true;
+ }
+ } else {
+ keepAliveData.userNotified = false;
+ }
+ }
+ }
+
+ function getAjaxUrl(connection, path) {
+ var url = connection.url + path;
+
+ if (connection.transport) {
+ url += "?transport=" + connection.transport.name;
+ }
+
+ return transportLogic.prepareQueryString(connection, url);
+ }
+
+ function InitHandler(connection) {
+ this.connection = connection;
+
+ this.startRequested = false;
+ this.startCompleted = false;
+ this.connectionStopped = false;
+ }
+
+ InitHandler.prototype = {
+ start: function (transport, onSuccess, onFallback) {
+ var that = this,
+ connection = that.connection,
+ failCalled = false;
+
+ if (that.startRequested || that.connectionStopped) {
+ connection.log("WARNING! " + transport.name + " transport cannot be started. Initialization ongoing or completed.");
+ return;
+ }
+
+ connection.log(transport.name + " transport starting.");
+
+ transport.start(connection, function () {
+ if (!failCalled) {
+ that.initReceived(transport, onSuccess);
+ }
+ }, function (error) {
+ // Don't allow the same transport to cause onFallback to be called twice
+ if (!failCalled) {
+ failCalled = true;
+ that.transportFailed(transport, error, onFallback);
+ }
+
+ // Returns true if the transport should stop;
+ // false if it should attempt to reconnect
+ return !that.startCompleted || that.connectionStopped;
+ });
+
+ that.transportTimeoutHandle = window.setTimeout(function () {
+ if (!failCalled) {
+ failCalled = true;
+ connection.log(transport.name + " transport timed out when trying to connect.");
+ that.transportFailed(transport, undefined, onFallback);
+ }
+ }, connection._.totalTransportConnectTimeout);
+ },
+
+ stop: function () {
+ this.connectionStopped = true;
+ window.clearTimeout(this.transportTimeoutHandle);
+ signalR.transports._logic.tryAbortStartRequest(this.connection);
+ },
+
+ initReceived: function (transport, onSuccess) {
+ var that = this,
+ connection = that.connection;
+
+ if (that.startRequested) {
+ connection.log("WARNING! The client received multiple init messages.");
+ return;
+ }
+
+ if (that.connectionStopped) {
+ return;
+ }
+
+ that.startRequested = true;
+ window.clearTimeout(that.transportTimeoutHandle);
+
+ connection.log(transport.name + " transport connected. Initiating start request.");
+ signalR.transports._logic.ajaxStart(connection, function () {
+ that.startCompleted = true;
+ onSuccess();
+ });
+ },
+
+ transportFailed: function (transport, error, onFallback) {
+ var connection = this.connection,
+ deferred = connection._deferral,
+ wrappedError;
+
+ if (this.connectionStopped) {
+ return;
+ }
+
+ window.clearTimeout(this.transportTimeoutHandle);
+
+ if (!this.startRequested) {
+ transport.stop(connection);
+
+ connection.log(transport.name + " transport failed to connect. Attempting to fall back.");
+ onFallback();
+ } else if (!this.startCompleted) {
+ // Do not attempt to fall back if a start request is ongoing during a transport failure.
+ // Instead, trigger an error and stop the connection.
+ wrappedError = signalR._.error(signalR.resources.errorDuringStartRequest, error);
+
+ connection.log(transport.name + " transport failed during the start request. Stopping the connection.");
+ $(connection).triggerHandler(events.onError, [wrappedError]);
+ if (deferred) {
+ deferred.reject(wrappedError);
+ }
+
+ connection.stop();
+ } else {
+ // The start request has completed, but the connection has not stopped.
+ // No need to do anything here. The transport should attempt its normal reconnect logic.
+ }
+ }
+ };
+
+ transportLogic = signalR.transports._logic = {
+ ajax: function (connection, options) {
+ return $.ajax(
+ $.extend(/*deep copy*/ true, {}, $.signalR.ajaxDefaults, {
+ type: "GET",
+ data: {},
+ xhrFields: { withCredentials: connection.withCredentials },
+ contentType: connection.contentType,
+ dataType: connection.ajaxDataType
+ }, options));
+ },
+
+ pingServer: function (connection) {
+ /// Pings the server
+ /// Connection associated with the server ping
+ ///
+ var url,
+ xhr,
+ deferral = $.Deferred();
+
+ if (connection.transport) {
+ url = connection.url + "/ping";
+
+ url = transportLogic.addQs(url, connection.qs);
+
+ xhr = transportLogic.ajax(connection, {
+ url: url,
+ headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
+ success: function (result) {
+ var data;
+
+ try {
+ data = connection._parseResponse(result);
+ }
+ catch (error) {
+ deferral.reject(
+ signalR._.transportError(
+ signalR.resources.pingServerFailedParse,
+ connection.transport,
+ error,
+ xhr
+ )
+ );
+ connection.stop();
+ return;
+ }
+
+ if (data.Response === "pong") {
+ deferral.resolve();
+ }
+ else {
+ deferral.reject(
+ signalR._.transportError(
+ signalR._.format(signalR.resources.pingServerFailedInvalidResponse, result),
+ connection.transport,
+ null /* error */,
+ xhr
+ )
+ );
+ }
+ },
+ error: function (error) {
+ if (error.status === 401 || error.status === 403) {
+ deferral.reject(
+ signalR._.transportError(
+ signalR._.format(signalR.resources.pingServerFailedStatusCode, error.status),
+ connection.transport,
+ error,
+ xhr
+ )
+ );
+ connection.stop();
+ }
+ else {
+ deferral.reject(
+ signalR._.transportError(
+ signalR.resources.pingServerFailed,
+ connection.transport,
+ error,
+ xhr
+ )
+ );
+ }
+ }
+ });
+ }
+ else {
+ deferral.reject(
+ signalR._.transportError(
+ signalR.resources.noConnectionTransport,
+ connection.transport
+ )
+ );
+ }
+
+ return deferral.promise();
+ },
+
+ prepareQueryString: function (connection, url) {
+ var preparedUrl;
+
+ // Use addQs to start since it handles the ?/& prefix for us
+ preparedUrl = transportLogic.addQs(url, "clientProtocol=" + connection.clientProtocol);
+
+ if (typeof (connection._.redirectQs) === "string") {
+ // Add the redirect-specified query string params if any
+ preparedUrl = transportLogic.addQs(preparedUrl, connection._.redirectQs);
+ } else {
+ // Otherwise, add the user-specified query string params if any
+ preparedUrl = transportLogic.addQs(preparedUrl, connection.qs);
+ }
+
+ if (connection.token) {
+ preparedUrl += "&connectionToken=" + window.encodeURIComponent(connection.token);
+ }
+
+ if (connection.data) {
+ preparedUrl += "&connectionData=" + window.encodeURIComponent(connection.data);
+ }
+
+ return preparedUrl;
+ },
+
+ addQs: function (url, qs) {
+ var appender = url.indexOf("?") !== -1 ? "&" : "?",
+ firstChar;
+
+ if (!qs) {
+ return url;
+ }
+
+ if (typeof (qs) === "object") {
+ return url + appender + $.param(qs);
+ }
+
+ if (typeof (qs) === "string") {
+ firstChar = qs.charAt(0);
+
+ if (firstChar === "?" || firstChar === "&") {
+ appender = "";
+ }
+
+ return url + appender + qs;
+ }
+
+ throw new Error("Query string property must be either a string or object.");
+ },
+
+ // BUG #2953: The url needs to be same otherwise it will cause a memory leak
+ getUrl: function (connection, transport, reconnecting, poll, ajaxPost) {
+ /// Gets the url for making a GET based connect request
+ var baseUrl = transport === "webSockets" ? "" : connection.baseUrl,
+ url = baseUrl + connection.appRelativeUrl,
+ qs = "transport=" + transport;
+
+ if (!ajaxPost && connection.groupsToken) {
+ qs += "&groupsToken=" + window.encodeURIComponent(connection.groupsToken);
+ }
+
+ if (!reconnecting) {
+ url += "/connect";
+ } else {
+ if (poll) {
+ // longPolling transport specific
+ url += "/poll";
+ } else {
+ url += "/reconnect";
+ }
+
+ if (!ajaxPost && connection.messageId) {
+ qs += "&messageId=" + window.encodeURIComponent(connection.messageId);
+ }
+ }
+ url += "?" + qs;
+ url = transportLogic.prepareQueryString(connection, url);
+
+ // With sse or ws, access_token in request header is not supported
+ if (connection.transport && connection.accessToken) {
+ if (connection.transport.name === "serverSentEvents" || connection.transport.name === "webSockets") {
+ url += "&access_token=" + window.encodeURIComponent(connection.accessToken);
+ }
+ }
+
+ if (!ajaxPost) {
+ url += "&tid=" + Math.floor(Math.random() * 11);
+ }
+
+ return url;
+ },
+
+ maximizePersistentResponse: function (minPersistentResponse) {
+ return {
+ MessageId: minPersistentResponse.C,
+ Messages: minPersistentResponse.M,
+ Initialized: typeof (minPersistentResponse.S) !== "undefined" ? true : false,
+ ShouldReconnect: typeof (minPersistentResponse.T) !== "undefined" ? true : false,
+ LongPollDelay: minPersistentResponse.L,
+ GroupsToken: minPersistentResponse.G,
+ Error: minPersistentResponse.E
+ };
+ },
+
+ updateGroups: function (connection, groupsToken) {
+ if (groupsToken) {
+ connection.groupsToken = groupsToken;
+ }
+ },
+
+ stringifySend: function (connection, message) {
+ if (typeof (message) === "string" || typeof (message) === "undefined" || message === null) {
+ return message;
+ }
+ return connection.json.stringify(message);
+ },
+
+ ajaxSend: function (connection, data) {
+ var payload = transportLogic.stringifySend(connection, data),
+ url = getAjaxUrl(connection, "/send"),
+ xhr,
+ onFail = function (error, connection) {
+ $(connection).triggerHandler(events.onError, [signalR._.transportError(signalR.resources.sendFailed, connection.transport, error, xhr), data]);
+ };
+
+
+ xhr = transportLogic.ajax(connection, {
+ url: url,
+ type: connection.ajaxDataType === "jsonp" ? "GET" : "POST",
+ contentType: signalR._.defaultContentType,
+ headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
+ data: {
+ data: payload
+ },
+ success: function (result) {
+ var res;
+
+ if (result) {
+ try {
+ res = connection._parseResponse(result);
+ }
+ catch (error) {
+ onFail(error, connection);
+ connection.stop();
+ return;
+ }
+
+ transportLogic.triggerReceived(connection, res);
+ }
+ },
+ error: function (error, textStatus) {
+ if (textStatus === "abort" || textStatus === "parsererror") {
+ // The parsererror happens for sends that don't return any data, and hence
+ // don't write the jsonp callback to the response. This is harder to fix on the server
+ // so just hack around it on the client for now.
+ return;
+ }
+
+ onFail(error, connection);
+ }
+ });
+
+ return xhr;
+ },
+
+ ajaxAbort: function (connection, async) {
+ if (typeof (connection.transport) === "undefined") {
+ return;
+ }
+
+ // Async by default unless explicitly overidden
+ async = typeof async === "undefined" ? true : async;
+
+ var url = getAjaxUrl(connection, "/abort");
+
+ var requestHeaders = connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {};
+
+ //option #1 - send "fetch" with keepalive
+ if (window.fetch) {
+ // use the fetch API with keepalive
+ window.fetch(url, {
+ method: "POST",
+ keepalive: true,
+ headers: requestHeaders,
+ credentials: connection.withCredentials === true ? "include" : "same-origin"
+ });
+ }
+ else {
+ // fetch is not available - fallback to $.ajax
+ transportLogic.ajax(connection, {
+ url: url,
+ async: async,
+ timeout: 1000,
+ type: "POST",
+ headers: requestHeaders,
+ dataType: "text" // We don't want to use JSONP here even when JSONP is enabled
+ });
+ }
+
+ connection.log("Fired ajax abort async = " + async + ".");
+ },
+
+ ajaxStart: function (connection, onSuccess) {
+ var rejectDeferred = function (error) {
+ var deferred = connection._deferral;
+ if (deferred) {
+ deferred.reject(error);
+ }
+ },
+ triggerStartError = function (error) {
+ connection.log("The start request failed. Stopping the connection.");
+ $(connection).triggerHandler(events.onError, [error]);
+ rejectDeferred(error);
+ connection.stop();
+ };
+
+ connection._.startRequest = transportLogic.ajax(connection, {
+ url: getAjaxUrl(connection, "/start"),
+ headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
+ success: function (result, statusText, xhr) {
+ var data;
+
+ try {
+ data = connection._parseResponse(result);
+ } catch (error) {
+ triggerStartError(signalR._.error(
+ signalR._.format(signalR.resources.errorParsingStartResponse, result),
+ error, xhr));
+ return;
+ }
+
+ if (data.Response === "started") {
+ onSuccess();
+ } else {
+ triggerStartError(signalR._.error(
+ signalR._.format(signalR.resources.invalidStartResponse, result),
+ null /* error */, xhr));
+ }
+ },
+ error: function (xhr, statusText, error) {
+ if (statusText !== startAbortText) {
+ triggerStartError(signalR._.error(
+ signalR.resources.errorDuringStartRequest,
+ error, xhr));
+ } else {
+ // Stop has been called, no need to trigger the error handler
+ // or stop the connection again with onStartError
+ connection.log("The start request aborted because connection.stop() was called.");
+ rejectDeferred(signalR._.error(
+ signalR.resources.stoppedDuringStartRequest,
+ null /* error */, xhr));
+ }
+ }
+ });
+ },
+
+ tryAbortStartRequest: function (connection) {
+ if (connection._.startRequest) {
+ // If the start request has already completed this will noop.
+ connection._.startRequest.abort(startAbortText);
+ delete connection._.startRequest;
+ }
+ },
+
+ tryInitialize: function (connection, persistentResponse, onInitialized) {
+ if (persistentResponse.Initialized && onInitialized) {
+ onInitialized();
+ } else if (persistentResponse.Initialized) {
+ connection.log("WARNING! The client received an init message after reconnecting.");
+ }
+
+ },
+
+ triggerReceived: function (connection, data) {
+ if (!connection._.connectingMessageBuffer.tryBuffer(data)) {
+ $(connection).triggerHandler(events.onReceived, [data]);
+ }
+ },
+
+ processMessages: function (connection, minData, onInitialized) {
+ var data;
+
+ if(minData && (typeof minData.I !== "undefined")) {
+ // This is a response to a message the client sent
+ transportLogic.triggerReceived(connection, minData);
+ return;
+ }
+
+ // Update the last message time stamp
+ transportLogic.markLastMessage(connection);
+
+ if (minData) {
+ // This is a message send directly to the client
+ data = transportLogic.maximizePersistentResponse(minData);
+
+ if (data.Error) {
+ // This is a global error, stop the connection.
+ connection.log("Received an error message from the server: " + minData.E);
+ $(connection).triggerHandler(signalR.events.onError, [signalR._.error(minData.E, /* source */ "ServerError")]);
+ connection.stop(/* async */ false, /* notifyServer */ false);
+ return;
+ }
+
+ transportLogic.updateGroups(connection, data.GroupsToken);
+
+ if (data.MessageId) {
+ connection.messageId = data.MessageId;
+ }
+
+ if (data.Messages) {
+ $.each(data.Messages, function (index, message) {
+ transportLogic.triggerReceived(connection, message);
+ });
+
+ transportLogic.tryInitialize(connection, data, onInitialized);
+ }
+ }
+ },
+
+ monitorKeepAlive: function (connection) {
+ var keepAliveData = connection._.keepAliveData;
+
+ // If we haven't initiated the keep alive timeouts then we need to
+ if (!keepAliveData.monitoring) {
+ keepAliveData.monitoring = true;
+
+ transportLogic.markLastMessage(connection);
+
+ // Save the function so we can unbind it on stop
+ connection._.keepAliveData.reconnectKeepAliveUpdate = function () {
+ // Mark a new message so that keep alive doesn't time out connections
+ transportLogic.markLastMessage(connection);
+ };
+
+ // Update Keep alive on reconnect
+ $(connection).bind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate);
+
+ 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);
+ } else {
+ connection.log("Tried to monitor keep alive but it's already being monitored.");
+ }
+ },
+
+ stopMonitoringKeepAlive: function (connection) {
+ var keepAliveData = connection._.keepAliveData;
+
+ // Only attempt to stop the keep alive monitoring if its being monitored
+ if (keepAliveData.monitoring) {
+ // Stop monitoring
+ keepAliveData.monitoring = false;
+
+ // Remove the updateKeepAlive function from the reconnect event
+ $(connection).unbind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate);
+
+ // Clear all the keep alive data
+ connection._.keepAliveData = {};
+ connection.log("Stopping the monitoring of the keep alive.");
+ }
+ },
+
+ startHeartbeat: function (connection) {
+ connection._.lastActiveAt = new Date().getTime();
+ beat(connection);
+ },
+
+ markLastMessage: function (connection) {
+ connection._.lastMessageAt = new Date().getTime();
+ connection._.lastActiveAt = connection._.lastMessageAt;
+ },
+
+ markActive: function (connection) {
+ if (transportLogic.verifyLastActive(connection)) {
+ connection._.lastActiveAt = new Date().getTime();
+ return true;
+ }
+
+ return false;
+ },
+
+ isConnectedOrReconnecting: function (connection) {
+ return connection.state === signalR.connectionState.connected ||
+ connection.state === signalR.connectionState.reconnecting;
+ },
+
+ ensureReconnectingState: function (connection) {
+ if (changeState(connection,
+ signalR.connectionState.connected,
+ signalR.connectionState.reconnecting) === true) {
+ $(connection).triggerHandler(events.onReconnecting);
+ }
+ return connection.state === signalR.connectionState.reconnecting;
+ },
+
+ clearReconnectTimeout: function (connection) {
+ if (connection && connection._.reconnectTimeout) {
+ window.clearTimeout(connection._.reconnectTimeout);
+ delete connection._.reconnectTimeout;
+ }
+ },
+
+ verifyLastActive: function (connection) {
+ // If there is no keep alive configured, we cannot assume that timer callbacks will
+ // run frequently enough to keep lastActiveAt updated.
+ // https://github.com/SignalR/SignalR/issues/4536
+ if (!connection._.keepAliveData.activated ||
+ new Date().getTime() - connection._.lastActiveAt < connection.reconnectWindow) {
+ return true;
+ }
+
+ var message = signalR._.format(signalR.resources.reconnectWindowTimeout, new Date(connection._.lastActiveAt), connection.reconnectWindow);
+ connection.log(message);
+ $(connection).triggerHandler(events.onError, [signalR._.error(message, /* source */ "TimeoutException")]);
+ connection.stop(/* async */ false, /* notifyServer */ false);
+ return false;
+ },
+
+ reconnect: function (connection, transportName) {
+ var transport = signalR.transports[transportName];
+
+ // We should only set a reconnectTimeout if we are currently connected
+ // and a reconnectTimeout isn't already set.
+ if (transportLogic.isConnectedOrReconnecting(connection) && !connection._.reconnectTimeout) {
+ // Need to verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration.
+ if (!transportLogic.verifyLastActive(connection)) {
+ return;
+ }
+
+ connection._.reconnectTimeout = window.setTimeout(function () {
+ if (!transportLogic.verifyLastActive(connection)) {
+ return;
+ }
+
+ transport.stop(connection);
+
+ if (transportLogic.ensureReconnectingState(connection)) {
+ connection.log(transportName + " reconnecting.");
+ transport.start(connection);
+ }
+ }, connection.reconnectDelay);
+ }
+ },
+
+ handleParseFailure: function (connection, result, error, onFailed, context) {
+ var wrappedError = signalR._.transportError(
+ signalR._.format(signalR.resources.parseFailed, result),
+ connection.transport,
+ error,
+ context);
+
+ // If we're in the initialization phase trigger onFailed, otherwise stop the connection.
+ if (onFailed && onFailed(wrappedError)) {
+ connection.log("Failed to parse server response while attempting to connect.");
+ } else {
+ $(connection).triggerHandler(events.onError, [wrappedError]);
+ connection.stop();
+ }
+ },
+
+ initHandler: function (connection) {
+ return new InitHandler(connection);
+ },
+
+ foreverFrame: {
+ count: 0,
+ connections: {}
+ }
+ };
+
+}(window.jQuery, window));
+/* jquery.signalR.transports.webSockets.js */
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+
+/*global window:false */
+///
+
+(function ($, window, undefined) {
+
+ var signalR = $.signalR,
+ events = $.signalR.events,
+ changeState = $.signalR.changeState,
+ transportLogic = signalR.transports._logic;
+
+ signalR.transports.webSockets = {
+ name: "webSockets",
+
+ supportsKeepAlive: function () {
+ return true;
+ },
+
+ send: function (connection, data) {
+ var payload = transportLogic.stringifySend(connection, data);
+
+ try {
+ connection.socket.send(payload);
+ } catch (ex) {
+ $(connection).triggerHandler(events.onError,
+ [signalR._.transportError(
+ signalR.resources.webSocketsInvalidState,
+ connection.transport,
+ ex,
+ connection.socket
+ ),
+ data]);
+ }
+ },
+
+ start: function (connection, onSuccess, onFailed) {
+ var url,
+ opened = false,
+ that = this,
+ reconnecting = !onSuccess,
+ $connection = $(connection);
+
+ if (!window.WebSocket) {
+ onFailed();
+ return;
+ }
+
+ if (!connection.socket) {
+ if (connection.webSocketServerUrl) {
+ url = connection.webSocketServerUrl;
+ } else {
+ url = connection.wsProtocol + connection.host;
+ }
+
+ url += transportLogic.getUrl(connection, this.name, reconnecting);
+
+ connection.log("Connecting to websocket endpoint '" + url + "'.");
+ connection.socket = new window.WebSocket(url);
+
+ connection.socket.onopen = function () {
+ opened = true;
+ connection.log("Websocket opened.");
+
+ transportLogic.clearReconnectTimeout(connection);
+
+ if (changeState(connection,
+ signalR.connectionState.reconnecting,
+ signalR.connectionState.connected) === true) {
+ $connection.triggerHandler(events.onReconnect);
+ }
+ };
+
+ connection.socket.onclose = function (event) {
+ var error;
+
+ // Only handle a socket close if the close is from the current socket.
+ // Sometimes on disconnect the server will push down an onclose event
+ // to an expired socket.
+
+ if (this === connection.socket) {
+ if (opened && typeof event.wasClean !== "undefined" && event.wasClean === false) {
+ // Ideally this would use the websocket.onerror handler (rather than checking wasClean in onclose) but
+ // I found in some circumstances Chrome won't call onerror. This implementation seems to work on all browsers.
+ error = signalR._.transportError(
+ signalR.resources.webSocketClosed,
+ connection.transport,
+ event);
+
+ connection.log("Unclean disconnect from websocket: " + (event.reason || "[no reason given]."));
+ } else {
+ connection.log("Websocket closed.");
+ }
+
+ if (!onFailed || !onFailed(error)) {
+ if (error) {
+ $(connection).triggerHandler(events.onError, [error]);
+ }
+
+ that.reconnect(connection);
+ }
+ }
+ };
+
+ connection.socket.onmessage = function (event) {
+ var data;
+
+ try {
+ data = connection._parseResponse(event.data);
+ }
+ catch (error) {
+ transportLogic.handleParseFailure(connection, event.data, error, onFailed, event);
+ return;
+ }
+
+ if (data) {
+ transportLogic.processMessages(connection, data, onSuccess);
+ }
+ };
+ }
+ },
+
+ reconnect: function (connection) {
+ transportLogic.reconnect(connection, this.name);
+ },
+
+ lostConnection: function (connection) {
+ this.reconnect(connection);
+ },
+
+ stop: function (connection) {
+ // Don't trigger a reconnect after stopping
+ transportLogic.clearReconnectTimeout(connection);
+
+ if (connection.socket) {
+ connection.log("Closing the Websocket.");
+ connection.socket.close();
+ connection.socket = null;
+ }
+ },
+
+ abort: function (connection, async) {
+ transportLogic.ajaxAbort(connection, async);
+ }
+ };
+
+}(window.jQuery, window));
+/* jquery.signalR.transports.serverSentEvents.js */
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+
+/*global window:false */
+///
+
+(function ($, window, undefined) {
+
+ var signalR = $.signalR,
+ events = $.signalR.events,
+ changeState = $.signalR.changeState,
+ transportLogic = signalR.transports._logic,
+ clearReconnectAttemptTimeout = function (connection) {
+ window.clearTimeout(connection._.reconnectAttemptTimeoutHandle);
+ delete connection._.reconnectAttemptTimeoutHandle;
+ };
+
+ signalR.transports.serverSentEvents = {
+ name: "serverSentEvents",
+
+ supportsKeepAlive: function () {
+ return true;
+ },
+
+ timeOut: 3000,
+
+ start: function (connection, onSuccess, onFailed) {
+ var that = this,
+ opened = false,
+ $connection = $(connection),
+ reconnecting = !onSuccess,
+ url;
+
+ if (connection.eventSource) {
+ connection.log("The connection already has an event source. Stopping it.");
+ connection.stop();
+ }
+
+ if (!window.EventSource) {
+ if (onFailed) {
+ connection.log("This browser doesn't support SSE.");
+ onFailed();
+ }
+ return;
+ }
+
+ url = transportLogic.getUrl(connection, this.name, reconnecting);
+
+ try {
+ connection.log("Attempting to connect to SSE endpoint '" + url + "'.");
+ connection.eventSource = new window.EventSource(url, { withCredentials: connection.withCredentials });
+ }
+ catch (e) {
+ connection.log("EventSource failed trying to connect with error " + e.Message + ".");
+ if (onFailed) {
+ // The connection failed, call the failed callback
+ onFailed();
+ } else {
+ $connection.triggerHandler(events.onError, [signalR._.transportError(signalR.resources.eventSourceFailedToConnect, connection.transport, e)]);
+ if (reconnecting) {
+ // If we were reconnecting, rather than doing initial connect, then try reconnect again
+ that.reconnect(connection);
+ }
+ }
+ return;
+ }
+
+ if (reconnecting) {
+ connection._.reconnectAttemptTimeoutHandle = window.setTimeout(function () {
+ if (opened === false) {
+ // If we're reconnecting and the event source is attempting to connect,
+ // don't keep retrying. This causes duplicate connections to spawn.
+ if (connection.eventSource.readyState !== window.EventSource.OPEN) {
+ // If we were reconnecting, rather than doing initial connect, then try reconnect again
+ that.reconnect(connection);
+ }
+ }
+ },
+ that.timeOut);
+ }
+
+ connection.eventSource.addEventListener("open", function (e) {
+ connection.log("EventSource connected.");
+
+ clearReconnectAttemptTimeout(connection);
+ transportLogic.clearReconnectTimeout(connection);
+
+ if (opened === false) {
+ opened = true;
+
+ if (changeState(connection,
+ signalR.connectionState.reconnecting,
+ signalR.connectionState.connected) === true) {
+ $connection.triggerHandler(events.onReconnect);
+ }
+ }
+ }, false);
+
+ connection.eventSource.addEventListener("message", function (e) {
+ var res;
+
+ // process messages
+ if (e.data === "initialized") {
+ return;
+ }
+
+ try {
+ res = connection._parseResponse(e.data);
+ }
+ catch (error) {
+ transportLogic.handleParseFailure(connection, e.data, error, onFailed, e);
+ return;
+ }
+
+ transportLogic.processMessages(connection, res, onSuccess);
+ }, false);
+
+ connection.eventSource.addEventListener("error", function (e) {
+ var error = signalR._.transportError(
+ signalR.resources.eventSourceError,
+ connection.transport,
+ e);
+
+ // Only handle an error if the error is from the current Event Source.
+ // Sometimes on disconnect the server will push down an error event
+ // to an expired Event Source.
+ if (this !== connection.eventSource) {
+ return;
+ }
+
+ if (onFailed && onFailed(error)) {
+ return;
+ }
+
+ connection.log("EventSource readyState: " + connection.eventSource.readyState + ".");
+
+ if (e.eventPhase === window.EventSource.CLOSED) {
+ // We don't use the EventSource's native reconnect function as it
+ // doesn't allow us to change the URL when reconnecting. We need
+ // to change the URL to not include the /connect suffix, and pass
+ // the last message id we received.
+ connection.log("EventSource reconnecting due to the server connection ending.");
+ that.reconnect(connection);
+ } else {
+ // connection error
+ connection.log("EventSource error.");
+ $connection.triggerHandler(events.onError, [error]);
+ }
+ }, false);
+ },
+
+ reconnect: function (connection) {
+ transportLogic.reconnect(connection, this.name);
+ },
+
+ lostConnection: function (connection) {
+ this.reconnect(connection);
+ },
+
+ send: function (connection, data) {
+ transportLogic.ajaxSend(connection, data);
+ },
+
+ stop: function (connection) {
+ // Don't trigger a reconnect after stopping
+ clearReconnectAttemptTimeout(connection);
+ transportLogic.clearReconnectTimeout(connection);
+
+ if (connection && connection.eventSource) {
+ connection.log("EventSource calling close().");
+ connection.eventSource.close();
+ connection.eventSource = null;
+ delete connection.eventSource;
+ }
+ },
+
+ abort: function (connection, async) {
+ transportLogic.ajaxAbort(connection, async);
+ }
+ };
+
+}(window.jQuery, window));
+/* jquery.signalR.transports.foreverFrame.js */
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+
+/*global window:false */
+///
+
+(function ($, window, undefined) {
+
+ var signalR = $.signalR,
+ events = $.signalR.events,
+ changeState = $.signalR.changeState,
+ transportLogic = signalR.transports._logic,
+ createFrame = function () {
+ var frame = window.document.createElement("iframe");
+ frame.setAttribute("style", "position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;");
+ return frame;
+ },
+ // Used to prevent infinite loading icon spins in older versions of ie
+ // We build this object inside a closure so we don't pollute the rest of
+ // the foreverFrame transport with unnecessary functions/utilities.
+ loadPreventer = (function () {
+ var loadingFixIntervalId = null,
+ loadingFixInterval = 1000,
+ attachedTo = 0;
+
+ return {
+ prevent: function () {
+ // Prevent additional iframe removal procedures from newer browsers
+ if (signalR._.ieVersion <= 8) {
+ // We only ever want to set the interval one time, so on the first attachedTo
+ if (attachedTo === 0) {
+ // Create and destroy iframe every 3 seconds to prevent loading icon, super hacky
+ loadingFixIntervalId = window.setInterval(function () {
+ var tempFrame = createFrame();
+
+ window.document.body.appendChild(tempFrame);
+ window.document.body.removeChild(tempFrame);
+
+ tempFrame = null;
+ }, loadingFixInterval);
+ }
+
+ attachedTo++;
+ }
+ },
+ cancel: function () {
+ // Only clear the interval if there's only one more object that the loadPreventer is attachedTo
+ if (attachedTo === 1) {
+ window.clearInterval(loadingFixIntervalId);
+ }
+
+ if (attachedTo > 0) {
+ attachedTo--;
+ }
+ }
+ };
+ })();
+
+ signalR.transports.foreverFrame = {
+ name: "foreverFrame",
+
+ supportsKeepAlive: function () {
+ return true;
+ },
+
+ // Added as a value here so we can create tests to verify functionality
+ iframeClearThreshold: 50,
+
+ start: function (connection, onSuccess, onFailed) {
+ if (connection.accessToken) {
+ if (onFailed) {
+ connection.log("Forever Frame does not support connections that require a Bearer token to connect, such as the Azure SignalR Service.");
+ onFailed();
+ }
+ return;
+ }
+
+ var that = this,
+ frameId = (transportLogic.foreverFrame.count += 1),
+ url,
+ frame = createFrame(),
+ frameLoadHandler = function () {
+ connection.log("Forever frame iframe finished loading and is no longer receiving messages.");
+ if (!onFailed || !onFailed()) {
+ that.reconnect(connection);
+ }
+ };
+
+ if (window.EventSource) {
+ // If the browser supports SSE, don't use Forever Frame
+ if (onFailed) {
+ connection.log("Forever Frame is not supported by SignalR on browsers with SSE support.");
+ onFailed();
+ }
+ return;
+ }
+
+ frame.setAttribute("data-signalr-connection-id", connection.id);
+
+ // Start preventing loading icon
+ // This will only perform work if the loadPreventer is not attached to another connection.
+ loadPreventer.prevent();
+
+ // Build the url
+ url = transportLogic.getUrl(connection, this.name);
+ url += "&frameId=" + frameId;
+
+ // add frame to the document prior to setting URL to avoid caching issues.
+ window.document.documentElement.appendChild(frame);
+
+ connection.log("Binding to iframe's load event.");
+
+ if (frame.addEventListener) {
+ frame.addEventListener("load", frameLoadHandler, false);
+ } else if (frame.attachEvent) {
+ frame.attachEvent("onload", frameLoadHandler);
+ }
+
+ frame.src = url;
+ transportLogic.foreverFrame.connections[frameId] = connection;
+
+ connection.frame = frame;
+ connection.frameId = frameId;
+
+ if (onSuccess) {
+ connection.onSuccess = function () {
+ connection.log("Iframe transport started.");
+ onSuccess();
+ };
+ }
+ },
+
+ reconnect: function (connection) {
+ var that = this;
+
+ // Need to verify connection state and verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration.
+ if (transportLogic.isConnectedOrReconnecting(connection) && transportLogic.verifyLastActive(connection)) {
+ window.setTimeout(function () {
+ // Verify that we're ok to reconnect.
+ if (!transportLogic.verifyLastActive(connection)) {
+ return;
+ }
+
+ if (connection.frame && transportLogic.ensureReconnectingState(connection)) {
+ var frame = connection.frame,
+ src = transportLogic.getUrl(connection, that.name, true) + "&frameId=" + connection.frameId;
+ connection.log("Updating iframe src to '" + src + "'.");
+ frame.src = src;
+ }
+ }, connection.reconnectDelay);
+ }
+ },
+
+ lostConnection: function (connection) {
+ this.reconnect(connection);
+ },
+
+ send: function (connection, data) {
+ transportLogic.ajaxSend(connection, data);
+ },
+
+ receive: function (connection, data) {
+ var cw,
+ body,
+ response;
+
+ if (connection.json !== connection._originalJson) {
+ // If there's a custom JSON parser configured then serialize the object
+ // using the original (browser) JSON parser and then deserialize it using
+ // the custom parser (connection._parseResponse does that). This is so we
+ // can easily send the response from the server as "raw" JSON but still
+ // support custom JSON deserialization in the browser.
+ data = connection._originalJson.stringify(data);
+ }
+
+ response = connection._parseResponse(data);
+
+ transportLogic.processMessages(connection, response, connection.onSuccess);
+
+ // Protect against connection stopping from a callback trigger within the processMessages above.
+ if (connection.state === $.signalR.connectionState.connected) {
+ // Delete the script & div elements
+ connection.frameMessageCount = (connection.frameMessageCount || 0) + 1;
+ if (connection.frameMessageCount > signalR.transports.foreverFrame.iframeClearThreshold) {
+ connection.frameMessageCount = 0;
+ cw = connection.frame.contentWindow || connection.frame.contentDocument;
+ if (cw && cw.document && cw.document.body) {
+ body = cw.document.body;
+
+ // Remove all the child elements from the iframe's body to conserver memory
+ while (body.firstChild) {
+ body.removeChild(body.firstChild);
+ }
+ }
+ }
+ }
+ },
+
+ stop: function (connection) {
+ var cw = null;
+
+ // Stop attempting to prevent loading icon
+ loadPreventer.cancel();
+
+ if (connection.frame) {
+ if (connection.frame.stop) {
+ connection.frame.stop();
+ } else {
+ try {
+ cw = connection.frame.contentWindow || connection.frame.contentDocument;
+ if (cw.document && cw.document.execCommand) {
+ cw.document.execCommand("Stop");
+ }
+ }
+ catch (e) {
+ connection.log("Error occurred when stopping foreverFrame transport. Message = " + e.message + ".");
+ }
+ }
+
+ // Ensure the iframe is where we left it
+ if (connection.frame.parentNode === window.document.documentElement) {
+ window.document.documentElement.removeChild(connection.frame);
+ }
+
+ delete transportLogic.foreverFrame.connections[connection.frameId];
+ connection.frame = null;
+ connection.frameId = null;
+ delete connection.frame;
+ delete connection.frameId;
+ delete connection.onSuccess;
+ delete connection.frameMessageCount;
+ connection.log("Stopping forever frame.");
+ }
+ },
+
+ abort: function (connection, async) {
+ transportLogic.ajaxAbort(connection, async);
+ },
+
+ getConnection: function (id) {
+ return transportLogic.foreverFrame.connections[id];
+ },
+
+ started: function (connection) {
+ if (changeState(connection,
+ signalR.connectionState.reconnecting,
+ signalR.connectionState.connected) === true) {
+
+ $(connection).triggerHandler(events.onReconnect);
+ }
+ }
+ };
+
+}(window.jQuery, window));
+/* jquery.signalR.transports.longPolling.js */
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+
+/*global window:false */
+///
+
+(function ($, window, undefined) {
+
+ var signalR = $.signalR,
+ events = $.signalR.events,
+ changeState = $.signalR.changeState,
+ isDisconnecting = $.signalR.isDisconnecting,
+ transportLogic = signalR.transports._logic;
+
+ signalR.transports.longPolling = {
+ name: "longPolling",
+
+ supportsKeepAlive: function () {
+ return false;
+ },
+
+ reconnectDelay: 3000,
+
+ start: function (connection, onSuccess, onFailed) {
+ /// Starts the long polling connection
+ /// The SignalR connection to start
+ var that = this,
+ fireConnect = function () {
+ fireConnect = $.noop;
+
+ connection.log("LongPolling connected.");
+
+ if (onSuccess) {
+ onSuccess();
+ } else {
+ connection.log("WARNING! The client received an init message after reconnecting.");
+ }
+ },
+ tryFailConnect = function (error) {
+ if (onFailed(error)) {
+ connection.log("LongPolling failed to connect.");
+ return true;
+ }
+
+ return false;
+ },
+ privateData = connection._,
+ reconnectErrors = 0,
+ fireReconnected = function (instance) {
+ window.clearTimeout(privateData.reconnectTimeoutId);
+ privateData.reconnectTimeoutId = null;
+
+ if (changeState(instance,
+ signalR.connectionState.reconnecting,
+ signalR.connectionState.connected) === true) {
+ // Successfully reconnected!
+ instance.log("Raising the reconnect event");
+ $(instance).triggerHandler(events.onReconnect);
+ }
+ },
+ // 1 hour
+ maxFireReconnectedTimeout = 3600000;
+
+ if (connection.pollXhr) {
+ connection.log("Polling xhr requests already exists, aborting.");
+ connection.stop();
+ }
+
+ connection.messageId = null;
+
+ privateData.reconnectTimeoutId = null;
+
+ privateData.pollTimeoutId = window.setTimeout(function () {
+ (function poll(instance, raiseReconnect) {
+ var messageId = instance.messageId,
+ connect = (messageId === null),
+ reconnecting = !connect,
+ polling = !raiseReconnect,
+ url = transportLogic.getUrl(instance, that.name, reconnecting, polling, true /* use Post for longPolling */),
+ postData = {};
+
+ if (instance.messageId) {
+ postData.messageId = instance.messageId;
+ }
+
+ if (instance.groupsToken) {
+ postData.groupsToken = instance.groupsToken;
+ }
+
+ // If we've disconnected during the time we've tried to re-instantiate the poll then stop.
+ if (isDisconnecting(instance) === true) {
+ return;
+ }
+
+ connection.log("Opening long polling request to '" + url + "'.");
+ instance.pollXhr = transportLogic.ajax(connection, {
+ xhrFields: {
+ onprogress: function () {
+ transportLogic.markLastMessage(connection);
+ }
+ },
+ url: url,
+ type: "POST",
+ contentType: signalR._.defaultContentType,
+ data: postData,
+ timeout: connection._.pollTimeout,
+ headers: connection.accessToken ? { "Authorization": "Bearer " + connection.accessToken } : {},
+ success: function (result) {
+ var minData,
+ delay = 0,
+ data,
+ shouldReconnect;
+
+ connection.log("Long poll complete.");
+
+ // Reset our reconnect errors so if we transition into a reconnecting state again we trigger
+ // reconnected quickly
+ reconnectErrors = 0;
+
+ try {
+ // Remove any keep-alives from the beginning of the result
+ minData = connection._parseResponse(result);
+ }
+ catch (error) {
+ transportLogic.handleParseFailure(instance, result, error, tryFailConnect, instance.pollXhr);
+ return;
+ }
+
+ // If there's currently a timeout to trigger reconnect, fire it now before processing messages
+ if (privateData.reconnectTimeoutId !== null) {
+ fireReconnected(instance);
+ }
+
+ if (minData) {
+ data = transportLogic.maximizePersistentResponse(minData);
+ }
+
+ transportLogic.processMessages(instance, minData, fireConnect);
+
+ if (data &&
+ $.type(data.LongPollDelay) === "number") {
+ delay = data.LongPollDelay;
+ }
+
+ if (isDisconnecting(instance) === true) {
+ return;
+ }
+
+ shouldReconnect = data && data.ShouldReconnect;
+ if (shouldReconnect) {
+ // Transition into the reconnecting state
+ // If this fails then that means that the user transitioned the connection into a invalid state in processMessages.
+ if (!transportLogic.ensureReconnectingState(instance)) {
+ return;
+ }
+ }
+
+ // We never want to pass a raiseReconnect flag after a successful poll. This is handled via the error function
+ if (delay > 0) {
+ privateData.pollTimeoutId = window.setTimeout(function () {
+ poll(instance, shouldReconnect);
+ }, delay);
+ } else {
+ poll(instance, shouldReconnect);
+ }
+ },
+
+ error: function (data, textStatus) {
+ var error = signalR._.transportError(signalR.resources.longPollFailed, connection.transport, data, instance.pollXhr);
+
+ // Stop trying to trigger reconnect, connection is in an error state
+ // If we're not in the reconnect state this will noop
+ window.clearTimeout(privateData.reconnectTimeoutId);
+ privateData.reconnectTimeoutId = null;
+
+ if (textStatus === "abort") {
+ connection.log("Aborted xhr request.");
+ return;
+ }
+
+ if (!tryFailConnect(error)) {
+
+ // Increment our reconnect errors, we assume all errors to be reconnect errors
+ // In the case that it's our first error this will cause Reconnect to be fired
+ // after 1 second due to reconnectErrors being = 1.
+ reconnectErrors++;
+
+ if (connection.state !== signalR.connectionState.reconnecting) {
+ connection.log("An error occurred using longPolling. Status = " + textStatus + ". Response = " + data.responseText + ".");
+ $(instance).triggerHandler(events.onError, [error]);
+ }
+
+ // We check the state here to verify that we're not in an invalid state prior to verifying Reconnect.
+ // If we're not in connected or reconnecting then the next ensureReconnectingState check will fail and will return.
+ // Therefore we don't want to change that failure code path.
+ if ((connection.state === signalR.connectionState.connected ||
+ connection.state === signalR.connectionState.reconnecting) &&
+ !transportLogic.verifyLastActive(connection)) {
+ return;
+ }
+
+ // Transition into the reconnecting state
+ // If this fails then that means that the user transitioned the connection into the disconnected or connecting state within the above error handler trigger.
+ if (!transportLogic.ensureReconnectingState(instance)) {
+ return;
+ }
+
+ // Call poll with the raiseReconnect flag as true after the reconnect delay
+ privateData.pollTimeoutId = window.setTimeout(function () {
+ poll(instance, true);
+ }, that.reconnectDelay);
+ }
+ }
+ });
+
+ // This will only ever pass after an error has occurred via the poll ajax procedure.
+ if (reconnecting && raiseReconnect === true) {
+ // We wait to reconnect depending on how many times we've failed to reconnect.
+ // This is essentially a heuristic that will exponentially increase in wait time before
+ // triggering reconnected. This depends on the "error" handler of Poll to cancel this
+ // timeout if it triggers before the Reconnected event fires.
+ // The Math.min at the end is to ensure that the reconnect timeout does not overflow.
+ privateData.reconnectTimeoutId = window.setTimeout(function () { fireReconnected(instance); }, Math.min(1000 * (Math.pow(2, reconnectErrors) - 1), maxFireReconnectedTimeout));
+ }
+ }(connection));
+ }, 250); // Have to delay initial poll so Chrome doesn't show loader spinner in tab
+ },
+
+ lostConnection: function (connection) {
+ if (connection.pollXhr) {
+ connection.pollXhr.abort("lostConnection");
+ }
+ },
+
+ send: function (connection, data) {
+ transportLogic.ajaxSend(connection, data);
+ },
+
+ stop: function (connection) {
+ /// Stops the long polling connection
+ /// The SignalR connection to stop
+
+ window.clearTimeout(connection._.pollTimeoutId);
+ window.clearTimeout(connection._.reconnectTimeoutId);
+
+ delete connection._.pollTimeoutId;
+ delete connection._.reconnectTimeoutId;
+
+ if (connection.pollXhr) {
+ connection.pollXhr.abort();
+ connection.pollXhr = null;
+ delete connection.pollXhr;
+ }
+ },
+
+ abort: function (connection, async) {
+ transportLogic.ajaxAbort(connection, async);
+ }
+ };
+
+}(window.jQuery, window));
+/* jquery.signalR.hubs.js */
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+/*global window:false */
+///
+
+(function ($, window, undefined) {
+
+ var nextGuid = 0;
+ var eventNamespace = ".hubProxy",
+ signalR = $.signalR;
+
+ function makeEventName(event) {
+ return event + eventNamespace;
+ }
+
+ // Equivalent to Array.prototype.map
+ function map(arr, fun, thisp) {
+ var i,
+ length = arr.length,
+ result = [];
+ for (i = 0; i < length; i += 1) {
+ if (arr.hasOwnProperty(i)) {
+ result[i] = fun.call(thisp, arr[i], i, arr);
+ }
+ }
+ return result;
+ }
+
+ function getArgValue(a) {
+ return $.isFunction(a) ? null : ($.type(a) === "undefined" ? null : a);
+ }
+
+ function hasMembers(obj) {
+ for (var key in obj) {
+ // If we have any properties in our callback map then we have callbacks and can exit the loop via return
+ if (obj.hasOwnProperty(key)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ function clearInvocationCallbacks(connection, error) {
+ ///
+ var callbacks = connection._.invocationCallbacks,
+ callback;
+
+ if (hasMembers(callbacks)) {
+ connection.log("Clearing hub invocation callbacks with error: " + error + ".");
+ }
+
+ // Reset the callback cache now as we have a local var referencing it
+ connection._.invocationCallbackId = 0;
+ delete connection._.invocationCallbacks;
+ connection._.invocationCallbacks = {};
+
+ // Loop over the callbacks and invoke them.
+ // We do this using a local var reference and *after* we've cleared the cache
+ // so that if a fail callback itself tries to invoke another method we don't
+ // end up with its callback in the list we're looping over.
+ for (var callbackId in callbacks) {
+ callback = callbacks[callbackId];
+ callback.method.call(callback.scope, { E: error });
+ }
+ }
+
+ function isCallbackFromGeneratedHubProxy(callback) {
+ // https://github.com/SignalR/SignalR/issues/4310
+ // The stringified callback from the old generated hub proxy is 137 characters in Edge, Firefox and Chrome.
+ // We slice to avoid wasting too many cycles searching through the text of a long large function.
+ return $.isFunction(callback) && callback.toString().slice(0, 256).indexOf("// Call the client hub method") >= 0;
+ }
+
+ // hubProxy
+ function hubProxy(hubConnection, hubName) {
+ ///
+ /// Creates a new proxy object for the given hub connection that can be used to invoke
+ /// methods on server hubs and handle client method invocation requests from the server.
+ ///
+ return new hubProxy.fn.init(hubConnection, hubName);
+ }
+
+ hubProxy.fn = hubProxy.prototype = {
+ init: function (connection, hubName) {
+ this.state = {};
+ this.connection = connection;
+ this.hubName = hubName;
+ this._ = {
+ callbackMap: {}
+ };
+ },
+
+ constructor: hubProxy,
+
+ hasSubscriptions: function () {
+ return hasMembers(this._.callbackMap);
+ },
+
+ on: function (eventName, callback, callbackIdentity) {
+ /// Wires up a callback to be invoked when a invocation request is received from the server hub.
+ /// The name of the hub event to register the callback for.
+ /// The callback to be invoked.
+ /// An optional object to use as the "identity" for the callback when checking if the handler has already been registered. Defaults to the value of 'callback' if not provided.
+ var that = this,
+ callbackMap = that._.callbackMap,
+ isFromOldGeneratedHubProxy = !callbackIdentity && isCallbackFromGeneratedHubProxy(callback);
+
+ // We need the third "identity" argument because the registerHubProxies call made by signalr/js wraps the user-provided callback in a custom wrapper which breaks the identity comparison.
+ // callbackIdentity allows the caller of `on` to provide a separate object to use as the "identity". `registerHubProxies` uses the original user callback as this identity object.
+ callbackIdentity = callbackIdentity || callback;
+
+ // Assign a global ID to the identity object. This tags the object so we can detect the same object when it comes back.
+ if(!callbackIdentity._signalRGuid) {
+ callbackIdentity._signalRGuid = nextGuid++;
+ }
+
+ // Normalize the event name to lowercase
+ eventName = eventName.toLowerCase();
+
+ // If there is not an event registered for this callback yet we want to create its event space in the callback map.
+ var callbackSpace = callbackMap[eventName];
+ if (!callbackSpace) {
+ callbackSpace = [];
+ callbackMap[eventName] = callbackSpace;
+ }
+
+ // Check if there's already a registration
+ var registration;
+ for (var i = 0; i < callbackSpace.length; i++) {
+ if (callbackSpace[i].guid === callbackIdentity._signalRGuid || (isFromOldGeneratedHubProxy && callbackSpace[i].isFromOldGeneratedHubProxy)) {
+ registration = callbackSpace[i];
+ }
+ }
+
+ // Create a registration if there isn't one already
+ if (!registration) {
+ registration = {
+ guid: callbackIdentity._signalRGuid,
+ eventHandlers: [],
+ isFromOldGeneratedHubProxy: isFromOldGeneratedHubProxy
+ };
+ callbackMap[eventName].push(registration);
+ }
+
+ var handler = function (e, data) {
+ callback.apply(that, data);
+ };
+ registration.eventHandlers.push(handler);
+
+ $(that).bind(makeEventName(eventName), handler);
+
+ return that;
+ },
+
+ off: function (eventName, callback, callbackIdentity) {
+ /// Removes the callback invocation request from the server hub for the given event name.
+ /// The name of the hub event to unregister the callback for.
+ /// The callback to be removed.
+ /// An optional object to use as the "identity" when looking up the callback. Corresponds to the same parameter provided to 'on'. Defaults to the value of 'callback' if not provided.
+ var that = this,
+ callbackMap = that._.callbackMap,
+ callbackSpace,
+ isFromOldGeneratedHubProxy = !callbackIdentity && isCallbackFromGeneratedHubProxy(callback);
+
+ callbackIdentity = callbackIdentity || callback;
+
+ // Normalize the event name to lowercase
+ eventName = eventName.toLowerCase();
+
+ callbackSpace = callbackMap[eventName];
+
+ // Verify that there is an event space to unbind
+ if (callbackSpace) {
+
+ if (callback) {
+ // Find the callback registration
+ var callbackRegistration;
+ var callbackIndex;
+ for (var i = 0; i < callbackSpace.length; i++) {
+ if (callbackSpace[i].guid === callbackIdentity._signalRGuid || (isFromOldGeneratedHubProxy && callbackSpace[i].isFromOldGeneratedHubProxy)) {
+ callbackIndex = i;
+ callbackRegistration = callbackSpace[i];
+ }
+ }
+
+ // Only unbind if there's an event bound with eventName and a callback with the specified callback
+ if (callbackRegistration) {
+ // Unbind all event handlers associated with the registration.
+ for (var j = 0; j < callbackRegistration.eventHandlers.length; j++) {
+ $(that).unbind(makeEventName(eventName), callbackRegistration.eventHandlers[j]);
+ }
+
+ // Remove the registration from the list
+ callbackSpace.splice(i, 1);
+
+ // Check if there are any registrations left, if not we need to destroy it.
+ if (callbackSpace.length === 0) {
+ delete callbackMap[eventName];
+ }
+ }
+ } else if (!callback) { // Check if we're removing the whole event and we didn't error because of an invalid callback
+ $(that).unbind(makeEventName(eventName));
+
+ delete callbackMap[eventName];
+ }
+ }
+
+ return that;
+ },
+
+ invoke: function (methodName) {
+ /// Invokes a server hub method with the given arguments.
+ /// The name of the server hub method.
+
+ var that = this,
+ connection = that.connection,
+ args = $.makeArray(arguments).slice(1),
+ argValues = map(args, getArgValue),
+ data = { H: that.hubName, M: methodName, A: argValues, I: connection._.invocationCallbackId },
+ d = $.Deferred(),
+ callback = function (minResult) {
+ var result = that._maximizeHubResponse(minResult),
+ source,
+ error;
+
+ // Update the hub state
+ $.extend(that.state, result.State);
+
+ if (result.Progress) {
+ if (d.notifyWith) {
+ // Progress is only supported in jQuery 1.7+
+ d.notifyWith(that, [result.Progress.Data]);
+ } else if (!connection._.progressjQueryVersionLogged) {
+ 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.");
+ connection._.progressjQueryVersionLogged = true;
+ }
+ } else if (result.Error) {
+ // Server hub method threw an exception, log it & reject the deferred
+ if (result.StackTrace) {
+ connection.log(result.Error + "\n" + result.StackTrace + ".");
+ }
+
+ // result.ErrorData is only set if a HubException was thrown
+ source = result.IsHubException ? "HubException" : "Exception";
+ error = signalR._.error(result.Error, source);
+ error.data = result.ErrorData;
+
+ connection.log(that.hubName + "." + methodName + " failed to execute. Error: " + error.message);
+ d.rejectWith(that, [error]);
+ } else {
+ // Server invocation succeeded, resolve the deferred
+ connection.log("Invoked " + that.hubName + "." + methodName);
+ d.resolveWith(that, [result.Result]);
+ }
+ };
+
+ connection._.invocationCallbacks[connection._.invocationCallbackId.toString()] = { scope: that, method: callback };
+ connection._.invocationCallbackId += 1;
+
+ if (!$.isEmptyObject(that.state)) {
+ data.S = that.state;
+ }
+
+ connection.log("Invoking " + that.hubName + "." + methodName);
+ connection.send(data);
+
+ return d.promise();
+ },
+
+ _maximizeHubResponse: function (minHubResponse) {
+ return {
+ State: minHubResponse.S,
+ Result: minHubResponse.R,
+ Progress: minHubResponse.P ? {
+ Id: minHubResponse.P.I,
+ Data: minHubResponse.P.D
+ } : null,
+ Id: minHubResponse.I,
+ IsHubException: minHubResponse.H,
+ Error: minHubResponse.E,
+ StackTrace: minHubResponse.T,
+ ErrorData: minHubResponse.D
+ };
+ }
+ };
+
+ hubProxy.fn.init.prototype = hubProxy.fn;
+
+ // hubConnection
+ function hubConnection(url, options) {
+ /// Creates a new hub connection.
+ /// [Optional] The hub route url, defaults to "/signalr".
+ /// [Optional] Settings to use when creating the hubConnection.
+ var settings = {
+ qs: null,
+ logging: false,
+ useDefaultPath: true
+ };
+
+ $.extend(settings, options);
+
+ if (!url || settings.useDefaultPath) {
+ url = (url || "") + "/signalr";
+ }
+ return new hubConnection.fn.init(url, settings);
+ }
+
+ hubConnection.fn = hubConnection.prototype = $.connection();
+
+ hubConnection.fn.init = function (url, options) {
+ var settings = {
+ qs: null,
+ logging: false,
+ useDefaultPath: true
+ },
+ connection = this;
+
+ $.extend(settings, options);
+
+ // Call the base constructor
+ $.signalR.fn.init.call(connection, url, settings.qs, settings.logging);
+
+ // Object to store hub proxies for this connection
+ connection.proxies = {};
+
+ connection._.invocationCallbackId = 0;
+ connection._.invocationCallbacks = {};
+
+ // Wire up the received handler
+ connection.received(function (minData) {
+ var data, proxy, dataCallbackId, callback, hubName, eventName;
+ if (!minData) {
+ return;
+ }
+
+ // We have to handle progress updates first in order to ensure old clients that receive
+ // progress updates enter the return value branch and then no-op when they can't find
+ // the callback in the map (because the minData.I value will not be a valid callback ID)
+ // Process progress notification
+ if (typeof (minData.P) !== "undefined") {
+ dataCallbackId = minData.P.I.toString();
+ callback = connection._.invocationCallbacks[dataCallbackId];
+ if (callback) {
+ callback.method.call(callback.scope, minData);
+ }
+ } else if (typeof (minData.I) !== "undefined") {
+ // We received the return value from a server method invocation, look up callback by id and call it
+ dataCallbackId = minData.I.toString();
+ callback = connection._.invocationCallbacks[dataCallbackId];
+ if (callback) {
+ // Delete the callback from the proxy
+ connection._.invocationCallbacks[dataCallbackId] = null;
+ delete connection._.invocationCallbacks[dataCallbackId];
+
+ // Invoke the callback
+ callback.method.call(callback.scope, minData);
+ }
+ } else {
+ data = this._maximizeClientHubInvocation(minData);
+
+ // We received a client invocation request, i.e. broadcast from server hub
+ connection.log("Triggering client hub event '" + data.Method + "' on hub '" + data.Hub + "'.");
+
+ // Normalize the names to lowercase
+ hubName = data.Hub.toLowerCase();
+ eventName = data.Method.toLowerCase();
+
+ // Trigger the local invocation event
+ proxy = this.proxies[hubName];
+
+ // Update the hub state
+ $.extend(proxy.state, data.State);
+ $(proxy).triggerHandler(makeEventName(eventName), [data.Args]);
+ }
+ });
+
+ connection.error(function (errData, origData) {
+ var callbackId, callback;
+
+ if (!origData) {
+ // No original data passed so this is not a send error
+ return;
+ }
+
+ callbackId = origData.I;
+ callback = connection._.invocationCallbacks[callbackId];
+
+ // Verify that there is a callback bound (could have been cleared)
+ if (callback) {
+ // Delete the callback
+ connection._.invocationCallbacks[callbackId] = null;
+ delete connection._.invocationCallbacks[callbackId];
+
+ // Invoke the callback with an error to reject the promise
+ callback.method.call(callback.scope, { E: errData });
+ }
+ });
+
+ connection.reconnecting(function () {
+ if (connection.transport && connection.transport.name === "webSockets") {
+ clearInvocationCallbacks(connection, "Connection started reconnecting before invocation result was received.");
+ }
+ });
+
+ connection.disconnected(function () {
+ clearInvocationCallbacks(connection, "Connection was disconnected before invocation result was received.");
+ });
+ };
+
+ hubConnection.fn._maximizeClientHubInvocation = function (minClientHubInvocation) {
+ return {
+ Hub: minClientHubInvocation.H,
+ Method: minClientHubInvocation.M,
+ Args: minClientHubInvocation.A,
+ State: minClientHubInvocation.S
+ };
+ };
+
+ hubConnection.fn._registerSubscribedHubs = function () {
+ ///
+ /// Sets the starting event to loop through the known hubs and register any new hubs
+ /// that have been added to the proxy.
+ ///
+ var connection = this;
+
+ if (!connection._subscribedToHubs) {
+ connection._subscribedToHubs = true;
+ connection.starting(function () {
+ // Set the connection's data object with all the hub proxies with active subscriptions.
+ // These proxies will receive notifications from the server.
+ var subscribedHubs = [];
+
+ $.each(connection.proxies, function (key) {
+ if (this.hasSubscriptions()) {
+ subscribedHubs.push({ name: key });
+ connection.log("Client subscribed to hub '" + key + "'.");
+ }
+ });
+
+ if (subscribedHubs.length === 0) {
+ 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.");
+ }
+
+ connection.data = connection.json.stringify(subscribedHubs);
+ });
+ }
+ };
+
+ hubConnection.fn.createHubProxy = function (hubName) {
+ ///
+ /// Creates a new proxy object for the given hub connection that can be used to invoke
+ /// methods on server hubs and handle client method invocation requests from the server.
+ ///
+ ///
+ /// The name of the hub on the server to create the proxy for.
+ ///
+
+ // Normalize the name to lowercase
+ hubName = hubName.toLowerCase();
+
+ var proxy = this.proxies[hubName];
+ if (!proxy) {
+ proxy = hubProxy(this, hubName);
+ this.proxies[hubName] = proxy;
+ }
+
+ this._registerSubscribedHubs();
+
+ return proxy;
+ };
+
+ hubConnection.fn.init.prototype = hubConnection.fn;
+
+ $.hubConnection = hubConnection;
+
+}(window.jQuery, window));
+/* jquery.signalR.version.js */
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+
+/*global window:false */
+///
+(function ($, undefined) {
+ // This will be modified by the build script
+ $.signalR.version = "2.4.3";
+}(window.jQuery));
diff --git a/CWASP Razor Edition/wwwroot/lib/signalr/jquery.signalR.min.js b/CWASP Razor Edition/wwwroot/lib/signalr/jquery.signalR.min.js
new file mode 100644
index 0000000..3b60a2f
--- /dev/null
+++ b/CWASP Razor Edition/wwwroot/lib/signalr/jquery.signalR.min.js
@@ -0,0 +1,9 @@
+/*!
+ * ASP.NET SignalR JavaScript Library 2.4.3
+ * http://signalr.net/
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+ *
+ */
+(function(n,t,i){function w(t,i){var u,f;if(n.isArray(t)){for(u=t.length-1;u>=0;u--)f=t[u],n.type(f)==="string"&&r.transports[f]||(i.log("Invalid transport: "+f+", removing it from the transports list."),t.splice(u,1));t.length===0&&(i.log("No transports remain within the specified transport array."),t=null)}else if(r.transports[t]||t==="auto"){if(t==="auto"&&r._.ieVersion<=8)return["longPolling"]}else i.log("Invalid transport: "+t.toString()+"."),t=null;return t}function b(n){return n==="http:"?80:n==="https:"?443:void 0}function a(n,t){return t.match(/:\d+$/)?t:t+":"+b(n)}function k(t,i){var u=this,r=[];u.tryBuffer=function(i){return t.state===n.signalR.connectionState.connecting?(r.push(i),!0):!1};u.drain=function(){if(t.state===n.signalR.connectionState.connected)while(r.length>0)i(r.shift())};u.clear=function(){r=[]}}var f={nojQuery:"jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.",noTransportOnInit:"No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.",errorOnNegotiate:"Error during negotiation request.",stoppedWhileLoading:"The connection was stopped during page load.",stoppedWhileNegotiating:"The connection was stopped during the negotiate request.",errorParsingNegotiateResponse:"Error parsing negotiate response.",errorRedirectionExceedsLimit:"Negotiate redirection limit exceeded.",errorDuringStartRequest:"Error during start request. Stopping the connection.",errorFromServer:"Error message received from the server: '{0}'.",stoppedDuringStartRequest:"The connection was stopped during the start request.",errorParsingStartResponse:"Error parsing start response: '{0}'. Stopping the connection.",invalidStartResponse:"Invalid start response: '{0}'. Stopping the connection.",protocolIncompatible:"You are using a version of the client that isn't compatible with the server. Client version {0}, server version {1}.",aspnetCoreSignalrServer:"Detected a connection attempt to an ASP.NET Core SignalR Server. This client only supports connecting to an ASP.NET SignalR Server. See https://aka.ms/signalr-core-differences for details.",sendFailed:"Send failed.",parseFailed:"Failed at parsing response: {0}",longPollFailed:"Long polling request failed.",eventSourceFailedToConnect:"EventSource failed to connect.",eventSourceError:"Error raised by EventSource",webSocketClosed:"WebSocket closed.",pingServerFailedInvalidResponse:"Invalid ping response when pinging server: '{0}'.",pingServerFailed:"Failed to ping server.",pingServerFailedStatusCode:"Failed to ping server. Server responded with status code {0}, stopping the connection.",pingServerFailedParse:"Failed to parse ping server response, stopping the connection.",noConnectionTransport:"Connection is in an invalid state, there is no transport active.",webSocketsInvalidState:"The Web Socket transport is in an invalid state, transitioning into reconnecting.",reconnectTimeout:"Couldn't reconnect within the configured timeout of {0} ms, disconnecting.",reconnectWindowTimeout:"The client has been inactive since {0} and it has exceeded the inactivity timeout of {1} ms. Stopping the connection.",jsonpNotSupportedWithAccessToken:"The JSONP protocol does not support connections that require a Bearer token to connect, such as the Azure SignalR Service."};if(typeof n!="function")throw new Error(f.nojQuery);var r,h,o=t.document.readyState==="complete",e=n(t),c="__Negotiate Aborted__",u={onStart:"onStart",onStarting:"onStarting",onReceived:"onReceived",onError:"onError",onConnectionSlow:"onConnectionSlow",onReconnecting:"onReconnecting",onReconnect:"onReconnect",onStateChanged:"onStateChanged",onDisconnect:"onDisconnect"},v=function(n,i){if(i!==!1){var r;typeof t.console!="undefined"&&(r="["+(new Date).toTimeString()+"] SignalR: "+n,t.console.debug?t.console.debug(r):t.console.log&&t.console.log(r))}},s=function(t,i,r){return i===t.state?(t.state=r,n(t).triggerHandler(u.onStateChanged,[{oldState:i,newState:r}]),!0):!1},y=function(n){return n.state===r.connectionState.disconnected},l=function(n){return n._.keepAliveData.activated&&n.transport.supportsKeepAlive(n)},p=function(i){var f,e;i._.configuredStopReconnectingTimeout||(e=function(t){var i=r._.format(r.resources.reconnectTimeout,t.disconnectTimeout);t.log(i);n(t).triggerHandler(u.onError,[r._.error(i,"TimeoutException")]);t.stop(!1,!1)},i.reconnecting(function(){var n=this;n.state===r.connectionState.reconnecting&&(f=t.setTimeout(function(){e(n)},n.disconnectTimeout))}),i.stateChanged(function(n){n.oldState===r.connectionState.reconnecting&&t.clearTimeout(f)}),i._.configuredStopReconnectingTimeout=!0)};if(r=function(n,t,i){return new r.fn.init(n,t,i)},r._={defaultContentType:"application/x-www-form-urlencoded; charset=UTF-8",ieVersion:function(){var i,n;return t.navigator.appName==="Microsoft Internet Explorer"&&(n=/MSIE ([0-9]+\.[0-9]+)/.exec(t.navigator.userAgent),n&&(i=t.parseFloat(n[1]))),i}(),error:function(n,t,i){var r=new Error(n);return r.source=t,typeof i!="undefined"&&(r.context=i),r},transportError:function(n,t,r,u){var f=this.error(n,r,u);return f.transport=t?t.name:i,f},format:function(){for(var t=arguments[0],n=0;n<\/script>.");}},typeof e.on=="function")e.on("load",function(){o=!0});else e.load(function(){o=!0});r.fn=r.prototype={init:function(t,i,r){var f=n(this);this.url=t;this.qs=i;this.lastError=null;this._={keepAliveData:{},connectingMessageBuffer:new k(this,function(n){f.triggerHandler(u.onReceived,[n])}),lastMessageAt:(new Date).getTime(),lastActiveAt:(new Date).getTime(),beatInterval:5e3,beatHandle:null,totalTransportConnectTimeout:0,redirectQs:null};typeof r=="boolean"&&(this.logging=r)},_parseResponse:function(n){var t=this;return n?typeof n=="string"?t.json.parse(n):n:n},_originalJson:t.JSON,json:t.JSON,isCrossDomain:function(i,r){var u;return(i=n.trim(i),r=r||t.location,i.indexOf("http")!==0)?!1:(u=t.document.createElement("a"),u.href=i,u.protocol+a(u.protocol,u.host)!==r.protocol+a(r.protocol,r.host))},ajaxDataType:"text",contentType:"application/json; charset=UTF-8",logging:!1,state:r.connectionState.disconnected,clientProtocol:"2.1",supportedProtocols:["1.5","2.0","2.1"],negotiateRedirectSupportedProtocols:["2.0","2.1"],reconnectDelay:2e3,transportConnectTimeout:0,disconnectTimeout:3e4,reconnectWindow:3e4,keepAliveWarnAt:2/3,start:function(i,h){var a=this,v={pingInterval:3e5,waitForPageLoad:!0,transport:"auto",jsonp:!1},g,y=a._deferral||n.Deferred(),b=t.document.createElement("a"),nt=function(i,u){i.url===u&&i.baseUrl||(i.url=u,b.href=i.url,b.protocol&&b.protocol!==":"?(i.protocol=b.protocol,i.host=b.host):(i.protocol=t.document.location.protocol,i.host=b.host||t.document.location.host),i.baseUrl=i.protocol+"//"+i.host,i.wsProtocol=i.protocol==="https:"?"wss://":"ws://",i.url.indexOf("//")===0&&(i.url=t.location.protocol+i.url,i.log("Protocol relative URL detected, normalizing it to '"+i.url+"'.")),i.isCrossDomain(i.url)&&(i.log("Auto detected cross domain url."),v.transport==="auto"&&(v.transport=["webSockets","serverSentEvents","longPolling"]),typeof i.withCredentials=="undefined"&&(i.withCredentials=!0),n.support.cors||(i.ajaxDataType="jsonp",i.log("Using jsonp because this browser doesn't support CORS.")),i.contentType=r._.defaultContentType))},d,k;if(a.lastError=null,a._deferral=y,!a.json)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.");if(n.type(i)==="function"?h=i:n.type(i)==="object"&&(n.extend(v,i),n.type(v.callback)==="function"&&(h=v.callback)),v.transport=w(v.transport,a),!v.transport)throw new Error("SignalR: Invalid transport(s) specified, aborting start.");return(a._.config=v,!o&&v.waitForPageLoad===!0)?(a._.deferredStartHandler=function(){a.start(i,h)},e.bind("load",a._.deferredStartHandler),y.promise()):a.state===r.connectionState.connecting?y.promise():s(a,r.connectionState.disconnected,r.connectionState.connecting)===!1?(y.resolve(a),y.promise()):(p(a),v.transport==="auto"&&v.jsonp===!0&&(v.transport="longPolling"),a.withCredentials=v.withCredentials,a._originalUrl=a.url,a.ajaxDataType=v.jsonp?"jsonp":"text",nt(a,a.url),n(a).bind(u.onStart,function(){n.type(h)==="function"&&h.call(a);y.resolve(a)}),a._.initHandler=r.transports._logic.initHandler(a),g=function(i,o){var c=r._.error(f.noTransportOnInit);if(o=o||0,o>=i.length){o===0?a.log("No transports supported by the server were selected."):o===1?a.log("No fallback transports were selected."):a.log("Fallback transports exhausted.");n(a).triggerHandler(u.onError,[c]);y.reject(c);a.stop();return}if(a.state!==r.connectionState.disconnected){var p=i[o],h=r.transports[p],v=function(){g(i,o+1)};a.transport=h;try{a._.initHandler.start(h,function(){var f=r._.firefoxMajorVersion(t.navigator.userAgent)>=11,i=!0;a.log("The start request succeeded. Transitioning to the connected state.");l(a)&&r.transports._logic.monitorKeepAlive(a);a._.keepAliveData.activated&&r.transports._logic.startHeartbeat(a);r._.configurePingInterval(a);s(a,r.connectionState.connecting,r.connectionState.connected)||a.log("WARNING! The connection was not in the connecting state.");a._.connectingMessageBuffer.drain();n(a).triggerHandler(u.onStart);e.bind("unload",function(){a.log("Window unloading, stopping the connection.");a.stop(i)});f&&e.bind("beforeunload",function(){t.setTimeout(function(){a.stop(i)},0)})},v)}catch(w){a.log(h.name+" transport threw '"+w.message+"' when attempting to start.");v()}}},d=a.url+"/negotiate",k=function(t,i){var e=r._.error(f.errorOnNegotiate,t,i._.negotiateRequest);n(i).triggerHandler(u.onError,e);y.reject(e);i.stop()},n(a).triggerHandler(u.onStarting),d=r.transports._logic.prepareQueryString(a,d),a.log("Negotiating with '"+d+"'."),a._.negotiateRequest=function(){var t,h=0,w=100,i,e,o=[],s=[],l=function(n,t){var u=r.transports._logic.prepareQueryString(n,n.url+"/negotiate"),i;return n.log("Negotiating with '"+u+"'."),i={url:u,error:function(t,i){i!==c?k(t,n):y.reject(r._.error(f.stoppedWhileNegotiating,null,n._.negotiateRequest))},success:t},n.accessToken&&(i.headers={Authorization:"Bearer "+n.accessToken}),r.transports._logic.ajax(n,i)},p=function(c){try{t=a._parseResponse(c)}catch(d){k(r._.error(f.errorParsingNegotiateResponse,d),a);return}if(t.availableTransports){e=r._.error(f.aspnetCoreSignalrServer);n(a).triggerHandler(u.onError,[e]);y.reject(e);return}if(!t.ProtocolVersion||a.supportedProtocols.indexOf(t.ProtocolVersion)===-1){e=r._.error(r._.format(f.protocolIncompatible,a.clientProtocol,t.ProtocolVersion));n(a).triggerHandler(u.onError,[e]);y.reject(e);return}if(a.negotiateRedirectSupportedProtocols.indexOf(t.ProtocolVersion)!==-1){if(t.Error){e=r._.error(r._.format(f.errorFromServer,t.Error));n(a).triggerHandler(u.onError,[e]);y.reject(e);return}if(t.RedirectUrl){if(h===w){k(r._.error(f.errorRedirectionExceedsLimit),a);return}v.transport==="auto"&&(v.transport=["webSockets","serverSentEvents","longPolling"]);a.log("Received redirect to: "+t.RedirectUrl);a.accessToken=t.AccessToken;var b=t.RedirectUrl.split("?",2);if(nt(a,b[0]),a._.redirectQs=b.length===2?b[1]:null,a.ajaxDataType==="jsonp"&&a.accessToken){k(r._.error(f.jsonpNotSupportedWithAccessToken),a);return}h++;l(a,p);return}}i=a._.keepAliveData;a.appRelativeUrl=t.Url;a.id=t.ConnectionId;a.token=t.ConnectionToken;a.webSocketServerUrl=t.WebSocketServerUrl;a._.pollTimeout=t.ConnectionTimeout*1e3+1e4;a.disconnectTimeout=t.DisconnectTimeout*1e3;a._.totalTransportConnectTimeout=a.transportConnectTimeout+t.TransportConnectTimeout*1e3;t.KeepAliveTimeout?(i.activated=!0,i.timeout=t.KeepAliveTimeout*1e3,i.timeoutWarning=i.timeout*a.keepAliveWarnAt,a._.beatInterval=(i.timeout-i.timeoutWarning)/3):i.activated=!1;a.reconnectWindow=a.disconnectTimeout+(i.timeout||0);n.each(r.transports,function(n){if(n.indexOf("_")===0||n==="webSockets"&&!t.TryWebSockets)return!0;s.push(n)});n.isArray(v.transport)?n.each(v.transport,function(t,i){n.inArray(i,s)>=0&&o.push(i)}):v.transport==="auto"?o=s:n.inArray(v.transport,s)>=0&&o.push(v.transport);g(o)};return l(a,p)}(),y.promise())},starting:function(t){var i=this;return n(i).bind(u.onStarting,function(){t.call(i)}),i},send:function(n){var t=this;if(t.state===r.connectionState.disconnected)throw new Error("SignalR: Connection must be started before data can be sent. Call .start() before .send()");if(t.state===r.connectionState.connecting)throw new Error("SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.");return t.transport.send(t,n),t},received:function(t){var i=this;return n(i).bind(u.onReceived,function(n,r){t.call(i,r)}),i},stateChanged:function(t){var i=this;return n(i).bind(u.onStateChanged,function(n,r){t.call(i,r)}),i},error:function(t){var i=this;return n(i).bind(u.onError,function(n,r,u){i.lastError=r;t.call(i,r,u)}),i},disconnected:function(t){var i=this;return n(i).bind(u.onDisconnect,function(){t.call(i)}),i},connectionSlow:function(t){var i=this;return n(i).bind(u.onConnectionSlow,function(){t.call(i)}),i},reconnecting:function(t){var i=this;return n(i).bind(u.onReconnecting,function(){t.call(i)}),i},reconnected:function(t){var i=this;return n(i).bind(u.onReconnect,function(){t.call(i)}),i},stop:function(i,h){var a=this,v=a._deferral;if(a._.deferredStartHandler&&e.unbind("load",a._.deferredStartHandler),delete a._.config,delete a._.deferredStartHandler,!o&&(!a._.config||a._.config.waitForPageLoad===!0)){a.log("Stopping connection prior to negotiate.");v&&v.reject(r._.error(f.stoppedWhileLoading));return}if(a.state!==r.connectionState.disconnected)return a.log("Stopping connection."),t.clearTimeout(a._.beatHandle),t.clearInterval(a._.pingIntervalId),a.transport&&(a.transport.stop(a),h!==!1&&a.transport.abort(a,i),l(a)&&r.transports._logic.stopMonitoringKeepAlive(a),a.transport=null),a._.negotiateRequest&&(a._.negotiateRequest.abort(c),delete a._.negotiateRequest),a._.initHandler&&a._.initHandler.stop(),delete a._deferral,delete a.messageId,delete a.groupsToken,delete a.id,delete a._.pingIntervalId,delete a._.lastMessageAt,delete a._.lastActiveAt,a._.connectingMessageBuffer.clear(),n(a).unbind(u.onStart),delete a.accessToken,delete a.protocol,delete a.host,delete a.baseUrl,delete a.wsProtocol,delete a.contentType,a.url=a._originalUrl,a._.redirectQs=null,s(a,a.state,r.connectionState.disconnected),n(a).triggerHandler(u.onDisconnect),a},log:function(n){v(n,this.logging)}};r.fn.init.prototype=r.fn;r.noConflict=function(){return n.connection===r&&(n.connection=h),r};n.connection&&(h=n.connection);n.connection=n.signalR=r})(window.jQuery,window),function(n,t,i){function s(n){n._.keepAliveData.monitoring&&l(n);u.markActive(n)&&(n._.beatHandle=t.setTimeout(function(){s(n)},n._.beatInterval))}function l(t){var i=t._.keepAliveData,u;t.state===r.connectionState.connected&&(u=(new Date).getTime()-t._.lastMessageAt,u>=i.timeout?(t.log("Keep alive timed out. Notifying transport that connection has been lost."),t.transport.lostConnection(t)):u>=i.timeoutWarning?i.userNotified||(t.log("Keep alive has been missed, connection may be dead/slow."),n(t).triggerHandler(f.onConnectionSlow),i.userNotified=!0):i.userNotified=!1)}function e(n,t){var i=n.url+t;return n.transport&&(i+="?transport="+n.transport.name),u.prepareQueryString(n,i)}function h(n){this.connection=n;this.startRequested=!1;this.startCompleted=!1;this.connectionStopped=!1}var r=n.signalR,f=n.signalR.events,c=n.signalR.changeState,o="__Start Aborted__",u;r.transports={};h.prototype={start:function(n,r,u){var f=this,e=f.connection,o=!1;if(f.startRequested||f.connectionStopped){e.log("WARNING! "+n.name+" transport cannot be started. Initialization ongoing or completed.");return}e.log(n.name+" transport starting.");n.start(e,function(){o||f.initReceived(n,r)},function(t){return o||(o=!0,f.transportFailed(n,t,u)),!f.startCompleted||f.connectionStopped});f.transportTimeoutHandle=t.setTimeout(function(){o||(o=!0,e.log(n.name+" transport timed out when trying to connect."),f.transportFailed(n,i,u))},e._.totalTransportConnectTimeout)},stop:function(){this.connectionStopped=!0;t.clearTimeout(this.transportTimeoutHandle);r.transports._logic.tryAbortStartRequest(this.connection)},initReceived:function(n,i){var u=this,f=u.connection;if(u.startRequested){f.log("WARNING! The client received multiple init messages.");return}u.connectionStopped||(u.startRequested=!0,t.clearTimeout(u.transportTimeoutHandle),f.log(n.name+" transport connected. Initiating start request."),r.transports._logic.ajaxStart(f,function(){u.startCompleted=!0;i()}))},transportFailed:function(i,u,e){var o=this.connection,h=o._deferral,s;this.connectionStopped||(t.clearTimeout(this.transportTimeoutHandle),this.startRequested?this.startCompleted||(s=r._.error(r.resources.errorDuringStartRequest,u),o.log(i.name+" transport failed during the start request. Stopping the connection."),n(o).triggerHandler(f.onError,[s]),h&&h.reject(s),o.stop()):(i.stop(o),o.log(i.name+" transport failed to connect. Attempting to fall back."),e()))}};u=r.transports._logic={ajax:function(t,i){return n.ajax(n.extend(!0,{},n.signalR.ajaxDefaults,{type:"GET",data:{},xhrFields:{withCredentials:t.withCredentials},contentType:t.contentType,dataType:t.ajaxDataType},i))},pingServer:function(t){var e,f,i=n.Deferred();return t.transport?(e=t.url+"/ping",e=u.addQs(e,t.qs),f=u.ajax(t,{url:e,headers:t.accessToken?{Authorization:"Bearer "+t.accessToken}:{},success:function(n){var u;try{u=t._parseResponse(n)}catch(e){i.reject(r._.transportError(r.resources.pingServerFailedParse,t.transport,e,f));t.stop();return}u.Response==="pong"?i.resolve():i.reject(r._.transportError(r._.format(r.resources.pingServerFailedInvalidResponse,n),t.transport,null,f))},error:function(n){n.status===401||n.status===403?(i.reject(r._.transportError(r._.format(r.resources.pingServerFailedStatusCode,n.status),t.transport,n,f)),t.stop()):i.reject(r._.transportError(r.resources.pingServerFailed,t.transport,n,f))}})):i.reject(r._.transportError(r.resources.noConnectionTransport,t.transport)),i.promise()},prepareQueryString:function(n,i){var r;return r=u.addQs(i,"clientProtocol="+n.clientProtocol),r=typeof n._.redirectQs=="string"?u.addQs(r,n._.redirectQs):u.addQs(r,n.qs),n.token&&(r+="&connectionToken="+t.encodeURIComponent(n.token)),n.data&&(r+="&connectionData="+t.encodeURIComponent(n.data)),r},addQs:function(t,i){var r=t.indexOf("?")!==-1?"&":"?",u;if(!i)return t;if(typeof i=="object")return t+r+n.param(i);if(typeof i=="string")return u=i.charAt(0),(u==="?"||u==="&")&&(r=""),t+r+i;throw new Error("Query string property must be either a string or object.");},getUrl:function(n,i,r,f,e){var h=i==="webSockets"?"":n.baseUrl,o=h+n.appRelativeUrl,s="transport="+i;return!e&&n.groupsToken&&(s+="&groupsToken="+t.encodeURIComponent(n.groupsToken)),r?(o+=f?"/poll":"/reconnect",!e&&n.messageId&&(s+="&messageId="+t.encodeURIComponent(n.messageId))):o+="/connect",o+="?"+s,o=u.prepareQueryString(n,o),n.transport&&n.accessToken&&(n.transport.name==="serverSentEvents"||n.transport.name==="webSockets")&&(o+="&access_token="+t.encodeURIComponent(n.accessToken)),e||(o+="&tid="+Math.floor(Math.random()*11)),o},maximizePersistentResponse:function(n){return{MessageId:n.C,Messages:n.M,Initialized:typeof n.S!="undefined"?!0:!1,ShouldReconnect:typeof n.T!="undefined"?!0:!1,LongPollDelay:n.L,GroupsToken:n.G,Error:n.E}},updateGroups:function(n,t){t&&(n.groupsToken=t)},stringifySend:function(n,t){return typeof t=="string"||typeof t=="undefined"||t===null?t:n.json.stringify(t)},ajaxSend:function(t,i){var h=u.stringifySend(t,i),c=e(t,"/send"),o,s=function(t,u){n(u).triggerHandler(f.onError,[r._.transportError(r.resources.sendFailed,u.transport,t,o),i])};return o=u.ajax(t,{url:c,type:t.ajaxDataType==="jsonp"?"GET":"POST",contentType:r._.defaultContentType,headers:t.accessToken?{Authorization:"Bearer "+t.accessToken}:{},data:{data:h},success:function(n){var i;if(n){try{i=t._parseResponse(n)}catch(r){s(r,t);t.stop();return}u.triggerReceived(t,i)}},error:function(n,i){i!=="abort"&&i!=="parsererror"&&s(n,t)}})},ajaxAbort:function(n,i){if(typeof n.transport!="undefined"){i=typeof i=="undefined"?!0:i;var r=e(n,"/abort"),f=n.accessToken?{Authorization:"Bearer "+n.accessToken}:{};t.fetch?t.fetch(r,{method:"POST",keepalive:!0,headers:f,credentials:n.withCredentials===!0?"include":"same-origin"}):u.ajax(n,{url:r,async:i,timeout:1e3,type:"POST",headers:f,dataType:"text"});n.log("Fired ajax abort async = "+i+".")}},ajaxStart:function(t,i){var h=function(n){var i=t._deferral;i&&i.reject(n)},s=function(i){t.log("The start request failed. Stopping the connection.");n(t).triggerHandler(f.onError,[i]);h(i);t.stop()};t._.startRequest=u.ajax(t,{url:e(t,"/start"),headers:t.accessToken?{Authorization:"Bearer "+t.accessToken}:{},success:function(n,u,f){var e;try{e=t._parseResponse(n)}catch(o){s(r._.error(r._.format(r.resources.errorParsingStartResponse,n),o,f));return}e.Response==="started"?i():s(r._.error(r._.format(r.resources.invalidStartResponse,n),null,f))},error:function(n,i,u){i!==o?s(r._.error(r.resources.errorDuringStartRequest,u,n)):(t.log("The start request aborted because connection.stop() was called."),h(r._.error(r.resources.stoppedDuringStartRequest,null,n)))}})},tryAbortStartRequest:function(n){n._.startRequest&&(n._.startRequest.abort(o),delete n._.startRequest)},tryInitialize:function(n,t,i){t.Initialized&&i?i():t.Initialized&&n.log("WARNING! The client received an init message after reconnecting.")},triggerReceived:function(t,i){t._.connectingMessageBuffer.tryBuffer(i)||n(t).triggerHandler(f.onReceived,[i])},processMessages:function(t,i,f){var e;if(i&&typeof i.I!="undefined"){u.triggerReceived(t,i);return}if(u.markLastMessage(t),i){if(e=u.maximizePersistentResponse(i),e.Error){t.log("Received an error message from the server: "+i.E);n(t).triggerHandler(r.events.onError,[r._.error(i.E,"ServerError")]);t.stop(!1,!1);return}u.updateGroups(t,e.GroupsToken);e.MessageId&&(t.messageId=e.MessageId);e.Messages&&(n.each(e.Messages,function(n,i){u.triggerReceived(t,i)}),u.tryInitialize(t,e,f))}},monitorKeepAlive:function(t){var i=t._.keepAliveData;i.monitoring?t.log("Tried to monitor keep alive but it's already being monitored."):(i.monitoring=!0,u.markLastMessage(t),t._.keepAliveData.reconnectKeepAliveUpdate=function(){u.markLastMessage(t)},n(t).bind(f.onReconnect,t._.keepAliveData.reconnectKeepAliveUpdate),t.log("Now monitoring keep alive with a warning timeout of "+i.timeoutWarning+", keep alive timeout of "+i.timeout+" and disconnecting timeout of "+t.disconnectTimeout))},stopMonitoringKeepAlive:function(t){var i=t._.keepAliveData;i.monitoring&&(i.monitoring=!1,n(t).unbind(f.onReconnect,t._.keepAliveData.reconnectKeepAliveUpdate),t._.keepAliveData={},t.log("Stopping the monitoring of the keep alive."))},startHeartbeat:function(n){n._.lastActiveAt=(new Date).getTime();s(n)},markLastMessage:function(n){n._.lastMessageAt=(new Date).getTime();n._.lastActiveAt=n._.lastMessageAt},markActive:function(n){return u.verifyLastActive(n)?(n._.lastActiveAt=(new Date).getTime(),!0):!1},isConnectedOrReconnecting:function(n){return n.state===r.connectionState.connected||n.state===r.connectionState.reconnecting},ensureReconnectingState:function(t){return c(t,r.connectionState.connected,r.connectionState.reconnecting)===!0&&n(t).triggerHandler(f.onReconnecting),t.state===r.connectionState.reconnecting},clearReconnectTimeout:function(n){n&&n._.reconnectTimeout&&(t.clearTimeout(n._.reconnectTimeout),delete n._.reconnectTimeout)},verifyLastActive:function(t){if(!t._.keepAliveData.activated||(new Date).getTime()-t._.lastActiveAt0&&n--}}}();r.transports.foreverFrame={name:"foreverFrame",supportsKeepAlive:function(){return!0},iframeClearThreshold:50,start:function(n,r,e){if(n.accessToken){e&&(n.log("Forever Frame does not support connections that require a Bearer token to connect, such as the Azure SignalR Service."),e());return}var l=this,s=i.foreverFrame.count+=1,h,o=u(),c=function(){n.log("Forever frame iframe finished loading and is no longer receiving messages.");e&&e()||l.reconnect(n)};if(t.EventSource){e&&(n.log("Forever Frame is not supported by SignalR on browsers with SSE support."),e());return}o.setAttribute("data-signalr-connection-id",n.id);f.prevent();h=i.getUrl(n,this.name);h+="&frameId="+s;t.document.documentElement.appendChild(o);n.log("Binding to iframe's load event.");o.addEventListener?o.addEventListener("load",c,!1):o.attachEvent&&o.attachEvent("onload",c);o.src=h;i.foreverFrame.connections[s]=n;n.frame=o;n.frameId=s;r&&(n.onSuccess=function(){n.log("Iframe transport started.");r()})},reconnect:function(n){var r=this;i.isConnectedOrReconnecting(n)&&i.verifyLastActive(n)&&t.setTimeout(function(){if(i.verifyLastActive(n)&&n.frame&&i.ensureReconnectingState(n)){var u=n.frame,t=i.getUrl(n,r.name,!0)+"&frameId="+n.frameId;n.log("Updating iframe src to '"+t+"'.");u.src=t}},n.reconnectDelay)},lostConnection:function(n){this.reconnect(n)},send:function(n,t){i.ajaxSend(n,t)},receive:function(t,u){var f,e,o;if(t.json!==t._originalJson&&(u=t._originalJson.stringify(u)),o=t._parseResponse(u),i.processMessages(t,o,t.onSuccess),t.state===n.signalR.connectionState.connected&&(t.frameMessageCount=(t.frameMessageCount||0)+1,t.frameMessageCount>r.transports.foreverFrame.iframeClearThreshold&&(t.frameMessageCount=0,f=t.frame.contentWindow||t.frame.contentDocument,f&&f.document&&f.document.body)))for(e=f.document.body;e.firstChild;)e.removeChild(e.firstChild)},stop:function(n){var r=null;if(f.cancel(),n.frame){if(n.frame.stop)n.frame.stop();else try{r=n.frame.contentWindow||n.frame.contentDocument;r.document&&r.document.execCommand&&r.document.execCommand("Stop")}catch(u){n.log("Error occurred when stopping foreverFrame transport. Message = "+u.message+".")}n.frame.parentNode===t.document.documentElement&&t.document.documentElement.removeChild(n.frame);delete i.foreverFrame.connections[n.frameId];n.frame=null;n.frameId=null;delete n.frame;delete n.frameId;delete n.onSuccess;delete n.frameMessageCount;n.log("Stopping forever frame.")}},abort:function(n,t){i.ajaxAbort(n,t)},getConnection:function(n){return i.foreverFrame.connections[n]},started:function(t){o(t,r.connectionState.reconnecting,r.connectionState.connected)===!0&&n(t).triggerHandler(e.onReconnect)}}}(window.jQuery,window),function(n,t){var r=n.signalR,u=n.signalR.events,e=n.signalR.changeState,f=n.signalR.isDisconnecting,i=r.transports._logic;r.transports.longPolling={name:"longPolling",supportsKeepAlive:function(){return!1},reconnectDelay:3e3,start:function(o,s,h){var a=this,v=function(){v=n.noop;o.log("LongPolling connected.");s?s():o.log("WARNING! The client received an init message after reconnecting.")},y=function(n){return h(n)?(o.log("LongPolling failed to connect."),!0):!1},c=o._,l=0,p=function(i){t.clearTimeout(c.reconnectTimeoutId);c.reconnectTimeoutId=null;e(i,r.connectionState.reconnecting,r.connectionState.connected)===!0&&(i.log("Raising the reconnect event"),n(i).triggerHandler(u.onReconnect))},w=36e5;o.pollXhr&&(o.log("Polling xhr requests already exists, aborting."),o.stop());o.messageId=null;c.reconnectTimeoutId=null;c.pollTimeoutId=t.setTimeout(function(){(function e(s,h){var g=s.messageId,nt=g===null,k=!nt,tt=!h,d=i.getUrl(s,a.name,k,tt,!0),b={};(s.messageId&&(b.messageId=s.messageId),s.groupsToken&&(b.groupsToken=s.groupsToken),f(s)!==!0)&&(o.log("Opening long polling request to '"+d+"'."),s.pollXhr=i.ajax(o,{xhrFields:{onprogress:function(){i.markLastMessage(o)}},url:d,type:"POST",contentType:r._.defaultContentType,data:b,timeout:o._.pollTimeout,headers:o.accessToken?{Authorization:"Bearer "+o.accessToken}:{},success:function(r){var h,w=0,u,a;o.log("Long poll complete.");l=0;try{h=o._parseResponse(r)}catch(b){i.handleParseFailure(s,r,b,y,s.pollXhr);return}(c.reconnectTimeoutId!==null&&p(s),h&&(u=i.maximizePersistentResponse(h)),i.processMessages(s,h,v),u&&n.type(u.LongPollDelay)==="number"&&(w=u.LongPollDelay),f(s)!==!0)&&(a=u&&u.ShouldReconnect,!a||i.ensureReconnectingState(s))&&(w>0?c.pollTimeoutId=t.setTimeout(function(){e(s,a)},w):e(s,a))},error:function(f,h){var v=r._.transportError(r.resources.longPollFailed,o.transport,f,s.pollXhr);if(t.clearTimeout(c.reconnectTimeoutId),c.reconnectTimeoutId=null,h==="abort"){o.log("Aborted xhr request.");return}if(!y(v)){if(l++,o.state!==r.connectionState.reconnecting&&(o.log("An error occurred using longPolling. Status = "+h+". Response = "+f.responseText+"."),n(s).triggerHandler(u.onError,[v])),(o.state===r.connectionState.connected||o.state===r.connectionState.reconnecting)&&!i.verifyLastActive(o))return;if(!i.ensureReconnectingState(s))return;c.pollTimeoutId=t.setTimeout(function(){e(s,!0)},a.reconnectDelay)}}}),k&&h===!0&&(c.reconnectTimeoutId=t.setTimeout(function(){p(s)},Math.min(1e3*(Math.pow(2,l)-1),w))))})(o)},250)},lostConnection:function(n){n.pollXhr&&n.pollXhr.abort("lostConnection")},send:function(n,t){i.ajaxSend(n,t)},stop:function(n){t.clearTimeout(n._.pollTimeoutId);t.clearTimeout(n._.reconnectTimeoutId);delete n._.pollTimeoutId;delete n._.reconnectTimeoutId;n.pollXhr&&(n.pollXhr.abort(),n.pollXhr=null,delete n.pollXhr)},abort:function(n,t){i.ajaxAbort(n,t)}}}(window.jQuery,window),function(n){function r(n){return n+s}function c(n,t,i){for(var f=n.length,u=[],r=0;r=0}function i(n,t){return new i.fn.init(n,t)}function t(i,r){var u={qs:null,logging:!1,useDefaultPath:!0};return n.extend(u,r),(!i||u.useDefaultPath)&&(i=(i||"")+"/signalr"),new t.fn.init(i,u)}var o=0,s=".hubProxy",h=n.signalR;i.fn=i.prototype={init:function(n,t){this.state={};this.connection=n;this.hubName=t;this._={callbackMap:{}}},constructor:i,hasSubscriptions:function(){return u(this._.callbackMap)},on:function(t,i,u){var c=this,l=c._.callbackMap,v=!u&&e(i),f,h,s,a;for(u=u||i,u._signalRGuid||(u._signalRGuid=o++),t=t.toLowerCase(),f=l[t],f||(f=[],l[t]=f),s=0;s