Пример #1
0
        public MogmogConnection(string hostname, int channelId, bool saveAccessCode)
        {
            this.ChannelId      = channelId;
            this.SaveAccessCode = saveAccessCode;
            this.tokenSource    = new CancellationTokenSource();
            this.channel        = GrpcChannel.ForAddress(hostname);
            this.chatClient     = new ChatServiceClient(channel);
            var serverInfo = this.chatClient.GetChatServerInfo(new ReqChatServerInfo());
            var flags      = (ServerFlags)serverInfo.Flags;

            Mogger.Log($"Server flags for {hostname}: {flags}");
            var callOptions = new CallOptions()
                              .WithCancellationToken(this.tokenSource.Token)
                              .WithDeadline(DateTime.UtcNow.AddMinutes(1))
                              .WithWaitForReady();

            if (flags.HasFlag(ServerFlags.RequiresDiscordOAuth2))
            {
                oAuth2 = new DiscordOAuth2();
                oAuth2.Authenticate(serverInfo.ServerId);
                var headers = new Metadata
                {
                    new Entry("code", oAuth2.OAuth2Code),
                };
                callOptions = callOptions.WithHeaders(headers);
            }
            this.chatStream = this.chatClient.Chat(callOptions);
            _ = ChatLoop(this.tokenSource.Token);
        }
Пример #2
0
        public void AddHost(string hostname, bool saveAccessCode)
        {
            if (this.config.Hosts.FirstOrDefault(h => h.Hostname == hostname) == null)
            {
                Mogger.LogError(LogMessages.HostExists);
                return;
            }
            var host = new Host {
                Hostname = hostname, SaveAccessCode = saveAccessCode
            };

            this.config.Hosts.Add(host);
            MogmogConnection connection;

            try
            {
                connection = new MogmogConnection(hostname, this.config.Hosts.IndexOf(host), saveAccessCode);
            }
            catch (RpcException e)
            {
                this.config.Hosts.Remove(host);
                if (e.Status.Detail == "Error starting gRPC call: No connection could be made because the target machine actively refused it.")
                {
                    Mogger.LogError(LogMessages.HostOffline); // A more user-friendly error
                }
                else
                {
                    Mogger.LogError(e.Message);
                }
                return;
            }
            connection.MessageReceivedEvent += MessageReceived;
            this.connections.Add(connection);
        }
Пример #3
0
        public void Authenticate(string serverAccountId)
        {
            Mogger.Log(LogMessages.DiscordAuthInProgress);
            this.handlerCompleted = false;
            var        stateString = OAuth2Utils.GenerateStateString(20);
            HttpServer authServer  = null;

            for (var i = 0; i < reservedPorts.Length && authServer == null; i++)
            {
                try
                {
                    authServer = new HttpServer(reservedPorts[i], Mogger.Log);
                }
                catch (PortUnavailableException e)
                {
                    Mogger.LogError(e.Message);
                    if (i == reservedPorts.Length - 1)
                    {
                        throw;
                    }
                }
            }
            // ReSharper disable once PossibleNullReferenceException
            authServer.AddHtmlDocumentHandler((processor, stream) => OAuth2RedirectHandler(processor, authServer.Port, stateString));
            OpenUrl(GetOAuth2Url(serverAccountId, authServer.Port, stateString));
            while (!this.handlerCompleted)
            {
                Task.Delay(50).Wait();
            }
            authServer.Dispose();
        }
Пример #4
0
 public void UnmuteUser(string name, int worldId, string senderName, int senderWorldId, int channelId)
 {
     if (this.connections[channelId] == null)
     {
         Mogger.LogError(LogMessages.HostNotFound);
         return;
     }
     _ = this.connections[channelId].UnmuteUser(name, worldId, senderName, senderWorldId);
 }
Пример #5
0
 public static void LogMessageReceived(GenericInterop logInfo)
 {
     if (bool.Parse(logInfo.Arg))
     {
         Mogger.LogError(logInfo.Command);
     }
     else
     {
         Mogger.Log(logInfo.Command);
     }
 }
Пример #6
0
 public void MessageSend(ChatMessage message, int channelId)
 {
     if (this.connections.Count <= channelId || channelId < 0)
     {
         Mogger.LogError(LogMessages.HostNotFound + $" {this.connections.Count} connections found.");
         return;
     }
     if (this.connections[channelId] == null) // Shouldn't happen but might
     {
         Mogger.LogError(LogMessages.HostNotFound);
         return;
     }
     this.connections[channelId].SendMessage(message);
 }
Пример #7
0
        /// <summary>
        /// Redirect handler for Discord OAuth2.
        /// </summary>
        /// <returns cref="HttpServerPipelineResult">The success status of the handler action.</returns>
        /// <exception cref="KeyNotFoundException">Thrown if no access code is returned by the server.</exception>
        private string OAuth2RedirectHandler(HttpProcessor processor, int port, string state)
        {
            var uri         = new Uri("http://localhost:" + port + processor.FullUrl);
            var queryParams = uri.ParseQueryString().ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            Mogger.Log($"Sent state {state}, receiving state {queryParams["state"]}");
            if (queryParams["state"] != state)
            {
                throw new CSRFInvalidationException(ExceptionMessages.CSRFInvalidation);
            }
            OAuth2Code            = queryParams["code"];
            this.handlerCompleted = true;
            return("Success"); // TODO: Make a full success page
        }
Пример #8
0
        public void RemoveHost(string hostname)
        {
            var host = this.config.Hosts.FirstOrDefault(h => h.Hostname == hostname);
            var i    = this.config.Hosts.IndexOf(host);

            if (host == null || i == -1)
            {
                Mogger.LogError(LogMessages.HostNotFound);
                return;
            }

            this.config.Hosts.RemoveAt(i);
            this.connections[i].MessageReceivedEvent -= MessageReceived;
            this.connections.RemoveAt(i);
        }
Пример #9
0
        public void ReloadHost(string hostname)
        {
            var host = this.config.Hosts.FirstOrDefault(h => h.Hostname == hostname);
            var i    = this.config.Hosts.IndexOf(host);

            if (host == null || i == -1)
            {
                Mogger.LogError(LogMessages.HostNotFound);
                return;
            }

            var saveAccessCode = this.connections[i].SaveAccessCode;
            var channelId      = this.connections[i].ChannelId;

            this.connections[i].Dispose();
            this.connections[i] = new MogmogConnection(hostname, channelId, saveAccessCode);
        }
Пример #10
0
 public override void Write(string message)
 => Mogger.LogError(message);