2
0

WXUserReader.cs 16 KB

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