コード例 #1
0
        public virtual async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            //进行 APM 记录
            ExecuteStatTime = SystemTime.Now;

            DataOperation apm = new DataOperation(PostModel?.DomainId);

            await apm.SetAsync(NeuCharApmKind.Message_Request.ToString(), 1, tempStorage : OpenId).ConfigureAwait(false);

            if (CancelExcute)
            {
                return;
            }

            await OnExecutingAsync(cancellationToken).ConfigureAwait(false);

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                await BuildResponseMessageAsync(cancellationToken).ConfigureAwait(false);

                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
                await apm.SetAsync(NeuCharApmKind.Message_SuccessResponse.ToString(), 1, tempStorage : OpenId).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                apm.SetAsync(NeuCharApmKind.Message_Exception.ToString(), 1, tempStorage: OpenId).ConfigureAwait(false).GetAwaiter().GetResult();
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                await OnExecutedAsync(cancellationToken).ConfigureAwait(false);

                await apm.SetAsync(NeuCharApmKind.Message_ResponseMillisecond.ToString(), (SystemTime.Now - this.ExecuteStatTime).TotalMilliseconds, tempStorage : OpenId).ConfigureAwait(false);
            }

            //await Task.Run(() => this.Execute()).ConfigureAwait(false);
        }
コード例 #2
0
        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="postDataDocument"></param>
        /// <param name="postModel"></param>
        /// <returns></returns>
        public override XDocument Init(XDocument postDataDocument, IEncryptPostModel postModel)
        {
            //进行加密判断并处理
            _postModel = postModel as PostModel ?? new PostModel();
            var postDataStr = postDataDocument.ToString();

            XDocument decryptDoc = postDataDocument;

            if (_postModel != null && !_postModel.Token.IsNullOrWhiteSpace() &&
                postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value))
            {
                //使用了加密
                UsingEcryptMessage    = true;
                EcryptRequestDocument = postDataDocument;

                WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId);
                string        msgXml   = null;
                var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

                //判断result类型
                if (result != 0)
                {
                    //验证没有通过,取消执行
                    CancelExcute = true;
                    return(null);
                }

                if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value))
                {
                    //TODO:使用了兼容模式,进行验证即可
                    UsingCompatibilityModelEcryptMessage = true;
                }

                decryptDoc = XDocument.Parse(msgXml);//完成解密
            }

            RequestMessage = RequestMessageFactory.GetRequestEntity(decryptDoc);
            if (UsingEcryptMessage)
            {
                RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value;
            }


            //记录上下文
            if (MessageContextGlobalConfig.UseMessageContext)
            {
                GlobalMessageContext.InsertMessage(RequestMessage);
            }

            return(decryptDoc);
        }
コード例 #3
0
        /// <summary>
        /// 执行微信请求(如果没有被 CancelExcute=true 中断)
        /// </summary>
        public void Execute()
        {
            //进行 APM 记录
            ExecuteStatTime = SystemTime.Now;

            DataOperation apm = new DataOperation(PostModel?.DomainId);

            apm.Set(NeuCharApmKind.Message_Request.ToString(), 1, tempStorage: OpenId);

            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                BuildResponseMessage();

                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
                apm.Set(NeuCharApmKind.Message_SuccessResponse.ToString(), 1, tempStorage: OpenId);
            }
            catch (Exception ex)
            {
                apm.Set(NeuCharApmKind.Message_Exception.ToString(), 1, tempStorage: OpenId);
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
                apm.Set(NeuCharApmKind.Message_ResponseMillisecond.ToString(), (SystemTime.Now - this.ExecuteStatTime).TotalMilliseconds, tempStorage: OpenId);
            }
        }
コード例 #4
0
        public override XDocument Init(XDocument postDataDocument, IEncryptPostModel postModel)
        {
            _postModel = postModel as PostModel ?? new PostModel();


            UsingEcryptMessage = true;//Work中消息都是强制加密的
            var postDataStr = postDataDocument.ToString();

            EncryptPostData = RequestMessageFactory.GetEncryptPostData(postDataStr);

            //2、解密:获得明文字符串
            WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.CorpId);
            string        msgXml   = null;
            var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

            /* msgXml
             * <xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName>
             * <FromUserName><![CDATA[001]]></FromUserName>
             * <CreateTime>1412585107</CreateTime>
             * <MsgType><![CDATA[text]]></MsgType>
             * <Content><![CDATA[你好]]></Content>
             * <MsgId>4299263624800632834</MsgId>
             * <AgentID>2</AgentID>
             * </xml>
             */

            //判断result类型
            if (result != 0)
            {
                //验证没有通过,取消执行
                CancelExcute = true;
                return(null);
            }

            var requestDocument = XDocument.Parse(msgXml);

            RequestMessage = RequestMessageFactory.GetRequestEntity(requestDocument);

            //记录上下文
            if (RequestMessage.MsgType != RequestMsgType.Unknown && MessageContextGlobalConfig.UseMessageContext)
            {
                GlobalMessageContext.InsertMessage(RequestMessage);
            }

            return(requestDocument);
        }
コード例 #5
0
        ///// <summary>
        ///// 根据当前的RequestMessage创建指定类型的ResponseMessage
        ///// </summary>
        ///// <typeparam name="TR">基于ResponseMessageBase的响应消息类型</typeparam>
        ///// <returns></returns>
        //public ResponseMessageText CreateResponseMessage<TR>(string content) where TR : ResponseMessageText
        //{
        //    if (RequestMessage == null)
        //    {
        //        return null;
        //    }

        //    var responseMessage = RequestMessage.CreateResponseMessage<TR>();
        //    responseMessage.Content = content;
        //    return responseMessage;
        //}

        #endregion

        /// <summary>
        /// 执行微信请求
        /// </summary>
        public override void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                #region NeuChar 执行过程

                //TODO:Neuchar:在这里先做一次NeuChar标准的判断

                var neuralSystem = NeuralSystem.Instance;

                #region 添加模拟数据

                //var fakeMessageHandlerNode = new MessageHandlerNode()
                //{
                //    Name = "MessageHandlerNode",
                //};

                //fakeMessageHandlerNode.Config.MessagePair.Add(new MessagePair()
                //{
                //    Request = new Request
                //    {
                //        Type = RequestMsgType.Text,
                //        Keywords = new List<string>() { "nc", "neuchar" }
                //    },
                //    Response = new Response() { Type = ResponseMsgType.Text, Content = "这条消息来自NeuChar\r\n\r\n当前时间:{now}" }
                //});

                //fakeMessageHandlerNode.Config.MessagePair.Add(new MessagePair()
                //{
                //    Request = new Request
                //    {
                //        Type = RequestMsgType.Text,
                //        Keywords = new List<string>() { "senparc", "s" }
                //    },
                //    Response = new Response() { Type = ResponseMsgType.Text, Content = "这条消息同样来自NeuChar\r\n\r\n当前时间:{now}" }
                //});

                //neuralSystem.Root.SetChildNode(fakeMessageHandlerNode);//TODO:模拟添加(应当在初始化的时候就添加)

                #endregion

                var messageHandlerNode = neuralSystem.GetNode("MessageHandlerNode");

                //不同类型请求的委托
                Func <IResponseMessageBase> executeFunc = () =>
                {
                    IResponseMessageBase responseMessage = null;
                    switch (RequestMessage.MsgType)
                    {
                    case RequestMsgType.Text:
                    {
                        var requestMessage = RequestMessage as RequestMessageText;
                        responseMessage = OnTextOrEventRequest(requestMessage) ?? OnTextRequest(requestMessage);
                    }
                    break;

                    case RequestMsgType.Location:
                        responseMessage = OnLocationRequest(RequestMessage as RequestMessageLocation);
                        break;

                    case RequestMsgType.Image:
                        responseMessage = OnImageRequest(RequestMessage as RequestMessageImage);
                        break;

                    case RequestMsgType.Voice:
                        responseMessage = OnVoiceRequest(RequestMessage as RequestMessageVoice);
                        break;

                    case RequestMsgType.Video:
                        responseMessage = OnVideoRequest(RequestMessage as RequestMessageVideo);
                        break;

                    case RequestMsgType.Link:
                        responseMessage = OnLinkRequest(RequestMessage as RequestMessageLink);
                        break;

                    case RequestMsgType.ShortVideo:
                        responseMessage = OnShortVideoRequest(RequestMessage as RequestMessageShortVideo);
                        break;

                    case RequestMsgType.File:
                        responseMessage = OnFileRequest(RequestMessage as RequestMessageFile);
                        break;

                    case RequestMsgType.NeuChar:
                        responseMessage = OnNeuCharRequest(RequestMessage as RequestMessageNeuChar);
                        break;

                    case RequestMsgType.Unknown:
                        responseMessage = OnUnknownTypeRequest(RequestMessage as RequestMessageUnknownType);
                        break;

                    case RequestMsgType.Event:
                    {
                        var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                        responseMessage = OnTextOrEventRequest(requestMessageText)
                                          ?? OnEventRequest(RequestMessage as IRequestMessageEventBase);
                    }
                    break;

                    default:
                        Weixin.WeixinTrace.SendCustomLog("NeuChar", "未知的MsgType请求类型" + RequestMessage.MsgType);
                        //throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                        break;
                    }

                    return(responseMessage);
                };

                if (messageHandlerNode != null && messageHandlerNode is MessageHandlerNode)
                {
                    Weixin.WeixinTrace.SendCustomLog("NeuChar", "进入判断流程 ((MessageHandlerNode)messageHandlerNode).GetResponseMessage");

                    ResponseMessage = ((MessageHandlerNode)messageHandlerNode).GetResponseMessage(RequestMessage, executeFunc);
                }

                //如果没有得到结果,则继续运行编译好的代码
                if (ResponseMessage == null)
                {
                    Weixin.WeixinTrace.SendCustomLog("NeuChar", "executeFunc()");
                    ResponseMessage = executeFunc();//直接执行
                }

                #endregion

                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
            }
        }
コード例 #6
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="postDataDocument"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public override XDocument Init(XDocument postDataDocument, object postData = null)
        {
            //进行加密判断并处理
            _postModel = postData as PostModel;
            var postDataStr = postDataDocument.ToString();

            XDocument decryptDoc = postDataDocument;

            if (_postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value))
            {
                //使用了加密
                UsingEcryptMessage    = true;
                EcryptRequestDocument = postDataDocument;

                WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId);
                string        msgXml   = null;
                var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

                //判断result类型
                if (result != 0)
                {
                    //验证没有通过,取消执行
                    CancelExcute = true;
                    return(null);
                }

                if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value))
                {
                    //TODO:使用了兼容模式,进行验证即可
                    UsingCompatibilityModelEcryptMessage = true;
                }

                decryptDoc = XDocument.Parse(msgXml);//完成解密
            }

            RequestMessage = RequestMessageFactory.GetRequestEntity(decryptDoc);
            if (UsingEcryptMessage)
            {
                RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value;
            }


            //TODO:分布式系统中本地的上下文会有同步问题,需要同步使用远程的储存
            if (MessageContextGlobalConfig.UseMessageContext)
            {
                var omit = OmitRepeatedMessageFunc == null || OmitRepeatedMessageFunc(RequestMessage);

                lock (MessageContextGlobalConfig.OmitRepeatLock)//TODO:使用分布式锁
                {
                    #region 消息去重

                    if (omit &&
                        OmitRepeatedMessage &&
                        CurrentMessageContext.RequestMessages.Count > 0
                        //&& !(RequestMessage is RequestMessageEvent_Merchant_Order)批量订单的MsgId可能会相同
                        )
                    {
                        //lastMessage必定有值(除非极端小的过期时间条件下,几乎不可能发生)
                        var lastMessage = CurrentMessageContext.RequestMessages[CurrentMessageContext.RequestMessages.Count - 1];

                        if (
                            //使用MsgId去重
                            (lastMessage.MsgId != 0 && lastMessage.MsgId == RequestMessage.MsgId) ||
                            //使用CreateTime去重(OpenId对象已经是同一个)
                            (lastMessage.MsgId == RequestMessage.MsgId &&
                             lastMessage.CreateTime == RequestMessage.CreateTime &&
                             lastMessage.MsgType == RequestMessage.MsgType)
                            )
                        {
                            MarkRepeatedMessage();//标记为已重复
                        }

                        //判断特殊事件
                        if (!MessageIsRepeated &&
                            lastMessage is RequestMessageEventBase &&
                            RequestMessage is RequestMessageEventBase &&
                            (lastMessage as RequestMessageEventBase).Event == (RequestMessage as RequestMessageEventBase).Event
                            )
                        {
                            var lastEventMessage    = lastMessage as RequestMessageEventBase;
                            var currentEventMessage = RequestMessage as RequestMessageEventBase;
                            switch (lastEventMessage.Event)
                            {
                            case Event.user_get_card:    //领取事件推送
                                //文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025274
                                //问题反馈:https://github.com/JeffreySu/WeiXinMPSDK/issues/1106
                                var lastGetUserCardMessage    = lastMessage as RequestMessageEvent_User_Get_Card;
                                var currentGetUserCardMessage = RequestMessage as RequestMessageEvent_User_Get_Card;
                                if (lastGetUserCardMessage.UserCardCode == currentGetUserCardMessage.UserCardCode &&
                                    lastGetUserCardMessage.CardId == currentGetUserCardMessage.CardId)
                                {
                                    MarkRepeatedMessage();    //标记为已重复
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }

                    #endregion

                    //在消息没有被去重的情况下记录上下文
                    if (!MessageIsRepeated)
                    {
                        GlobalMessageContext.InsertMessage(RequestMessage);
                    }
                }
            }


            return(decryptDoc);
        }
コード例 #7
0
        ///// <summary>
        ///// 根据当前的RequestMessage创建指定类型的ResponseMessage
        ///// </summary>
        ///// <typeparam name="TR">基于ResponseMessageBase的响应消息类型</typeparam>
        ///// <returns></returns>
        //public ResponseMessageText CreateResponseMessage<TR>(string content) where TR : ResponseMessageText
        //{
        //    if (RequestMessage == null)
        //    {
        //        return null;
        //    }

        //    var responseMessage = RequestMessage.CreateResponseMessage<TR>();
        //    responseMessage.Content = content;
        //    return responseMessage;
        //}

        #endregion

        /// <summary>
        /// 执行微信请求
        /// </summary>
        public override void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                #region NeuChar 执行过程
                //TODO:Neuchar:在这里先做一次NeuChar标准的判断

                var neuralSystem       = NeuralSystem.Instance;
                var messageHandlerNode = neuralSystem.GetNode("MessageHandlerNode") as MessageHandlerNode;

                messageHandlerNode = messageHandlerNode ?? new MessageHandlerNode();

                #region 添加模拟数据

                //var fakeMessageHandlerNode = new MessageHandlerNode()
                //{
                //    Name = "MessageHandlerNode",
                //};

                //fakeMessageHandlerNode.Config.MessagePair.Add(new MessagePair()
                //{
                //    Request = new Request
                //    {
                //        Type = RequestMsgType.Text,
                //        Keywords = new List<string>() { "nc", "neuchar" }
                //    },
                //    Response = new Response() { Type = ResponseMsgType.Text, Content = "这条消息来自NeuChar\r\n\r\n当前时间:{now}" }
                //});

                //fakeMessageHandlerNode.Config.MessagePair.Add(new MessagePair()
                //{
                //    Request = new Request
                //    {
                //        Type = RequestMsgType.Text,
                //        Keywords = new List<string>() { "senparc", "s" }
                //    },
                //    Response = new Response() { Type = ResponseMsgType.Text, Content = "这条消息同样来自NeuChar\r\n\r\n当前时间:{now}" }
                //});

                //neuralSystem.Root.SetChildNode(fakeMessageHandlerNode);//TODO:模拟添加(应当在初始化的时候就添加)

                #endregion

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Text:
                {
                    var requestMessage = RequestMessage as RequestMessageText;

                    ResponseMessage = messageHandlerNode.Execute(requestMessage, this, Config.SenparcWeixinSetting.WeixinAppId) ??
                                      (OnTextOrEventRequest(requestMessage) ?? OnTextRequest(requestMessage));
                }
                break;

                case RequestMsgType.Location:
                    ResponseMessage = OnLocationRequest(RequestMessage as RequestMessageLocation);
                    break;

                case RequestMsgType.Image:
                    ResponseMessage = messageHandlerNode.Execute(RequestMessage, this, Config.SenparcWeixinSetting.WeixinAppId) ?? OnImageRequest(RequestMessage as RequestMessageImage);
                    break;

                case RequestMsgType.Voice:
                    ResponseMessage = OnVoiceRequest(RequestMessage as RequestMessageVoice);
                    break;

                case RequestMsgType.Video:
                    ResponseMessage = OnVideoRequest(RequestMessage as RequestMessageVideo);
                    break;

                case RequestMsgType.Link:
                    ResponseMessage = OnLinkRequest(RequestMessage as RequestMessageLink);
                    break;

                case RequestMsgType.ShortVideo:
                    ResponseMessage = OnShortVideoRequest(RequestMessage as RequestMessageShortVideo);
                    break;

                case RequestMsgType.File:
                    ResponseMessage = OnFileRequest(RequestMessage as RequestMessageFile);
                    break;

                case RequestMsgType.NeuChar:
                    ResponseMessage = OnNeuCharRequest(RequestMessage as RequestMessageNeuChar);
                    break;

                case RequestMsgType.Unknown:
                    ResponseMessage = OnUnknownTypeRequest(RequestMessage as RequestMessageUnknownType);
                    break;

                case RequestMsgType.Event:
                {
                    var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                    ResponseMessage = OnTextOrEventRequest(requestMessageText)
                                      ?? OnEventRequest(RequestMessage as IRequestMessageEventBase);
                }
                break;

                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                }

                #endregion

                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
            }
        }
コード例 #8
0
        /// <summary>
        /// 执行微信请求
        /// </summary>
        public override void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                #region NeuChar 执行过程

                var neuralSystem       = NeuralSystem.Instance;
                var messageHandlerNode = neuralSystem.GetNode("MessageHandlerNode") as MessageHandlerNode;

                messageHandlerNode = messageHandlerNode ?? new MessageHandlerNode();


                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Text:
                {
                    SenparcTrace.SendCustomLog("wxTest-request", RequestMessage.ToJson());
                    ResponseMessage = messageHandlerNode.Execute(RequestMessage, this, Config.SenparcWeixinSetting.WxOpenAppId) ??
                                      OnTextRequest(RequestMessage as RequestMessageText);
                    SenparcTrace.SendCustomLog("wxTest-response", ResponseMessage.ToJson());
                }
                break;

                case RequestMsgType.Image:
                {
                    ResponseMessage = messageHandlerNode.Execute(RequestMessage, this, Config.SenparcWeixinSetting.WxOpenAppId) ??
                                      OnImageRequest(RequestMessage as RequestMessageImage);
                }
                break;

                case RequestMsgType.Event:
                {
                    OnEventRequest(RequestMessage as IRequestMessageEventBase);
                }
                break;

                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                }


                #endregion

                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
            }
        }
コード例 #9
0
        public override void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Unknown:    //第三方回调
                {
                    if (RequestMessage is IThirdPartyInfoBase)
                    {
                        var thirdPartyInfo = RequestMessage as IThirdPartyInfoBase;
                        TextResponseMessage = OnThirdPartyEvent(thirdPartyInfo);
                    }
                    else
                    {
                        throw new WeixinException("没有找到合适的消息类型。");
                    }
                }
                break;

                //以下是普通信息
                case RequestMsgType.Text:
                {
                    var requestMessage = RequestMessage as RequestMessageText;
                    ResponseMessage = OnTextOrEventRequest(requestMessage) ?? OnTextRequest(requestMessage);
                }
                break;

                case RequestMsgType.Location:
                    ResponseMessage = OnLocationRequest(RequestMessage as RequestMessageLocation);
                    break;

                case RequestMsgType.Image:
                    ResponseMessage = OnImageRequest(RequestMessage as RequestMessageImage);
                    break;

                case RequestMsgType.Voice:
                    ResponseMessage = OnVoiceRequest(RequestMessage as RequestMessageVoice);
                    break;

                case RequestMsgType.Video:
                    ResponseMessage = OnVideoRequest(RequestMessage as RequestMessageVideo);
                    break;

                case RequestMsgType.ShortVideo:
                    ResponseMessage = OnShortVideoRequest(RequestMessage as RequestMessageShortVideo);
                    break;

                case RequestMsgType.File:
                    ResponseMessage = OnFileRequest(RequestMessage as RequestMessageFile);
                    break;

                case RequestMsgType.Event:
                {
                    var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                    ResponseMessage = OnTextOrEventRequest(requestMessageText) ?? OnEventRequest(RequestMessage as IRequestMessageEventBase);
                }
                break;

                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                }

                //记录上下文
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null)
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
            }
        }
コード例 #10
0
        /// <summary>
        /// 【异步方法】执行微信请求
        /// </summary>
        public override async Task ExecuteAsync()
        {
            if (CancelExcute)
            {
                return;
            }

            await OnExecutingAsync();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }


                #region NeuChar 执行过程

                var weixinAppId = this._postModel.AppId;

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Text:
                {
                    try
                    {
                        var requestMessage = RequestMessage as RequestMessageText;
                        ResponseMessage = await CurrentMessageHandlerNode.ExecuteAsync(requestMessage, this, weixinAppId)
                                          ?? ((await(OnTextOrEventRequestAsync(requestMessage))
                                               ?? (await OnTextRequestAsync(requestMessage))));
                    }
                    catch (Exception ex)
                    {
                        SenparcTrace.SendCustomLog("mp-response error", ex.Message + "\r\n|||\r\n" + (ex.InnerException != null ? ex.InnerException.ToString() : ""));
                    }
                }
                break;

                case RequestMsgType.Location:
                    ResponseMessage = await OnLocationRequestAsync(RequestMessage as RequestMessageLocation);

                    break;

                case RequestMsgType.Image:

                    WeixinTrace.SendCustomLog("NeuChar Image", $"appid:{weixinAppId}");

                    ResponseMessage = await CurrentMessageHandlerNode.ExecuteAsync(RequestMessage, this, weixinAppId) ?? await OnImageRequestAsync(RequestMessage as RequestMessageImage);

                    break;

                case RequestMsgType.Voice:
                    ResponseMessage = await OnVoiceRequestAsync(RequestMessage as RequestMessageVoice);

                    break;

                case RequestMsgType.Video:
                    ResponseMessage = await OnVideoRequestAsync(RequestMessage as RequestMessageVideo);

                    break;

                case RequestMsgType.Link:
                    ResponseMessage = await OnLinkRequestAsync(RequestMessage as RequestMessageLink);

                    break;

                case RequestMsgType.ShortVideo:
                    ResponseMessage = await OnShortVideoRequestAsync(RequestMessage as RequestMessageShortVideo);

                    break;

                case RequestMsgType.File:
                    ResponseMessage = await OnFileRequestAsync(RequestMessage as RequestMessageFile);

                    break;

                case RequestMsgType.NeuChar:
                    ResponseMessage = await OnNeuCharRequestAsync(RequestMessage as RequestMessageNeuChar);

                    break;

                case RequestMsgType.Unknown:
                    ResponseMessage = await OnUnknownTypeRequestAsync(RequestMessage as RequestMessageUnknownType);

                    break;

                case RequestMsgType.Event:
                {
                    var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                    ResponseMessage = await CurrentMessageHandlerNode.ExecuteAsync(RequestMessage, this, weixinAppId) ??
                                      await OnTextOrEventRequestAsync(requestMessageText) ??
                                      (await OnEventRequestAsync(RequestMessage as IRequestMessageEventBase));
                }
                break;

                default:
                    Weixin.WeixinTrace.SendCustomLog("NeuChar", "未知的MsgType请求类型" + RequestMessage.MsgType);
                    //throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                    break;
                }

                #endregion


                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                await OnExecutedAsync();
            }
        }
コード例 #11
0
ファイル: MessageHandlerAsync.cs プロジェクト: wyh0395/Berry
        /// <summary>
        /// 【异步方法】执行微信请求
        /// </summary>
        public override async Task ExecuteAsync()
        {
            if (CancelExcute)
            {
                return;
            }

            await OnExecutingAsync();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }


                #region NeuChar 执行过程

                //TODO:Neuchar:在这里先做一次NeuChar标准的判断

                var neuralSystem = NeuralSystem.Instance;

                //获取当前设置节点
                var messageHandlerNode = neuralSystem.GetNode("MessageHandlerNode");

                //Weixin.WeixinTrace.SendCustomLog("NeuChar JSON",
                //    Newtonsoft.Json.JsonConvert.SerializeObject(messageHandlerNode, Newtonsoft.Json.Formatting.Indented/*,new Newtonsoft.Json.JsonSerializerSettings() {  }*/));


                //不同类型请求的委托
                Func <IResponseMessageBase> executeFunc = () => Task.Run(async() =>
                {
                    IResponseMessageBase responseMessage = null;
                    switch (RequestMessage.MsgType)
                    {
                    case RequestMsgType.Text:
                        {
                            var requestMessage = RequestMessage as RequestMessageText;
                            responseMessage    = (await(OnTextOrEventRequestAsync(requestMessage))
                                                  ?? (await OnTextRequestAsync(requestMessage)));
                        }
                        break;

                    case RequestMsgType.Location:
                        responseMessage = await OnLocationRequestAsync(RequestMessage as RequestMessageLocation);
                        break;

                    case RequestMsgType.Image:
                        responseMessage = await OnImageRequestAsync(RequestMessage as RequestMessageImage);
                        break;

                    case RequestMsgType.Voice:
                        responseMessage = await OnVoiceRequestAsync(RequestMessage as RequestMessageVoice);
                        break;

                    case RequestMsgType.Video:
                        responseMessage = await OnVideoRequestAsync(RequestMessage as RequestMessageVideo);
                        break;

                    case RequestMsgType.Link:
                        responseMessage = await OnLinkRequestAsync(RequestMessage as RequestMessageLink);
                        break;

                    case RequestMsgType.ShortVideo:
                        responseMessage = await OnShortVideoRequestAsync(RequestMessage as RequestMessageShortVideo);
                        break;

                    case RequestMsgType.File:
                        responseMessage = await OnFileRequestAsync(RequestMessage as RequestMessageFile);
                        break;

                    case RequestMsgType.NeuChar:
                        responseMessage = await OnNeuCharRequestAsync(RequestMessage as RequestMessageNeuChar);
                        break;

                    case RequestMsgType.Unknown:
                        responseMessage = await OnUnknownTypeRequestAsync(RequestMessage as RequestMessageUnknownType);
                        break;

                    case RequestMsgType.Event:
                        {
                            var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                            responseMessage        = (await(OnTextOrEventRequestAsync(requestMessageText)))
                                                     ?? (await OnEventRequestAsync(RequestMessage as IRequestMessageEventBase));
                        }
                        break;

                    default:
                        Weixin.WeixinTrace.SendCustomLog("NeuChar", "未知的MsgType请求类型" + RequestMessage.MsgType);
                        //throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                        break;
                    }

                    return(responseMessage);
                }).Result;

                if (messageHandlerNode != null && messageHandlerNode is MessageHandlerNode)
                {
                    ResponseMessage = await((MessageHandlerNode)messageHandlerNode).GetResponseMessageAsync(RequestMessage, executeFunc);
                }

                //如果没有得到结果,则继续运行编译好的代码
                if (ResponseMessage == null)
                {
                    //Weixin.WeixinTrace.SendCustomLog("NeuChar", "executeFunc()");
                    ResponseMessage = executeFunc();//直接执行
                }

                #endregion


                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecutedAsync();
            }
        }
コード例 #12
0
        /// <summary>
        /// 【异步方法】执行微信请求
        /// </summary>
        public override async Task ExecuteAsync()
        {
            if (CancelExcute)
            {
                return;
            }

            await OnExecutingAsync();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }


                #region NeuChar 执行过程

                //TODO:Neuchar:在这里先做一次NeuChar标准的判断

                var neuralSystem = NeuralSystem.Instance;

                //获取当前设置节点
                var messageHandlerNode = neuralSystem.GetNode("MessageHandlerNode") as MessageHandlerNode;

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Text:
                {
                    var requestMessage = RequestMessage as RequestMessageText;
                    ResponseMessage = await messageHandlerNode.ExecuteAsync(requestMessage) ?? (await(OnTextOrEventRequestAsync(requestMessage))
                                                                                                ?? (await OnTextRequestAsync(requestMessage)));
                }
                break;

                case RequestMsgType.Location:
                    ResponseMessage = await OnLocationRequestAsync(RequestMessage as RequestMessageLocation);

                    break;

                case RequestMsgType.Image:
                    ResponseMessage = await messageHandlerNode.ExecuteAsync(RequestMessage) ?? await OnImageRequestAsync(RequestMessage as RequestMessageImage);

                    break;

                case RequestMsgType.Voice:
                    ResponseMessage = await OnVoiceRequestAsync(RequestMessage as RequestMessageVoice);

                    break;

                case RequestMsgType.Video:
                    ResponseMessage = await OnVideoRequestAsync(RequestMessage as RequestMessageVideo);

                    break;

                case RequestMsgType.Link:
                    ResponseMessage = await OnLinkRequestAsync(RequestMessage as RequestMessageLink);

                    break;

                case RequestMsgType.ShortVideo:
                    ResponseMessage = await OnShortVideoRequestAsync(RequestMessage as RequestMessageShortVideo);

                    break;

                case RequestMsgType.File:
                    ResponseMessage = await OnFileRequestAsync(RequestMessage as RequestMessageFile);

                    break;

                case RequestMsgType.NeuChar:
                    ResponseMessage = await OnNeuCharRequestAsync(RequestMessage as RequestMessageNeuChar);

                    break;

                case RequestMsgType.Unknown:
                    ResponseMessage = await OnUnknownTypeRequestAsync(RequestMessage as RequestMessageUnknownType);

                    break;

                case RequestMsgType.Event:
                {
                    var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                    ResponseMessage = (await(OnTextOrEventRequestAsync(requestMessageText)))
                                      ?? (await OnEventRequestAsync(RequestMessage as IRequestMessageEventBase));
                }
                break;

                default:
                    Weixin.WeixinTrace.SendCustomLog("NeuChar", "未知的MsgType请求类型" + RequestMessage.MsgType);
                    //throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                    break;
                }

                #endregion


                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                await OnExecutedAsync();
            }
        }
コード例 #13
0
        /// <summary>
        /// 执行微信请求
        /// </summary>
        public override void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Text:
                {
                    ResponseMessage = OnTextRequest(RequestMessage as RequestMessageText);
                }
                break;

                case RequestMsgType.Image:
                {
                    ResponseMessage = OnImageRequest(RequestMessage as RequestMessageImage);
                }
                break;

                case RequestMsgType.Event:
                {
                    OnEventRequest(RequestMessage as IRequestMessageEventBase);
                }
                break;

                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                }

                //记录上下文
                //此处修改
                if (MessageContextGlobalConfig.UseMessageContext && ResponseMessage != null && !string.IsNullOrEmpty(ResponseMessage.FromUserName))
                {
                    GlobalMessageContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
            }
        }