-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathClient.cs
1150 lines (1103 loc) · 50.8 KB
/
Client.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using WeChatAPI.Modal;
using WeChatAPI.Modal.Request;
using WeChatAPI.Modal.Response;
namespace WeChatAPI
{
public class GetContactException : Exception
{
public GetContactException(string msg) : base(msg) { }
}
public class Client
{
private AsyncOperation asyncOperation;
private TaskFactory factory;
private CancellationTokenSource source;
private WxHttpClient httpClient = new WxHttpClient();
private bool finishGetContactList = false;
private bool syncPolling = true;
#region 重要内部参数
private string passTicket;
/// <summary>
/// 扫码之后返回要跳转跳转页面,通过这个地址获取cookie等总要信息
/// </summary>
private string cookieRedirectUri;
private SyncKey syncKey;
private BaseRequest baseRequest;
private User user;
/// <summary>
/// 检测是否扫码用
/// </summary>
private string uuid = string.Empty;
private string host = Const.HOST;
private string pushHost = Const.PUSH_HOST;
private string uploadHost = Const.UPLOAD_HOST;
public string Host
{
get
{
return this.host;
}
}
/// <summary>
/// 当前登录用户
/// </summary>
public User CurrentUser
{
get
{
return user;
}
}
/// <summary>
/// 是否读取完联系人
/// </summary>
public bool IsFinishGetContactList
{
get
{
return finishGetContactList;
}
set
{
finishGetContactList = value;
}
}
#endregion
private List<MPSubscribeMsg> mpSubscribeMsgList = new List<MPSubscribeMsg>();
private Dictionary<string, string> uploadMedia = new Dictionary<string, string>();
#region 异步回调事件
/// <summary>
/// 异步调用的异常都会反馈在这里。
/// </summary>
public event EventHandler<TEventArgs<Exception>> ExceptionCatched;
/// <summary>
/// 获取登陆二维码
/// </summary>
public event EventHandler<TEventArgs<byte[]>> GetLoginQrCodeComplete;
/// <summary>
/// 用户扫码
/// </summary>
public event EventHandler<TEventArgs<byte[]>> CheckScanComplete;
/// <summary>
/// 登陆成功,返回当前登录用户信息
/// </summary>
public event EventHandler<TEventArgs<User>> LoginComplete;
/// <summary>
/// 批次读取联系人信息
/// </summary>
public event EventHandler<TEventArgs<List<Contact>>> BatchGetContactComplete;
/// <summary>
/// 获取联系人列表
/// </summary>
public event EventHandler<TEventArgs<List<Contact>>> GetContactComplete;
/// <summary>
/// 登出
/// </summary>
public event EventHandler<TEventArgs<User>> LogoutComplete;
/// <summary>
/// 接受消息
/// </summary>
public event EventHandler<TEventArgs<List<AddMsg>>> ReceiveMsg;
/// <summary>
/// 公众号文章读取完成
/// </summary>
public event EventHandler<TEventArgs<List<MPSubscribeMsg>>> MPSubscribeMsgListComplete;
/// <summary>
/// 删除联系人完成
/// </summary>
public event EventHandler<TEventArgs<List<DelContactItem>>> DelContactListComplete;
/// <summary>
/// 修改联系人完成
/// </summary>
public event EventHandler<TEventArgs<List<ModContactItem>>> ModContactListComplete;
//public event EventHandler<TEventArgs<List<>>> ModChatRoomMemberListComplete;
#endregion
public Client()
{
baseRequest = new BaseRequest();
asyncOperation = AsyncOperationManager.CreateOperation(null);
source = new CancellationTokenSource();
factory = new TaskFactory(source.Token);
}
/// <summary>
/// 启动客户端
/// </summary>
public void Start()
{
if (syncPolling != false)
{
factory.StartNew(() => GetLoginQrCode())
.ContinueWith((antecedent) => CheckSacnLogin(), source.Token, TaskContinuationOptions.NotOnFaulted, TaskScheduler.Default)
.ContinueWith((antecedent) => Init(), source.Token, TaskContinuationOptions.NotOnFaulted, TaskScheduler.Default)
.ContinueWith((antecedent) => StatusNotify(), source.Token, TaskContinuationOptions.NotOnFaulted, TaskScheduler.Default)
.ContinueWith((antecedent) => GetContact(), source.Token, TaskContinuationOptions.NotOnFaulted, TaskScheduler.Default)
.ContinueWith((antecedent) => Sync(), source.Token, TaskContinuationOptions.NotOnFaulted, TaskScheduler.Default);
}
else
{
throw new ObjectDisposedException("Client", "客户端已经登出释放,请重新实例化。");
}
}
/// <summary>
/// 如果还未sync,调用此方法结束客户端,否则调用logout
/// </summary>
public void Close()
{
syncPolling = false;
source.Cancel();
}
/// <summary>
/// 同步登出客户端
/// </summary>
/// <returns>可以不用理会结果</returns>
public string Logout()
{
string logoutUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxlogout?redirect=1&type=0&skey={0}", baseRequest.Skey);
string body = string.Format("sid={0}&uin={1}", baseRequest.Sid, baseRequest.Uin);
string result = string.Empty;
result = httpClient.PostFormString(logoutUrl, body);
Utils.Debug(result, "logout");
Close();
return result;
}
/// <summary>
/// 异步登出客户端
/// </summary>
public void LogoutAsync()
{
Task.Factory.StartNew(() =>
{
if (baseRequest != null)
{
try
{
string result = Logout();
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
LogoutComplete?.Invoke(this, new TEventArgs<User>((User)obj));
}), user);
}
catch (Exception e)
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
throw e;
}
}
});
}
/// <summary>
/// 获取登陆二维码
/// </summary>
private void GetLoginQrCode()
{
try
{
string jsloginUrl = $"https://login.wx2.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx2.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_={Utils.GetJavaTimeStamp()}";
string result = httpClient.GetString(jsloginUrl);
Utils.Debug("GetLoginQrCode " + result);
string qruuidStr = "window.QRLogin.uuid = \"";
int index = result.IndexOf("window.QRLogin.uuid = \"");
if (index == -1)
{
throw new Exception("获取登陆二维码失败,请稍后再试。");
}
else
{
uuid = result.Substring(index + qruuidStr.Length, result.Length - index - qruuidStr.Length - "\";".Length);
}
string qrcodeUrl = string.Format("https://login.weixin.qq.com/qrcode/{0}", uuid);
var img = httpClient.GetImage(qrcodeUrl);
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
GetLoginQrCodeComplete?.Invoke(this, new TEventArgs<byte[]>((byte[])obj));
}), img);
}
catch (Exception e)
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
throw e;
}
}
private enum ScanState { UnKnown, Timeout, Scan, Login, Expires };
/// <summary>
/// 检测手机是否扫码
/// </summary>
private void CheckSacnLogin()
{
try
{
byte[] userAvatar = null;
ScanState scanState = ScanState.UnKnown;
while (syncPolling && (scanState != ScanState.Login))
{
string timespan = Utils.GetTimeStamp();
string loginUrl = string.Format("https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=0&r={1}&_={2}", uuid, Utils.Get_r(), Utils.GetTimeStamp());
//采用长轮询的方式,25秒返内回一次检测数据。
string checkResult = httpClient.GetString(loginUrl);
Utils.Debug("CheckSacnLogin " + checkResult);
if (checkResult.IndexOf("window.code=408;") != -1)
{
scanState = ScanState.Timeout;
}
else if (checkResult.IndexOf("window.code=201;") != -1)
{
scanState = ScanState.Scan;
//有些号没有头像就跳过这个步骤
if (checkResult.IndexOf("window.userAvatar") != -1)
{
//扫码返回的头像是base64格式,需要转化
string subStr = "window.code=201;window.userAvatar = 'data:img/jpg;base64,";
string base64UserAvatar = checkResult.Substring(subStr.Length, checkResult.Length - subStr.Length - 2);
byte[] arr = Convert.FromBase64String(base64UserAvatar);
userAvatar = arr;
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
CheckScanComplete?.Invoke(this, new TEventArgs<byte[]>((byte[])obj));
}), userAvatar);
}
}
else if (checkResult.IndexOf("window.code=200;") != -1)
{
scanState = ScanState.Login;
string subStr = "window.code=200;\nwindow.redirect_uri=\"";
cookieRedirectUri = checkResult.Substring(subStr.Length, checkResult.Length - subStr.Length - 2);
//跳转登录页获取cookie,并且获取关键参数,根据跳转地址,获相应提交地址
string cookieRedirectResult = httpClient.LoginString(cookieRedirectUri);
if (cookieRedirectUri.StartsWith("https://wx2.qq.com"))
{
host = "https://wx2.qq.com";
pushHost = "https://webpush.wx2.qq.com";
uploadHost = "https://file.wx2.qq.com";
}
else if (cookieRedirectUri.StartsWith("https://wx8.qq.com"))
{
host = "https://wx8.qq.com";
pushHost = "https://webpush.wx8.qq.com";
uploadHost = "https://file.wx8.qq.com";
}
else if (cookieRedirectUri.StartsWith("https://web2.wechat.com"))
{
host = "https://web2.wechat.com";
pushHost = "https://webpush.web2.wechat.com";
uploadHost = "https://file.web2.wechat.com";
}
else if (cookieRedirectUri.StartsWith("https://web.wechat.com"))
{
host = "https://web.wechat.com";
pushHost = "https://webpush.web.wechat.com";
uploadHost = "https://file.web.wechat.com";
}
else
{
host = "https://wx.qq.com";
pushHost = "https://webpush.wx.qq.com";
uploadHost = "https://file.wx.qq.com";
}
httpClient.Referer = host;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(cookieRedirectResult);
//如果返回异常,则可能被暂封,无法登陆网页版
if (xmlDoc["error"]["ret"].InnerText != "0")
{
throw new Exception(xmlDoc["error"]["message"].InnerText);
}
else
{
baseRequest.Sid = xmlDoc["error"]["wxsid"].InnerText;
baseRequest.Uin = Convert.ToInt64(xmlDoc["error"]["wxuin"].InnerText);
baseRequest.Skey = xmlDoc["error"]["skey"].InnerText;
passTicket = xmlDoc["error"]["pass_ticket"].InnerText;
}
}
else if (checkResult.IndexOf("window.code=400;") != -1)
{
scanState = ScanState.Expires;
GetLoginQrCode();
}
else
{
scanState = ScanState.UnKnown;
}
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
FileLog.Exception("CheckSacnLogin", ex);
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), ex);
throw ex;
}
}
/// <summary>
/// 开始初始化所有关键内容
/// </summary>
private void Init()
{
try
{
string webwxinitUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxinit?r={0}pass_ticket={1}", Utils.Get_r(), passTicket);
JObject postjson = JObject.FromObject(new
{
BaseRequest = baseRequest
});
InitResponse initMsg = httpClient.PostJson<InitResponse>(webwxinitUrl, postjson);
if (initMsg.BaseResponse.Ret != 0)
{
throw new Exception("程序初始化失败");
}
//初始化2次,官网也是初始化2次,这样貌似比较稳定
httpClient.PostJson<InitResponse>(webwxinitUrl, postjson);
user = initMsg.User;
mpSubscribeMsgList = initMsg.MPSubscribeMsgList;
syncKey = initMsg.SyncKey;
//初始化的时候会返回一个最近联系人列表,但是主要还是以第一次sync获得的最近联系人为准。
asyncOperation.Post(
new SendOrPostCallback((list) =>
{
BatchGetContactComplete?.Invoke(this, new TEventArgs<List<Contact>>((List<Contact>)list));
}), initMsg.ContactList);
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
LoginComplete?.Invoke(this, new TEventArgs<User>((User)obj));
}), user);
}
catch (Exception ex)
{
FileLog.Exception("Init", ex);
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), ex);
//throw ex;
}
}
/// <summary>
/// 主要用于提醒手机端,同步状态
/// </summary>
private void StatusNotify()
{
try
{
//反馈服务器
string webwxstatusnotifyUrl = host + "/cgi-bin/mmwebwx-bin/webwxstatusnotify";
StatusNotifyRequest statusNotifyRequest = new StatusNotifyRequest();
statusNotifyRequest.BaseRequest = baseRequest;
statusNotifyRequest.Code = 3;
statusNotifyRequest.FromUserName = user.UserName;
statusNotifyRequest.ToUserName = user.UserName;
statusNotifyRequest.ClientMsgId = Utils.GetJavaTimeStamp();
//反馈结果可以不理
httpClient.PostJson<StatusNotifyResponse>(webwxstatusnotifyUrl, statusNotifyRequest);
}
catch (Exception e)
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
throw e;
}
}
/// <summary>
/// 获取联系人信息,例如初始化、群聊里面。
/// </summary>
/// <param name="statusNotifyUserName">需要获取的UserName列表,包括群,个人用户,用英文,分割</param>
/// <param name="EncryChatRoomId">默认为空,如果是获取群内成员详细信息,则填写encryChatRoomId,也就是群的UserName</param>
public void GetBatchGetContactAsync(string statusNotifyUserName, string encryChatRoomId = "")
{
Task.Factory.StartNew(() =>
{
try
{
//获取历史会话列表
string webwxbatchgetcontactUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r={0}", Utils.GetJavaTimeStamp());
string[] chatNameArr = statusNotifyUserName.Split(',');
bool finishGetChatList = false;
BatchGetContactRequest batchGetContactRequest = new BatchGetContactRequest();
batchGetContactRequest.BaseRequest = baseRequest;
int count = chatNameArr.Length;
int index = 0;
//一批次最多获取50条,多出来分批获取
while (!finishGetChatList)
{
batchGetContactRequest.List = new List<ChatRoom>();
if (((index + 1) * 50) < count)
{
for (int i = index * 50; i < (index + 1) * 50; i++)
{
batchGetContactRequest.List.Add(new ChatRoom { UserName = chatNameArr[i], EncryChatRoomId = encryChatRoomId });
}
}
else
{
for (int i = index * 50; i < count; i++)
{
batchGetContactRequest.List.Add(new ChatRoom { UserName = chatNameArr[i], EncryChatRoomId = encryChatRoomId });
}
finishGetChatList = true;
}
BatchGetContactResponse batchGetContactMsg = httpClient.PostJson<BatchGetContactResponse>(webwxbatchgetcontactUrl, batchGetContactRequest);
asyncOperation.Post(
new SendOrPostCallback((list) =>
{
BatchGetContactComplete?.Invoke(this, new TEventArgs<List<Contact>>((List<Contact>)list));
}), batchGetContactMsg.ContactList);
index++;
}
}
catch (Exception e)
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
}
});
}
/// <summary>
/// 读取用户的联系人列表,其中只包含公众号,个人号,如果返回值seq不为0,那么用户列表还没获取完(因为可能会有几千人的号,不可能一次获取完),则附带上seq的值继续获取。
/// </summary>
private void GetContact()
{
try
{
//获取联系人列表
finishGetContactList = false;
string getContactUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxgetcontact?r={0}&seq={1}&skey={2}", Utils.GetJavaTimeStamp(), 0, baseRequest.Skey);
while (!finishGetContactList)
{
string contactResult = httpClient.GetStringOnce(getContactUrl);
GetContactResponse getContactResponse = JsonConvert.DeserializeObject<GetContactResponse>(contactResult);
asyncOperation.Post(
new SendOrPostCallback((list) =>
{
GetContactComplete?.Invoke(this, new TEventArgs<List<Contact>>((List<Contact>)list));
}), getContactResponse.MemberList);
if (getContactResponse.Seq == 0)
{
finishGetContactList = true;
}
else
{
getContactUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxgetcontact?r={0}&seq={1}&skey={2}", Utils.GetJavaTimeStamp(), getContactResponse.Seq, baseRequest.Skey);
}
}
//获取完联系人中的公众号,才能获得名称,这个时候再发送图文消息事件。
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
MPSubscribeMsgListComplete?.Invoke(this, new TEventArgs<List<MPSubscribeMsg>>((List<MPSubscribeMsg>)obj));
}), mpSubscribeMsgList);
}
catch (Exception e)
{
if (e is WebException)
{
WebException we = e as WebException;
if (we.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.ServiceUnavailable)
{
//过千人账号有时候获取不到联系人列表,服务器返回503,官方测试结果也是反馈503导致获取不到,为了不影响正常使用,跳过获取联系人步骤
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), new GetContactException("无法获取好友列表"));
}
}
else
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
}
}
}
/// <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);
}
}
}
/// <summary>
/// 同步发送文字消息
/// </summary>
/// <param name="msg">文字</param>
/// <param name="toUserName">发送人UserName</param>
/// <returns></returns>
public SendMsgResponse SendMsg(string msg, string toUserName)
{
try
{
string time = Utils.GetJavaTimeStamp().ToString();
string sendMsgUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsendmsg?pass_ticket={0}", passTicket);
SendMsgRequest sendMsgRequest = new SendMsgRequest()
{
BaseRequest = baseRequest,
Msg = new Msg()
{
FromUserName = user.UserName,
ToUserName = toUserName,
ClientMsgId = time,
LocalID = time,
Type = MSGTYPE.MSGTYPE_TEXT,
Content = msg
},
Scene = 0
};
SendMsgResponse sendMsgResponse = httpClient.PostJson<SendMsgResponse>(sendMsgUrl, sendMsgRequest);
return sendMsgResponse;
}
catch (Exception ex)
{
Console.WriteLine($"Send Msg {ex.Message}");
throw ex;
}
}
/// <summary>
/// 同步发送文件,自动分块上传,文件较大可能会卡住进程,建议异步发送
/// </summary>
/// <param name="fileInfo">文件信息</param>
/// <param name="toUserName">发送人UserName</param>
/// <returns></returns>
public SendMsgResponse SendMsg(FileInfo fileInfo, string toUserName)
{
string mediaId = string.Empty;
if (uploadMedia.Keys.Contains(fileInfo.Name))
{
mediaId = uploadMedia[fileInfo.Name];
}
else
{
UploadMediaResponse uploadMediaResponse = UploadFile(fileInfo, toUserName);
mediaId = uploadMediaResponse.MediaId;
}
string mime = MimeMapping.GetMimeMapping(fileInfo.Name);
string time = Utils.GetJavaTimeStamp().ToString();
SendMsgResponse response = null;
if (mime.StartsWith("image"))
{
string sendMsgUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket={0}", passTicket);
SendMediaMsgRequest sendImgMsgRequest = new SendMediaMsgRequest()
{
BaseRequest = baseRequest,
Msg = new MediaMsg()
{
ClientMsgId = time,
FromUserName = user.UserName,
LocalID = time,
MediaId = mediaId,
ToUserName = toUserName,
Type = MSGTYPE.MSGTYPE_IMAGE
},
Scene = 0
};
response = httpClient.PostJson<SendMsgResponse>(sendMsgUrl, sendImgMsgRequest);
}
else if (mime.StartsWith("video"))
{
string sendMsgUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsendvideomsg?fun=async&f=json&lang=zh_CN&pass_ticket={0}", passTicket);
SendMediaMsgRequest sendImgMsgRequest = new SendMediaMsgRequest()
{
BaseRequest = baseRequest,
Msg = new MediaMsg()
{
ClientMsgId = time,
FromUserName = user.UserName,
LocalID = time,
MediaId = mediaId,
ToUserName = toUserName,
Type = MSGTYPE.MSGTYPE_IMAGE
},
Scene = 0
};
response = httpClient.PostJson<SendMsgResponse>(sendMsgUrl, sendImgMsgRequest);
}
else
{
string sendMsgUrl = string.Format(host + "/cgi-bin/mmwebwx-bin/webwxsendappmsg?fun=async&f=json&lang=zh_CN&pass_ticket={0}", passTicket);
SendMsgRequest sendAppMsgRequest = new SendMsgRequest()
{
BaseRequest = baseRequest,
Msg = new Msg()
{
ClientMsgId = time,
Content = string.Format("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>{0}</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>{1}</totallen><attachid>{2}</attachid><fileext>{3}</fileext></appattach><extinfo></extinfo></appmsg>", fileInfo.Name, fileInfo.Length, mediaId, fileInfo.Extension.Substring(1)),
FromUserName = user.UserName,
ToUserName = toUserName,
LocalID = time,
Type = MSGTYPE.MSGTYPE_DOC
},
Scene = 0
};
response = httpClient.PostJson<SendMsgResponse>(sendMsgUrl, sendAppMsgRequest);
}
return response;
}
/// <summary>
/// 异步发送文件
/// </summary>
/// <param name="fileInfo">文件信息</param>
/// <param name="toUserName">发送人UserName</param>
public void SendMsgAsync(FileInfo fileInfo, string toUserName)
{
Task.Factory.StartNew(() =>
{
try
{
SendMsg(fileInfo, toUserName);
}
catch (Exception e)
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
}
});
}
/// <summary>
/// 异步发送文字消息
/// </summary>
/// <param name="msg">消息</param>
/// <param name="toUserName">发送人UserName</param>
public void SendMsgAsync(string msg, string toUserName)
{
Task.Factory.StartNew(() =>
{
try
{
SendMsg(msg, toUserName);
}
catch (Exception e)
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
}
});
}
/// <summary>
/// 获取头像,因为请求的时候需要带Cookie等相关参数,所以直接用新的http请求不行,务必使用客户端API来获取
/// </summary>
/// <param name="url">头像地址,例如/cgi-bin/mmwebwx-bin/webwxgeticon?seq=0&username=filehelper&skey=@crypt_372b266_540d016177e861740ee84fec697a3b01 </param>
/// <param name="action">委托Action</param>
/// <returns></returns>
public void GetIconAsync(string url, Action<byte[]> action)
{
string fullUrl = host + url;
new Task(() =>
{
try
{
var img = httpClient.GetImage(fullUrl);
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
action((byte[])obj);
}), img);
}
catch (Exception e)
{
asyncOperation.Post(
new SendOrPostCallback((obj) =>
{
ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
}), e);
}
}).Start();
}
/// <summary>
/// 同步上传文件
/// </summary>
/// <param name="fileInfo">文件信息</param>
/// <returns></returns>
public UploadMediaResponse UploadFile(FileInfo fileInfo)
{
return UploadFile(fileInfo, user.UserName);
}
/// <summary>
/// 同步上传文件
/// </summary>
/// <param name="fileInfo">文件信息</param>
/// <param name="toUserName">发送人UserName,其实没什么用,但是官方有这个参数</param>
/// <returns></returns>
public UploadMediaResponse UploadFile(FileInfo fileInfo, string toUserName)
{
string postUrl = uploadHost + "/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";
int bufferLength = 512 * 1024;
string datetime = DateTime.Now.ToString("ddd MMM dd yyyy HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US")) + " GMT+0800 (中国标准时间)";
UploadMediaRequest uploadMediaRequest = new UploadMediaRequest()
{
UploadType = 2,
BaseRequest = baseRequest,
ClientMediaId = Utils.GetJavaTimeStamp(),
TotalLen = fileInfo.Length,
StartPos = 0,
DataLen = fileInfo.Length,
MediaType = 4,
FromUserName = user.UserName,
ToUserName = toUserName,
FileMd5 = Utils.GetFileMD5Hash(fileInfo)
};
UploadMediaResponse response = null;
//文件大小超过512Kb,分块上传。
if (fileInfo.Length > bufferLength)
{
int chunks = (int)Math.Ceiling((double)fileInfo.Length / bufferLength);
byte[] buffer = new byte[bufferLength];
Stream readStream = fileInfo.OpenRead();
int chunk = 0;
int readLength = 0;
while ((readLength = readStream.Read(buffer, 0, buffer.Length)) != 0)
{
List<FormDataItem> dataList = new List<FormDataItem>()
{
new FormDataItem("id","WU_FILE_"+uploadMedia.Count),
new FormDataItem("name",fileInfo.Name),
new FormDataItem("type",MimeMapping.GetMimeMapping(fileInfo.Name)),
new FormDataItem("lastModifiedDate",datetime),
new FormDataItem("size",fileInfo.Length.ToString()),
new FormDataItem("chunks",chunks.ToString()),
new FormDataItem("chunk",chunk.ToString()),
new FormDataItem("mediatype",GetMediaType(fileInfo.Extension)),
new FormDataItem("uploadmediarequest",JsonConvert.SerializeObject(uploadMediaRequest, Newtonsoft.Json.Formatting.None)),
new FormDataItem("webwx_data_ticket",httpClient.CookieContainer.GetCookies(new Uri(cookieRedirectUri))["webwx_data_ticket"].Value),
new FormDataItem("pass_ticket",passTicket),
new FormDataItem("filename",fileInfo.Name,buffer,readLength)
};
string result = httpClient.PostMutipart(postUrl, dataList);
response = JsonConvert.DeserializeObject<UploadMediaResponse>(result);
chunk++;
}
}
else
{
byte[] buffer = new byte[fileInfo.Length];
Stream readStream = fileInfo.OpenRead();
int readLength = readStream.Read(buffer, 0, buffer.Length);
List<FormDataItem> dataList = new List<FormDataItem>()
{
new FormDataItem("id","WU_FILE_"+uploadMedia.Count),
new FormDataItem("name",fileInfo.Name),
new FormDataItem("type",MimeMapping.GetMimeMapping(fileInfo.Name)),
new FormDataItem("lastModifiedDate",datetime),
new FormDataItem("size",fileInfo.Length.ToString()),
new FormDataItem("mediatype",GetMediaType(fileInfo.Extension)),
new FormDataItem("uploadmediarequest",JsonConvert.SerializeObject(uploadMediaRequest, Newtonsoft.Json.Formatting.None)),
new FormDataItem("webwx_data_ticket",httpClient.CookieContainer.GetCookies(new Uri(cookieRedirectUri))["webwx_data_ticket"].Value),
new FormDataItem("pass_ticket",passTicket),
new FormDataItem("filename",fileInfo.Name,buffer,readLength)
};
string result = httpClient.PostMutipart(postUrl, dataList);
response = JsonConvert.DeserializeObject<UploadMediaResponse>(result);
}
uploadMedia.Add(fileInfo.Name, response.MediaId);
return response;
}
/// <summary>
/// 同步通过好友认证
/// </summary>
/// <param name="info">sync中获得的申请信息</param>
/// <returns></returns>
public SimpleResponse VerifyUser(RecommendInfo info)
{
string verifyUserUrl = host + "/cgi-bin/mmwebwx-bin/webwxverifyuser?r=" + Utils.GetJavaTimeStamp();