2
0

WXUserReader.cs 17 KB

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