예제 #1
0
        /// <summary>
        /// Build a connection to the shield hub for the current protection process.
        /// </summary>
        /// <param name="externalConnection"></param>
        /// <param name="withLogger"></param>
        /// <returns></returns>
        private HubConnection InstanceHubConnector(HubConnectionExternalModel externalConnection, bool withLogger)
        {
            try
            {
                Parent.CustomLogger?.LogDebug("Starting the negotiation with the notification server.");

                var request = new RestRequest("/logger/negotiate");

                var negotiation = _client.Get <NegotiateModel>(request);

                if (!negotiation.IsSuccessful)
                {
                    throw new Exception("Can't negotiate");
                }

                //Creates logger hub
                var connection = new HubConnectionBuilder()
                                 .WithUrl($"{negotiation?.Data.Url}{externalConnection.ToQueryString()}", options =>
                {
                    options.SkipNegotiation = true;     //Negotiation previously done.
                    options.Transports      = HttpTransportType.WebSockets;

                    options.AccessTokenProvider = () => Task.FromResult(negotiation?.Data.AccessToken);     //Add bearer token for current connection
                })
#if !DEBUG
                                 .ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.None))
#endif
                                 .WithAutomaticReconnect()
                                 .Build(); //Build hub

                Parent.CustomLogger?.LogDebug("The connection to the shield notification server has been created.");

                if (!withLogger)
                {
                    return(connection);
                }

                if (Parent.CustomLogger is null)
                {
                    throw new Exception("The \"WithLogger\" method cannot be called if a custom logger has not been provided in the shield client.");
                }

                Parent.CustomLogger?.LogDebug("The current logger has been configured as the output of the connection logs.");

                connection.OnLog(externalConnection.OnLogger, OnCustomLog);

                return(connection);
            }
            catch (Exception ex)
            {
                Parent.CustomLogger?.LogCritical("An error occurred while creating the connection to the shield server for the current process.");
                throw new Exception($"An error occurred while creating the connection to the shield server for the current process: {ex.Message}");
            }
        }