Exemplo n.º 1
0
        /// <inheritdoc />
        public void SendMessage(string message, string author = "Server", long playerId = 0, string font = MyFontEnum.Red)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            ChatHistory.Add(new ChatMessage(DateTime.Now, 0, author, message));
            if (_commandManager.IsCommand(message))
            {
                var response = _commandManager.HandleCommandFromServer(message);
                ChatHistory.Add(new ChatMessage(DateTime.Now, 0, author, response));
            }
            else
            {
                var msg = new ScriptedChatMsg {
                    Author = author, Font = font, Target = playerId, Text = message
                };
                MyMultiplayerBase.SendScriptedChatMessage(ref msg);
                var character = MySession.Static.Players.TryGetIdentity(playerId)?.Character;
                var steamId   = GetSteamId(playerId);
                if (character == null)
                {
                    return;
                }

                var addToGlobalHistoryMethod = typeof(MyCharacter).GetMethod("OnGlobalMessageSuccess", BindingFlags.Instance | BindingFlags.NonPublic);
                _networkManager.RaiseEvent(addToGlobalHistoryMethod, character, steamId, steamId, message);
            }
        }
Exemplo n.º 2
0
        private void OnRecvChatMessage(IChannel channel, Message message)
        {
            Console.WriteLine("OnRecvChatMessage");
            CChatMessage request = message as CChatMessage;
            Player       player  = (Player)channel.GetContent();
            string       toWho   = request.toName;
            string       content = request.chatContext;

            SChatMessage chatMessage = new SChatMessage()
            {
                fromName    = player.user,
                chatContext = content,
            };

            // for debug
            Console.WriteLine("recieve chat msg from :{0}", player.user);

            if (toWho == "WorldChat")
            {
                chatMessage.fromName = toWho;
                player.Broadcast(chatMessage, true);
            }


            else
            {
                Player toPlayer = OnlinePlayers[toWho];
                toPlayer.connection.Send(chatMessage);
            }

            ChatHistory.Add(string.Format("('{0}','{1}','{2}','{3}')", player.user, toWho, content, System.DateTime.Now));
        }
Exemplo n.º 3
0
        private void Instance_MessageRecieved(ChatMsg msg, ref bool sendToOthers)
        {
            var message = ChatMessage.FromChatMsg(msg);

            ChatHistory.Add(message);
            MessageReceived?.Invoke(message, ref sendToOthers);
        }
Exemplo n.º 4
0
    public void Send()
    {
        var text = inputField.text;

        if (text == string.Empty)
        {
            return;
        }

        print("sending: '" + text + "'");

        Message message = new Message(username.options[username.value].text, text, DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).Ticks, Platform.Mockup);

        try
        {
            ChatAPI.NotifyNewMessageToListeners(message);
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            inputField.text = string.Empty;
            inputField.ActivateInputField();

            if (chatHistory)
            {
                chatHistory.Add(message);
            }
        }
    }
        private void StartReadingChatServer()
        {
            var cts = new CancellationTokenSource();

            _ = m_chatService.ChatLogs()
                .ForEachAsync((x) => ChatHistory.Add($"{x.At.ToDateTime().ToString("HH:mm:ss")} {x.Name}: {x.Content}"), cts.Token);

            App.Current.Exit += (_, __) => cts.Cancel();
        }
 private void PopulateHistory(List <KeyValuePair <string, string> > response)
 {
     var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         foreach (var historyItem in response)
         {
             ChatHistory.Add(new ChatMessage(historyItem.Key, historyItem.Value));
         }
     });
 }
Exemplo n.º 7
0
        private async Task SendMessage(string message)
        {
            var response = await _wrapper.SendMessage(message);

            foreach (var historyItem in response)
            {
                ChatHistory.Add(new ChatMessage(historyItem.Key, historyItem.Value));
            }

            MessageText = string.Empty;
        }
Exemplo n.º 8
0
        private void StartReadingChatServer()
        {
            var cts = new CancellationTokenSource();

            _ = m_chatService.ChatLogs(new Username {
                Name = Name,
            })
                .ForEachAsync((x) => {
                foreach (var newChat in FormatText(x.Time.ToDateTime().ToString("HH:mm:ss"), x.Name, x.Content))
                {
                    ChatHistory.Add(new Tuple <string, FontStyle, string, string>(newChat.Item1, newChat.Item2, newChat.Item3, newChat.Item4));
                }
            }, cts.Token);

            App.Current.Exit += (_, __) => cts.Cancel();
        }
Exemplo n.º 9
0
        /// <summary>Returns the json string that this chat message generates.</summary>
        public string SendChatMessageToAll(string message, string name = null, string color = Helper.ServerMessageColor, string nameColor = Helper.DefaultNameColor)
        {
            if (!Sockets.Any())
            {
                return(null);
            }

            string jsonStr = null;

            Sockets.ForEach(socket => jsonStr = socket.GetInfo().SendChatMessage(message, color, name, nameColor));

            var prefix = name != null ? (name + ": ") : "";

            ChatHistory.Add(prefix + message);

            return(jsonStr);
        }
Exemplo n.º 10
0
        //Process any server event
        override protected async Task ProcessEvent(GameEvent E)
        {
            if (E.Type == GameEvent.EventType.Connect)
            {
                // special case for IW5 when connect is from the log
                if (E.Extra != null)
                {
                    var logClient = (Player)E.Extra;
                    var client    = (await this.GetStatusAsync())
                                    .Single(c => c.ClientNumber == logClient.ClientNumber &&
                                            c.Name == logClient.Name);
                    client.NetworkId = logClient.NetworkId;

                    await AddPlayer(client);

                    // hack: to prevent plugins from registering it as a real connect
                    E.Type = GameEvent.EventType.Unknown;
                }

                else
                {
                    ChatHistory.Add(new ChatInfo()
                    {
                        Name    = E.Origin.Name,
                        Message = "CONNECTED",
                        Time    = DateTime.UtcNow
                    });

                    if (E.Origin.Level > Player.Permission.Moderator)
                    {
                        await E.Origin.Tell(string.Format(loc["SERVER_REPORT_COUNT"], E.Owner.Reports.Count));
                    }
                }
            }

            else if (E.Type == GameEvent.EventType.Disconnect)
            {
                ChatHistory.Add(new ChatInfo()
                {
                    Name    = E.Origin.Name,
                    Message = "DISCONNECTED",
                    Time    = DateTime.UtcNow
                });
            }

            else if (E.Type == GameEvent.EventType.Script)
            {
                await ExecuteEvent(new GameEvent(GameEvent.EventType.Kill, E.Data, E.Origin, E.Target, this));
            }

            if (E.Type == GameEvent.EventType.Say && E.Data.Length >= 2)
            {
                if (E.Data.Substring(0, 1) == "!" || E.Data.Substring(0, 1) == "@" || E.Origin.Level == Player.Permission.Console)
                {
                    Command C = null;

                    try
                    {
                        C = await ValidateCommand(E);
                    }

                    catch (CommandException e)
                    {
                        Logger.WriteInfo(e.Message);
                    }

                    if (C != null)
                    {
                        if (C.RequiresTarget && E.Target == null)
                        {
                            Logger.WriteWarning("Requested event (command) requiring target does not have a target!");
                        }

                        try
                        {
                            if (!E.Remote && E.Origin.Level != Player.Permission.Console)
                            {
                                await ExecuteEvent(new GameEvent()
                                {
                                    Type   = GameEvent.EventType.Command,
                                    Data   = string.Empty,
                                    Origin = E.Origin,
                                    Target = E.Target,
                                    Owner  = this,
                                    Extra  = C,
                                    Remote = E.Remote
                                });
                            }

                            await C.ExecuteAsync(E);
                        }

                        catch (AuthorizationException e)
                        {
                            await E.Origin.Tell($"{loc["COMMAND_NOTAUTHORIZED"]} - {e.Message}");
                        }

                        catch (Exception Except)
                        {
                            Logger.WriteError(String.Format("A command request \"{0}\" generated an error.", C.Name));
                            Logger.WriteDebug(String.Format("Error Message: {0}", Except.Message));
                            Logger.WriteDebug(String.Format("Error Trace: {0}", Except.StackTrace));
                            await E.Origin.Tell("^1An internal error occured while processing your command^7");

#if DEBUG
                            await E.Origin.Tell(Except.Message);
#endif
                        }
                    }
                }

                else // Not a command
                {
                    E.Data = E.Data.StripColors();

                    ChatHistory.Add(new ChatInfo()
                    {
                        Name    = E.Origin.Name,
                        Message = E.Data,
                        Time    = DateTime.UtcNow
                    });
                }
            }

            if (E.Type == GameEvent.EventType.MapChange)
            {
                Logger.WriteInfo($"New map loaded - {ClientNum} active players");

                var dict = (Dictionary <string, string>)E.Extra;
                Gametype = dict["g_gametype"].StripColors();
                Hostname = dict["sv_hostname"].StripColors();

                string mapname = dict["mapname"].StripColors();
                CurrentMap = Maps.Find(m => m.Name == mapname) ?? new Map()
                {
                    Alias = mapname, Name = mapname
                };
            }

            if (E.Type == GameEvent.EventType.MapEnd)
            {
                Logger.WriteInfo("Game ending...");
            }

            //todo: move
            while (ChatHistory.Count > Math.Ceiling((double)ClientNum / 2))
            {
                ChatHistory.RemoveAt(0);
            }

            // the last client hasn't fully disconnected yet
            // so there will still be at least 1 client left
            if (ClientNum < 2)
            {
                ChatHistory.Clear();
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Perform the server specific tasks when an event occurs
        /// </summary>
        /// <param name="E"></param>
        /// <returns></returns>
        override protected async Task <bool> ProcessEvent(GameEvent E)
        {
            if (E.Type == GameEvent.EventType.ConnectionLost)
            {
                var exception = E.Extra as Exception;
                Logger.WriteError(exception.Message);
                if (exception.Data["internal_exception"] != null)
                {
                    Logger.WriteDebug($"Internal Exception: {exception.Data["internal_exception"]}");
                }
                Logger.WriteInfo("Connection lost to server, so we are throttling the poll rate");
                Throttled = true;
            }

            if (E.Type == GameEvent.EventType.ConnectionRestored)
            {
                if (Throttled)
                {
                    Logger.WriteVerbose(loc["MANAGER_CONNECTION_REST"].FormatExt($"[{IP}:{Port}]"));
                }
                Logger.WriteInfo("Connection restored to server, so we are no longer throttling the poll rate");
                Throttled = false;
            }

            if (E.Type == GameEvent.EventType.ChangePermission)
            {
                var newPermission = (Permission)E.Extra;

                if (newPermission < Permission.Moderator)
                {
                    // remove banned or demoted privileged user
                    Manager.GetPrivilegedClients().Remove(E.Target.ClientId);
                }

                else
                {
                    if (Manager.GetPrivilegedClients().ContainsKey(E.Target.ClientId))
                    {
                        Manager.GetPrivilegedClients()[E.Target.ClientId] = E.Target;
                    }

                    else
                    {
                        Manager.GetPrivilegedClients().Add(E.Target.ClientId, E.Target);
                    }
                }

                Logger.WriteInfo($"{E.Origin} is setting {E.Target} to permission level {newPermission}");
                await Manager.GetClientService().UpdateLevel(newPermission, E.Target, E.Origin);
            }

            else if (E.Type == GameEvent.EventType.PreConnect)
            {
                // we don't want to track bots in the database at all if ignore bots is requested
                if (E.Origin.IsBot && Manager.GetApplicationSettings().Configuration().IgnoreBots)
                {
                    return(false);
                }

                var existingClient = GetClientsAsList().FirstOrDefault(_client => _client.Equals(E.Origin));

                // they're already connected
                if (existingClient != null)
                {
                    Logger.WriteWarning($"detected preconnect for {E.Origin}, but they are already connected");
                    return(false);
                }

CONNECT:
                if (Clients[E.Origin.ClientNumber] == null)
                {
#if DEBUG == true
                    Logger.WriteDebug($"Begin PreConnect for {E.Origin}");
#endif
                    // we can go ahead and put them in so that they don't get re added
                    Clients[E.Origin.ClientNumber] = E.Origin;
                    await OnClientConnected(E.Origin);

                    ChatHistory.Add(new ChatInfo()
                    {
                        Name    = E.Origin.Name,
                        Message = "CONNECTED",
                        Time    = DateTime.UtcNow
                    });

                    if (E.Origin.Level > EFClient.Permission.Moderator)
                    {
                        E.Origin.Tell(string.Format(loc["SERVER_REPORT_COUNT"], E.Owner.Reports.Count));
                    }
                }

                // for some reason there's still a client in the spot
                else
                {
                    Logger.WriteWarning($"{E.Origin} is connecteding but {Clients[E.Origin.ClientNumber]} is currently in that client slot");
                    await OnClientDisconnected(Clients[E.Origin.ClientNumber]);

                    goto CONNECT;
                }
            }

            else if (E.Type == GameEvent.EventType.Flag)
            {
                // todo: maybe move this to a seperate function
                Penalty newPenalty = new Penalty()
                {
                    Type     = Penalty.PenaltyType.Flag,
                    Expires  = DateTime.UtcNow,
                    Offender = E.Target,
                    Offense  = E.Data,
                    Punisher = E.Origin,
                    When     = DateTime.UtcNow,
                    Link     = E.Target.AliasLink
                };

                var addedPenalty = await Manager.GetPenaltyService().Create(newPenalty);

                E.Target.SetLevel(Permission.Flagged, E.Origin);
            }

            else if (E.Type == GameEvent.EventType.Unflag)
            {
                var unflagPenalty = new Penalty()
                {
                    Type     = Penalty.PenaltyType.Unflag,
                    Expires  = DateTime.UtcNow,
                    Offender = E.Target,
                    Offense  = E.Data,
                    Punisher = E.Origin,
                    When     = DateTime.UtcNow,
                    Link     = E.Target.AliasLink
                };

                await Manager.GetPenaltyService().Create(unflagPenalty);

                E.Target.SetLevel(Permission.User, E.Origin);
            }

            else if (E.Type == GameEvent.EventType.Report)
            {
                Reports.Add(new Report()
                {
                    Origin = E.Origin,
                    Target = E.Target,
                    Reason = E.Data
                });
            }

            else if (E.Type == GameEvent.EventType.TempBan)
            {
                await TempBan(E.Data, (TimeSpan)E.Extra, E.Target, E.Origin);;
            }

            else if (E.Type == GameEvent.EventType.Ban)
            {
                bool isEvade = E.Extra != null ? (bool)E.Extra : false;
                await Ban(E.Data, E.Target, E.Origin, isEvade);
            }

            else if (E.Type == GameEvent.EventType.Unban)
            {
                await Unban(E.Data, E.Target, E.Origin);
            }

            else if (E.Type == GameEvent.EventType.Kick)
            {
                await Kick(E.Data, E.Target, E.Origin);
            }

            else if (E.Type == GameEvent.EventType.Warn)
            {
                await Warn(E.Data, E.Target, E.Origin);
            }

            else if (E.Type == GameEvent.EventType.Disconnect)
            {
                ChatHistory.Add(new ChatInfo()
                {
                    Name    = E.Origin.Name,
                    Message = "DISCONNECTED",
                    Time    = DateTime.UtcNow
                });

                await new MetaService().AddPersistentMeta("LastMapPlayed", CurrentMap.Alias, E.Origin);
                await new MetaService().AddPersistentMeta("LastServerPlayed", E.Owner.Hostname, E.Origin);
            }

            else if (E.Type == GameEvent.EventType.PreDisconnect)
            {
                // predisconnect comes from minimal rcon polled players and minimal log players
                // so we need to disconnect the "full" version of the client
                var client = GetClientsAsList().FirstOrDefault(_client => _client.Equals(E.Origin));

                if (client != null)
                {
#if DEBUG == true
                    Logger.WriteDebug($"Begin PreDisconnect for {client}");
#endif
                    await OnClientDisconnected(client);

#if DEBUG == true
                    Logger.WriteDebug($"End PreDisconnect for {client}");
#endif
                }

                else if (client?.State != ClientState.Disconnecting)
                {
                    Logger.WriteWarning($"Client {E.Origin} detected as disconnecting, but could not find them in the player list");
                    Logger.WriteDebug($"Expected {E.Origin} but found {GetClientsAsList().FirstOrDefault(_client => _client.ClientNumber == E.Origin.ClientNumber)}");
                    return(false);
                }
            }

            else if (E.Type == GameEvent.EventType.Update)
            {
#if DEBUG == true
                Logger.WriteDebug($"Begin Update for {E.Origin}");
#endif
                await OnClientUpdate(E.Origin);
            }

            if (E.Type == GameEvent.EventType.Say)
            {
                E.Data = E.Data.StripColors();

                if (E.Data?.Length > 0)
                {
                    string message = E.Data;
                    if (E.Data.IsQuickMessage())
                    {
                        try
                        {
                            message = Manager.GetApplicationSettings().Configuration()
                                      .QuickMessages
                                      .First(_qm => _qm.Game == GameName)
                                      .Messages[E.Data.Substring(1)];
                        }
                        catch { }
                    }

                    ChatHistory.Add(new ChatInfo()
                    {
                        Name    = E.Origin.Name,
                        Message = message,
                        Time    = DateTime.UtcNow
                    });
                }
            }

            if (E.Type == GameEvent.EventType.MapChange)
            {
                Logger.WriteInfo($"New map loaded - {ClientNum} active players");

                // iw4 doesn't log the game info
                if (E.Extra == null)
                {
                    var dict = await this.GetInfoAsync();

                    if (dict == null)
                    {
                        Logger.WriteWarning("Map change event response doesn't have any data");
                    }

                    else
                    {
                        Gametype = dict["gametype"].StripColors();
                        Hostname = dict["hostname"]?.StripColors();

                        string mapname = dict["mapname"]?.StripColors() ?? CurrentMap.Name;
                        CurrentMap = Maps.Find(m => m.Name == mapname) ?? new Map()
                        {
                            Alias = mapname, Name = mapname
                        };
                    }
                }

                else
                {
                    var dict = (Dictionary <string, string>)E.Extra;
                    Gametype   = dict["g_gametype"].StripColors();
                    Hostname   = dict["sv_hostname"].StripColors();
                    MaxClients = int.Parse(dict["sv_maxclients"]);

                    string mapname = dict["mapname"].StripColors();
                    CurrentMap = Maps.Find(m => m.Name == mapname) ?? new Map()
                    {
                        Alias = mapname,
                        Name  = mapname
                    };
                }
            }

            if (E.Type == GameEvent.EventType.MapEnd)
            {
                Logger.WriteInfo("Game ending...");
                SessionStart = DateTime.UtcNow;
            }

            if (E.Type == GameEvent.EventType.Tell)
            {
                await Tell(E.Message, E.Target);
            }

            if (E.Type == GameEvent.EventType.Broadcast)
            {
#if DEBUG == false
                // this is a little ugly but I don't want to change the abstract class
                if (E.Data != null)
                {
                    await E.Owner.ExecuteCommandAsync(E.Data);
                }
#endif
            }

            lock (ChatHistory)
            {
                while (ChatHistory.Count > Math.Ceiling(ClientNum / 2.0))
                {
                    ChatHistory.RemoveAt(0);
                }
            }

            // the last client hasn't fully disconnected yet
            // so there will still be at least 1 client left
            if (ClientNum < 2)
            {
                ChatHistory.Clear();
            }

            return(true);
        }
Exemplo n.º 12
0
        private void OnChatMessage(IAsyncReceive receiveEvent)
        {
            var data = (OnChatMessage)receiveEvent;

            ChatHistory.Add(data.Message);
        }
 private void StartReadingChatServer()
 {
     m_chatService.ChatLogs()
     .Subscribe((x) => ChatHistory.Add($"{x.At.ToDateTime().ToString("HH:mm:ss")} {x.Name}: {x.Content}"));
 }
Exemplo n.º 14
0
        void OnChatReceived(object _sender, ChatReceivedEventArgs e)
        {
            App.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                const int FontSize = 14;

                var message = e.Message.Text;
                var font    = e.Message.Font;
                var sender  = e.Message.Sender;

                // Add this color to the brush cache if it's not there already
                var brush = App.GetBrush(font.Color);

                Paragraph paragraph;
                if (sender != lastSender)
                {
                    lastSender = sender;
                    paragraph  = new Paragraph()
                    {
                        FontSize        = FontSize + 2,
                        Foreground      = Brushes.Black,
                        FontWeight      = FontWeights.Light,
                        Margin          = new Thickness(0, 4.0, 0, 2.0),
                        Padding         = new Thickness(0, 0, 0, 2.0),
                        BorderBrush     = Brushes.LightGray,
                        BorderThickness = new Thickness(0, 0, 0, 1),
                    };
                    paragraph.Inlines.Add(new Run(sender.DisplayName));
                    ChatHistory.Add(paragraph);
                }

                paragraph = new Paragraph()
                {
                    FontFamily = new FontFamily(font.Family),
                    FontSize   = FontSize,
                    LineHeight = 3 * FontSize / 2,
                    Foreground = brush,
                    Margin     = new Thickness(16.0, 0, 0, 0),
                    TextIndent = 0,
                };

/*				var path = new System.Windows.Shapes.Path()
 *                              {
 *                                      Stroke = Brushes.Black,
 *                                      StrokeThickness = 2,
 *                                      Data = App.Current.FindResource("CrossGeometry") as Geometry,
 *                                      Width = 12,
 *                                      Height = paragraph.FontSize,
 *                                      Margin = new Thickness(0, 0, 4, 0),
 *                              };
 *
 *                              paragraph.Inlines.Add(new InlineUIContainer(path));*/

                var stops = new List <ChatStop>();

                foreach (var emoteStop in App.EmoticonManager.SearchForEmoticons(message))
                {
                    stops.Add(new ChatStop()
                    {
                        Index  = emoteStop.Key,
                        Length = emoteStop.Value.Shortcut.Length,
                        Type   = StopType.Emoticon,
                        Data   = emoteStop.Value,
                    });
                }

                string[] urls = new string[] { "http://", "https://" };
                foreach (var url in urls)
                {
                    int index = message.IndexOf(url);
                    while (index != -1)
                    {
                        int endIndex = message.IndexOf(' ', index);
                        if (endIndex == -1)
                        {
                            endIndex = message.Length - 1;
                        }
                        stops.Add(new ChatStop()
                        {
                            Index  = index,
                            Length = endIndex - index + 1,
                            Type   = StopType.Url,
                        });

                        index = message.IndexOf(url, endIndex);
                    }
                }

                var orderedStops = stops.OrderBy(_ => _.Index);

                int startIndex = 0;
                foreach (var stop in orderedStops)
                {
                    if (stop.Index < startIndex)
                    {
                        continue;
                    }
                    if (stop.Index != startIndex)
                    {
                        paragraph.Inlines.Add(new Run(message.Substring(startIndex, stop.Index - startIndex)));
                    }

                    switch (stop.Type)
                    {
                    case StopType.Emoticon:
                        var picture = new EmoteImage()
                        {
                            SnapsToDevicePixels = true,
                            Emote = stop.Data as Emoticon,
                        };

                        paragraph.Inlines.Add(new InlineUIContainer(picture));
                        break;

                    case StopType.Url:
                        var text    = message.Substring(stop.Index, stop.Length);
                        var link    = new Hyperlink(new Run(text));
                        link.Tag    = text;
                        link.Click += OnChatLinkClicked;
                        paragraph.Inlines.Add(link);
                        break;
                    }

                    startIndex = stop.Index + stop.Length;
                }

                paragraph.Inlines.Add(new Run(message.Substring(startIndex)));

                if (font.Style.HasFlag(Protocol.FontStyle.Bold))
                {
                    paragraph.FontWeight = FontWeights.Bold;
                }
                if (font.Style.HasFlag(Protocol.FontStyle.Italic))
                {
                    paragraph.FontStyle = FontStyles.Italic;
                }
                if (font.Style.HasFlag(Protocol.FontStyle.Underline))
                {
                    paragraph.TextDecorations = new TextDecorationCollection();
                    paragraph.TextDecorations.Add(System.Windows.TextDecorations.Underline);
                }

                ChatHistory.Add(paragraph);
            }));
        }