Example #1
0
        /// <summary>
        /// 消息同步
        /// </summary>
        void wxSync()
        {
            string url = String.Format("{0}/cgi-bin/mmwebwx-bin/webwxsync?sid={1}&skey={2}&pass_ticket={3}", gateway, baseRequest.Sid, baseRequest.Skey, passticket);
            var    o   = new
            {
                BaseRequest = baseRequest,
                SyncKey     = _syncKey,
                rr          = getcurrentseconds()
            };
            var rsp = wc.PostStr(url, Serialize.ToJson(o));

            outLog("sync->" + Serialize.ToJson(rsp));

            if (rsp.err)
            {
                throw new Exception("消息获取失败->" + Serialize.ToJson(rsp));
            }

            _syncKey = Serialize.FromJson <SyncKey>(rsp.data + "", "SyncKey");

            var msglist = Serialize.FromJson <List <Msg> >(rsp.data + "", "AddMsgList");

            foreach (var m in msglist)
            {
                if (m.FromUserName != user.UserName)
                {
                    outLog("msg->" + user.Uin + "->" + m.Content); NewMsg?.Invoke(m, ukey);
                }                                                                                                                                      // Debug.WriteLine(user.Uin + "收到消息->" + m.MsgId + "--->>>" + m.Content);
            }
        }
Example #2
0
        /// <summary>
        /// 处理消息
        /// </summary>
        void recProc()
        {
            try
            {
                while (!stop)
                {
                    if (data.Count < 7)
                    {
                        Thread.Sleep(500); continue;
                    }

                    var head = data.Take(5).ToArray();
                    if (Encoding.UTF8.GetString(head) != "x.rbt")
                    {
                        continue;
                    }

                    var len  = BitConverter.ToUInt16(data.Skip(5).Take(2).ToArray(), 0);
                    var body = Encoding.UTF8.GetString(data.Skip(7).Take(len).ToArray());
                    lock (data) data.RemoveRange(0, len + 7);

                    NewMsg?.Invoke(Serialize.FromJson <msg>(body));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("tc.recProc->" + ex.Message);
                exit(1);
            }
        }
Example #3
0
 /// <summary>
 /// Включает прослушивание TCP канала порта
 /// </summary>
 public void ListenTCP()
 {
     try
     {
         while (true)
         {
             byte[] bufer    = new byte[1024];
             int    bytesRec = SRV.Receive(bufer);
             NewMsg?.Invoke(Encoding.ASCII.GetString(bufer, 0, bytesRec));
         }
     }
     catch (Exception)
     {
         Error?.Invoke("Сервер отключился");
     }
 }
Example #4
0
        /// <summary>
        /// 消息同步
        /// </summary>
        void wxSync()
        {
            string url = String.Format("{0}/cgi-bin/mmwebwx-bin/webwxsync?sid={1}&skey={2}&pass_ticket={3}", gateway, baseRequest.Sid, baseRequest.Skey, passticket);
            var    o   = new
            {
                BaseRequest = baseRequest,
                SyncKey     = _syncKey,
                rr          = getcurrentseconds()
            };
            var rsp = wc.PostStr(url, Serialize.ToJson(o));

            outLog("sync->" + Serialize.ToJson(rsp));

            if (rsp.err)
            {
                throw new Exception("消息获取失败->" + Serialize.ToJson(rsp));
            }

            _syncKey = Serialize.FromJson <SyncKey>(rsp.data + "", "SyncKey");

            var msglist = Serialize.FromJson <List <Msg> >(rsp.data + "", "AddMsgList");

            foreach (var m in msglist)
            {
                if (m.FromUserName == user.UserName)
                {
                    continue;
                }



                //outLog("msg->" + user.Uin + "->" + m.Content);

                //if (m.Content.Contains("你的朋友验证请求,") && m.Content.Contains("可以开始聊天了"))
                //{
                //    var rp = db.x_reply.Where(r => r.user_id == lg.user_id);
                //}

                //var rps = db.x_reply.FirstOrDefault(o => o.keys)

                NewMsg?.Invoke(m);
            }

            // Debug.WriteLine(user.Uin + "收到消息->" + m.MsgId + "--->>>" + m.Content);
        }
Example #5
0
 protected virtual void OnNewMsg(object sender, NewMsgEventArgs e)
 {
     NewMsg?.Invoke(sender, e);
 }
Example #6
0
 public void UseEvent()
 {
     NewMsg?.Invoke();
 }
Example #7
0
 public void ClearDiary()
 {
     _diary = null;
     newMsgCb?.Invoke();
 }
Example #8
0
        /// <summary>
        /// 解析消息
        /// </summary>
        void Prase()
        {
            var list = new List <byte>();

            string str = "";

            while (!stop)
            {
                if (data.Count == 0)
                {
                    Thread.Sleep(500); continue;
                }

                var dh = data.Take(2).ToArray();
                lock (data) { data.RemoveRange(0, 2); }

                var opcode = dh[0] & 15;

                if (opcode == 8)
                {
                    exit(1); return;
                }                                    //断开

                var mask = (dh[1] >> 7) == 1;

                ulong len = (uint)dh[1] & 127;
                if (len > 125)
                {
                    var max = len == 126 ? 2 : 8;
                    var dl  = data.Take(max).Reverse().ToArray();
                    lock (data) { data.RemoveRange(0, max); }
                    len = (max == 2 ? BitConverter.ToUInt16(dl, 0) : BitConverter.ToUInt64(dl, 0));
                }

                var mkey = new byte[4];
                if (mask)
                {
                    mkey = data.Take(4).ToArray();
                    lock (data) { data.RemoveRange(0, 4); }
                }

                var dt = data.Take((int)len).ToArray();
                while (true)
                {
                    if ((ulong)dt.Length == len)
                    {
                        break;
                    }
                    Thread.Sleep(500);
                }
                ;
                lock (data) { data.RemoveRange(0, (int)len); }

                if (mask)
                {
                    for (var i = 0; i < dt.Length; i++)
                    {
                        dt[i] = (byte)(dt[i] ^ mkey[i % 4]);
                    }
                }

                str = Encoding.UTF8.GetString(dt);

                try
                {
                    var m = Serialize.FromJson <msg>(str);

                    if (m == null)
                    {
                        return;
                    }
                    if (m.act == "setcode")
                    {
                        code = m.body;
                    }

                    NewMsg?.Invoke(m, this);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("tcp.prase->" + ex.Message);
                    exit(1);
                }
            }
        }
Example #9
0
        /// <summary>
        /// 解析消息
        /// </summary>
        void Prase()
        {
            string str  = "";
            int    hlen = 9;

            while (stop == 0)
            {
                if (data.Count < hlen)
                {
                    Thread.Sleep(500); continue;
                }

                byte[] head = null;
                lock (data) head = data.Take(5).ToArray();
                if (Encoding.UTF8.GetString(head) != "x.rbt")
                {
                    lock (data) data.RemoveRange(0, hlen); continue;
                }

                var len = BitConverter.ToInt32(data.Skip(5).Take(4).ToArray(), 0) + 32;
                if (data.Count() < len)
                {
                    continue;
                }

                byte[] msg = null;
                lock (data) msg = data.Skip(9).Take(len).ToArray();
                lock (data) data.RemoveRange(0, len + 9);

                try
                {
                    str = Encoding.UTF8.GetString(Encry.Decode(msg, key));

                    Console.WriteLine("parse->" + str);
                    Debug.WriteLine("parse->" + str);

                    var sign = str.Substring(0, 32);
                    var json = str.Substring(32);
                    if (sign != Secret.MD5(json + key))
                    {
                        throw new Exception("签名验证失败");
                    }
                    var m = Serialize.FromJson <msg>(json);
                    switch (m.act)
                    {
                    case "heart":
                        continue;

                    case "exit":
                        exit(1);
                        break;

                    case "msg":
                        NewMsg?.Invoke(m.from, m.body, this);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (ex.Message == "Decode Error")
                    {
                        exit(2);
                    }
                    Console.WriteLine("parse->err." + ex.Message);
                    Debug.WriteLine("parse->err." + ex.Message);
                }
            }
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="list"></param>
        /// <param name="cts"></param>
        /// <param name="nks"></param>
        /// <param name="t"></param>
        List <object> toContact(List <Contact> list, Dictionary <string, int> nks, long gpid)
        {
            var cts = new List <x_contact>();
            var gps = new List <object>();

            foreach (var c in list)
            {
                var n = c.NickName;
                if (!string.IsNullOrEmpty(c.RemarkName))
                {
                    n = c.RemarkName;
                }
                if (gpid > 0)
                {
                    n += gpid;
                }
                n += user.Uin;
                if (nks.ContainsKey(n))
                {
                    c.RemarkName = c.NickName + (++nks[n]).ToString("000");
                }                                                                                  //SetRemark(c.UserName, c.RemarkName);
                else
                {
                    nks.Add(n, 0); c.RemarkName = n;
                }

                var no = Secret.MD5(n);
                var ct = db.x_contact.FirstOrDefault(t => t.no == no && t.uin == user.Uin);
                if (ct == null)
                {
                    ct = new x_contact()
                    {
                        uin = user.Uin, no = no
                    }
                }
                ;

                ct.user_id     = lg.user_id;
                ct.remarkname  = c.RemarkName;
                ct.nickname    = Tools.RemoveHtml(c.NickName);
                ct.flag        = c.UserName[1] == '@' ? 2 : 1;
                ct.group_id    = gpid;
                ct.membercount = c.MemberCount;
                ct.signature   = c.Signature;
                ct.username    = c.UserName;
                ct.imgurl      = c.HeadImgUrl;

                var m = new Regex("(\\d{11})").Match(c.NickName);
                if (m.Success)
                {
                    ct.tel = m.Groups[1].Value;
                }
                if (ct.contact_id == 0)
                {
                    cts.Add(ct);
                }

                if (c.UserName[1] == '@')
                {
                    gps.Add(new
                    {
                        EncryChatRoomId = c.EncryChatRoomId,
                        UserName        = c.UserName
                    });
                }
            }
            if (cts.Count > 0)
            {
                db.x_contact.InsertAllOnSubmit(cts);
            }
            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
                db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            }
            catch (ChangeConflictException)
            {
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    occ.Resolve(RefreshMode.KeepChanges);
                }
            }
            catch (Exception ex)
            {
                outLog("toContact->err:" + ex.Message);
            }
            return(gps);
        }

        /// <summary>
        /// 同步检测
        /// </summary>
        void SyncCheck()
        {
            var url = String.Format("{0}/cgi-bin/mmwebwx-bin/synccheck?r={1}&sid={2}&uin={3}&skey={4}&deviceid={5}&synckey={6}&_{7}", gateway, getcurrentseconds(), baseRequest.Sid, baseRequest.Uin, baseRequest.Skey, baseRequest.DeviceID, synckey, getcurrentseconds());
            var rsp = wc.GetStr(url);

            outLog("synccheck->" + Serialize.ToJson(rsp));

            if (rsp.err)
            {
                return; throw new Exception("心跳同步失败->" + Serialize.ToJson(rsp));
            }

            var reg = new Regex("{retcode:\"(\\d+)\",selector:\"(\\d+)\"}");
            var m   = reg.Match(rsp.data + "");

            var rt  = int.Parse(m.Groups[1].Value);
            var sel = int.Parse(m.Groups[2].Value);

            if (isquit || rt != 0)
            {
                exit(1);
            }
            else if (sel == 2 || sel == 4 || sel == 6)
            {
                wxSync();
            }
        }

        /// <summary>
        /// 消息同步
        /// </summary>
        void wxSync()
        {
            string url = String.Format("{0}/cgi-bin/mmwebwx-bin/webwxsync?sid={1}&skey={2}&pass_ticket={3}", gateway, baseRequest.Sid, baseRequest.Skey, passticket);
            var    o   = new
            {
                BaseRequest = baseRequest,
                SyncKey     = _syncKey,
                rr          = getcurrentseconds()
            };
            var rsp = wc.PostStr(url, Serialize.ToJson(o));

            outLog("sync->" + Serialize.ToJson(rsp));

            if (rsp.err)
            {
                throw new Exception("消息获取失败->" + Serialize.ToJson(rsp));
            }

            _syncKey = Serialize.FromJson <SyncKey>(rsp.data + "", "SyncKey");

            var msglist = Serialize.FromJson <List <Msg> >(rsp.data + "", "AddMsgList");

            foreach (var m in msglist)
            {
                if (m.FromUserName == user.UserName)
                {
                    continue;
                }
                outLog("msg->" + user.Uin + "->" + m.Content);

                if (m.Content.Contains("你的朋友验证请求,") && m.Content.Contains("可以开始聊天了"))
                {
                    var rp = db.x_reply.Where(r => r.user_id == lg.user_id);
                }

                //var rps = db.x_reply.FirstOrDefault(o => o.keys)

                NewMsg?.Invoke(m);
            }

            // Debug.WriteLine(user.Uin + "收到消息->" + m.MsgId + "--->>>" + m.Content);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="ToUserName"></param>
        /// <param name="Content"></param>
        void sendText(string ToUserName, string Content)
        {
            string url = String.Format("{0}/cgi-bin/mmwebwx-bin/webwxsendmsg?pass_ticket={1}", gateway, passticket);

            Content = Content.Replace("<br/>", "\n");
            var o = new
            {
                BaseRequest = baseRequest,
                Msg         = new
                {
                    Type         = 1,
                    Content      = Content,
                    FromUserName = user.UserName,
                    ToUserName   = ToUserName,
                    LocalID      = getcurrentseconds(),
                    ClientMsgId  = getcurrentseconds()
                }
            };

            var rsp = op.PostStr(url, Serialize.ToJson(o));

            outLog("SendMsg->" + Serialize.ToJson(rsp));
        }

        /// <summary>
        /// 发送图片
        /// </summary>
        /// <param name="ToUserName"></param>
        /// <param name="url"></param>
        void sendImg(string ToUserName, string mmid)
        {
            //var mmid = uploadImg(ToUserName, url);
            //if (string.IsNullOrEmpty(mmid)) return;

            string api = String.Format("{0}/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&pass_ticket={1}", gateway, passticket);
            var    o   = new
            {
                BaseRequest = baseRequest,
                Msg         = new
                {
                    Type         = 3,
                    MediaId      = mmid,
                    FromUserName = user.UserName,
                    ToUserName   = ToUserName,
                    LocalID      = getcurrentseconds(),
                    ClientMsgId  = getcurrentseconds()
                },
                Scene = 0
            };

            var rsp = op.PostStr(api, Serialize.ToJson(o));

            if (!(rsp.data + "").Contains("\"Ret\": 0"))
            {
                Thread.Sleep(5 * 1000);
            }

            outLog("SendImg->" + Serialize.ToJson(rsp));
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        string uploadImg(string img)
        {
            var fs = op.GetFile(img);

            if (fs.err)
            {
                return("");
            }

            string url = gateway.Replace("https://", "https://file.") + "/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";
            var    o   = new
            {
                UploadType    = 2,
                BaseRequest   = baseRequest,
                ClientMediaId = getcurrentseconds(),
                TotalLen      = (fs.data as byte[]).Length,
                StartPos      = 0,
                DataLen       = (fs.data as byte[]).Length,
                MediaType     = 4
            };

            Dictionary <string, string> dict = new Dictionary <string, string>();

            dict.Add("id", "WU_FILE_" + filecount++);
            dict.Add("name", img.Substring(img.LastIndexOf('/') + 1));
            dict.Add("type", Tools.GetMimeType(img.Substring(img.LastIndexOf('.') + 1)));
            dict.Add("lastModifiedDate", "Wed Sep 07 2016 10:38:12 GMT+0800");//DateTime.Now.ToString("r")
            dict.Add("size", (fs.data as byte[]).Length + "");
            dict.Add("mediatype", "pic");
            dict.Add("uploadmediarequest", Serialize.ToJson(o));
            dict.Add("webwx_data_ticket", wc.GetCookie("webwx_data_ticket"));
            dict.Add("pass_ticket", passticket);

            var rsp = op.PostFile(url, dict, fs.data as byte[]);

            outLog("UploadImg->" + Serialize.ToJson(rsp));

            if (rsp.err)
            {
                return("");
            }

            return(Serialize.FromJson <string>(rsp.data + "", "MediaId"));
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="c"></param>
        void exit(int c)
        {
            outLog("exit");
            isquit = true;

            if (lg != null)
            {
                lg.uuid   = null;
                lg.qrcode = null;
                lg.status = 1;

                try
                {
                    db.SubmitChanges();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    outLog("exit->err:" + ex.Message);
                }
            }
            if (c == 1)
            {
                Logout?.Invoke();
            }
        }
Example #11
0
 public override void Write(string message)
 {
     NewMsg?.Invoke(message, this.IndentLevel);
 }