Exemple #1
0
        public override void ChannelActive(IChannelHandlerContext contex)
        {
            IChannelGroup g = Group;

            if (g == null)
            {
                lock (this)
                {
                    g = Group ?? (Group = new DefaultChannelGroup(contex.Executor));
                }
            }
            base.ChannelActive(contex);
            string msg = $"欢迎 to {0} secure chat server! { Dns.GetHostName()}\n";

            ReplyContent <string> reply = new ReplyContent <string>()
            {
                ConnectionId = $"{contex.Channel.Id}",
                Cmd          = 0,
                Scope        = 0,
                Message      = msg
            };

            contex.WriteAndFlushAsync(reply.ToString());
            g.Add(contex.Channel);
        }
        public string replyContent(string ToUserName, string FromUserName, string Content)
        {
            ReplyContent replycontext = new ReplyContent();

            replycontext.ToUserName   = "******" + ToUserName + "]]>";
            replycontext.FromUserName = "******" + FromUserName + "]]>";
            replycontext.CreateTime   = Util.ConvertDateTimeInt(DateTime.Now);
            replycontext.MsgType      = "<![CDATA[" + FromUserName + "]]>";
            replycontext.Content      = "<![CDATA[" + Content + "]]>";
            //序列化这个对象
            string        str = "";
            XmlSerializer xz  = new XmlSerializer(replycontext.GetType());

            using (StringWriter sw = new StringWriter())
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = false;
                XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
                xns.Add("", "");
                xz.Serialize(sw, replycontext, xns);
                //xz.Serialize(sw, replycontext);
                str = sw.ToString();
            }
            //str = str.Replace("","");
            str = str.Substring(str.IndexOf("<xml>"));
            str = str.Replace("\r\n", "");
            return(str);
        }
Exemple #3
0
        /// <summary>
        /// Gets the bot's reply to a given message.
        /// </summary>
        /// <param name="s">The incoming message.</param>
        public override string GetReply(string msg)
        {
            string reply = String.Empty;

            dominantCategory = ReplyContent.None;
            RequestState prevState   = this.requestState;
            RequestState storedState = RequestState.None;
            bool         blockCore2  = false;

            // Split the message into its component clauses.
            string[] s = Util.Split(msg, EndMarks.ToCharArray(), false);
            lastGreet    = usedGreet; // lastGreet is used to determine if a greeting in the user's message was a statement or a response.
            usedGreet    = false;
            genericReply = false;
            // First, compute a reply to the entire message for consistency. Then look at each individual clause.
            for (int i = -1; i < s.Length; i++)
            {
                // Compute a reply to the current clause.
                string si;
                if (i == -1)
                {
                    si           = GetReplyCore1(msg);
                    mainContent  = dominantCategory;
                    genericReply = true; // The bot will only reply generically if the complete message is indifferent.
                }
                else
                {
                    si = GetReplyCore1(s[i], mainContent);
                }
                reply += si;
                if (!String.IsNullOrEmpty(reply))
                {
                    if (!Char.IsWhiteSpace(reply, reply.Length - 1))
                    {
                        reply += ' ';
                    }
                }
                // If a request has been made, store the request in memory, but do not use it when computing replies to remaining clauses.
                if (requestState != prevState && requestState != RequestState.None)
                {
                    storedState  = requestState;
                    requestState = RequestState.None;
                    blockCore2   = true;
                }
            }
            reply = reply.Trim();
            if (openReply > 0 && !blockCore2)
            {
                bool runCore2 = Util.RandomBoolean(openReply);
                if (runCore2)
                {
                    reply += ' ' + GetReplyCore2();
                }
            }
            reply = reply.Trim();
            reply = Util.Capitalize(reply);
            reply = method1(reply);
            return(reply);
        }
Exemple #4
0
        private void Handler_OnChannelActive(object sender, IChannelHandlerContext e)
        {
            ReplyContent <object> reply = new ReplyContent <object>
            {
                Cmd   = 0,
                Scope = 0,
            };

            Clients.All.SendAsync("", reply);
        }
        private void Handler_OnChannelActive(object sender, IChannelHandlerContext e)
        {
            ReplyContent <object> reply = new ReplyContent <object>
            {
                Cmd   = "active",
                Scope = "tcp",
            };

            Clients.All.Send(reply);
        }
        internal ReplyContent CreatReplyContent(ReplyStatus status, ReplyMethodName methodName, string content)
        {
            ReplyContent replyModel = new ReplyContent()
            {
                ReplyStatus     = status,
                ReplyMethodName = methodName,
                Content         = content
            };

            return(replyModel);
        }
        public Task SendToOthers(string name, string message)
        {
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = "hub",
                Cmd          = "SendToOthers"
            };

            return(Clients.Others.Send(reply));
        }
Exemple #8
0
        public Task SendToOthers(string name, string message)
        {
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = 0,
                Cmd          = 8
            };

            return(Clients.Others.SendAsync("sendToOthers", reply));
        }
        public override Task OnDisconnectedAsync(Exception exception)
        {
            var name = Context.GetHttpContext().Request.Query["name"];
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Message      = $"{name} left the chat",
                Cmd          = "disconnected"
            };

            return(Clients.All.Send(reply));
        }
Exemple #10
0
        public Task Token(string request)
        {
            string connectionId         = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = connectionId,
                Scope        = 0,
                Cmd          = 2
            };

            return(Clients.Caller.SendAsync("receive", reply));
        }
        private async Task <HubConnection> ConnectionAsync()
        {
            int reConnectionCount = 0;

            while (true)
            {
                var HubConnection = new HubConnectionBuilder()
                                    .WithUrl(baseUri)
                                    .WithConsoleLogger()
                                    .Build();

                try {
                    HubConnection.On <string> ("Reply", (Result) => {
                        ReplyContent result = PublicMethod.JsonDeSerialize <ReplyContent> (Result);
                        switch (result.ReplyMethodName)
                        {
                        case ReplyMethodName.Connection:
                            HubToken = result.Content;
                            break;

                        case ReplyMethodName.Subscribe:
                            GroupList.Add(result.Content);
                            break;

                        case ReplyMethodName.DeSubscribe:
                            GroupList.Remove(result.Content);
                            break;

                        default:
                            break;
                        }
                    });
                    HubConnection.On <string> ("Send", (content) => {
                        if (ReceiveMessage != null)
                        {
                            ReceiveMessage.Invoke(this, new ReceiveEventArgs(PublicMethod.JsonDeSerialize <SendContent> (content)));
                        }
                    });
                    await HubConnection.StartAsync();
                    await awaitHubtoken();

                    return(HubConnection);
                } catch (Exception e) {
                    reConnectionCount++;
                    if (reConnectionCount >= 3)
                    {
                        CommunicationError(this, new ErrorEventArgs(true, e.ToString()));
                        return(HubConnection);
                    }
                    await Task.Delay(5000);
                }
            }
        }
Exemple #12
0
        public Task SendToGroup(string groupName, string name, string message)
        {
            string connectionId         = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = 0,
                Cmd          = 2
            };

            return(Clients.Group(groupName).SendAsync("toGroup", reply));
        }
        public Task Token(string request)
        {
            string connectionId         = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = "hub",
                Cmd          = "token"
            };

            return(Clients.Caller.Send(reply));
        }
        public Task SendToConnection(string connectionId, string name, string message)
        {
            string connectionIdFrom     = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = "hub",
                Cmd          = "SendToConnection"
            };

            return(Clients.Client(connectionId).Send(reply));
        }
        public Task Login(RequestCommand request)
        {
            string connectionId         = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = "hub",
                Cmd          = "login"
            };

            return(Clients.Caller.Send(reply));
        }
Exemple #16
0
        public Task SendTo(string connectionId, string message)
        {
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = 0,
                Cmd          = 2,
                Message      = message
            };

            return(Clients.Client(connectionId).SendAsync("sendTo", reply));
        }
        public Task SendToOthersInGroup(string groupName, string name, string message)
        {
            string connectionId         = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = "hub",
                Cmd          = "SendToOthersInGroup"
            };

            return(Clients.OthersInGroup(groupName).Send(reply));
        }
        public async Task LeaveGroup(string groupName, string name)
        {
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = "hub",
                Cmd          = "LeaveGroup"
            };

            await Clients.Group(groupName).Send(reply);

            await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
        }
        public string strreplyContent(string ToUserName, string FromUserName, string Content)
        {
            ReplyContent replycontext = new ReplyContent();

            replycontext.ToUserName   = ToUserName;
            replycontext.FromUserName = FromUserName;
            replycontext.CreateTime   = Util.ConvertDateTimeInt(DateTime.Now);
            replycontext.MsgType      = "text";
            replycontext.Content      = Content;
            string str = string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]</Content></xml>", replycontext.ToUserName, replycontext.FromUserName, replycontext.CreateTime, replycontext.MsgType, replycontext.Content);

            return(str);
        }
        public async Task JoinGroup(string groupName, string name)
        {
            string connectionId         = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = "hub",
                Cmd          = "JoinGroup"
            };
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

            await Clients.Group(groupName).Send(reply);
        }
        private void Subscribe(string channel)
        {
            ISubscriber sub = Redis.GetSubscriber();

            sub.Subscribe(channel, (channel, message) =>
            {
                long id = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                System.Diagnostics.Debug.WriteLine(message);

                ReplyContent <object> reply = new ReplyContent <object>
                {
                };
                reply.Result = new { };
                Clients.All.Send(reply);
            });
        }
        public NotificationHub(ILogger <string> logger)
        {
            _logger = logger;

            Subscribe("new_order");
            ServerHandler.Handler.OnChannelActive += Handler_OnChannelActive;
            ServerHandler.Handler.OnChannelRead0  += (e, s) =>
            {
                ReplyContent <object> reply = new ReplyContent <object>
                {
                    Scope   = "tcp",
                    Cmd     = "push",
                    Message = s
                };
                Clients.All.Send(reply);
            };
        }
Exemple #23
0
        public override Task OnConnectedAsync()
        {
            StringValues id = Context.GetHttpContext().Request.Query["id"];

            Connections.Add(this.Context);

            //var targetUser =  _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName(name));

            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Message      = "连接成功",// $"{CurrentUser.UserName}",
                Scope        = 0,
                Cmd          = 2
            };

            return(Clients.All.SendAsync("connected", reply));
        }
Exemple #24
0
        public Task Handler(RequestCommand request)
        {
            //if (ChannelGroup != null && ChannelGroup.Count > 0)
            //{
            //    ChannelGroup.WriteAndFlushAsync(request, ChannelMatchers.All());
            //}
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = request.Scope,
                Message      = request.Message,
                Cmd          = request.Cmd
            };

            _eventBus.PublishAsync(typeof(object), reply);

            return(Clients.Caller.SendAsync("receive", reply));
        }
        public Task Handler(string scope, string cmd, string message)
        {
            if (ChannelGroup != null && ChannelGroup.Count > 0)
            {
                ChannelGroup.WriteAndFlushAsync(message, ChannelMatchers.All());
            }

            string connectionId         = Context.ConnectionId;
            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Scope        = scope,
                Message      = message,
                Cmd          = "handler"
            };

            return(Clients.Caller.Send(reply));
        }
        public override Task OnConnectedAsync()
        {
            StringValues names = Context.GetHttpContext().Request.Query["name"];
            string       name  = names.Count >= 1 ? names[0] : "unknown";

            Connections.Add(this.Context);


            ReplyContent <object> reply = new ReplyContent <object>
            {
                ConnectionId = Context.ConnectionId,
                Message      = $"{name} join the chat",
                Scope        = "hub",
                Cmd          = "connected"
            };

            return(Clients.All.Send(reply));
        }
Exemple #27
0
        public string resText(RequestXML requestXML)
        {
            string resxml = "";
            Reply  reply  = new Reply();

            if (requestXML.Content.Equals("1"))
            {
                var mediaId = new MultimediaService().UploadMultimedia(GlobalToken.AccessToken, "image", "test1.jpg");
                resxml = reply.strreplyImage(requestXML.FromUserName, requestXML.ToUserName, mediaId);
                //Util.WriteTxt(resxml);
            }
            if (requestXML.Content.Equals("2"))
            {
                resxml = reply.strreplyImage(requestXML.FromUserName, requestXML.ToUserName, "L7vNwJMTBWViMx7fQeFsHSzXv9Sgz1E9ECvNq1qnjTRSp9tF7p7Owc_60zSknHMG");
                //Util.WriteTxt(resxml);
            }
            if (requestXML.Content.Equals("3"))
            {
                var mediaId = new MultimediaService().UploadMultimedia(GlobalToken.AccessToken, "voice", "test1.amr");
                resxml = reply.strreplyVoice(requestXML.FromUserName, requestXML.ToUserName, mediaId);
                // Util.WriteTxt(resxml);
            }
            if (requestXML.Content.Equals("4"))
            {
                new PushMessageService().pushMessage();
                //Util.WriteTxt(resxml);
            }
            if (requestXML.Content.Equals("5"))
            {
                new PushMessageService().pushImage();
                //Util.WriteTxt(resxml);
            }
            if (requestXML.Content.Equals("6"))
            {
                resxml = new ReplyContent().replyContent(requestXML.FromUserName, requestXML.ToUserName, "测试");
            }
            return(resxml);
        }
Exemple #28
0
        protected override void ChannelRead0(IChannelHandlerContext contex, string msg)
        {
            if (!RequestCommand <string> .TryGetCommand(msg, out RequestCommand <string> cmd))
            {
                contex.WriteAndFlushAsync("无法识别的JSON指令;" + msg);
                return;
            }
            ReplyContent <string> reply = new ReplyContent <string>()
            {
                ConnectionId = $"{contex.Channel}",
                Cmd          = cmd.Cmd,
                Scope        = cmd.Scope
            };

            //OnMessageReceived
            // Group.WriteAndFlushAsync(reply, new AllChannelMatcher(contex.Channel.Id));
            contex.WriteAndFlushAsync(reply.ToString());
            OnMessageReceived(contex);
            if (string.Equals("bye", msg, StringComparison.OrdinalIgnoreCase))
            {
                contex.CloseAsync();
            }
        }
Exemple #29
0
        /// <summary>
        /// Core logic for computing replies to messages. This method scans the user's message and attempts to construct an appropriate response. If the dominant category of the user's message
        /// is the same as the specified ReplyContent, a reply will not be generated for this message.
        /// </summary>
        /// <param name="s">The message to reply to.</param>
        /// <returns>A suitable reply, mostly in lowercase except for special cases.</returns>
        private string GetReplyCore1(string s, ReplyContent c)
        {
            dominantCategory = ReplyContent.None;
            // Using Reinterpret, compile the following structures: words, the list of individual words and separators; rwords, the same list but case-sensitive; message, the complete reinterpreted message.
            string[] words0 = Util.Split(s, Separators.ToCharArray(), true);
            string[] rwords = new string[words0.Length * 2];
            string[] words  = new string[words0.Length * 2];
            int      wi     = 0;

            for (int i = 0; i < words0.Length; i++)
            {
                string w  = Reinterpret(words0[i]);
                string rw = SensitiveReinterpret(words0[i]); // rwords[i] is defined as words[i] with the capitalization the user used when typing the word
                if (w.Contains(' '))
                {
                    string[] split = w.Split(' '); string[] rsplit = rw.Split(' ');
                    words[wi] = split[0]; rwords[wi] = rsplit[0]; wi++;
                    words[wi] = split[1]; rwords[wi] = rsplit[1]; wi++;
                }
                else
                {
                    words[wi] = w; rwords[wi] = rw; wi++;
                }
            }
            rwords = Util.RefineLength(rwords);
            words  = Util.RefineLength(words);
            string[] withspace = (string[])words.Clone();
            for (int i = 0; i < words.Length - 1; i++)
            {
                if (!EndMarks.Contains(words[i + 1]))
                {
                    withspace[i] += ' ';
                }
            }
            string message = String.Concat(withspace);

            // Scan the user message for responses to the bot's most recent request, if there is one. If it returns a response, it must assign dominantCategory accordingly or it will default to None.
            switch (requestState)
            {
            case RequestState.Name:
                if (c == ReplyContent.Name)
                {
                    break;
                }
                int r = SearchName(words, message);
                if (r == 1)
                {
                    openReply = 100; dominantCategory = ReplyContent.Name; return(Greet(true, true, 0, 0));
                }
                if (r == PRIVATE)
                {
                    openReply = 100; return(GenericReply());
                }
                break;

            case RequestState.Mood:
                if (c == ReplyContent.Mood)
                {
                    break;
                }
                int moodResponse = SearchMood(words, message);
                if (moodResponse != NO_MOOD)
                {
                    openReply = 100; dominantCategory = ReplyContent.Mood; return(ReplyMood(words, message));
                }
                break;

            case RequestState.Place:
                if (c == ReplyContent.Place)
                {
                    break;
                }
                int rplace = SearchPlace(words, rwords, message);
                if (rplace == 1)
                {
                    dominantCategory = ReplyContent.Place; return(ReplyPlace());
                }
                if (rplace == PRIVATE)
                {
                    openReply = 100; return(GenericReply());
                }
                break;
            }
            // Scan the user message for recognised reply categories.
            for (int i = 0; i < contentCount; i++)
            {
                replyContent[i] = 0;
            }
            // Greeting
            if (Util.IndexOfAny(message, ReadGreetings) > -1 || message.IndexOf("good day") == 0) // "Good day" is recognised as a greeting only if it is at the start of a sentence.
            {
                replyContent[(int)ReplyContent.Greeting] += 13;
            }
            if (!knowsName)
            {
                replyContent[(int)ReplyContent.Greeting] += 2;
            }
            // Name
            if (Util.IndexOfAny(Refine(message), ReadGivenName) > -1)
            {
                if (SearchName(words, message) == 1)
                {
                    replyContent[(int)ReplyContent.Name] += 37;
                }
            }
            // Mood
            int moodMod = SearchMood(words, message);

            if (moodMod != NO_MOOD)
            {
                replyContent[(int)ReplyContent.Mood] += (Math.Abs(moodMod) * 7) + 3;
            }
            // Place
            if (Util.IndexOfAny(Refine(message), ReadGivenPlace) > -1)
            {
                if (SearchPlace(words, rwords, message) == 1)
                {
                    replyContent[(int)ReplyContent.Place] += 31;
                }
            }
            // Compute a dominant category set. Currently only supports one dominant category.
            int categoryIndex = 0;
            int maxValue      = -1;

            replyContent[(int)ReplyContent.NA] = -2;
            for (int i = 0; i < contentCount; i++)
            {
                if (replyContent[i] > maxValue)
                {
                    maxValue      = replyContent[i];
                    categoryIndex = i;
                }
            }
            dominantCategory = (ReplyContent)categoryIndex;
            // Check that we are not repeating a response to the main message. Note that if s is the main message itself, the reply content of c is "not applicable" (NA).
            if (dominantCategory == c)
            {
                return(String.Empty);
            }
            // Compute a response based on the dominant category.
            openReply = 0;
            switch (dominantCategory)
            {
            case ReplyContent.Mood:     // Express feelings on the user's mood.
            { openReply = 100; return(ReplyMood(words, message)); }

            case ReplyContent.Name:     // Greet the user by name, request the user's mood.
                return(Greet(true, true, 0, 100));

            case ReplyContent.Greeting:     // Greet the user if it was an initial greeting; otherwise leave the reply open. Depends on lastGreet.
                if (lastGreet)
                {
                    openReply = 100; return(String.Empty);
                }
                else
                {
                    return(Greet(true, Util.RandomBoolean(60)));
                }

            case ReplyContent.Place:
                return(ReplyPlace());

            default:
                openReply = 100; dominantCategory = ReplyContent.None; return(GenericReply());
            }
        }
        private async Task <ConnectionInfo> ConnectionAsync(string baseUrl, ConnectionType type = ConnectionType.Base)
        {
            ConnectionInfo connectionObject = new ConnectionInfo()
            {
                Url            = baseUrl,
                ConnectionType = type
            };

            while (true)
            {
                connectionObject.HubConnection = new HubConnectionBuilder()
                                                 .WithUrl(baseUrl)
                                                 .WithConsoleLogger()
                                                 .Build();

                try
                {
                    connectionObject.HubConnection.On <string>("Reply", (Result) =>
                    {
                        ReplyContent result = PublicMethod.JsonDeSerialize <ReplyContent>(Result);
                        switch (result.ReplyMethodName)
                        {
                        case ReplyMethodName.Connection:
                            connectionObject.HubToken = result.Content;
                            break;

                        case ReplyMethodName.Subscribe:
                            break;

                        default:
                            break;
                        }
                    });
                    connectionObject.HubConnection.On <string>("Send", content =>
                    {
                        if (!_isTerminal)
                        {
                            _connectionList.Where(x => x.ConnectionType == ConnectionType.Self).FirstOrDefault().HubConnection.InvokeAsync("Send", content, true);
                        }
                    });
                    connectionObject.HubConnection.Closed += (e) =>
                    {
                        if (connectionObject.ConnectionType == ConnectionType.SubHub)
                        {
                            _connectionList.Remove(connectionObject);
                        }
                        DisposeConnection(connectionObject).GetAwaiter().GetResult();
                        ReConnection(connectionObject).GetAwaiter().GetResult();
                    };
                    if (type == ConnectionType.SubHub)
                    {
                        // connectionObject.HubConnection.Connected += () =>
                        // {
                        //     var task = Task.Run(() =>
                        //     {
                        //         DateTime timer = DateTime.Now;
                        //         while (DateTime.Now.Subtract(timer).Minutes < 3)
                        //         {
                        //             Task.Delay(10000).GetAwaiter().GetResult();
                        //         }
                        //         DisposeConnection(connectionObject).GetAwaiter().GetResult();
                        //     });
                        //     return Task.Run(() => { });
                        // };
                    }

                    await connectionObject.HubConnection.StartAsync();

                    while (String.IsNullOrEmpty(connectionObject.HubToken))
                    {
                        Task.Delay(100).GetAwaiter().GetResult();
                    }
                    return(connectionObject);
                }
                catch (Exception)
                {
                    await Task.Delay(5000);
                }
            }
        }