Ejemplo n.º 1
0
        public int UpdateSendMsgById(int msgid, string replyContent, string replier, DateTime replyTime)
        {
            SendMsg sendMsg = sendMsgBLL.Get("MsgId", msgid);

            sendMsg.ReplyContent = replyContent;
            sendMsg.Replier      = replier;
            sendMsg.ReplyTime    = replyTime;
            sendMsg.Editor       = UserCookies.AdminName;
            int count = sendMsgBLL.Update(sendMsg);
            //添加到收件箱表
            ReceiveMsg receiveMsg = new ReceiveMsg();

            receiveMsg.Content       = sendMsg.ReplyContent;
            receiveMsg.SenderId      = 0;
            receiveMsg.Sender        = sendMsg.Replier;
            receiveMsg.ReceiverId    = sendMsg.QuCustomerId;
            receiveMsg.Receiver      = sendMsg.QuCustomerName;
            receiveMsg.CreaedTime    = DateTime.Now;
            receiveMsg.SendTime      = DateTime.Now;
            receiveMsg.MsgSource     = 2;
            receiveMsg.MsgSourceId   = sendMsg.MsgId;
            receiveMsg.ReplyQuestion = sendMsg.MsgContent;
            receiveMsg.Status        = 1;
            receiveMsgBLL.Add(receiveMsg);
            return(count);
        }
        /// <summary>
        /// 接收微信服务器消息
        /// </summary>
        private void receiveMessages()
        {
            if (this.checkSign)
            {
                if (_context.Request.Method.ToUpper() == "POST")
                {
                    using (Stream stream = _context.Request.Body)
                    {
                        byte[] bytes = new byte[_context.Request.ContentLength.Value];
                        stream.Read(bytes, 0, bytes.Length);
                        stream.Dispose();

                        string postString = Encoding.UTF8.GetString(bytes);
                        if (!string.IsNullOrEmpty(postString))
                        {
                            _wechatmsg = postString;
                            _basemsg   = XmlHelper.deserialize <ReceiveMsg>(_wechatmsg);
                        }
                    }
                }
                else
                {
                    Encoding.GetEncoding("utf-8");
                    string echoString = _params["echostr"];
                    _context.Response.WriteAsync(echoString);
                }
            }
            else
            {
                throw new WeChatError("验签不通过");
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// XML字符串转成接收消息对象
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static ReceiveMsg XmlToReceiveMsg(string msg)
        {
            ReceiveMsg retVal = null;
            //封装请求类
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(msg);
            XmlElement rootElement = doc.DocumentElement;
            //MsgType
            XmlNode MsgType = rootElement.SelectSingleNode("MsgType");

            switch (MsgType.InnerText)
            {
            case ReceiveMsg.TYPE_TEXT:     //文本消息
                retVal = new ReceiveTextMsg()
                {
                    MsgId = rootElement.SelectSingleNode("MsgId").InnerText, Content = rootElement.SelectSingleNode("Content").InnerText
                };
                break;

            case ReceiveMsg.TYPE_IMAGE:     //图片
                retVal = new ReceiveImageMsg()
                {
                    MsgId = rootElement.SelectSingleNode("MsgId").InnerText, PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText, MediaId = rootElement.SelectSingleNode("MediaId").InnerText
                };
                break;

            case ReceiveMsg.TYPE_VOICE:
                retVal = new ReceiveVoiceMsg()
                {
                    MsgId = rootElement.SelectSingleNode("MsgId").InnerText, Format = rootElement.SelectSingleNode("Format").InnerText, MediaId = rootElement.SelectSingleNode("MediaId").InnerText
                };
                break;

            case ReceiveMsg.TYPE_LOCATION:     //位置
                break;

            case ReceiveMsg.TYPE_LINK:     //链接
                break;

            case ReceiveMsg.TYPE_EVENT:     //事件推送 支持V4.5+
                retVal = new ReceiveEventMsg()
                {
                    Event = rootElement.SelectSingleNode("Event").InnerText, EventKey = rootElement.SelectSingleNode("EventKey").InnerText
                };
                break;
            }

            //接收的值--->接收消息类(也称为消息推送)
            retVal.ToUserName   = rootElement.SelectSingleNode("ToUserName").InnerText;
            retVal.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;

            int ct = int.Parse(rootElement.SelectSingleNode("CreateTime").InnerText);

            retVal.CreateTime = SecondToDateTime(ct);

            //            retVal.MsgType = MsgType.InnerText;

            return(retVal);
        }
Ejemplo n.º 4
0
        private void Digest(ReceiveMsg msg)
        {
            SendTextMsg textMsg = null;

            switch (msg.MsgType)
            {
            case ReceiveMsg.TYPE_TEXT:
                textMsg = new SendTextMsg()
                {
                    touser = msg.FromUserName
                };
                textMsg.text.content = ((ReceiveTextMsg)msg).Content;

                WeiXinUtil.PostSendMsgJson(CustomSendUrl, weiXinPublic.AccessToken.access_token, textMsg);
                //WeiXinMsgSend.PostMsgJson(weiXinPublic.AccessToken.access_token, tmj);
                break;

            case ReceiveMsg.TYPE_EVENT:
                textMsg = new SendTextMsg()
                {
                    touser = msg.FromUserName
                };
                textMsg.text.content = ((ReceiveEventMsg)msg).Event;

                WeiXinUtil.PostSendMsgJson(CustomSendUrl, weiXinPublic.AccessToken.access_token, textMsg);
                break;
            }
        }
Ejemplo n.º 5
0
 // 处理消息
 public void DealWithSocketData(ReceiveMsg msgData)
 {
     // lua 处理协议
     SLua.LuaFunction func = LuaGameManager.Instance().GetState().getFunction("OnProtobufCallBack");
     if (func != null)
     {
         func.call(msgData.data.handleId, new SLua.ByteArray(msgData.data.data));
     }
 }
Ejemplo n.º 6
0
        public ActionResult Index()
        {
            Stream requestStream = System.Web.HttpContext.Current.Request.InputStream;
            string requestStr    = StreamUtil.StreamToStr(requestStream);

            //由POST过来的字符串转成微信消息对象
            ReceiveMsg msg = WeiXinUtil.XmlToReceiveMsg(requestStr);

            //处理消息
            Digest(msg);

            return(Content("success"));
        }
Ejemplo n.º 7
0
 private async void WriteReceiveMsgAsync(string msg)
 {
     await Dispatcher.BeginInvoke(() =>
     {
         //大于100行清除记录,可选
         if (ReceiveMsg.LineCount > 100)
         {
             ReceiveMsg.Clear();
         }
         ReceiveMsg.AppendText(msg + "\n");
         ReceiveMsg.ScrollToEnd();
     });
 }
Ejemplo n.º 8
0
        public void ReceiveMessage(IAsyncResult async_result)
        {
            try
            {
                var socket_con_get = async_result.AsyncState as Socket;


                var i_data_length = socket_con_get.EndReceive(async_result);
                var string_data   = Encoding.UTF8.GetString(b_data_buffer, 0, i_data_length);

                // #####################################################
                // 线程通信 消息分发
                ChatReceiveFilter receive_filter = new ChatReceiveFilter();
                int             rest             = 0;
                ChatRequestInfo request_info     = receive_filter.Filter(b_data_buffer, 0, i_data_length, false, out rest);

                ICommand command = null;
                if (request_info != null)
                {
                    switch (request_info.Key)
                    {
                    case "Login": command = new Login(); break;

                    case "FriendList": command = new FriendList(); break;

                    case "ReceiveMsg": command = new ReceiveMsg(); break;

                    case "UpdatePw": command = new UpdatePw(); break;

                    case "SearchFriend": command = new SearchFriend(); break;
                    }
                }

                if (command != null)
                {
                    command.ExecuteCommand(request_info.Body);
                }
                // #####################################################

                socket_connect.BeginReceive(b_data_buffer,
                                            START_POS,
                                            b_data_buffer.Length,
                                            SocketFlags.None,
                                            new AsyncCallback(ReceiveMessage),
                                            socket_connect);
            }
            catch (Exception ex)
            {
                // 异常处理
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// 插入微信接收消息
 /// </summary>
 /// <param name="info"></param>
 public void InsertInfo(ReceiveMsg info)
 {
     string sql = @"INSERT INTO [WX_ReceiveMsg]
                ([WXConfigID]
                ,[ToUserName]
                ,[FromUserName]
                ,[CreateTime]
                ,[MsgType]
                ,[MsgId]
                ,[Event]
                ,[EventKey]
                ,[MsgBody]
                ,[ReceiveTime]
                ,[Remark])
          VALUES
                (@WXConfigID
                 ,@ToUserName
                 ,@FromUserName
                 ,@CreateTime
                 ,@MsgType
                 ,@MsgId
                 ,@Event
                 ,@EventKey
                 ,@MsgBody
                 ,@ReceiveTime
                 ,@Remark)";
     System.Data.SqlClient.SqlParameter[] paras = new System.Data.SqlClient.SqlParameter[]
     {
         new System.Data.SqlClient.SqlParameter("@WXConfigID", info.WXConfigID),
         new System.Data.SqlClient.SqlParameter("@ToUserName", info.ToUserName),
         new System.Data.SqlClient.SqlParameter("@FromUserName", info.FromUserName),
         new System.Data.SqlClient.SqlParameter("@CreateTime", info.CreateTime),
         new System.Data.SqlClient.SqlParameter("@MsgType", info.MsgType),
         new System.Data.SqlClient.SqlParameter("@MsgId", info.MsgId),
         new System.Data.SqlClient.SqlParameter("@Event", info.Event),
         new System.Data.SqlClient.SqlParameter("@EventKey", info.EventKey),
         new System.Data.SqlClient.SqlParameter("@MsgBody", info.MsgBody),
         new System.Data.SqlClient.SqlParameter("@ReceiveTime", info.ReceiveTime),
         new System.Data.SqlClient.SqlParameter("@Remark", info.Remark)
     };
     DbHelperSQL.ExecuteSql(sql, paras);
 }
Ejemplo n.º 10
0
        public ServerMQTT(IMqttServer server, string internalClientId)
        {
            _server    = server;
            servername = internalClientId;

            _server.UseClientConnectedHandler(async e =>
            {
                MqttClientStatus clientStatus = (MqttClientStatus)(await _server.GetClientStatusAsync()).FirstOrDefault(o => o.ClientId == e.ClientId);

                Console.WriteLine($"Connectd {e.ClientId}");
                Console.WriteLine($"{clientStatus.Endpoint}");

                await clientStatus.Session.ClearPendingApplicationMessagesAsync();

                ReceiveMsg?.Invoke(this, new GatewayStarted(e.ClientId, clientStatus.Endpoint));
            });

            _server.UseClientDisconnectedHandler(e =>
            {
                ReceiveMsg?.Invoke(this, new GatewayDisconnected(e.ClientId));
            });

            _server.UseApplicationMessageReceivedHandler(msg =>
            {
                Console.WriteLine($"Topic {msg.ClientId} {msg.ApplicationMessage.Topic} payload {msg.ApplicationMessage.ConvertPayloadToString()}");

                if (msg.ClientId == _server.Options.ClientId || msg.ClientId == servername)
                {
                    return;
                }

                var msgContext = ToMessage(msg.ApplicationMessage.Topic, msg.ApplicationMessage.ConvertPayloadToString());

                if (msgContext != null)
                {
                    ReceiveMsg?.Invoke(this, msgContext);
                }
            });
        }
Ejemplo n.º 11
0
    // 每帧检查处理消息
    public void UpdateSocket()
    {
        // 向 Lua 发送缓存的socket链接状态
        if (cacheConnectEvent != SocketConnectionEvent.None)
        {
            Debug.Log(cacheConnectEvent.ToString());

            LuaUtils.PostLuaEvent(cacheConnectEvent.ToString(), null);
            cacheConnectEvent = SocketConnectionEvent.None;
        }
        // 检查是否有消息来了
        if (null != _conn && _conn.State == SocketConnectionState.Connected)
        {
            List <SocketData> sockDatas = _conn.RecvSocketDataList();

            if (sockDatas != null && sockDatas.Count > 0)
            {
                for (int i = 0; i < sockDatas.Count; ++i)
                {
                    SocketData data    = sockDatas [i];
                    ReceiveMsg msgData = new ReceiveMsg();
                    msgData.data = data;

                    tobeHandledSocketData.Enqueue(msgData);
                }
            }
        }
        // 处理接收的消息
        if (tobeHandledSocketData.Count > 0)
        {
            ReceiveMsg msgData = tobeHandledSocketData.Dequeue();
            DealWithSocketData(msgData);
        }
        else
        {
        }
    }
        public async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs)
        {
            var topic = eventArgs.ApplicationMessage.Topic;

            if (topic == MQTTTopic.Msg.ToString() + "-" + App.CurrentUser.Id)
            {
                var content = Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload);
                ReceiveMsg?.Invoke(content);
            }
            else if (topic == MQTTTopic.Register.ToString())
            {
                var content  = Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload);
                var userinfo = JsonConvert.DeserializeObject <UserInfo>(content);
                if (userinfo != null && userinfo.Id > 0)
                {
                    Register?.Invoke(userinfo);
                }
            }
            else if (topic == MQTTTopic.Online.ToString())
            {
                var content  = Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload);
                var userinfo = JsonConvert.DeserializeObject <UserInfo>(content);
                if (userinfo != null && userinfo.Id > 0)
                {
                    ReceiveOnLine?.Invoke(userinfo.Id);
                }
            }
            else if (topic == MQTTTopic.Offline.ToString())
            {
                var content  = Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload);
                var userinfo = JsonConvert.DeserializeObject <UserInfo>(content);
                if (userinfo != null && userinfo.Id > 0)
                {
                    ReceiveOffline?.Invoke(userinfo.Id);
                }
            }
        }
Ejemplo n.º 13
0
        ///

        /*
         * 这个方法为接受信息时调用的方法。为了避免堵塞将在新线程中处理每条消息,如果需要在接受信息时修改数据请自行保证线程安全性,可以认为每次调用该方法都是一个新线程。
         *
         *
         */

        public override sendBack ReceiveMessage(ReceiveMsg rmg)
        {
            if (rmg.called)
            {
                QQLinker.SendMessage(packSendBack(rmg.type, true, rmg.from_qq, Coding("被@")));
            }
            Console.WriteLine("|{0}|", rmg.message);
            Console.WriteLine(rmg.type);
            Console.WriteLine("Called? :{0}", rmg.called);
            string message = qqLinker.getSingleLongNick(rmg.senderUin) + "|";

            switch (rmg.type)
            {
            case polltype.discu_message:
                message += "\n" + qqLinker.getDisInfo(rmg.from_qq);
                break;

            case polltype.group_message:
                message += "\n" + qqLinker.getGroupInfo(rmg.from_qq);
                break;

            case polltype.message:
                message += "\n" + qqLinker.getFrindInfo(rmg.from_qq);
                break;

            default:
                break;
            }
            message = message.Replace("\"", "\\\\\\\"");
            Console.WriteLine(message);

            //  sendBack s = packSendBack(rmg.type,true, rmg.from_qq, message);
            QQLinker.SendMessage(packSendBack(rmg.type, true, rmg.from_qq, rmg.from_qq + "|" + rmg.senderUin));
            //    return DontSend;
            return(packSendBack(rmg.type, true, rmg.from_qq, Coding("测试\"成功")));        //s;
        }
Ejemplo n.º 14
0
    /// <summary>
    /// 处理队列中的消息
    /// </summary>
    /// <param name="msg"></param>
    private void DoReceiveMsg(ReceiveMsg msg)
    {
        ResetSendTime();//收到任何消息,重置发送消息的计时和状态
        ResetHeartbeat();

        if (_responseProtoIds != null && _responseProtoIds.Contains(msg.ProtoId))
        {
            //置空发送消息时缓存的接收对应消息protoid列表
            SetEmptyArray(_responseProtoIds, -1);
            OnSendSuccessCallback();
        }

        ResponseProto response;

        if (ResponseProtoDictionary.TryGetValue(msg.ProtoId, out response))
        {
            MemoryStream stream    = new MemoryStream(msg.ContentBytes);
            var          paramType = response.GetParamType();
            var          content   = Serializer.NonGeneric.Deserialize(paramType, stream);
            stream.Close();

            var field         = response.GetFieldInfo();
            var eventDelegate = field.GetValue(this) as MulticastDelegate;
            if (eventDelegate == null)
            {
                LogUtil.Log(string.Format("事件“{0}”没有注册方法", field.Name));
                return;
            }

            foreach (var eventHandler in eventDelegate.GetInvocationList())
            {
                eventHandler.Method.Invoke(eventHandler.Target, new object[] { content });
            }
        }
        else
        {
            LogUtil.Log("ProtoDictionary 字典里没有对应的 protoId:" + msg.ProtoId);
        }

        //        //        count++;
        //        int protoId = msg.ProtoId;
        //        List<URLMapRecord> records;
        //        if (GameManager.instance.GetUrlMapRecords().TryGetValue(protoId, out records))
        //        {
        //            LogUtil.Log(string.Format("收到服务器消息,protoId为{0}", protoId));
        //            foreach (var record in records)
        //            {
        //                LogUtil.Log(record.GetClassType().Name);
        //                //必须是在场景中存在且在Hierarchy层次结构中active为true的组件
        //                MonoBehaviour monoObj = FindObjectOfType(record.GetClassType()) as MonoBehaviour;
        //                if (!monoObj)
        //                {
        //                    continue;
        //                }
        //                try
        //                {
        //                    //拿到数据,执行方法
        //                    MemoryStream stream = new MemoryStream(msg.ContentBytes);
        //                    object paramobj = Serializer.NonGeneric.Deserialize(record.GetParamType(), stream);
        //                    stream.Close();
        //                    record.GetMethodInfo().Invoke(monoObj, new object[] { paramobj });
        //                }
        //                catch (Exception e)
        //                {
        //                    Console.WriteLine(e);
        //                }
        //            }
        //            //            LogUtil.Log("count = " + count);
        //        }
        //        else
        //        {
        //            LogUtil.LogWarning("错误的protoId = " + protoId);
        //        }
    }
Ejemplo n.º 15
0
 /// <summary>
 /// 更新单条数据
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public int Update(ReceiveMsg obj)
 {
     return(dal.Update(obj));
 }
Ejemplo n.º 16
0
        /// <summary>
        /// 接收消息时,记录消息信息
        /// </summary>
        /// <param name="doc"></param>
        public void MsgReceiving(XmlDocument doc)
        {
            if (doc != null)
            {
                ReceiveMsgDAL dal  = new ReceiveMsgDAL();
                ReceiveMsg    info = new ReceiveMsg()
                {
                    WXConfigID   = wxConfig.ID,
                    CreateTime   = doc.DocumentElement.SelectSingleNode("CreateTime").InnerText,
                    FromUserName = doc.DocumentElement.SelectSingleNode("FromUserName").InnerText,
                    ToUserName   = doc.DocumentElement.SelectSingleNode("ToUserName").InnerText,
                    MsgType      = doc.DocumentElement.SelectSingleNode("MsgType").InnerText,
                    MsgBody      = doc.InnerXml
                };
                dal.InsertInfo(info);

                string msgType = doc.DocumentElement.SelectSingleNode("MsgType").InnerText;
                if (msgType.ToLower() == "text")
                {
                    ReceiveTextMsgDAL receiveTextMsgDAL = new ReceiveTextMsgDAL();
                    ReceiveTextMsg    receiveTextMsg    = new ReceiveTextMsg()
                    {
                        WXConfigID   = wxConfig.ID,
                        CreateTime   = doc.DocumentElement.SelectSingleNode("CreateTime").InnerText,
                        FromUserName = doc.DocumentElement.SelectSingleNode("FromUserName").InnerText,
                        ToUserName   = doc.DocumentElement.SelectSingleNode("ToUserName").InnerText,
                        MsgType      = doc.DocumentElement.SelectSingleNode("MsgType").InnerText,
                        Content      = doc.DocumentElement.SelectSingleNode("Content").InnerText,
                    };
                    receiveTextMsgDAL.Insert(receiveTextMsg);
                }

                string                msgcontent = string.Empty;
                string                openid     = string.Empty;
                DAL.CR.ChatRoomDAL    roomdal    = new DAL.CR.ChatRoomDAL();
                DAL.CR.ChatUsersDAL   userdal    = new DAL.CR.ChatUsersDAL();
                Model.CR.ChatUsers    usermodel  = new Model.CR.ChatUsers();
                DAL.CR.ChatMessageDAL msgdal     = new DAL.CR.ChatMessageDAL();
                Model.CR.ChatMessage  msgmodel   = new Model.CR.ChatMessage();
                UserDAL               wx_userdal = new UserDAL();
                User wx_usermodel = new User();
                openid = doc.DocumentElement.SelectSingleNode("FromUserName").InnerText;
                string ChatUserName = string.Empty;
                if (openid != null && openid != "")
                {
                    if (!wx_userdal.ExistUserByOpenID(openid))
                    {
                        UserInfo userinfo = weixin.GetUserInfo(openid);//获取用户信息
                        wx_usermodel.ID            = Guid.NewGuid().ToString("N").ToUpper();
                        wx_usermodel.City          = userinfo.City;
                        wx_usermodel.Country       = userinfo.Country;
                        wx_usermodel.HeadImgUrl    = userinfo.Headimgurl;
                        wx_usermodel.Language      = userinfo.Language;
                        wx_usermodel.NickName      = userinfo.NickName;
                        wx_usermodel.OpenID        = userinfo.OpenId;
                        wx_usermodel.Province      = userinfo.Province;
                        wx_usermodel.Sex           = userinfo.Sex;
                        wx_usermodel.Subscribe     = userinfo.Subscribe;
                        wx_usermodel.SubscribeTime = userinfo.Subscribe_Time;
                        ChatUserName = userinfo.NickName;
                        if (null != wx_usermodel.ID)
                        {
                            wx_userdal.Insert(wx_usermodel);
                        }
                    }
                    else
                    {
                        ChatUserName = wx_userdal.GetUserValueByOpenID("NickName", openid).ToString();
                    }
                }
                else////OpenID为空
                {
                }
                int strRoomID = 1;
                #region  墙信息
                if (msgType.ToLower() == "text")
                {
                    msgcontent = doc.DocumentElement.SelectSingleNode("Content").InnerText;
                    if (msgcontent.Contains("#"))
                    {
                        if (openid != null && openid != "")
                        {
                            #region  务号取用户加入信息
                            if (msgcontent.Length <= 1)                                         //判断是否单独发送 #
                            {
                                if (userdal.ExistChatUser(Convert.ToInt32(msgcontent), openid)) //如果存在该用户
                                {
                                    string uid = userdal.GetChatUserValueByOpenID("ID", openid, Convert.ToInt32(msgcontent)).ToString();
                                    if (uid.Trim() != null && uid.Trim() != "")
                                    {
                                        userdal.UpdateChatUserIsDel(uid);//更新用户状态  提示表示用户离开房间
                                    }
                                }
                            }
                            else
                            {
                                msgcontent = msgcontent.Substring(1);
                                if (Regex.IsMatch(msgcontent, @"^\d+$"))//判断是否为数字
                                {
                                    string roomsitecode = roomdal.GetChatRoomValueByID("SiteCode", Convert.ToInt32(msgcontent)).ToString();
                                    if (roomsitecode.Trim() != null && roomsitecode.Trim() != "")
                                    {
                                        if (roomdal.ExistChatRoomNum(roomsitecode, Convert.ToInt32(msgcontent)))
                                        {
                                            //提示房间存在
                                            if (userdal.ExistChatUser(Convert.ToInt32(msgcontent), openid))
                                            {
                                                //提示该用户已进入该房间
                                            }
                                            else
                                            {
                                                usermodel.ID     = Guid.NewGuid().ToString("N").ToUpper();
                                                usermodel.OpenID = openid;
                                                usermodel.RoomID = Convert.ToInt32(msgcontent);
                                                usermodel.IsDel  = 0;
                                                usermodel.IsWin  = 0;
                                                userdal.AddChatUsers(usermodel);
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            #region 订阅号获取上墙信息
                            string[] sArray   = msgcontent.Split('#');
                            string   username = string.Empty;
                            string   msginfo  = string.Empty;
                            try
                            {
                                username = sArray[0].ToString();
                            }
                            catch (Exception)
                            {
                            }
                            try
                            {
                                msginfo = sArray[1].ToString();
                            }
                            catch (Exception)
                            {
                            }
                            if (username.Trim() != null && username.Trim() != "")
                            {
                                if (userdal.ExistChatUser(username))//判断用户名是否已存在
                                {
                                    //已存在用户
                                    if (msginfo.Trim() == null || msginfo.Trim() == "")
                                    {
                                        userdal.UpdateChatUserIsDel(username);//删除用户
                                    }
                                }
                                else
                                {
                                    usermodel.ID     = Guid.NewGuid().ToString("N").ToUpper();
                                    usermodel.OpenID = username;
                                    usermodel.RoomID = strRoomID;
                                    usermodel.IsDel  = 0;
                                    usermodel.IsWin  = 0;
                                    userdal.AddChatUsers(usermodel);
                                }
                                if (msginfo.Trim() != null && msginfo.Trim() != "")
                                {
                                    msgmodel.ID       = Guid.NewGuid().ToString("N").ToUpper();
                                    msgmodel.UserID   = username;
                                    msgmodel.RoomID   = strRoomID;
                                    msgmodel.MsgType  = "text";
                                    msgmodel.MsgText  = msginfo;
                                    msgmodel.MsgState = 0;//1表示通过 0表示不通过
                                    msgmodel.IsDel    = 0;
                                    msgdal.AddChatMessage(msgmodel);
                                }
                            }
                            #endregion
                        }
                    }
                    else
                    {
                        #region  务号取上墙信息
                        if (userdal.ExistChatUser(strRoomID, openid))
                        {
                            //提示已经存在该用户
                            string userid = userdal.GetChatUserValueByOpenID("ID", openid, strRoomID).ToString();
                            msgmodel.ID       = Guid.NewGuid().ToString("N").ToUpper();
                            msgmodel.UserID   = userid;
                            msgmodel.RoomID   = strRoomID;
                            msgmodel.MsgType  = "text";
                            msgmodel.MsgText  = msgcontent;
                            msgmodel.MsgState = 0;//1表示通过 0表示不通过
                            msgmodel.IsDel    = 0;
                            msgdal.AddChatMessage(msgmodel);
                        }
                        #endregion
                    }
                }
                else if (msgType.ToLower() == "image")
                {
                    #region  务号取上墙信息
                    if (userdal.ExistChatUser(strRoomID, openid))
                    {
                        //提示已经存在该用户
                        string userid = userdal.GetChatUserValueByOpenID("ID", openid, strRoomID).ToString();
                        msgmodel.ID       = Guid.NewGuid().ToString("N").ToUpper();
                        msgmodel.UserID   = userid;
                        msgmodel.RoomID   = strRoomID;
                        msgmodel.MsgType  = "image";
                        msgmodel.MsgText  = msgcontent;
                        msgmodel.MsgState = 0;//1表示通过 0表示不通过
                        msgmodel.IsDel    = 0;
                        msgdal.AddChatMessage(msgmodel);
                    }
                    #endregion
                }
                #endregion
            }
        }
Ejemplo n.º 17
0
 void ChatService.ISendChatServiceCallback.ReceiveMessage(string msg, string receiver)
 {
     ReceiveMsg?.Invoke(receiver, msg);
 }
Ejemplo n.º 18
0
 /// <summary>
 /// 删除单条数据
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public int Delete(ReceiveMsg obj)
 {
     return(dal.Delete(obj));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 开始轮询检测是否有新消息
        /// </summary>
        private void Sync()
        {
            while (syncPolling)
            {
                try
                {
                    string syncCheckUrl    = string.Format(pushHost + "/cgi-bin/mmwebwx-bin/synccheck?r={0}&skey={1}&sid={2}&uin={3}&deviceid={4}&synckey={5}&_={6}", Utils.GetJavaTimeStamp(), baseRequest.Skey, baseRequest.Sid, baseRequest.Uin, baseRequest.DeviceID, syncKey.ToString(), syncKey.Step);
                    string syncCheckResult = httpClient.GetString(syncCheckUrl);
                    if (!syncPolling)
                    {
                        return;
                    }
                    MatchCollection matchCollection = Regex.Matches(syncCheckResult, @"\d+");
                    string          retcode         = matchCollection[0].Value;
                    string          selector        = matchCollection[1].Value;
                    Utils.Debug("retcode:" + retcode + " selector:" + selector);
                    switch (retcode)
                    {
                    case "0":
                        if (selector != "0")
                        {
                            //有新消息,拉取信息。
                            SyncRequest syncRequest = new SyncRequest();
                            syncRequest.BaseRequest = baseRequest;
                            syncRequest.SyncKey     = syncKey;
                            syncRequest.rr          = Utils.Get_r();
                            string       syncUrl      = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsync?sid={0}&skey={1}&pass_ticket={2}", baseRequest.Sid, baseRequest.Skey, passTicket);
                            SyncResponse syncResponse = httpClient.PostJson <SyncResponse>(syncUrl, syncRequest);
                            if (!syncPolling)
                            {
                                return;
                            }
                            else
                            {
                                syncKey = syncResponse.SyncKey;
                                //只要不是0,就是有消息,有消息我们处理就行了,不管selector是几
                                if (syncResponse.AddMsgCount == 0 && syncResponse.DelContactCount == 0 && syncResponse.ModContactCount == 0 && syncResponse.ModChatRoomMemberCount == 0)
                                {
                                    //会有这么一种情况,selector=2,但是没有任何消息体,这样会导致持续快速的空交互
                                    //除非下次有新消息,或者主动点击手机触发消息
                                    //为了防止这种情况,做个5秒停顿。
                                    Thread.Sleep(5000);
                                }
                                else
                                {
                                    if (syncResponse.AddMsgList.Count > 0)
                                    {
                                        asyncOperation.Post(
                                            new SendOrPostCallback((obj) =>
                                        {
                                            ReceiveMsg?.Invoke(this, new TEventArgs <List <AddMsg> >((List <AddMsg>)obj));
                                        }), syncResponse.AddMsgList);
                                    }

                                    if (syncResponse.ModContactCount > 0)
                                    {
                                        asyncOperation.Post(
                                            new SendOrPostCallback((obj) =>
                                        {
                                            ModContactListComplete?.Invoke(this, new TEventArgs <List <ModContactItem> >((List <ModContactItem>)obj));
                                        }), syncResponse.ModContactList);
                                    }
                                    if (syncResponse.DelContactCount > 0)
                                    {
                                        asyncOperation.Post(
                                            new SendOrPostCallback((obj) =>
                                        {
                                            DelContactListComplete?.Invoke(this, new TEventArgs <List <DelContactItem> >((List <DelContactItem>)obj));
                                        }), syncResponse.DelContactList);
                                    }
                                    if (syncResponse.ModChatRoomMemberCount > 0)
                                    {
                                        //待分析,这个消息基本没有
                                    }
                                }
                            }
                        }
                        break;

                    case "1100":
                        //登出了微信,很可能是wx.qq.com和wx2.qq.com调用接口不一致导致的,注意登陆时候的跳转地址
                        Close();
                        asyncOperation.Post(
                            new SendOrPostCallback((obj) =>
                        {
                            LogoutComplete?.Invoke(this, new TEventArgs <User>((User)obj));
                        }), user);
                        break;

                    case "1101":
                        Close();
                        asyncOperation.Post(
                            new SendOrPostCallback((obj) =>
                        {
                            LogoutComplete?.Invoke(this, new TEventArgs <User>((User)obj));
                        }), user);
                        throw new Exception("1101可能其他地方登录/登出了 WEB 版微信,请检查手机端已登出WEB微信,然后稍后再试");
                        break;

                    case "1102":
                        Close();
                        asyncOperation.Post(
                            new SendOrPostCallback((obj) =>
                        {
                            LogoutComplete?.Invoke(this, new TEventArgs <User>((User)obj));
                        }), user);
                        throw new Exception("1102被强制登出(很可能cookie冲突),请检查手机端已登出WEB微信,然后稍后再试");
                        break;

                    default:
                        //有其他任何异常,取消轮询
                        throw new Exception("轮询结果异常,停止轮询:" + syncCheckResult);
                        break;
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    FileLog.Exception("Init", ex);
                    asyncOperation.Post(
                        new SendOrPostCallback((obj) =>
                    {
                        ExceptionCatched?.Invoke(this, new TEventArgs <Exception>((Exception)obj));
                    }), ex);
                }
            }
        }
Ejemplo n.º 20
0
 void ISendChatServiceCallback.ReceiveMessage(string message, string receiver)
 {
     ReceiveMsg?.Invoke(receiver, message);
 }
Ejemplo n.º 21
0
 public void ReceiveMessage(string msg)
 {
     ReceiveMsg?.Invoke(msg);
 }
Ejemplo n.º 22
0
 /// <summary>
 ///     用来重载的接收方法
 /// </summary>
 /// <param name="rmg"></param>
 /// <returns>返回sendBack,可以调用packSendBack,如果需要设置字体,字号和颜色则需要手动设置(目前不支持)</returns>
 public virtual sendBack ReceiveMessage(ReceiveMsg rmg)
 {
     return(packSendBack(polltype.none));
 }
Ejemplo n.º 23
0
 public void AfterMsgCall(ReceiveMsg msg, ResponseMsg repMsg)
 {
 }
Ejemplo n.º 24
0
 private void OnReceiveData(string msg)
 {
     ReceiveMsg?.Invoke(msg);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// 添加单条数据
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public int Add(ReceiveMsg obj)
 {
     return(dal.Add(obj));
 }