-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathForm1.cs
1736 lines (1522 loc) · 69.3 KB
/
Form1.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 Browserform.common;
using CefSharp;
using CefSharp.WinForms;
using Microsoft.VisualBasic;
using MyDB;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Browserform
{
public partial class Form1 : Form
{
#region 初始参数 信息
public static Form1 Instance;
public static string RootPath = System.Environment.CurrentDirectory;
//关于该进程的唯一标识
public static int uuid = 0;
//public static Mywebbrowser mywebbrowser = new Mywebbrowser();
//public static WebBrowser browser;
//从treeview里面打开tab页时,有设备号参数
public static string DevNum;
//内存中的好友列表,用于聊天记录查询
private static Root friendsRoot = new Root();
/// <summary>
///微信昵称
/// </summary>
private string NickName = "";
//微信号唯一标识
private static string wxUin = "";
//自己的微信UserName
private static string MyUserName;
//机器模式
private static bool IsRobot = false;
private static CookieContainer myCookieContainer = new CookieContainer();
//登录相关信息
private LoginRedirectResult loginRedirectResult;
/// <summary>
/// 自己信息项,主要针对群消息存储
/// </summary>
private MyDB.Model.MyWxInfo mywxinfo = new MyDB.Model.MyWxInfo();
private static string Skey = "";
/// <summary>
/// 当前微信新老标识
/// </summary>
private static int WxorWx2 = 1;
#endregion
private static bool checkChildFrmExist(string childFrmName)//参数窗体名称
{
foreach (Form childFrm in Application.OpenForms)
{
if (childFrm.Name == childFrmName)
{
if (childFrm.WindowState == FormWindowState.Minimized)
childFrm.WindowState = FormWindowState.Normal;
childFrm.Activate();
return true;
}
}
return false;
}
public Form1()
{
InitializeComponent();
Instance = this;
SuppressWininetBehavior();
//启动时,调用接口取获取唯一标识UUID号,取到了UUID号,才可以进行下次一点击增加微信
MsgFilter myinfo = new MsgFilter();
Application.AddMessageFilter(myinfo);
}
private unsafe void SuppressWininetBehavior()
{
/* SOURCE: http://msdn.microsoft.com/en-us/library/windows/desktop/aa385328%28v=vs.85%29.aspx
* INTERNET_OPTION_SUPPRESS_BEHAVIOR (81):
* A general purpose option that is used to suppress behaviors on a process-wide basis.
* The lpBuffer parameter of the function must be a pointer to a DWORD containing the specific behavior to suppress.
* This option cannot be queried with InternetQueryOption.
*
* INTERNET_SUPPRESS_COOKIE_PERSIST (3):
* Suppresses the persistence of cookies, even if the server has specified them as persistent.
* Version: Requires Internet Explorer 8.0 or later.
*/
int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;
bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
MessageBox.Show("Something went wrong !>?");
}
}
[DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(int hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
static ChromiumWebBrowser web;
private void Form1_Load(object sender, EventArgs e)
{
try
{
//Connect();
InitSocket();
var re = new request();
//接收和发送的http消息
re.msg += Re_msg;
re.msg2 += Re_msg2;
web = new ChromiumWebBrowser("https://wx2.qq.com/?lang=zh_CN"); // 绑定 wx2.qq.com 定向不同
web.Dock = DockStyle.Fill;
web.RequestHandler = re;
web.FrameLoadStart += Web_FrameLoadStart;
web.FrameLoadEnd += Web_FrameLoadEnd;
web.LoadingStateChanged += Web_LoadingStateChanged;
this.Invoke(new Action(() =>
{
this.Controls.Add(web);
}));
}
catch (Exception ex)
{
throw;
}
}
private void Web_FrameLoadStart(object sender, FrameLoadStartEventArgs e)
{
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += Visitor_GetUin;
cookieManager.VisitAllCookies(visitor);
}
private void Web_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += Visitor_GetUin;
cookieManager.VisitAllCookies(visitor);
// modcssAsync();
// modcssAsync();
}
private void Visitor_GetUin(CefSharp.Cookie obj)
{
System.Net.Cookie ck = new System.Net.Cookie(obj.Name, obj.Value, obj.Path, obj.Domain);
myCookieContainer.Add(ck);
if (ck.Name == "wxuin") //获取微信号唯一标识Uid
{
wxUin = ck.Value;
mywxinfo.Uin = wxUin;
}
if (ck.Name == "wxsid")
{
loginRedirectResult.wxsid = ck.Value;
}
}
private void Web_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
ICookieManager cookieManager = CefSharp.Cef.GetGlobalCookieManager();
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += Visitor_SendCookie;
cookieManager.VisitAllCookies(visitor);
// modcssAsync();
//ItemClickAsync();
}
private void Visitor_SendCookie(CefSharp.Cookie obj)
{
System.Net.Cookie ck = new System.Net.Cookie(obj.Name, obj.Value, obj.Path, obj.Domain);
myCookieContainer.Add(ck);
if (ck.Name == "wxuin") //获取微信号唯一标识Uid
{
wxUin = ck.Value;
mywxinfo.Uin = wxUin;
}
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <param name="obj2"></param>
//发送http
private void Re_msg2(string obj, object obj2)
{
getReceiveMesAsync(obj);
}
string pass_ticket = String.Empty;
private void Re_msg(string obj)
{
// modcssAsync();
#region 1. wx2 新版微信
if (obj.Contains("https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true") || obj.Contains("https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true"))
{
getIconAsync(obj);
}
getSendMes(obj); //获取发送的消息
getQrcode(obj); //设备远程登录时,获取二维码
//开启线程,抓取用户列表并保存到数据库
if (obj.Contains("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?"))
{
modcssAsync();
///新加获取Cookie
WxorWx2 = 2;
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += Visitor_GetUin;
cookieManager.VisitAllCookies(visitor);
Thread getFriendsThread = new Thread(new ParameterizedThreadStart(getfriends));
getFriendsThread.IsBackground = true;
getFriendsThread.Start((Object)obj);
}
if (obj.Contains("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage"))
{
GetLoginInfo(obj.ToString());
}
#endregion
#region 2. wx 老版本微信
//开启线程,抓取用户列表并保存到数据库 在Respone获取 Re_msg2方法中
if (obj.Contains("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?pass_ticket") || obj.Contains("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?"))
{
modcssAsync();
WxorWx2 = 1;
///新加获取Cookie
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += Visitor_GetUin;
cookieManager.VisitAllCookies(visitor);
Thread getFriendsThread = new Thread(new ParameterizedThreadStart(getfriends));
getFriendsThread.IsBackground = true;
getFriendsThread.Start((Object)obj);
}
if (obj.Contains("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage"))
{
WxorWx2 = 1;
GetLoginInfo(obj.ToString());
}
#endregion
#region 3. 群组信息
if (obj.Contains("pass_ticket"))
{
NameValueCollection col = common.HtmlGetInfo.GetQueryString(obj.ToString());
pass_ticket = col["pass_ticket"];
}
#endregion
if (obj.Contains("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxlogout?") || obj.Contains("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxlogout?"))
{
Send("WinForm", 600, uuid, 0x80F0);
}
Application.DoEvents();
}
/// <summary>
/// 当前聊天组NickName
/// </summary>
string Group_NowNickName = String.Empty;
/// <summary>
/// 当前聊天组UserName
/// </summary>
string Group_NowUserName = String.Empty;
/// <summary>
/// 当前聊天群组 UserName和NickName
/// </summary>
List<common.GroupUserAndNickName> list_GroupName = new List<common.GroupUserAndNickName>();
/// <summary>
/// 获取组信息
/// </summary>
/// <param name="obj">群组消息</param>
/// <param name="Wx2orWx">老微信1,新微信2 </param>
/// <returns></returns>
private async Task getGroupsAsync(Object obj, int WxorWx2)
{
common.WxGroupMsg WXGroupMsg = JsonConvert.DeserializeObject<common.WxGroupMsg>(obj.ToString());
if (WXGroupMsg.Msg.Content == "")
return;
var html = await web.GetSourceAsync();
if (Group_NowNickName == "" && Group_NowUserName == "")
{
string GroupName = common.HtmlGetInfo.GetGroupNickName(html);
if (GroupName != "")
{
Group_NowNickName = GroupName;
}
Group_NowUserName = WXGroupMsg.Msg.ToUserName;
common.GroupUserAndNickName group = new common.GroupUserAndNickName();
group.NickName = Group_NowNickName;
group.UserName = Group_NowUserName;
if (!group.NickName.Contains("@@"))
{
list_GroupName.Add(group);
}
}
else
{
if (WXGroupMsg.Msg.ToUserName != Group_NowUserName)
{
string GroupName = common.HtmlGetInfo.GetGroupNickName(html);
if (GroupName != "")
Group_NowNickName = GroupName;
Group_NowUserName = WXGroupMsg.Msg.ToUserName;
common.GroupUserAndNickName group = new common.GroupUserAndNickName();
group.NickName = Group_NowNickName;
group.UserName = Group_NowUserName;
if (!group.NickName.Contains("@@"))
{
list_GroupName.Add(group);
}
}
}
// Console.WriteLine("当前聊天群组:" + Group_NowNickName + " " + Group_NowUserName);
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += Visitor_GetUin;
cookieManager.VisitAllCookies(visitor);
GetGroupUserList(WXGroupMsg, WxorWx2);
}
/// <summary>
/// 当前微信聊天群组人员
/// </summary>
List<common.MemberList> Group_MemberList = new List<common.MemberList>();
/// <summary>
/// 获取群组
/// </summary>
/// <param name="WxGroupMsg">获取群组 通过UserName</param>
/// <param name="WxorWx2">WxorWx2 新老微信标识, 老微信1 新微信2</param>
private void GetGroupUserList(common.WxGroupMsg WxGroupMsg, int WxorWx2)
{
common.Noumenon_GetGroupUser info = GetGroupInfoByGroupName(WxGroupMsg);
string froupname = WxGroupMsg.Msg.ToUserName;
if (Group_NowUserName != froupname)
{
JObject job = new JObject();
if (WxorWx2 == 1) //老微信
{
job = common.WXService.SendPostRequest_Old(info.Url, info.PostData, myCookieContainer);
}
if (WxorWx2 == 2) //新微信
{
job = common.WXService.SendPostRequest(info.Url, info.PostData, myCookieContainer);
}
try
{
var BaseResponse = job["BaseResponse"];
var Count = job["Count"];
var ContactList = job["ContactList"];
var arr = ContactList.Last.ToString();
JObject json1 = (JObject)JsonConvert.DeserializeObject(arr);
JArray MemberList = (JArray)json1["MemberList"];
for (int i = 0; i < MemberList.Count; i++)
{
common.MemberList infoM = new common.MemberList();
infoM.UserName = MemberList[i]["UserName"].ToString();
infoM.NickName = MemberList[i]["NickName"].ToString();
infoM.GroupUserName = WxGroupMsg.Msg.ToUserName;
if (!Group_MemberList.Contains(infoM))
Group_MemberList.Add(infoM);
}
}
catch (Exception ex)
{
}
}
}
public System.IO.StringReader DeCompress(byte[] str)
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
stream.Write(str, 0, str.Length);
stream.Position = 0;
GZipStream zip = new GZipStream(stream, CompressionMode.Decompress);
System.IO.StreamReader rd = new System.IO.StreamReader(zip);
return new System.IO.StringReader(rd.ReadToEnd());
}
private common.Noumenon_GetGroupUser GetGroupInfoByGroupName(common.WxGroupMsg WxGroupMsg)
{
string post_Uin = loginRedirectResult.wxuin;
string post_Sid = loginRedirectResult.wxsid;
string post_Skey = loginRedirectResult.skey;
string post_DeviceID = CreateNewDeviceID();
string post_GroupName = WxGroupMsg.Msg.ToUserName;
string ur1l = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r=";
if (WxorWx2 == 1)
{
ur1l = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r=";
}
else
{
ur1l = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r=";
}
common.Noumenon_GetGroupUser info = new common.Noumenon_GetGroupUser();
info.Url = String.Format(ur1l + "{0}&lang=zh_CN&pass_ticket={1}", getR().ToString(), pass_ticket);
info.ToUserName = WxGroupMsg.Msg.ToUserName;
info.PostData = "{\"BaseRequest\":{\"Uin\":" + post_Uin + ",\"Sid\":\"" + post_Sid + "\",\"Skey\":\"" + post_Skey + "\",\"DeviceID\":\"" + post_DeviceID + "\"},\"Count\":1,\"List\":[{\"UserName\":\"" + WxGroupMsg.Msg.ToUserName + "\",\"EncryChatRoomId\":\"" + "" + "\"}]}";
return info;
}
private async Task GetInfoNickNameAsync()
{
var html = await web.GetSourceAsync();
NickName = common.HtmlGetInfo.GetNickName(html);
SendServerMsgs(NickName);
//SendMsg(NickName);
CommonTools.LoginDir.AddNickname(uuid.ToString(), NickName);
Send("WinForm", 111, uuid, 0x80F0); //更新昵称
}
/// <summary>
/// 获取接收到的消息
/// </summary>
/// <param name="obj"></param>
private async Task getReceiveMesAsync(string obj)
{
//获取接收的消息
if (obj.Contains("MsgId") && obj.Contains("AddMsgCount") && obj.Contains("Val"))
{
ReceiveMessageRoot root = JsonConvert.DeserializeObject<MyDB.ReceiveMessageRoot>(obj);
///要排除的特殊消息体
if (Enum.IsDefined(typeof(common.WxMsg_Type_Neglect), root.AddMsgList[0].MsgType)) { return; }
if (MyUserName == null)
{
if (root.AddMsgList[0].MsgType == 51)
{
MyUserName = root.AddMsgList[0].FromUserName;
}
if (!root.AddMsgList[0].FromUserName.Contains("@@"))
{
MyUserName = root.AddMsgList[0].ToUserName;
}
if (root.AddMsgList[0].MsgType == 1 && !root.AddMsgList[0].FromUserName.Contains("@@")) //文本消息
{
SendMsg(root.AddMsgList[0].FromUserName, "XXXXX");
//发送回传到数据库 接收别人发给我的消息
int result = MyDB.WeChatUser.SaveWeCharChatLog(root, wxUin, friendsRoot, 1, NickName);
//保存到数据库
RecMessageOperation.writeMessage(root, wxUin, friendsRoot);
///告诉主线程新消息
//Send("WinForm", 222, uuid, 0x80F0); //更新消息
SendServer_NewMsg();
}
//来自群组的消息
if (root.AddMsgList[0].FromUserName.Contains("@@"))
{
List<MyDB.MemberListItem> listn = common.ConvertInfo.CovnertMemberListItem(Group_MemberList);
RecMessageOperation.WriteGroupMessage(mywxinfo, root, wxUin, friendsRoot, listn, GetNickNameByUserName(root.AddMsgList[0].FromUserName)); //Group_NowNickName
return;
}
}
else
{
if (root.AddMsgList[0].MsgType == 1 && !root.AddMsgList[0].Content.ToString().Substring(0, 1).Contains("@")) //文本消息
{
SendMsg(root.AddMsgList[0].FromUserName, "XXXXX");
//发送回传到数据库 接收别人发给我的消息
int result = MyDB.WeChatUser.SaveWeCharChatLog(root, wxUin, friendsRoot, 1, NickName);
//IsRobot = true;
if (IsRobot == true)
{
for (int i = 0; i < root.AddMsgList.Count; i++)
{
string ResultWord = GetResultWord(root.AddMsgList[i].Content);
//CheckAndSend(ResultWord);
// AutoSendMsg(root, ResultWord); 可以发送的
//loginRedirectResult.skey = Skey;
// common.WXService.AutoSendMsg(myCookieContainer, ResultWord, root.AddMsgList[0].FromUserName, root.AddMsgList[0].ToUserName, 1, loginRedirectResult);
string js_func = "window.chatFactory = angular.element(document).injector().get('chatFactory');";
js_func += "function wxSendTextMessage(tousername,msg,silent){";
js_func += "'use strict';";
js_func += "if ('current' == tousername)";
js_func += "{";
js_func += "tousername = angular.element(document).injector().get('chatFactory').getCurrentUserName();";
js_func += "}";
js_func += "try";
js_func += "{";
js_func += " if (silent)";
js_func += " {";
js_func += "let t = window.chatFactory.createMessage({";
js_func += "MsgType: angular.element(document).injector().get('confFactory').MSGTYPE_TEXT,";
js_func += "Type: angular.element(document).injector().get('confFactory').MSGTYPE_TEXT,";
js_func += "Content: msg,";
js_func += "ToUserName: tousername,";
js_func += "});";
js_func += "window.chatFactory.appendMessage(t);";
js_func += "window.chatFactory.sendMessage(t);";
js_func += "}";
js_func += "else";
js_func += "{";
js_func += "let oldusername = angular.element(document).injector().get('chatFactory').getCurrentUserName();";
js_func += "if (oldusername != tousername)";
js_func += "{";
js_func += "angular.element(document).injector().get('chatFactory').setCurrentUserName(tousername);";
js_func += "}";
js_func += "let oldmsg = angular.element('#editArea').scope().editAreaCtn;";
js_func += "angular.element('#editArea').scope().editAreaCtn = msg;";
js_func += "angular.element('#editArea').scope().sendTextMessage();";
js_func += "angular.element('#editArea').scope().editAreaCtn = oldmsg;";
js_func += "angular.element('#editArea').text(oldmsg);";
js_func += "angular.element(document).injector().get('chatFactory').setCurrentUserName(oldusername);";
js_func += "}";
js_func += "}";
js_func += "catch (err)";
js_func += "{";
js_func += "}";
js_func += "}";
js_func += "wxSendTextMessage('" + root.AddMsgList[i].FromUserName + "' ,'" + ResultWord + "' ,true)";
JavascriptResponse x = await web.EvaluateScriptAsync(js_func);
//Console.WriteLine(x);
}
}
//保存到数据库
RecMessageOperation.writeMessage(root, wxUin, friendsRoot);
}
if (root.AddMsgList[0].ToUserName.Contains("@@") && !root.AddMsgList[0].Content.Contains("<br/>"))
{
if (root.AddMsgList[0].Content == "")
{
// Console.WriteLine("==========打开其他设备消息:==========" + root.AddMsgList[0].Content);
}
else
{
// Console.WriteLine("==========来自其他设备消息:==========" + root.AddMsgList[0].Content);
}
List<MyDB.MemberListItem> listn = common.ConvertInfo.CovnertMemberListItem(Group_MemberList);
RecMessageOperation.WriteGroupMessage(mywxinfo, root, wxUin, friendsRoot, listn, Group_NowNickName);
return;
}
///群里来的图片消息
if (root.AddMsgList[0].FromUserName.Contains("@@") && root.AddMsgList[0].MsgType == 3)
{
// Console.WriteLine("群里来图片消息了");
}
///告诉主线程新消息
//Send("WinForm", 222, uuid, 0x80F0);
SendServer_NewMsg();
}
///群组消息
if (root.AddMsgList[0].FromUserName.Contains("@@"))//|| root.AddMsgList[0].ToUserName.Contains("@@"))//群组消息
{
GroupMsg(root);
}
// type 3 图片消息
if (root.AddMsgList[0].MsgType == 3) //&& !root.AddMsgList[0].FromUserName.Contains("@@")
{
loginRedirectResult.WxorWx2 = WxorWx2;
string result = common.DownFriendsInfo.SaveSendImgPath(myCookieContainer, root, loginRedirectResult);
if (result != "")
{
root.AddMsgList[0].Content = "file:" + result;
RecMessageOperation.writeMessage(root, wxUin, friendsRoot);
}
}
}
}
/// <summary>
/// 1.接收到的普通消息
/// </summary>
/// <param name="root"></param>
private void NormalMsg(ReceiveMessageRoot root)
{
}
/// <summary>
///2.接收到的群组消息
/// </summary>
/// <param name="root"></param>
private void GroupMsg(ReceiveMessageRoot root)
{
//Console.WriteLine("\r\n我通过客服接收到的群组消息:==========" + root.AddMsgList[0].Content);
List<MyDB.MemberListItem> listn = common.ConvertInfo.CovnertMemberListItem(Group_MemberList);
if (MyUserName == root.AddMsgList[0].FromUserName)
{
mywxinfo.UserName = MyUserName;
}
for (int i = 0; i < list_GroupName.Count; i++)
{
if (root.AddMsgList[0].FromUserName == list_GroupName[i].UserName)
{
Group_NowNickName = list_GroupName[i].NickName;
}
}
RecMessageOperation.WriteGroupMessage(mywxinfo, root, wxUin, friendsRoot, listn, Group_NowNickName);
}
/// <summary>
/// 3. 发送的群组消息
/// </summary>
private void SendGroupMsg(SendMsgRequest root)
{
//Console.WriteLine("\r\n我通过客服发送群的:==============" + root.Msg.Content);
List<MyDB.MemberListItem> listn = common.ConvertInfo.CovnertMemberListItem(Group_MemberList);
string nickname = GetNickNameByUserName(root.Msg.ToUserName);
if (nickname == "")
{
SaveWebToGroupMsg(root, wxUin, friendsRoot, listn);
}
else
{
RecMessageOperation.WriteGroupMessage(root, wxUin, friendsRoot, listn, nickname);
}
}
//发送消息
private void SendMsg(string toUserName, string content)
{
return; //不执行这个刷新
//构造参数
MyDB.Msg msg = new MyDB.Msg();
msg.FromUserName = MyUserName;
msg.ToUserName = toUserName;
msg.Content = content;
msg.ClientMsgId = DateTime.Now.Millisecond;//14948501206950223;
msg.LocalID = DateTime.Now.Millisecond; //14948501206950223;//
msg.Type = 1;
SendBaseRequest mBaseReq = new SendBaseRequest();
mBaseReq.Sid = loginRedirectResult.wxsid;
mBaseReq.Skey = Skey;
mBaseReq.Uin = loginRedirectResult.wxuin;
mBaseReq.DeviceID = CreateNewDeviceID();
//发送消息
string url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?sid={0}&r={1}&lang=zh_CN&pass_ticket={2}";
if (WxorWx2 == 1)
{
url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?sid={0}&r={1}&lang=zh_CN&pass_ticket={2}";
}
url = string.Format(url, mBaseReq.Sid, getR(), loginRedirectResult.pass_ticket);
SendMsgRequest req = new SendMsgRequest();
req.BaseRequest = mBaseReq;
req.Msg = msg;
req.Scene = DateTime.Now.Millisecond;
string requestJson = JsonConvert.SerializeObject(req);
string repJsonStr = PostString(url, requestJson);
//if (repJsonStr == null) return null;
//var rep = JsonConvert.DeserializeObject<SendMsgResponse>(repJsonStr);
//return rep;
}
/// <summary>
/// 自动发送消息
/// </summary>
/// <param name="resultMsg"></param>
private void AutoSendMsg(ReceiveMessageRoot root, string resultMsg)
{
///参数体
common.WxMsgParsed pa = new common.WxMsgParsed();
pa.Pass_Ticket = pass_ticket;
pa.Sid = loginRedirectResult.wxsid;
pa.SKey = Skey;
pa.Uin = wxUin;
///消息体
common.WXMsg_Message msg = new common.WXMsg_Message();
msg.From = root.AddMsgList[0].ToUserName;
msg.To = root.AddMsgList[0].FromUserName;
msg.Msg = resultMsg;
msg.Readed = false;
msg.Time = DateTime.Now;
msg.Type = 1;
common.UserMessage msginfo = new common.UserMessage();
string result = msginfo.SendMsg(pa, myCookieContainer, msg, false);
}
private string PostString(string url, string content)
{
//mHandler = new HttpClientHandler();
//mHandler.UseCookies = true;
//mHandler.AutomaticDecompression = DecompressionMethods.GZip;
//mHandler.AllowAutoRedirect = true;
//mHttpClient = new HttpClient(mHandler);
//mHttpClient.DefaultRequestHeaders.ExpectContinue = false;
//SetHttpHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
//SetHttpHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2");
//SetHttpHeader("Accept-Encoding", "gzip, deflate, sdch, br");
HttpResponseMessage response = mHttpClient.PostAsync(new Uri(url), new StringContent(content)).Result;
string ret = response.Content.ReadAsStringAsync().Result;
response.Dispose();
return ret;
}
/// <summary>
/// 从群组List里 根据UserName 获得NickName
/// </summary>
/// <param name="UserName">@@UserName</param>
/// <returns></returns>
private string GetNickNameByUserName(string UserName)
{
foreach (common.GroupUserAndNickName item in list_GroupName)
{
if (item.UserName == UserName)
{
return item.NickName;
}
}
return "";
}
/// <summary>
/// POST
/// </summary>
/// <param name="url">地址</param>
/// <param name="method">方法</param>
/// <param name="param">json参数</param>
/// <returns></returns>
public static string WebServiceApp(string url, string param)
{
//转换输入参数的编码类型,获取bytep[]数组
byte[] byteArray = Encoding.UTF8.GetBytes(param);
//初始化新的webRequst
//1. 创建httpWebRequest对象
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
//2. 初始化HttpWebRequest对象
webRequest.Method = "POST";
webRequest.CookieContainer = myCookieContainer;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
//3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
//4. 读取服务器的返回信息
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd();
return phpend;
}
HttpClientHandler mHandler;
HttpClient mHttpClient = new HttpClient();
private void SetHttpHeader(string name, string value)
{
if (mHttpClient.DefaultRequestHeaders.Contains(name))
{
mHttpClient.DefaultRequestHeaders.Remove(name);
}
mHttpClient.DefaultRequestHeaders.Add(name, value);
}
static long getR()
{
return GetTimeStamp();
}
public static long GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds);
}
private static string CreateNewDeviceID()
{
Random ran = new Random();
int rand1 = ran.Next(10000, 99999);
int rand2 = ran.Next(10000, 99999);
int rand3 = ran.Next(10000, 99999);
return string.Format("e{0}{1}{2}", rand1, rand2, rand3);
}
static int flagIndex = 0;
static bool isStart = false;
private void getSendMes(string obj)
{
//如果我在群里发送群组消息了 ,就开始记录这个群的聊天信息
if (obj.Contains("@@"))
{
try
{
common.WxGroupMsg groupmsg = JsonConvert.DeserializeObject<common.WxGroupMsg>(obj.ToString());
GetGroupUserList(groupmsg, WxorWx2);
}
catch (Exception ex)
{ }
}
//识别发送的消息
if (isStart == true)
flagIndex++;
if (obj.Contains("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg"))
{
flagIndex = 0;
isStart = true;
WxorWx2 = 2;
}
if (obj.Contains("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg"))
{
flagIndex = 0;
isStart = true;
WxorWx2 = 1;
}
if (flagIndex == 2)
{
SendMsgRequest root = JsonConvert.DeserializeObject<SendMsgRequest>(obj);
//保存到数据库 我发给群消息 ==》群别人的
if (root.Msg.ToUserName.Contains("@@"))
{
getGroupsAsync(obj, WxorWx2);
SendGroupMsg(root);
return;
}
//我发送给好友的消息(非群消息)
if (root.Msg.ToUserName != "filehelper" && friendsRoot.MemberList != null)//好友列表里面没有文件助手
{
SendMessageOperation.writeMessage(root, wxUin, friendsRoot);
//发送回传到数据库 我发给==》别人的
int reuslt1 = MyDB.WeChatUser.SaveWebCharLog1(root, wxUin, friendsRoot, 0, NickName);
Now_UserName = root.Msg.ToUserName;
wxSid = loginRedirectResult.wxsid;
//if (reuslt1 != 0)
// MessageBox.Show("发送存储失败!");
ffAsync();
}
}
}
private void SaveWebToGroupMsg(SendMsgRequest root, string wxUin, Root friendsRoot, List<MyDB.MemberListItem> listn)
{
//记录的是第一条发送的群组消息类型, 因不发送前是没有UserName的
var task = GetGroupNickNameByJS(root, wxUin, friendsRoot, listn);
if (!task.IsCompleted)
{
//Console.WriteLine("异步方法未完成,开始等待");
}
else
{
// Console.WriteLine("异步方法完成,开始等待");
}
}
string qrcode = "";
private void getQrcode(string obj)
{
try
{
if (DevNum == null) //如果没有设备号,则不用传输二维码
return;
if (!obj.Contains("https://login.weixin.qq.com/qrcode/"))
return;
string qrUrl = "";
if (!qrcode.Equals(obj))
{
qrUrl = obj.ToString();
}
string filePath = ""; //图片保存路径
HttpWebRequest request = HttpWebRequest.Create(qrUrl) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = null;
using (WebResponse wr = request.GetResponse())
{
response = wr as HttpWebResponse;
using (Stream stream = response.GetResponseStream())
{
//当前时间作为文件名
filePath = OperationRecord.QRFile() + @"/" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
using (Stream fsStream = new FileStream(filePath, FileMode.Create))
{
stream.CopyTo(fsStream);
}
}
}
//像服务器传输二维码
Cloud.Login(DevNum.TrimStart(), filePath);
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// 获取好友列表
/// </summary>
/// <param name="url">URL</param>
private void getfriends(object url)
{
try
{ //获得昵称
GetInfoNickNameAsync();
JObject obj = common.WXService.GetContactByUrl(url.ToString(), myCookieContainer, cookieLogin);
friendsRoot = JsonConvert.DeserializeObject<MyDB.Root>(obj.ToString());
//写入数据库
friendsOperation.WriteFriends(friendsRoot, wxUin);
//写入回传用户好友列表
int result = MyDB.WeChatUser.SaveWeChatFriendsList(friendsRoot, wxUin, NickName);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
MethodBase method = new System.Diagnostics.StackTrace().GetFrame(0).GetMethod();
CommonTools.ExceptionLogInfo.SaveExceptionInfo(method.ReflectedType.FullName, method.Name, ex.ToString() + "url:为:" + url);
}
}
string cookieLogin = "";
//获取登录信息
private void GetLoginInfo(string redirect_url)