Пример #1
0
        /// <summary>
        /// Create new channel in system
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id">useful for Private and Room type to setup the same Unique id that have for example Room. It also good becase it will not allow you to create sevearal channels for Room</param>
        /// <param name="name">is allowable for Custom type only, for other it will be ignored and name created by default</param>
        public ChatChannel(ChatChannelType type, string id = null, string name = null)
        {
            if (id == null || type == ChatChannelType.Custom)
            {
                Id = PowerGridEngine.EnergoServer.GenerateSmallUniqueId();
            }
            else
            {
                Id = id;
            }

            Type = type;

            if (Type == ChatChannelType.Custom && !string.IsNullOrWhiteSpace(name))
            {
                this.name = name;
            }
            else
            {
                this.name = Type.ToString();
            }

            _subscribers = new Dictionary <string, DateTime>();
            AccessList   = new Dictionary <string, bool>();
            _messages    = new List <ChatMessage>();
        }
Пример #2
0
        private static bool CanReceiveRPPoint(NWPlayer player, ChatChannelType channel)
        {
            // Party - Must be in a party with another PC.
            if (channel == ChatChannelType.PlayerParty)
            {
                return(player.PartyMembers.Any(x => x.GlobalID != player.GlobalID));
            }

            // Shout (Holonet) - Another player must be online.
            else if (channel == ChatChannelType.PlayerShout)
            {
                return(NWModule.Get().Players.Count() > 1);
            }

            // Talk - Another player must be nearby. (20.0 units)
            else if (channel == ChatChannelType.PlayerTalk)
            {
                return(NWModule.Get().Players.Any(nearby =>
                                                  player.GlobalID != nearby.GlobalID &&
                                                  _.GetDistanceBetween(player, nearby) <= 20.0f));
            }

            // Whisper - Another player must be nearby. (4.0 units)
            else if (channel == ChatChannelType.PlayerWhisper)
            {
                return(NWModule.Get().Players.Any(nearby =>
                                                  player.GlobalID != nearby.GlobalID &&
                                                  _.GetDistanceBetween(player, nearby) <= 4.0f));
            }

            return(false);
        }
Пример #3
0
        public BaseRoutableChatTextMessageEnteredEventListener(IChatTextMessageEnteredEventSubscribable subscriptionService,
                                                               [NotNull] IChatChannelJoinedEventSubscribable channelJoinedSubscriptionService,
                                                               [NotNull] ILog logger,
                                                               ChatChannelType channelType)
        {
            if (channelJoinedSubscriptionService == null)
            {
                throw new ArgumentNullException(nameof(channelJoinedSubscriptionService));
            }
            Logger      = logger ?? throw new ArgumentNullException(nameof(logger));
            ChannelType = channelType;

            //This just registers and wires up that when we join a channel we'll start recieveing that channels messages.
            channelJoinedSubscriptionService.OnChatChannelJoined += (o, e) =>
            {
                if (!CheckType(e))
                {
                    return;
                }

                subscriptionService.OnChatMessageEntered += (o2, e2) =>
                {
                    if (!CheckType(e2))
                    {
                        return;
                    }

                    OnEventFired(e.MessageSender, e2);
                };
            };
        }
Пример #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpeechPacket"/> class.
 /// </summary>
 /// <param name="type">The type of speech.</param>
 /// <param name="channelId">The channel type.</param>
 /// <param name="content">The content spoken.</param>
 /// <param name="receiver">Optional. The receiver of the message, if any.</param>
 public SpeechPacket(SpeechType type, ChatChannelType channelId, string content, string receiver = "")
 {
     this.SpeechType  = type;
     this.ChannelType = channelId;
     this.Content     = content;
     this.Receiver    = receiver;
 }
Пример #5
0
        private void OnChatMessageRecieved(ChatChannelType channelType, [NotNull] IChannelTextMessage args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }
            if (!Enum.IsDefined(typeof(ChatChannelType), channelType))
            {
                throw new InvalidEnumArgumentException(nameof(channelType), (int)channelType, typeof(ChatChannelType));
            }

            AccountId id          = args.Sender;
            int       characterId = int.Parse(id.Name);

            //TODO: We need to translate the guid to a name.
            NetworkEntityGuid guid = NetworkEntityGuidBuilder.New()
                                     .WithType(EntityType.Player)
                                     .WithId(characterId)
                                     .Build();

            if (NameQueryService.Exists(guid))
            {
                PublishTextData(channelType, args, guid, NameQueryService.Retrieve(guid));
            }
            else
            {
                UnityAsyncHelper.UnityMainThreadContext.PostAsync(async() =>
                {
                    string queryResponse = await NameQueryService.RetrieveAsync(guid)
                                           .ConfigureAwaitFalse();

                    PublishTextData(channelType, args, guid, queryResponse);
                });
            }
        }
Пример #6
0
 public ChatCacheData[] GetMessageCache(ChatChannelType type)
 {
     if (!mChanelCaches.ContainsKey((int)type))
     {
         return(null);
     }
     return(mChanelCaches[(int)type].ToArray());
 }
Пример #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpeechOperation"/> class.
 /// </summary>
 /// <param name="requestorId">The id of the creature speaking.</param>
 /// <param name="speechType">The type of speech.</param>
 /// <param name="channelType">The type of channel where the speech happens.</param>
 /// <param name="content">The content of the speech.</param>
 /// <param name="receiver">The receiver of the speech, if applicable.</param>
 public SpeechOperation(uint requestorId, SpeechType speechType, ChatChannelType channelType, string content, string receiver)
     : base(requestorId)
 {
     // this.ExhaustionCost = TimeSpan.FromSeconds(1);
     this.Type      = speechType;
     this.ChannelId = channelType;
     this.Content   = content;
     this.Receiver  = receiver;
 }
Пример #8
0
 /// <inheritdoc />
 public TextChatEventArgs([NotNull] string message, ChatChannelType messageType)
 {
     if (!Enum.IsDefined(typeof(ChatChannelType), messageType))
     {
         throw new InvalidEnumArgumentException(nameof(messageType), (int)messageType, typeof(ChatChannelType));
     }
     Message     = message ?? throw new ArgumentNullException(nameof(message));
     ChannelType = messageType;
     Sender      = NetworkEntityGuid.Empty;
 }
Пример #9
0
        public VivoxChannelTextMessageChatMessageAdapter([NotNull] IChannelTextMessage channelMessage, ChatChannelType channelType)
        {
            if (!Enum.IsDefined(typeof(ChatChannelType), channelType))
            {
                throw new InvalidEnumArgumentException(nameof(channelType), (int)channelType, typeof(ChatChannelType));
            }

            ChannelMessage = channelMessage ?? throw new ArgumentNullException(nameof(channelMessage));
            ChannelType    = channelType;
        }
 void ILobbyClientSessionHandler.OnChannelMessageReceived(
     ChatChannelType channel,
     string playerName,
     string message)
 {
     if (this.ChatHandler != null)
     {
         this.ChatHandler.ReceiveChatMessage(channel, playerName, message);
     }
     ChatBox.AddWhisperMessage(playerName, message);
 }
Пример #11
0
 public ChatBoxMessage(int playerId, int botNetId, byte isBotMessage, ChatChannelType channel, int unk1,
                       byte[] unk2, string content)
 {
     this.playerId     = playerId;
     this.botNetId     = botNetId;
     this.isBotMessage = isBotMessage;
     this.channel      = channel;
     this.unk1         = unk1;
     this.unk2         = unk2;
     this.content      = content;
 }
Пример #12
0
        public ChatChannelJoinedEventArgs(ChatChannelType channelType, [NotNull] IVivoxTextChannelMessageSubscribable channel, [NotNull] IChatChannelSender messageSender)
        {
            if (!Enum.IsDefined(typeof(ChatChannelType), channelType))
            {
                throw new InvalidEnumArgumentException(nameof(channelType), (int)channelType, typeof(ChatChannelType));
            }

            ChannelType   = channelType;
            Channel       = channel ?? throw new ArgumentNullException(nameof(channel));
            MessageSender = messageSender ?? throw new ArgumentNullException(nameof(messageSender));
        }
Пример #13
0
        public ChatTextMessageEnteredEventArgs(ChatChannelType requestedChannelType, [NotNull] string content)
        {
            if (!Enum.IsDefined(typeof(ChatChannelType), requestedChannelType))
            {
                throw new InvalidEnumArgumentException(nameof(requestedChannelType), (int)requestedChannelType, typeof(ChatChannelType));
            }
            if (string.IsNullOrWhiteSpace(content))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(content));
            }

            ChannelType = requestedChannelType;
            Content     = content;
        }
        public ChatChannel AddChannel(User user, ChatChannelType type, string id = null, string name = null)
        {
            //string subscriberId = null;
            if (type == ChatChannelType.Custom)
            {
                id = null; //can't setup id for custom, it should be generated by system
            }
            else
            {
                var sameChannel = LookupChannel(user, id, type);
                if (sameChannel != null)
                {
                    throw new ArgumentException(ErrMsg_SuchChannelExists);
                }
            }

            if (type == ChatChannelType.Room)
            {
                var room = ServerContext.Current.Server.TryToLookupRoom(id);
                if (room == null)
                {
                    throw new ArgumentException("No such room");
                }
                //subscriberId = room.Id;
            }
            else if (type == ChatChannelType.Private)
            {
                var priv = ServerContext.Current.Server.TryToLookupUser(id);
                if (priv == null)
                {
                    throw new ArgumentException("No such user");
                }
                //subscriberId = priv.Id;
            }

            var channel = new ChatChannel(type, id, name);

            Channels.Add(channel);

            //if (subscriberId != null)
            //    channel.Subscribe(subscriberId);
            //else
            if (type == ChatChannelType.Custom)
            {
                Join(user, channel);
            }

            return(channel);
        }
Пример #15
0
        /// <inheritdoc />
        public TextChatEventArgs CreateChatData <TMessageType>([NotNull] TMessageType incomingChatMessageEventData)
            where TMessageType : ITextMessageContainable, IChatChannelRoutable
        {
            if (incomingChatMessageEventData == null)
            {
                throw new ArgumentNullException(nameof(incomingChatMessageEventData));
            }

            ChatChannelType messageType = incomingChatMessageEventData.ChannelType;

            string renderableMessage = $"<color=#{ComputeColorFromChatType(messageType)}>{ComputeChannelText(messageType)}: {incomingChatMessageEventData.Message}</color>";

            TextChatEventArgs args = new TextChatEventArgs(renderableMessage, messageType);

            args.isFormattedText = true;
            return(args);
        }
Пример #16
0
    private void AddMessage(ChatChannelType type, string name, string msg)
    {
        string channelname = "[fed514]【城市】";

        if (type == ChatChannelType.ChannelType_World)
        {
            channelname = "[3eff00]【世界】";
        }
        if (type == ChatChannelType.ChannelType_System)
        {
            channelname = "[e92224]【系统】";
        }

        mAreaLabel.text += (channelname + "[u]" + name + "[/u]:[-] " + msg);

        mScrollView.ResetPosition();
    }
Пример #17
0
        public override void Deserialize(LittleEndianReader reader)
        {
            this.playerId     = reader.ReadInt();
            this.botNetId     = reader.ReadInt();
            this.isBotMessage = reader.ReadByte();
            this.channel      = (ChatChannelType)reader.ReadInt();
            this.unk1         = reader.ReadInt();
            this.length       = reader.ReadInt();
            this.unk2         = reader.ReadBytes(32);

            var bytes = new List <byte>();

            for (var i = 0; i < length; i++)
            {
                bytes.Add(reader.ReadByte());
            }
            this.content = Encoding.UTF8.GetString(bytes.ToArray());
        }
Пример #18
0
        private string ComputeChannelText(ChatChannelType messageType)
        {
            switch (messageType)
            {
            case ChatChannelType.Proximity:
                return("[Say]");

            case ChatChannelType.System:
                return("[System]");

            case ChatChannelType.Zone:
                return("[1. Zone]");

            case ChatChannelType.Guild:
                return("[Guild]");
            }

            throw new NotImplementedException($"Cannot handle Chat Type: {messageType}:{(int)messageType}");
        }
Пример #19
0
        private string ComputeColorFromChatType(ChatChannelType messageType)
        {
            switch (messageType)
            {
            case ChatChannelType.System:
                return("eff233ff");

            case ChatChannelType.Zone:
                return("AA9E92ff");

            case ChatChannelType.Guild:
                return("42f442ff");

            case ChatChannelType.Proximity:
                return("ffffffff");
            }

            throw new NotImplementedException($"Cannot handle Chat Type: {messageType}:{(int)messageType}");
        }
Пример #20
0
 private void OnChannelChanged()
 {
     if (mWorldToggle.value)
     {
         mCurChannel = ChatChannelType.ChannelType_World;
     }
     if (mCityToggle.value)
     {
         mCurChannel = ChatChannelType.ChannelType_City;
     }
     if (mSystemToggle.value)
     {
         mCurChannel = ChatChannelType.ChannelType_System;
         mInputBack.SetActive(false);
     }
     else
     {
         mInputBack.SetActive(true);
     }
     UpdateViews();
 }
Пример #21
0
        public void SpeechPacket_Initialization()
        {
            const SpeechType      ExpectedSpeechType  = SpeechType.Say;
            const ChatChannelType ExpectedChannelType = ChatChannelType.Game;
            const string          ExpectedContent     = "this is a test!";
            const string          ExpectedReceiver    = "Player 2";

            ISpeechInfo speechInfo = new SpeechPacket(ExpectedSpeechType, ExpectedChannelType, ExpectedContent);

            Assert.AreEqual(ExpectedSpeechType, speechInfo.SpeechType, $"Expected {nameof(speechInfo.SpeechType)} to match {ExpectedSpeechType}.");
            Assert.AreEqual(ExpectedChannelType, speechInfo.ChannelType, $"Expected {nameof(speechInfo.ChannelType)} to match {ExpectedChannelType}.");
            Assert.AreEqual(ExpectedContent, speechInfo.Content, $"Expected {nameof(speechInfo.Content)} to match {ExpectedContent}.");
            Assert.AreEqual(string.Empty, speechInfo.Receiver, $"Expected {nameof(speechInfo.Receiver)} to be empty.");

            ISpeechInfo speechInfoWithReceiver = new SpeechPacket(ExpectedSpeechType, ExpectedChannelType, ExpectedContent, ExpectedReceiver);

            Assert.AreEqual(ExpectedSpeechType, speechInfoWithReceiver.SpeechType, $"Expected {nameof(speechInfoWithReceiver.SpeechType)} to match {ExpectedSpeechType}.");
            Assert.AreEqual(ExpectedChannelType, speechInfoWithReceiver.ChannelType, $"Expected {nameof(speechInfoWithReceiver.ChannelType)} to match {ExpectedChannelType}.");
            Assert.AreEqual(ExpectedContent, speechInfoWithReceiver.Content, $"Expected {nameof(speechInfoWithReceiver.Content)} to match {ExpectedContent}.");
            Assert.AreEqual(ExpectedReceiver, speechInfoWithReceiver.Receiver, $"Expected {nameof(speechInfoWithReceiver.Receiver)} to match {ExpectedReceiver}.");
        }
Пример #22
0
    /// <summary>
    /// 채팅 보내기
    /// </summary>
    public void OnSubmit()
    {
        //빈건 안보냄
        if (string.IsNullOrEmpty(mUIInput.value))
        {
            return;
        }

        //월드채팅혹은 동맹채팅
        ChatChannelType currChannelType = ChatChannelType.WORLD;

        switch (CurrTap)
        {
        case TapType.ALLIANCE: currChannelType = ChatChannelType.ALLIANCE; break;

        case TapType.TOTAL: currChannelType = ChatChannelType.WORLD; break;
        }

        //보내기
        ChatNetworkManager.Instance.AddSendList(new SendChatPacket(currChannelType, mUIInput.value));

        //보낸내용 지우기
        mUIInput.value = string.Empty;
    }
Пример #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CreatureSpeechNotification"/> class.
 /// </summary>
 /// <param name="findTargetPlayers">A function to determine the target players of this notification.</param>
 /// <param name="creature">The creature that spoke.</param>
 /// <param name="speechType">The type of speech.</param>
 /// <param name="channelType">The channel type.</param>
 /// <param name="text">The message content.</param>
 /// <param name="receiver">Optional. The receiver of the message.</param>
 public CreatureSpeechNotification(Func <IEnumerable <IPlayer> > findTargetPlayers, ICreature creature, SpeechType speechType, ChatChannelType channelType, string text, string receiver = "")
     : base(findTargetPlayers)
 {
     this.Creature    = creature;
     this.SpeechType  = speechType;
     this.ChannelType = channelType;
     this.Text        = text;
     this.Receiver    = receiver;
 }
Пример #24
0
        private void PublishTextData(ChatChannelType channelType, IChannelTextMessage args, NetworkEntityGuid guid, string name)
        {
            TextChatEventArgs data = TextDataFactory.CreateChatData(new EntityAssociatedData <VivoxChannelTextMessageChatMessageAdapter>(guid, new VivoxChannelTextMessageChatMessageAdapter(args, channelType)), name);

            MessageRecievedPublisher.PublishEvent(this, data);
        }
Пример #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CreatureSpeechPacket"/> class.
 /// </summary>
 /// <param name="senderName"></param>
 /// <param name="speechType"></param>
 /// <param name="text"></param>
 /// <param name="location"></param>
 /// <param name="channelId"></param>
 /// <param name="time"></param>
 public CreatureSpeechPacket(string senderName, SpeechType speechType, string text, Location location, ChatChannelType channelId, uint time)
 {
     this.SenderName = senderName;
     this.SpeechType = speechType;
     this.Text       = text;
     this.Location   = location;
     this.ChannelId  = channelId;
     this.Time       = time;
 }
Пример #26
0
 /// <summary>
 /// Requests the gameworld to send a message on behalf of a player.
 /// </summary>
 /// <param name="playerId">The id of the player.</param>
 /// <param name="speechType">The type of speech this is.</param>
 /// <param name="channelType">The game channel over which the message should be sent.</param>
 /// <param name="content">The content of the message.</param>
 /// <param name="receiverId">The intended receiver of the message, if any.</param>
 public void RequestSendMessageAsync(uint playerId, SpeechType speechType, ChatChannelType channelType, string content, string receiverId)
 {
     this.gameworldClientAdapter.RequestSendMessageAsync(playerId, speechType, channelType, content, receiverId);
 }
Пример #27
0
        private void OnChatMessageEnterPressed()
        {
            if (Logger.IsDebugEnabled)
            {
                Logger.Debug($"Attempting to send ChatMessage: {ChatEnterText.Text}");
            }

            //TODO: Is this possible? Since I know InputField force clicks the button?
            if (!ChatEnterButton.IsInteractable)
            {
                if (Logger.IsWarnEnabled)
                {
                    Logger.Warn($"Button pressed event fired when Button: {nameof(ChatEnterButton)} {nameof(ChatEnterButton.IsInteractable)} was false.");
                }
                return;
            }

            //We shouldn't send nothing.
            if (String.IsNullOrWhiteSpace(ChatEnterText.Text))
            {
                return;
            }

            ChatEnterButton.IsInteractable = false;

            //Once pressed, we should just send the chat message.
            try
            {
                ChatChannelType type        = ChatChannelType.Proximity;
                string          chatMessage = ChatEnterText.Text;

                //If the first character is a slash
                //then they may want a specific channel
                if (ChatEnterText.Text[0] == '/')
                {
                    string inputType = ChatEnterText.Text.Split(' ').First().ToLower();
                    //Removed input type
                    chatMessage = new string(ChatEnterText.Text.Skip(inputType.Length).ToArrayTryAvoidCopy());

                    switch (inputType)
                    {
                    case "/guild":
                    case "/g":
                        type = ChatChannelType.Guild;
                        break;

                    case "/say":
                    case "/s":
                        type = ChatChannelType.Proximity;
                        break;
                    }
                }

                OnChatMessageEntered?.Invoke(this, new ChatTextMessageEnteredEventArgs(type, chatMessage));

                //We clear text here because we actually DON'T wanna clear the text if there was an error.
                ChatEnterText.Text = "";
            }
            catch (Exception e)
            {
                if (Logger.IsErrorEnabled)
                {
                    Logger.Error($"Could not send chat message. Exception {e.GetType().Name}: {e.Message}\n\nStackTrace:{e.StackTrace}");
                }

                throw;
            }
            finally
            {
                ChatEnterButton.IsInteractable = true;
            }

            //For reference

            /*if(ChatEnterText.Text.Contains("/invite"))
             * {
             *      string toInvite = ChatEnterText.Text.Split(' ').Last();
             *      if(Logger.IsDebugEnabled)
             *              Logger.Debug($"About to invite: {toInvite}");
             *
             *      await SendService.SendMessage(new ClientGroupInviteRequest(toInvite));
             * }
             * else
             *      await SendService.SendMessage(new ChatMessageRequest(new SayPlayerChatMessage(ChatLanguage.LANG_ORCISH, ChatEnterText.Text)))
             *              .ConfigureAwait(true);*/
        }
 public ClientChatMessageEventArgs(ChatChannelType channel, string content)
 {
     Channel = channel;
     Content = content;
 }
Пример #29
0
        private static void OnModuleNWNXChat()
        {
            ChatChannelType channel = (ChatChannelType)NWNXChat.GetChannel();

            // So we're going to play with a couple of channels here.

            // - PlayerTalk, PlayerWhisper, PlayerParty, and PlayerShout are all IC channels. These channels
            //   are subject to emote colouring and language translation. (see below for more info).
            // - PlayerParty is an IC channel with special behaviour. Those outside of the party but within
            //   range may listen in to the party chat. (see below for more information).
            // - PlayerShout sends a holocom message server-wide through the DMTell channel.
            // - PlayerDM echoes back the message received to the sender.

            bool inCharacterChat =
                channel == ChatChannelType.PlayerTalk ||
                channel == ChatChannelType.PlayerWhisper ||
                channel == ChatChannelType.PlayerParty ||
                channel == ChatChannelType.PlayerShout;

            bool messageToDm = channel == ChatChannelType.PlayerDM;

            if (!inCharacterChat && !messageToDm)
            {
                // We don't much care about traffic on the other channels.
                return;
            }

            NWObject sender  = NWNXChat.GetSender();
            string   message = NWNXChat.GetMessage().Trim();

            if (string.IsNullOrWhiteSpace(message))
            {
                // We can't handle empty messages, so skip it.
                return;
            }

            if (ChatCommandService.CanHandleChat(sender, message) ||
                BaseService.CanHandleChat(sender) ||
                CraftService.CanHandleChat(sender) ||
                MarketService.CanHandleChat(sender.Object) ||
                MessageBoardService.CanHandleChat(sender) ||
                ItemService.CanHandleChat(sender))
            {
                // This will be handled by other services, so just bail.
                return;
            }

            if (channel == ChatChannelType.PlayerDM)
            {
                // Simply echo the message back to the player.
                NWNXChat.SendMessage((int)ChatChannelType.ServerMessage, "(Sent to DM) " + message, sender, sender);
                return;
            }

            // At this point, every channel left is one we want to manually handle.
            NWNXChat.SkipMessage();

            // If this is a shout message, and the holonet is disabled, we disallow it.
            if (channel == ChatChannelType.PlayerShout && sender.IsPC &&
                sender.GetLocalInt("DISPLAY_HOLONET") == FALSE)
            {
                NWPlayer player = sender.Object;
                player.SendMessage("You have disabled the holonet and cannot send this message.");
                return;
            }

            List <ChatComponent> chatComponents;

            // Quick early out - if we start with "//" or "((", this is an OOC message.
            bool isOOC = false;

            if (message.Length >= 2 && (message.Substring(0, 2) == "//" || message.Substring(0, 2) == "(("))
            {
                ChatComponent component = new ChatComponent
                {
                    m_Text         = message,
                    m_CustomColour = true,
                    m_ColourRed    = 64,
                    m_ColourGreen  = 64,
                    m_ColourBlue   = 64,
                    m_Translatable = false
                };

                chatComponents = new List <ChatComponent> {
                    component
                };

                if (channel == ChatChannelType.PlayerShout)
                {
                    _.SendMessageToPC(sender, "Out-of-character messages cannot be sent on the Holonet.");
                    return;
                }

                isOOC = true;
            }
            else
            {
                if (EmoteStyleService.GetEmoteStyle(sender) == EmoteStyle.Regular)
                {
                    chatComponents = SplitMessageIntoComponents_Regular(message);
                }
                else
                {
                    chatComponents = SplitMessageIntoComponents_Novel(message);
                }

                // For any components with colour, set the emote colour.
                foreach (ChatComponent component in chatComponents)
                {
                    if (component.m_CustomColour)
                    {
                        component.m_ColourRed   = 0;
                        component.m_ColourGreen = 255;
                        component.m_ColourBlue  = 0;
                    }
                }
            }

            // Now, depending on the chat channel, we need to build a list of recipients.
            bool  needsAreaCheck = false;
            float distanceCheck  = 0.0f;

            // The sender always wants to see their own message.
            List <NWObject> recipients = new List <NWObject> {
                sender
            };

            // This is a server-wide holonet message (that receivers can toggle on or off).
            if (channel == ChatChannelType.PlayerShout)
            {
                recipients.AddRange(NWModule.Get().Players.Where(player => player.GetLocalInt("DISPLAY_HOLONET") == TRUE));
                recipients.AddRange(AppCache.ConnectedDMs);
            }
            // This is the normal party chat, plus everyone within 20 units of the sender.
            else if (channel == ChatChannelType.PlayerParty)
            {
                // Can an NPC use the playerparty channel? I feel this is safe ...
                NWPlayer player = sender.Object;
                recipients.AddRange(player.PartyMembers.Cast <NWObject>().Where(x => x != sender));
                recipients.AddRange(AppCache.ConnectedDMs);

                needsAreaCheck = true;
                distanceCheck  = 20.0f;
            }
            // Normal talk - 20 units.
            else if (channel == ChatChannelType.PlayerTalk)
            {
                needsAreaCheck = true;
                distanceCheck  = 20.0f;
            }
            // Whisper - 4 units.
            else if (channel == ChatChannelType.PlayerWhisper)
            {
                needsAreaCheck = true;
                distanceCheck  = 4.0f;
            }

            if (needsAreaCheck)
            {
                recipients.AddRange(sender.Area.Objects.Where(obj => obj.IsPC && _.GetDistanceBetween(sender, obj) <= distanceCheck));
                recipients.AddRange(AppCache.ConnectedDMs.Where(dm => dm.Area == sender.Area && _.GetDistanceBetween(sender, dm) <= distanceCheck));
            }

            // Now we have a list of who is going to actually receive a message, we need to modify
            // the message for each recipient then dispatch them.

            foreach (NWObject obj in recipients.Distinct())
            {
                // Generate the final message as perceived by obj.

                StringBuilder finalMessage = new StringBuilder();

                if (channel == ChatChannelType.PlayerShout)
                {
                    finalMessage.Append("[Holonet] ");
                }
                else if (channel == ChatChannelType.PlayerParty)
                {
                    finalMessage.Append("[Comms] ");

                    if (obj.IsDM)
                    {
                        // Convenience for DMs - append the party members.
                        finalMessage.Append("{ ");

                        int               count        = 0;
                        NWPlayer          player       = sender.Object;
                        List <NWCreature> partyMembers = player.PartyMembers.ToList();

                        foreach (NWCreature otherPlayer in partyMembers)
                        {
                            string name = otherPlayer.Name;
                            finalMessage.Append(name.Substring(0, Math.Min(name.Length, 10)));

                            ++count;

                            if (count >= 3)
                            {
                                finalMessage.Append(", ...");
                                break;
                            }
                            else if (count != partyMembers.Count)
                            {
                                finalMessage.Append(",");
                            }
                        }

                        finalMessage.Append(" } ");
                    }
                }

                SkillType language = LanguageService.GetActiveLanguage(sender);

                // Wookiees cannot speak any other language (but they can understand them).
                // Swap their language if they attempt to speak in any other language.
                CustomRaceType race = (CustomRaceType)_.GetRacialType(sender);
                if (race == CustomRaceType.Wookiee && language != SkillType.Shyriiwook)
                {
                    LanguageService.SetActiveLanguage(sender, SkillType.Shyriiwook);
                    language = SkillType.Shyriiwook;
                }

                int  colour = LanguageService.GetColour(language);
                byte r      = (byte)(colour >> 24 & 0xFF);
                byte g      = (byte)(colour >> 16 & 0xFF);
                byte b      = (byte)(colour >> 8 & 0xFF);

                if (language != SkillType.Basic)
                {
                    string languageName = LanguageService.GetName(language);
                    finalMessage.Append(ColorTokenService.Custom($"[{languageName}] ", r, g, b));
                }

                foreach (ChatComponent component in chatComponents)
                {
                    string text = component.m_Text;

                    if (component.m_Translatable && language != SkillType.Basic)
                    {
                        text = LanguageService.TranslateSnippetForListener(sender, obj.Object, language, component.m_Text);

                        if (colour != 0)
                        {
                            text = ColorTokenService.Custom(text, r, g, b);
                        }
                    }

                    if (component.m_CustomColour)
                    {
                        text = ColorTokenService.Custom(text, component.m_ColourRed, component.m_ColourGreen, component.m_ColourBlue);
                    }

                    finalMessage.Append(text);
                }

                // Dispatch the final message - method depends on the original chat channel.
                // - Shout and party is sent as DMTalk. We do this to get around the restriction that
                //   the PC needs to be in the same area for the normal talk channel.
                //   We could use the native channels for these but the [shout] or [party chat] labels look silly.
                // - Talk and whisper are sent as-is.

                ChatChannelType finalChannel = channel;

                if (channel == ChatChannelType.PlayerShout || channel == ChatChannelType.PlayerParty)
                {
                    finalChannel = ChatChannelType.DMTalk;
                }

                // There are a couple of colour overrides we want to use here.
                // - One for holonet (shout).
                // - One for comms (party chat).

                string finalMessageColoured = finalMessage.ToString();

                if (channel == ChatChannelType.PlayerShout)
                {
                    finalMessageColoured = ColorTokenService.Custom(finalMessageColoured, 0, 180, 255);
                }
                else if (channel == ChatChannelType.PlayerParty)
                {
                    finalMessageColoured = ColorTokenService.Orange(finalMessageColoured);
                }

                NWNXChat.SendMessage((int)finalChannel, finalMessageColoured, sender, obj);
            }

            MessageHub.Instance.Publish(new OnChatProcessed(sender, channel, isOOC));
        }
Пример #30
0
    public void SendText(ChatChannelType type, string msg)
    {
        if (msg.Length >= 1 && msg.StartsWith("."))
        {
            string commend = "";
            commend = msg.Remove(0, 1);
            if (string.IsNullOrEmpty(commend) || string.IsNullOrEmpty(commend))
            {
                return;
            }

            string[] paras = commend.Split(new string[] { " " }, System.StringSplitOptions.None);

            if (paras.Length <= 0)
            {
                return;
            }

            if (mParamList == null)
            {
                mParamList = new ArrayList();
            }
            else
            {
                mParamList.Clear();
            }

            for (int i = 1; i < paras.Length; i++)
            {
                mParamList.Add(paras[i]);
            }

            if (!GMHandler.Instance.DoHandler(PlayerController.Instance.GetControlObj(), paras[0], mParamList))
            {
                GMActionParam param = new GMActionParam();
                param.Cmd = commend;

                Net.Instance.DoAction((int)Message.MESSAGE_ID.ID_MSG_GM, param);
            }
        }
        else
        {
            //系统频道不允许玩家发送
            if (type == ChatChannelType.ChannelType_System)
            {
                return;
            }

            PlayerDataModule module = ModuleManager.Instance.FindModule <PlayerDataModule>();
            if (module == null)
            {
                return;
            }

            MainFlow mainFlow = GameApp.Instance.GetCurFlow() as MainFlow;
            if (mainFlow != null)
            {
                CSChatMessage packet = new CSChatMessage();
                packet.channel_type = (int)type;
                packet.name         = module.GetName();
                packet.msg          = msg;

                mainFlow.SendToChatServer(packet);
            }
            Role role = PlayerController.Instance.GetControlObj() as Role;
            if (role != null)
            {
                role.Talk(msg);
            }
        }
    }