Exemplo n.º 1
0
        private DiscordMessage GenerateMessage(string message)
        {
            DiscordMessage dm       = new DiscordMessage();
            List <string>  foundIDS = new List <string>();
            Regex          r        = new Regex("\\@\\w+");
            List <KeyValuePair <string, string> > toReplace = new List <KeyValuePair <string, string> >();

            foreach (Match m in r.Matches(message))
            {
                if (message[m.Index - 1] == '<')
                {
                    continue;
                }
                DiscordMember user = ServersList.Find(x => x.members.Find(y => y.user.username == m.Value.Trim('@')) != null).members.Find(y => y.user.username == m.Value.Trim('@'));
                foundIDS.Add(user.user.id);
                toReplace.Add(new KeyValuePair <string, string>(m.Value, user.user.id));
            }
            foreach (var k in toReplace)
            {
                message = message.Replace(k.Key, "<@" + k.Value + ">");
            }

            dm.content  = message;
            dm.mentions = foundIDS.ToArray();
            return(dm);
        }
Exemplo n.º 2
0
 //eh
 private void GetChannelsList(JObject m)
 {
     if (ServersList == null)
     {
         ServersList = new List <DiscordServer>();
     }
     foreach (var j in m["d"]["guilds"])
     {
         DiscordServer temp = new DiscordServer();
         temp.id       = j["id"].ToString();
         temp.name     = j["name"].ToString();
         temp.owner_id = j["owner_id"].ToString();
         List <DiscordChannel> tempSubs = new List <DiscordChannel>();
         foreach (var u in j["channels"])
         {
             DiscordChannel tempSub = new DiscordChannel();
             tempSub.id   = u["id"].ToString();
             tempSub.name = u["name"].ToString();
             tempSub.type = u["type"].ToString();
             tempSubs.Add(tempSub);
         }
         temp.channels = tempSubs;
         foreach (var mm in j["members"])
         {
             DiscordMember member = new DiscordMember();
             member.user.id       = mm["user"]["id"].ToString();
             member.user.username = mm["user"]["username"].ToString();
             temp.members.Add(member);
         }
         ServersList.Add(temp);
     }
 }
Exemplo n.º 3
0
        void TcpServer_ClientConnected(object sender, AsyncEventArgs e)
        {
            AsyncTCPServer server = sender as AsyncTCPServer;
            int            temp   = ServersList.ToList <ServersInfo>().FindIndex(ex => (ex.IPAddr.ToString() == server.Address.ToString() && ex.Port == server.Port));

            if (temp == -1)//列表中没找到服务器
            {
                return;
            }
            TCPClientState client     = e._state as TCPClientState;
            ClientsInfo    clientinfo = new ClientsInfo();

            clientinfo.IpEndPort    = client.TcpClient.Client.RemoteEndPoint;
            clientinfo.ClientState  = client;
            clientinfo.ParentServer = ServersList[temp];
            App.Current.Dispatcher.Invoke((System.Action)(() =>
            {
                ServersList[temp].ClientsList.Add(clientinfo);
                foreach (var ser in ServersList)
                {
                    ser.IsSelected = false;
                    foreach (var tmp in ser.ClientsList)
                    {
                        tmp.IsSelected = false;
                    }
                }
                SelectServer = ServersList[temp];
                SelectServer.SelectClient            = clientinfo;
                SelectServer.SelectClient.IsSelected = true;
                IsHaveClent = true;
            }));
        }
Exemplo n.º 4
0
        private void MessageCreateEvents(JObject message)
        {
            try
            {
                string tempChannelID = message["d"]["channel_id"].ToString();

                var foundServerChannel = ServersList.Find(x => x.channels.Find(y => y.id == tempChannelID) != null);
                if (foundServerChannel == null)
                {
                    var foundPM = PrivateChannels.Find(x => x.id == message["d"]["channel_id"].ToString());
                    DiscordPrivateMessageEventArgs dpmea = new DiscordPrivateMessageEventArgs();
                    dpmea.Channel = foundPM;
                    dpmea.message = message["d"]["content"].ToString();
                    DiscordMember tempMember = new DiscordMember();
                    tempMember.user.username = message["d"]["author"]["username"].ToString();
                    tempMember.user.id       = message["d"]["author"]["id"].ToString();
                    dpmea.author             = tempMember;

                    if (PrivateMessageReceived != null)
                    {
                        PrivateMessageReceived(this, dpmea);
                    }
                }
                else
                {
                    DiscordMessageEventArgs dmea = new DiscordMessageEventArgs();
                    dmea.Channel = foundServerChannel.channels.Find(y => y.id == tempChannelID);
                    dmea.message = message["d"]["content"].ToString();

                    DiscordMember tempMember = new DiscordMember();
                    tempMember  = foundServerChannel.members.Find(x => x.user.id == message["d"]["author"]["id"].ToString());
                    dmea.author = tempMember;

                    Regex r = new Regex("\\d+");
                    foreach (Match mm in r.Matches(dmea.message))
                    {
                        if (mm.Value == Me.user.id)
                        {
                            if (MentionReceived != null)
                            {
                                MentionReceived(this, dmea);
                            }
                        }
                    }
                    if (MessageReceived != null)
                    {
                        MessageReceived(this, dmea);
                    }

                    KeyValuePair <string, JObject> toAdd = new KeyValuePair <string, JObject>(message["d"]["id"].ToString(), message);
                    MessageLog.Add(toAdd);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("!!! {0}", ex.Message);
                Console.Beep(100, 1000);
            }
        }
Exemplo n.º 5
0
        public LobbyBackend(ServersList frontend)
        {
            KnownActiveGameServers = new List <GameServerEntry>();
            Frontend = frontend;

            Frontend.JoinClick    += OnJoin;
            Frontend.RefreshClick += OnRefresh;
        }
Exemplo n.º 6
0
 public void ServerClose_Click(object sender, RoutedEventArgs e)
 {
     if (ServersList.Count == 0 || SelectServer == null)
     {
         return;
     }
     SelectServer.TcpServer.Stop();
     ServersList.Remove(SelectServer);
 }
Exemplo n.º 7
0
        public SpeedTestHttpClient() : base(new HttpClientHandler() { Proxy = new WebProxy() })
        {
            Timeout = TimeSpan.FromSeconds(30);

            ServersConfig = new ServersList(
                JsonSerializer.Deserialize <List <Server> >(
                    LocalDataHelper.ReadLocalFile("servers.json")
                    )
                );
        }
Exemplo n.º 8
0
        private void MessageUpdateEvents(JObject message)
        {
            DiscordServer  pserver  = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null);
            DiscordChannel pchannel = pserver.channels.Find(x => x.id == message["d"]["channel_id"].ToString());

            if (pchannel != null)
            {
                if (message["d"]["author"] != null)
                {
                    if (MessageEdited != null)
                    {
                        MessageEdited(this, new DiscordMessageEditedEventArgs
                        {
                            author        = pserver.members.Find(x => x.user.id == message["d"]["author"]["id"].ToString()),
                            Channel       = pchannel,
                            message       = message["d"]["content"].ToString(),
                            MessageType   = DiscordMessageType.CHANNEL,
                            MessageEdited = new DiscordMessage
                            {
                                author  = pserver.members.Find(x => x.user.id == message["d"]["author"]["id"].ToString()),
                                content = MessageLog.Find(x => x.Key == message["d"]["id"].ToString()).Value["d"]["content"].ToString(),
                            }
                        });
                    }
                    var toRemove   = MessageLog.Find(x => x.Key == message["d"]["id"].ToString());
                    var jsonToEdit = toRemove.Value;
                    jsonToEdit["d"]["content"].Replace(JToken.FromObject(message["d"]["content"].ToString()));
                }
                else //I know they say assume makes an ass out of you and me...but we're assuming it's Discord's weird auto edit of a just URL message
                {
                    if (URLMessageAutoUpdate != null)
                    {
                        DiscordURLUpdateEventArgs asdf = new DiscordURLUpdateEventArgs(); //I'm running out of clever names and should probably split these off into different internal voids soon...
                        asdf.id      = message["d"]["id"].ToString();
                        asdf.channel = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null).channels.Find(x => x.id == message["d"]["channel_id"].ToString());
                        foreach (var embed in message["d"]["embeds"])
                        {
                            DiscordEmbeds temp = new DiscordEmbeds();
                            temp.url           = embed["url"].ToString();
                            temp.description   = embed["description"].ToString();
                            temp.provider_name = embed["provider"]["name"].ToString();
                            temp.provider_url  = embed["provider"]["url"].ToString();
                            temp.title         = embed["title"].ToString();
                            temp.type          = embed["type"].ToString();
                            asdf.embeds.Add(temp);
                        }
                        URLMessageAutoUpdate(this, asdf);
                    }
                }
            }
        }
Exemplo n.º 9
0
        private void NavigationChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
        {
            FrameworkElement newContent = null;

            if (args.SelectedItem == this.MenuItemServers)
            {
                newContent = new ServersList("server");
            }

            if (this.ContentFrame.Content != newContent)
            {
                this.ContentFrame.Content = newContent;
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// Returns all the available servers on the local network
 /// </summary>
 private async void GetServers()
 {
     await Task.Run(() =>
     {
         var servers = SQLNativeBrowser.GetServersNative();
         if (servers != null)
         {
             ServersList.Fill(servers.Select(e => new SQLServer(ServerConnected)
             {
                 Name = e
             }));
         }
         IsBusy = false;
     });
 }
Exemplo n.º 11
0
        void TcpServer_ClientDisconnected(object sender, AsyncEventArgs e)
        {
            AsyncTCPServer server = sender as AsyncTCPServer;
            int            temp   = ServersList.ToList <ServersInfo>().FindIndex(ex => (ex.IPAddr.ToString() == server.Address.ToString() && ex.Port == server.Port));

            if (temp == -1)//列表中没找到服务器
            {
                return;
            }
            TCPClientState client   = e._state as TCPClientState;
            EndPoint       endpoint = client.TcpClient.Client.RemoteEndPoint;

            App.Current.Dispatcher.Invoke((System.Action)(() =>
            {
                var tmp = ServersList[temp].ClientsList.First(ex => ex.IpEndPort == endpoint);
                ServersList[temp].ClientsList.Remove(tmp);
            }));
        }
Exemplo n.º 12
0
 private void ChannelCreateEvents(JObject message)
 {
     if (message["d"]["is_private"].ToString().ToLower() == "false")
     {
         var foundServer = ServersList.Find(x => x.id == message["d"]["guild_id"].ToString());
         if (foundServer != null)
         {
             DiscordChannel tempChannel = new DiscordChannel();
             tempChannel.name = message["d"]["name"].ToString();
             tempChannel.type = message["d"]["type"].ToString();
             tempChannel.id   = message["d"]["id"].ToString();
             foundServer.channels.Add(tempChannel);
             DiscordChannelCreateEventArgs fae = new DiscordChannelCreateEventArgs();
             fae.ChannelCreated = tempChannel;
             fae.ChannelType    = DiscordChannelCreateType.CHANNEL;
             if (ChannelCreated != null)
             {
                 ChannelCreated(this, fae);
             }
         }
     }
     else
     {
         DiscordPrivateChannel tempPrivate = new DiscordPrivateChannel();
         tempPrivate.id = message["d"]["id"].ToString();
         DiscordRecipient tempRec = new DiscordRecipient();
         tempRec.id            = message["d"]["recipient"]["id"].ToString();
         tempRec.username      = message["d"]["recipient"]["username"].ToString();
         tempPrivate.recipient = tempRec;
         PrivateChannels.Add(tempPrivate);
         DiscordPrivateChannelEventArgs fak = new DiscordPrivateChannelEventArgs {
             ChannelType = DiscordChannelCreateType.PRIVATE, ChannelCreated = tempPrivate
         };
         if (PrivateChannelCreated != null)
         {
             PrivateChannelCreated(this, fak);
         }
     }
 }
Exemplo n.º 13
0
        private const int MaxUploadSize = 4; // 400 KB

        #region ISpeedTestClient

        /// <inheritdoc />
        /// <exception cref="InvalidOperationException"></exception>
        public Settings GetSettings()
        {
            using (var client = new SpeedTestHttpClient())
            {
                var settings = client.GetConfig <Settings>(ConfigUrl).GetAwaiter().GetResult();

                var serversConfig = new ServersList();
                foreach (var serversUrl in ServersUrls)
                {
                    try
                    {
                        serversConfig = client.GetConfig <ServersList>(serversUrl).GetAwaiter().GetResult();
                        if (serversConfig.Servers.Count > 0)
                        {
                            break;
                        }
                    }
                    catch
                    {
                        //
                    }
                }

                if (serversConfig.Servers.Count <= 0)
                {
                    throw new InvalidOperationException("SpeedTest does not return any server");
                }

                var ignoredIds =
                    settings.ServerConfig.IgnoreIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                serversConfig.CalculateDistances(settings.Client.GeoCoordinate);
                settings.Servers = serversConfig.Servers
                                   .Where(s => !ignoredIds.Contains(s.Id.ToString()))
                                   .OrderBy(s => s.Distance)
                                   .ToList();

                return(settings);
            }
        }
        /// <summary>
        /// Read the server from the table of the Servers info.
        /// </summary>
        /// <param name="objServerData">Server info DataRow</param>
        private void LoadServerToList(DataRow objServerData)
        {
            Server objNewServer = new Server();

            if (!(objServerData["ServerName"] is System.DBNull))
            {
                objNewServer.ServerName = objServerData["ServerName"].ToString();
            }
            if (!(objServerData["InstanceName"] is System.DBNull))
            {
                objNewServer.InstanceName = objServerData["InstanceName"].ToString();
            }
            if (!(objServerData["IsClustered"] is System.DBNull))
            {
                objNewServer.IsClustered = objServerData["IsClustered"].ToString();
            }
            if (!(objServerData["Version"] is System.DBNull))
            {
                objNewServer.Version = objServerData["Version"].ToString();
            }

            ServersList.Add(objNewServer);
        }
Exemplo n.º 15
0
        private void PresenceUpdateEvents(JObject message)
        {
            DiscordPresenceUpdateEventArgs dpuea = new DiscordPresenceUpdateEventArgs();
            var user = ServersList.Find(x => x.members.Find(y => y.user.id == message["d"]["id"].ToString()) != null).members.Find(x => x.user.id == message["d"]["id"].ToString());

            dpuea.game_id = message["d"]["game_id"].ToString() == null ? "null" : message["d"]["game_id"].ToString();
            if (message["d"]["status"].ToString() == "online")
            {
                dpuea.status = DiscordUserStatus.ONLINE;
            }
            else if (message["d"]["status"].ToString() == "idle")
            {
                dpuea.status = DiscordUserStatus.IDLE;
            }
            else if (message["d"]["status"].ToString() == null || message["d"]["status"].ToString() == "offline")
            {
                dpuea.status = DiscordUserStatus.OFFLINE;
            }
            if (PresenceUpdated != null)
            {
                PresenceUpdated(this, dpuea);
            }
        }
Exemplo n.º 16
0
        public void NewServer_Click(object sender, RoutedEventArgs e)
        {
            MainWindow wnd = sender as MainWindow;

            Views.NewServerView view = new Views.NewServerView();
            view.Owner = wnd;
            if (view.ShowDialog() == true)
            {
                string ip = view.iptext.Text.Trim().ToString();
                if (ip == "127.0.0.1")
                {
                    ip = "0.0.0.0";
                }
                int         port = int.Parse(view.porttext.Text.Trim().ToString());
                ServersInfo ser  = new ServersInfo();
                ser.IPAddr    = IPAddress.Parse(ip);
                ser.Port      = port;
                ser.IpEndPort = new IPEndPoint(ser.IPAddr, ser.Port);
                if (ServersList.Count != 0)
                {
                    int temp = ServersList.ToList <ServersInfo>().FindIndex(ex => ex.IpEndPort.ToString() == ser.IpEndPort.ToString());
                    if (temp != -1)
                    {
                        MessageBox.Show("该服务器已添加");
                        return;
                    }
                }

                ser.TcpServer = new AsyncTCPServer(ser.IPAddr, ser.Port);
                ser.TcpServer.ClientConnected    += TcpServer_ClientConnected;
                ser.TcpServer.ClientDisconnected += TcpServer_ClientDisconnected;
                ser.TcpServer.DataReceived       += TcpServer_DataReceived;
                ServersList.Add(ser);
                SelectServer = ServersList[ServersList.Count - 1];
            }
        }
Exemplo n.º 17
0
 public ServersListCommandHandler(ServersList serversList, ServersListRenderer renderer)
 {
     _serversList = serversList;
     _renderer    = renderer;
 }
 /// <summary>
 /// Adds the new server.
 /// </summary>
 /// <param name="server">The server.</param>
 public void AddNewServer(FrameworkServer server)
 {
     _context.FrameworkServers.Add(server);
     ServersList.Add(server);
 }
Exemplo n.º 19
0
        public void ConnectAndReadMessages()
        {
            ws            = new WebSocket("wss://discordapp.com/hub");
            ws.OnMessage += (sender, e) =>
            {
                var message = JObject.Parse(e.Data);
                switch (message["t"].ToString())
                {
                case ("READY"):
                    using (var sw = new StreamWriter("READY"))
                        sw.Write(message);
                    Me = new DiscordMember {
                        user = new DiscordUser {
                            username = message["d"]["user"]["username"].ToString(),
                            id       = message["d"]["user"]["id"].ToString(), verified = message["d"]["user"]["verified"].ToObject <bool>(), avatar = message["d"]["user"]["avatar"].ToString(), discriminator = message["d"]["user"]["discriminator"].ToString()
                        }
                    };
                    HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString());
                    GetChannelsList(message);
                    if (Connected != null)
                    {
                        Connected(this, new DiscordConnectEventArgs {
                            user = Me
                        });                                                                 //Since I already know someone will ask for it.
                    }
                    break;

                case ("PRESENCE_UPDATE"):
                    PresenceUpdateEvents(message);
                    break;

                case ("MESSAGE_UPDATE"):
                    MessageUpdateEvents(message);
                    break;

                case ("TYPING_START"):
                    DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null);
                    if (server != null)
                    {
                        DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString());
                        DiscordMember  uuser   = server.members.Find(x => x.user.id == message["d"]["user_id"].ToString());
                        if (UserTypingStart != null)
                        {
                            UserTypingStart(this, new DiscordTypingStartEventArgs {
                                user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString())
                            });
                        }
                    }
                    break;

                case ("MESSAGE_CREATE"):
                    MessageCreateEvents(message);
                    break;

                case ("CHANNEL_CREATE"):
                    ChannelCreateEvents(message);
                    break;

#if DEBUG
                default:
                    ni.BalloonTipText = "Check console! New message type!";
                    ni.ShowBalloonTip(10 * 1000);
                    Console.WriteLine(message);
                    break;
#endif
                }
            };
            ws.OnOpen += (sender, e) =>
            {
                DiscordInitObj initObj = new DiscordInitObj();
                initObj.op      = 2;
                initObj.d.token = this.token;
                string json = initObj.AsJson();
                ws.Send(json);
                if (SocketOpened != null)
                {
                    SocketOpened(this, null);
                }
                Thread keepAlivetimer = new Thread(KeepAlive);
                keepAlivetimer.Start();
            };
            ws.OnClose += (sender, e) =>
            {
                DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                scev.Code     = e.Code;
                scev.Reason   = e.Reason;
                scev.WasClean = e.WasClean;
                if (SocketClosed != null)
                {
                    SocketClosed(this, scev);
                }
            };
            ws.Connect();
        }