Example #1
0
        private void backgroundWorkerSync_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //MsgHandle handle = new MsgHandle();
            string state = e.UserState as string;

            if (string.IsNullOrEmpty(state))
            {
                AddMsgList msg = e.UserState as AddMsgList;
                if (msg != null)
                {
                    LogOut(string.Format("消息类型:{0},FromUserName:{1},ToUserName:{2},消息内容:{3},\r\n NotifyUserName:{4},时间:{5}",
                                         msg.MsgType, msg.FromUserName, msg.ToUserName, msg.Content, msg.StatusNotifyUserName, DateTime.Now));

                    MsgHandle handle  = new MsgHandle();
                    int       msgType = msg.MsgType;
                    switch (msgType)
                    {
                    case (int)MsgTypeEnum.系统消息:
                        handle.InitWxUser(msg);
                        break;

                    case (int)MsgTypeEnum.加好友:
                        if (buyService.HaveUser(Global.robot.Id, msg.RecommendInfo.NickName))
                        {
                            var result = protocol.VerifyUser(msg.RecommendInfo.UserName, msg.RecommendInfo.Ticket, Global.robot.Cookie, Global.robot.CookieStr);
                            LogOut("加好友" + result.ErrMsg);
                            //加完好友之后增加到机器人的好友表中
                            //wx_friend friend = new wx_friend();
                            //friend.UserName = msg.RecommendInfo.UserName;
                            //friend.NickName = msg.RecommendInfo.NickName;
                            //friend.AttrStatus = msg.RecommendInfo.AttrStatus;
                            //ContactService service = new ContactService();
                            //service.AddContent(friend);
                            Global.robot.Contact = protocol.GetContact(Global.robot.Cookie, Global.robot.CookieStr).MemberList.ToList();
                            Task.Run(() =>
                            {
                                protocol.StatusNotify(Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                            });

                            //发送消息
                            protocol.SendMsg("请输入验证码,如未购买,请访问", msg.RecommendInfo.UserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                        }
                        break;

                    case (int)MsgTypeEnum.群通知:
                        //好友已添加,被拉进群
                        if (msg.FromUserName.StartsWith("@@"))
                        {
                            //拉进群
                            //初始化
                            //拉别人进群也会有此通知
                            //判断群id是否存在,不存在初始化
                            var user = Global.robot.WxUserList.Where(u => u.UserName == msg.FromUserName).FirstOrDefault();
                            if (user == null)
                            {
                                protocol.StatusNotify(Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                            }
                            //protocol.SendMsg("群绑定成功,机器人开始为您服务", msg.FromUserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                        }
                        else
                        {
                            //好友
                        }
                        break;

                    default:
                        if (msg.FromUserName.StartsWith("@@") && msg.ToUserName.StartsWith("@"))
                        {
                            //群消息对个人
                            string fromAlias = WechatCommon.GetTrueId(msg.FromUserName);
                            bool   isBind    = buyService.IsBind(fromAlias);
                            string content   = msg.Content;

                            if (isBind)
                            {
                                //聊天记录
                                wx_group_chat chat = new wx_group_chat();
                                chat.Createtime    = DateTime.Now;
                                chat.MsgType       = msg.MsgType;
                                chat.GroupUserName = msg.FromUserName;
                                chat.GroupId       = WechatCommon.GetTrueId(msg.FromUserName);

                                if (content.StartsWith("@"))
                                {
                                    int    startIndex   = content.IndexOf(':');
                                    string fromUserName = content.Substring(0, startIndex);
                                    chat.SendAlias      = WechatCommon.GetTrueId(fromUserName);
                                    chat.SendUserName   = fromUserName;
                                    chat.Content        = content.Substring(startIndex + 6);
                                    chat.SendNickName   = WechatCommon.GetNickNameFromGroup(msg.FromUserName, fromUserName);
                                    chat.SendAttrStatus = WechatCommon.GetAttrStatusFromGroup(msg.FromUserName, fromUserName);
                                }
                                else
                                {
                                    chat.Content = content;
                                }
                                msgService.InsertMsg(chat);
                            }
                            //判断是否是开通群空间
                            if (content.StartsWith("@"))
                            {
                                int    startIndex   = content.IndexOf(':');
                                string fromUserName = content.Substring(0, startIndex);
                                string sendAlias    = WechatCommon.GetTrueId(fromUserName);
                                string message      = content.Substring(startIndex + 6);

                                string[] c = message.Split(' ');
                                if (c != null && c.Length == 2)
                                {
                                    if (c[0] == "@" + Global.robot.NickName && c[1] == "开通群空间")
                                    {
                                        //判断已经开通的群无法再次开通
                                        if (!isBind)
                                        {
                                            int recordId = buyService.GetBuyRecordId(Global.robot.Id, sendAlias);
                                            if (recordId > 0)
                                            {
                                                int result = buyService.BindGroup(recordId, fromAlias);
                                                if (result > 0)
                                                {
                                                    protocol.SendMsg("群绑定成功,机器人开始为您服务", msg.FromUserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                                                    //群空间开通功能,捞取人员信息存入数据库等操作

                                                    var groupInfo = Global.robot.GroupInfo.Where(n => n.UserName == msg.FromUserName).FirstOrDefault();
                                                    if (groupInfo == null)
                                                    {
                                                        BatchGetContactResult contactResult = protocol.BatchGetContact(new List <string>()
                                                        {
                                                            msg.FromUserName
                                                        }, Global.robot.Cookie, Global.robot.CookieStr);
                                                        if (contactResult != null)
                                                        {
                                                            groupInfo = contactResult.ContactList[0];
                                                        }
                                                    }
                                                    //存数据库
                                                    Task.Run(() => {
                                                        GroupService groupService = new GroupService();
                                                        groupService.SyncGroup(groupInfo);
                                                    });
                                                }
                                                else
                                                {
                                                    protocol.SendMsg("群绑定失败", msg.FromUserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            protocol.SendMsg("群已经被绑定", msg.FromUserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                                        }
                                    }
                                }
                            }
                        }
                        else if (msg.FromUserName.StartsWith("@") && msg.ToUserName.StartsWith("@@"))
                        {
                            //个人发群消息
                        }
                        else if (msg.FromUserName.StartsWith("@") && msg.ToUserName.StartsWith("@"))
                        {
                            //个人对个人
                            if (msg.ToUserName == Global.robot.UserName)
                            {
                                //判断内容是否跟验证码符合
                                string nickName = Global.robot.Contact.Where(n => n.UserName == msg.FromUserName).Select(n => n.NickName).FirstOrDefault();
                                int    recordId = buyService.VaildCode(Global.robot.Id, nickName, msg.Content);
                                if (recordId > 0)
                                {
                                    //绑定成功
                                    string alias = WechatCommon.GetTrueId(msg.FromUserName);
                                    if (buyService.UseCode(recordId, alias) > 0)
                                    {
                                        protocol.SendMsg("验证成功,请添加到群中", msg.FromUserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                                    }
                                    else
                                    {
                                        protocol.SendMsg("验证失败,请重新输入", msg.FromUserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                                    }
                                }
                                else
                                {
                                    protocol.SendMsg("验证码错误,如未购买,请访问", msg.FromUserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                                }
                            }
                        }
                        break;
                    }

                    //if (msg.MsgType == (int)MsgTypeEnum.加好友)
                    //{
                    //    //加好友
                    //    var result = protocol.VerifyUser(msg.RecommendInfo.UserName, msg.RecommendInfo.Ticket, Global.robot.Cookie, Global.robot.CookieStr);
                    //    LogOut("加好友" + result.ErrMsg);
                    //}
                    //else if (msg.MsgType == (int)MsgTypeEnum.系统消息&&msg.ToUserName.StartsWith("@@"))
                    //{
                    //    //群
                    //    //protocol.SendMsg("欢迎加入群聊天", msg.ToUserName, 1, Global.robot.Cookie, Global.robot.CookieStr,Global.robot.UserName);
                    //    //string html = protocol.BatchGetContact(msg.ToUserName, Global.robot.Cookie, Global.robot.CookieStr);
                    //}
                }
            }
            else if (state == "1100")
            {
                LogOut("拉取消息请求超时,请重新登录" + DateTime.Now);
                syncRun = false;
            }
            else if (state == "正常")
            {
                LogOut("0正常捞取" + DateTime.Now);
            }
            else
            {
                LogOut(state + "未知异常,请重新登录" + DateTime.Now);
                syncRun = false;
            }
        }
Example #2
0
        /// <summary>
        /// 获取联系人信息
        /// </summary>
        /// <returns></returns>
        public ContactResult GetContact(WechatCookie wechatCookie, string cookieStr)
        {
            string url = string.Format(WechatUrl.ContentUrl, wechatCookie.Pass_Ticket, WechatCommon.GetTicks(), wechatCookie.Skey);

            string html = HttpCommon.instance.PostHttp(url, "{}", ContentType.json, cookieStr);

            AppLog.WriteInfo(string.Format("协议:{0},结果:{1}", "GetContact", html));

            ContactResult contact = new ContactResult();

            try
            {
                if (!string.IsNullOrEmpty(html) && html != "操作超时")
                {
                    contact = JsonConvert.DeserializeObject <ContactResult>(html);
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message);
            }
            return(contact);
        }
Example #3
0
        public void Sync(BackgroundWorker work, string host)
        {
            if (work.CancellationPending)
            {
                return;
            }

            var robot = Global.robot;

            if (robot.State == 1)
            {
                var result = protocol.SyncCheck(host, robot.Cookie, robot.CookieStr, robot.SynckeyStr);

                /*
                 * retcode:
                 *  0 正常
                 *  1100 失败/登出微信
                 * selector:
                 *  0 正常
                 *  2 新的消息
                 *  7 进入/离开聊天界面
                 */
                if (result.retcode == "0")
                {
                    //switch (result.selector)
                    //{
                    //    case "0":
                    //        work.ReportProgress(1, "正常");
                    //        break;
                    //    default:
                    SyncResult syncResult = protocol.Sync(robot.Cookie, robot.CookieStr, robot.SyncKey);
                    robot.SyncKey    = syncResult.SyncKey;
                    robot.SynckeyStr = WechatCommon.SyncKeyFormat(syncResult.SyncKey);
                    List <AddMsgList> msgList = syncResult.AddMsgList;

                    if (syncResult.ModContactCount > 0)
                    {
                        //群人员变化了
                        //判断是否已经存在的群,不存在的重新初始化
                        bool change = false;
                        foreach (var contact in syncResult.ModContactList)
                        {
                            if (contact.UserName.StartsWith("@@"))
                            {
                                WxUser user = Global.robot.WxUserList.Where(n => n.UserName == contact.UserName).FirstOrDefault();
                                if (user == null)
                                {
                                    change = true;
                                    break;
                                }
                            }
                        }
                        if (change)
                        {
                            protocol.StatusNotify(Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                        }

                        //欢迎通知逻辑;对比两个群人员列表
                        foreach (var contact in syncResult.ModContactList)
                        {
                            string fromAlias = WechatCommon.GetTrueId(contact.UserName);
                            bool   isBind    = buyService.IsBind(fromAlias);
                            if (isBind)
                            {
                                var newMember  = contact.MemberList;
                                var haveMember = Global.robot.GroupInfo.Where(n => n.UserName == contact.UserName).FirstOrDefault();
                                if (haveMember != null)
                                {
                                    MemberListComparer compar = new MemberListComparer();
                                    var welcomeUser           = newMember.Except(haveMember.MemberList, compar); //差集新增
                                    Task.Run(() =>
                                    {
                                        foreach (var u in welcomeUser)
                                        {
                                            protocol.SendMsg("欢迎" + u.NickName + "加入群!", contact.UserName, 1, Global.robot.Cookie, Global.robot.CookieStr, Global.robot.UserName);
                                            Thread.Sleep(2000);
                                        }
                                    });
                                    haveMember.MemberList  = newMember;
                                    haveMember.MemberCount = newMember.Count;
                                }
                            }
                        }
                    }
                    foreach (var msg in msgList)
                    {
                        work.ReportProgress(1, msg);
                    }
                    //  break;
                    //  }
                }
                else
                {
                    work.ReportProgress(1, result.retcode);
                }
            }
            else
            {
                //还未登录
                work.ReportProgress(1, "0");
            }
        }
Example #4
0
        /// <summary>
        /// 第五步:微信初始化
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public InitSyncResult Init(WechatCookie wechatCookie, string cookieStr)
        {
            if (wechatCookie == null)
            {
                throw new Exception("cookie值为空");
            }

            string url = string.Format(WechatUrl.InitUrl, wechatCookie.Pass_Ticket, wechatCookie.Skey, WechatCommon.GetTicks());

            BaseRequest baseRequest = new BaseRequest();

            baseRequest.DeviceID = DeviceID;
            baseRequest.Sid      = wechatCookie.Wxsid;
            baseRequest.Uin      = wechatCookie.Wxuin;
            baseRequest.Skey     = wechatCookie.Skey;
            InitParamter init = new InitParamter();

            init.BaseRequest = baseRequest;

            string postData = JsonConvert.SerializeObject(init);

            // string html =await HttpCommon.instance.PostHttp(url, postData, ContentType.json, cookieStr);
            HttpHelper http = new HttpHelper();
            HttpItem   item = new HttpItem()
            {
                URL         = url,                                                                        //URL     必需项
                Method      = "POST",                                                                     //URL     可选项 默认为Get
                Encoding    = Encoding.UTF8,
                UserAgent   = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0", //用户的浏览器类型,版本,操作系统     可选项有默认值
                Accept      = "text/html, application/xhtml+xml, */*",                                    //    可选项有默认值
                ContentType = "application/json; charset=UTF-8",                                          //返回类型    可选项有默认值
                Cookie      = cookieStr,                                                                  //字符串Cookie     可选项
                Postdata    = postData,                                                                   //Post数据     可选项GET时不需要写
            };
            HttpResult result = http.GetHtml(item);
            string     html   = result.Html;

            AppLog.WriteInfo(string.Format("协议:{0},结果:{1}", "Init", html));

            InitSyncResult syncKey = new InitSyncResult();

            try
            {
                if (!string.IsNullOrEmpty(html) && html != "操作超时")
                {
                    InitResult obj = JsonConvert.DeserializeObject <InitResult>(html);
                    syncKey.SynckeyStr = WechatCommon.SyncKeyFormat(obj.SyncKey);
                    syncKey.SyncKey    = obj.SyncKey;
                    syncKey.UserName   = obj.User.UserName;
                    syncKey.Uin        = obj.User.Uin;
                    syncKey.Nickname   = obj.User.NickName;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message);
            }
            return(syncKey);
        }