2
0

WXUserReader.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. using K4os.Compression.LZ4.Encoders;
  2. using K4os.Compression.LZ4;
  3. using SQLite;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Mime;
  11. using System.Security.Cryptography;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using System.Windows.Interop;
  15. using System.Windows.Media.Imaging;
  16. using System.Xml;
  17. using System.Xml.Linq;
  18. using WechatBakTool.Helpers;
  19. using WechatBakTool.Model;
  20. using System.Windows;
  21. namespace WechatBakTool
  22. {
  23. public class WXUserReader
  24. {
  25. private Dictionary<string, SQLiteConnection> DBInfo = new Dictionary<string, SQLiteConnection>();
  26. private UserBakConfig? UserBakConfig = null;
  27. private Hashtable HeadImgCache = new Hashtable();
  28. private Hashtable UserNameCache = new Hashtable();
  29. public WXUserReader(UserBakConfig userBakConfig) {
  30. string path = Path.Combine(userBakConfig.UserWorkspacePath, "DecDB");
  31. UserBakConfig = userBakConfig;
  32. LoadDB(path);
  33. InitCache();
  34. }
  35. public void LoadDB(string path)
  36. {
  37. string[] dbFileList = Directory.GetFiles(path);
  38. foreach (var item in dbFileList)
  39. {
  40. FileInfo fileInfo = new FileInfo(item);
  41. if (fileInfo.Extension != ".db")
  42. continue;
  43. SQLiteConnection con = new SQLiteConnection(item);
  44. string dbName = fileInfo.Name.Split('.')[0];
  45. DBInfo.Add(dbName, con);
  46. }
  47. }
  48. public void InitCache()
  49. {
  50. SQLiteConnection con = DBInfo["Misc"];
  51. if (con == null)
  52. return;
  53. string query = @"SELECT * FROM ContactHeadImg1";
  54. List<ContactHeadImg> imgs = con.Query<ContactHeadImg>(query);
  55. foreach(ContactHeadImg item in imgs)
  56. {
  57. if (!HeadImgCache.ContainsKey(item.usrName))
  58. {
  59. HeadImgCache.Add(item.usrName, item);
  60. }
  61. }
  62. List<WXContact> contacts = GetWXContacts(null, true).ToList();
  63. foreach(WXContact contact in contacts)
  64. {
  65. if (!UserNameCache.ContainsKey(contact.UserName))
  66. UserNameCache.Add(contact.UserName, contact);
  67. }
  68. }
  69. public byte[]? GetHeadImgCahce(string username)
  70. {
  71. if (HeadImgCache.ContainsKey(username))
  72. {
  73. ContactHeadImg? img = HeadImgCache[username] as ContactHeadImg;
  74. if (img == null)
  75. return null;
  76. else
  77. return img.smallHeadBuf;
  78. }
  79. return null;
  80. }
  81. public int[] GetWXCount()
  82. {
  83. SQLiteConnection con = DBInfo["MicroMsg"];
  84. if (con == null)
  85. return new int[] { 0, 0 };
  86. string query = @"select count(*) as count from contact where type != 4";
  87. int userCount = con.Query<WXCount>(query)[0].Count;
  88. int msgCount = 0;
  89. for (int i = 0; i <= 99; i++)
  90. {
  91. if (DBInfo.ContainsKey("MSG" + i.ToString()))
  92. {
  93. con = DBInfo["MSG" + i.ToString()];
  94. if (con == null)
  95. return new int[] { userCount, 0 };
  96. query = "select count(*) as count from MSG";
  97. msgCount += con.Query<WXCount>(query)[0].Count;
  98. }
  99. }
  100. return new int[] { userCount, msgCount };
  101. }
  102. public ObservableCollection<WXContact> GetWXContacts(string? name = null,bool all = false)
  103. {
  104. SQLiteConnection con = DBInfo["MicroMsg"];
  105. if (con == null)
  106. return new ObservableCollection<WXContact>();
  107. string query = @"select contact.*,session.strContent,contactHeadImgUrl.smallHeadImgUrl,contactHeadImgUrl.bigHeadImgUrl from contact
  108. left join session on session.strUsrName = contact.username
  109. left join contactHeadImgUrl on contactHeadImgUrl.usrName = contact.username
  110. where type != 4 {searchName}
  111. order by nOrder desc";
  112. if (all)
  113. {
  114. query = query.Replace("where type != 4 ", "");
  115. }
  116. List<WXContact>? contacts = null;
  117. if (name != null)
  118. {
  119. query = query.Replace("{searchName}", " and (username like ? or alias like ? or nickname like ? or remark like ?)");
  120. contacts = con.Query<WXContact>(query, $"%{name}%", $"%{name}%", $"%{name}%", $"%{name}%");
  121. }
  122. else
  123. {
  124. query = query.Replace("{searchName}", "");
  125. contacts = con.Query<WXContact>(query);
  126. }
  127. foreach (WXContact contact in contacts)
  128. {
  129. if(contact.Remark != "")
  130. contact.NickName = contact.Remark;
  131. byte[]? imgBytes = GetHeadImgCahce(contact.UserName);
  132. if (imgBytes != null)
  133. {
  134. MemoryStream stream = new MemoryStream(imgBytes);
  135. BitmapImage bitmapImage = new BitmapImage();
  136. bitmapImage.BeginInit();
  137. bitmapImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
  138. bitmapImage.StreamSource = stream;
  139. bitmapImage.EndInit();
  140. contact.Avatar = bitmapImage;
  141. }
  142. else
  143. continue;
  144. }
  145. return new ObservableCollection<WXContact>(contacts);
  146. }
  147. public List<WXUserImg>? GetUserImgs()
  148. {
  149. SQLiteConnection con = DBInfo["MicroMsg"];
  150. if (con == null)
  151. return null;
  152. string query = "select * from contactHeadImgUrl";
  153. return con.Query<WXUserImg>(query);
  154. }
  155. public List<WXChatRoom>? GetWXChatRooms()
  156. {
  157. SQLiteConnection con = DBInfo["MicroMsg"];
  158. if (con == null)
  159. return null;
  160. string query = "select * from ChatRoom";
  161. return con.Query<WXChatRoom>(query);
  162. }
  163. public List<WXMsg>? GetWXMsgs(string uid,string msg = "")
  164. {
  165. List<WXMsg> tmp = new List<WXMsg>();
  166. for (int i = 0; i <= 99; i++)
  167. {
  168. if(DBInfo.ContainsKey("MSG" + i.ToString()))
  169. {
  170. SQLiteConnection con = DBInfo["MSG" + i.ToString()];
  171. if (con == null)
  172. return tmp;
  173. List<WXMsg>? wXMsgs = null;
  174. if (msg == "")
  175. {
  176. string query = "select * from MSG where StrTalker=?";
  177. wXMsgs = con.Query<WXMsg>(query, uid);
  178. }
  179. else if(uid == "")
  180. {
  181. string query = "select * from MSG where StrContent like ?";
  182. wXMsgs = con.Query<WXMsg>(query, string.Format("%{0}%", msg));
  183. }
  184. else
  185. {
  186. string query = "select * from MSG where StrTalker=? and StrContent like ?";
  187. wXMsgs = con.Query<WXMsg>(query, uid, string.Format("%{0}%", msg));
  188. }
  189. foreach (WXMsg w in wXMsgs)
  190. {
  191. if (UserNameCache.ContainsKey(w.StrTalker))
  192. {
  193. WXContact? contact = UserNameCache[w.StrTalker] as WXContact;
  194. if (contact != null)
  195. {
  196. if (contact.Remark != "")
  197. w.NickName = contact.Remark;
  198. else
  199. w.NickName = contact.NickName;
  200. }
  201. }
  202. if (uid.Contains("@chatroom"))
  203. {
  204. string userId = "";
  205. if (w.BytesExtra == null)
  206. continue;
  207. string sl = BitConverter.ToString(w.BytesExtra).Replace("-", "");
  208. ProtoMsg protoMsg;
  209. using (MemoryStream stream = new MemoryStream(w.BytesExtra))
  210. {
  211. protoMsg = ProtoBuf.Serializer.Deserialize<ProtoMsg>(stream);
  212. }
  213. if(protoMsg.TVMsg != null)
  214. {
  215. foreach(TVType _tmp in protoMsg.TVMsg)
  216. {
  217. if (_tmp.Type == 1)
  218. userId = _tmp.TypeValue;
  219. }
  220. }
  221. if (!w.IsSender)
  222. {
  223. if(UserNameCache.ContainsKey(userId))
  224. {
  225. WXContact? contact = UserNameCache[userId] as WXContact;
  226. if (contact != null)
  227. w.NickName = contact.Remark == "" ? contact.NickName : contact.Remark;
  228. }
  229. else
  230. {
  231. w.NickName = userId;
  232. }
  233. }
  234. else
  235. {
  236. w.NickName = "我";
  237. }
  238. }
  239. tmp.Add(w);
  240. }
  241. }
  242. }
  243. return tmp;
  244. }
  245. public List<WXSessionAttachInfo>? GetWXMsgAtc()
  246. {
  247. SQLiteConnection con = DBInfo["MultiSearchChatMsg"];
  248. if (con == null)
  249. return null;
  250. string query = "select * from SessionAttachInfo";
  251. List<WXSessionAttachInfo> list = con.Query<WXSessionAttachInfo>(query);
  252. if (list.Count != 0)
  253. {
  254. return list;
  255. }
  256. else
  257. return null;
  258. }
  259. public WXSessionAttachInfo? GetWXMsgAtc(WXMsg msg)
  260. {
  261. SQLiteConnection con = DBInfo["MultiSearchChatMsg"];
  262. if (con == null)
  263. return null;
  264. string query = "select * from SessionAttachInfo where msgId = ? order by attachsize desc";
  265. List<WXSessionAttachInfo> list = con.Query<WXSessionAttachInfo>(query, msg.MsgSvrID);
  266. if (list.Count != 0)
  267. {
  268. //部分附件可能有md5校验,这里移除校验,给的是正确路径
  269. WXSessionAttachInfo acc = list[0];
  270. int index = acc.attachPath.IndexOf(".dat");
  271. int index2 = acc.attachPath.IndexOf(".dat");
  272. if (acc.attachPath.Length - index > 10 && index != -1)
  273. {
  274. acc.attachPath = acc.attachPath.Substring(0, acc.attachPath.Length - 32);
  275. }
  276. if (acc.attachPath.Length - index2 > 10 && index2 != -1)
  277. {
  278. acc.attachPath = acc.attachPath.Substring(0, acc.attachPath.Length - 32);
  279. }
  280. return acc;
  281. }
  282. else
  283. return null;
  284. }
  285. public WXMediaMsg? GetVoiceMsg(WXMsg msg)
  286. {
  287. for (int i = 0; i <= 99; i++)
  288. {
  289. if(DBInfo.ContainsKey("MediaMSG" + i.ToString()))
  290. {
  291. SQLiteConnection con = DBInfo["MediaMSG" + i.ToString()];
  292. if (con == null)
  293. continue;
  294. string query = "select * from Media where Reserved0=?";
  295. List<WXMediaMsg> wXMsgs = con.Query<WXMediaMsg>(query, msg.MsgSvrID);
  296. if (wXMsgs.Count != 0)
  297. return wXMsgs[0];
  298. }
  299. }
  300. return null;
  301. }
  302. public string? GetAttachment(WXMsgType type, WXMsg msg)
  303. {
  304. if (UserBakConfig == null)
  305. return null;
  306. string? tmpPath = Path.Combine(UserBakConfig.UserWorkspacePath, "Temp");
  307. if (!Directory.Exists(tmpPath))
  308. Directory.CreateDirectory(tmpPath);
  309. // 如果是图片和视频,从附件库中搜索
  310. string? path = null;
  311. if (type == WXMsgType.Image || type == WXMsgType.Video)
  312. {
  313. WXSessionAttachInfo? atcInfo = GetWXMsgAtc(msg);
  314. if (atcInfo == null)
  315. return null;
  316. path = atcInfo.attachPath;
  317. }
  318. // 如果是从语音,从媒体库查找
  319. else if (type == WXMsgType.Audio)
  320. {
  321. WXMediaMsg? voiceMsg = GetVoiceMsg(msg);
  322. if (voiceMsg == null)
  323. return null;
  324. if (voiceMsg.Buf == null)
  325. return null;
  326. // 从DB取音频文件到临时目录
  327. string tmp_file_path = Path.Combine(tmpPath, voiceMsg.Key + ".arm");
  328. using (FileStream stream = new FileStream(tmp_file_path, FileMode.OpenOrCreate))
  329. {
  330. stream.Write(voiceMsg.Buf, 0, voiceMsg.Buf.Length);
  331. }
  332. path = tmp_file_path;
  333. }
  334. if (path == null)
  335. return null;
  336. // 获取到原路径后,开始进行解密转移,只有图片和语音需要解密,解密后是直接归档目录
  337. if(type == WXMsgType.Image || type== WXMsgType.Audio)
  338. {
  339. path = DecryptAttachment(type, path);
  340. }
  341. else if (type == WXMsgType.Video)
  342. {
  343. string video_dir = Path.Combine(UserBakConfig.UserWorkspacePath, "Video");
  344. if(!Directory.Exists(video_dir))
  345. Directory.CreateDirectory(video_dir);
  346. FileInfo fileInfo = new FileInfo(path);
  347. string video_file_path = Path.Combine(video_dir, fileInfo.Name);
  348. // 视频的路径是相对路径,需要加上资源目录
  349. path = Path.Combine(UserBakConfig.UserResPath, path);
  350. if(!File.Exists(video_file_path))
  351. File.Copy(path, video_file_path);
  352. path = video_file_path;
  353. }
  354. if (path == null)
  355. return null;
  356. // 改相对路径
  357. path = path.Replace(UserBakConfig.UserWorkspacePath + "\\", "");
  358. return path;
  359. }
  360. public string? DecryptAttachment(WXMsgType type, string path)
  361. {
  362. if (UserBakConfig == null)
  363. return null;
  364. string? file_path = null;
  365. switch (type)
  366. {
  367. case WXMsgType.Image:
  368. string img_dir = Path.Combine(UserBakConfig.UserWorkspacePath, "Image");
  369. if (!Directory.Exists(img_dir))
  370. Directory.CreateDirectory(img_dir);
  371. // 图片的路径是相对路径,需要加上资源目录
  372. path = Path.Combine(UserBakConfig.UserResPath, path);
  373. byte[] decFileByte = DecryptionHelper.DecImage(path);
  374. string decFiletype = DecryptionHelper.CheckFileType(decFileByte);
  375. file_path = DecryptionHelper.SaveDecImage(decFileByte, path, img_dir, decFiletype);
  376. break;
  377. case WXMsgType.Audio:
  378. string audio_dir = Path.Combine(UserBakConfig.UserWorkspacePath, "Audio");
  379. if (!Directory.Exists(audio_dir))
  380. Directory.CreateDirectory(audio_dir);
  381. FileInfo fileInfo = new FileInfo(path);
  382. string audio_file_dir = Path.Combine(audio_dir, fileInfo.Name + ".mp3");
  383. ToolsHelper.DecodeVoice(path, path + ".pcm", audio_file_dir);
  384. file_path = audio_file_dir;
  385. break;
  386. }
  387. return file_path;
  388. }
  389. public List<WXMsgGroup> GetWXMsgGroup()
  390. {
  391. List<WXMsgGroup> g = new List<WXMsgGroup>();
  392. for (int i = 0; i <= 99; i++)
  393. {
  394. if (DBInfo.ContainsKey("MSG" + i.ToString()))
  395. {
  396. SQLiteConnection con = DBInfo["MSG" + i.ToString()];
  397. if (con == null)
  398. return g;
  399. string query = "select StrTalker,Count(localId) as MsgCount from MSG GROUP BY StrTalker";
  400. List<WXMsgGroup> wXMsgs = con.Query<WXMsgGroup>(query);
  401. foreach (WXMsgGroup w in wXMsgs)
  402. {
  403. WXMsgGroup? tmp = g.Find(x => x.UserName == w.UserName);
  404. if (tmp == null)
  405. g.Add(w);
  406. else
  407. tmp.MsgCount += g.Count;
  408. }
  409. }
  410. }
  411. return g;
  412. }
  413. }
  414. public enum WXMsgType
  415. {
  416. Image = 0,
  417. Video = 1,
  418. Audio = 2,
  419. File = 3,
  420. }
  421. }