2
0

WXUserReader.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. namespace WechatBakTool
  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 sl = BitConverter.ToString(w.BytesExtra).Replace("-", "");
  184. ProtoMsg protoMsg;
  185. using (MemoryStream stream = new MemoryStream(w.BytesExtra))
  186. {
  187. protoMsg = ProtoBuf.Serializer.Deserialize<ProtoMsg>(stream);
  188. }
  189. if(protoMsg.TVMsg != null)
  190. {
  191. foreach(TVType _tmp in protoMsg.TVMsg)
  192. {
  193. if (_tmp.Type == 1)
  194. userId = _tmp.TypeValue;
  195. }
  196. }
  197. if (!w.IsSender)
  198. {
  199. if(UserNameCache.ContainsKey(userId))
  200. {
  201. WXContact? contact = UserNameCache[userId] as WXContact;
  202. if (contact != null)
  203. w.NickName = contact.Remark == "" ? contact.NickName : contact.Remark;
  204. }
  205. else
  206. {
  207. w.NickName = userId;
  208. }
  209. }
  210. else
  211. {
  212. w.NickName = "我";
  213. }
  214. }
  215. tmp.Add(w);
  216. }
  217. }
  218. }
  219. return tmp;
  220. }
  221. public List<WXSessionAttachInfo>? GetWXMsgAtc()
  222. {
  223. SQLiteConnection con = DBInfo["MultiSearchChatMsg"];
  224. if (con == null)
  225. return null;
  226. string query = "select * from SessionAttachInfo";
  227. List<WXSessionAttachInfo> list = con.Query<WXSessionAttachInfo>(query);
  228. if (list.Count != 0)
  229. {
  230. return list;
  231. }
  232. else
  233. return null;
  234. }
  235. public WXSessionAttachInfo? GetWXMsgAtc(WXMsg msg)
  236. {
  237. SQLiteConnection con = DBInfo["MultiSearchChatMsg"];
  238. if (con == null)
  239. return null;
  240. string query = "select * from SessionAttachInfo where msgId = ? order by attachsize desc";
  241. List<WXSessionAttachInfo> list = con.Query<WXSessionAttachInfo>(query, msg.MsgSvrID);
  242. if (list.Count != 0)
  243. {
  244. //部分附件可能有md5校验,这里移除校验,给的是正确路径
  245. WXSessionAttachInfo acc = list[0];
  246. int index = acc.attachPath.IndexOf(".dat");
  247. int index2 = acc.attachPath.IndexOf(".dat");
  248. if (acc.attachPath.Length - index > 10 && index != -1)
  249. {
  250. acc.attachPath = acc.attachPath.Substring(0, acc.attachPath.Length - 32);
  251. }
  252. if (acc.attachPath.Length - index2 > 10 && index2 != -1)
  253. {
  254. acc.attachPath = acc.attachPath.Substring(0, acc.attachPath.Length - 32);
  255. }
  256. return acc;
  257. }
  258. else
  259. return null;
  260. }
  261. public WXMediaMsg? GetVoiceMsg(WXMsg msg)
  262. {
  263. for (int i = 0; i <= 99; i++)
  264. {
  265. if(DBInfo.ContainsKey("MediaMSG" + i.ToString()))
  266. {
  267. SQLiteConnection con = DBInfo["MediaMSG" + i.ToString()];
  268. if (con == null)
  269. continue;
  270. string query = "select * from Media where Reserved0=?";
  271. List<WXMediaMsg> wXMsgs = con.Query<WXMediaMsg>(query, msg.MsgSvrID);
  272. if (wXMsgs.Count != 0)
  273. return wXMsgs[0];
  274. }
  275. }
  276. return null;
  277. }
  278. public string? GetAttachment(WXMsgType type, WXMsg msg)
  279. {
  280. if (UserBakConfig == null)
  281. return null;
  282. string? tmpPath = Path.Combine(UserBakConfig.UserWorkspacePath, "Temp");
  283. if (!Directory.Exists(tmpPath))
  284. Directory.CreateDirectory(tmpPath);
  285. // 如果是图片和视频,从附件库中搜索
  286. string? path = null;
  287. if (type == WXMsgType.Image || type == WXMsgType.Video)
  288. {
  289. WXSessionAttachInfo? atcInfo = GetWXMsgAtc(msg);
  290. if (atcInfo == null)
  291. return null;
  292. path = atcInfo.attachPath;
  293. }
  294. // 如果是从语音,从媒体库查找
  295. else if (type == WXMsgType.Audio)
  296. {
  297. WXMediaMsg? voiceMsg = GetVoiceMsg(msg);
  298. if (voiceMsg == null)
  299. return null;
  300. if (voiceMsg.Buf == null)
  301. return null;
  302. // 从DB取音频文件到临时目录
  303. string tmp_file_path = Path.Combine(tmpPath, voiceMsg.Key + ".arm");
  304. using (FileStream stream = new FileStream(tmp_file_path, FileMode.OpenOrCreate))
  305. {
  306. stream.Write(voiceMsg.Buf, 0, voiceMsg.Buf.Length);
  307. }
  308. path = tmp_file_path;
  309. }
  310. if (path == null)
  311. return null;
  312. // 获取到原路径后,开始进行解密转移,只有图片和语音需要解密,解密后是直接归档目录
  313. if(type == WXMsgType.Image || type== WXMsgType.Audio)
  314. {
  315. path = DecryptAttachment(type, path);
  316. }
  317. else if (type == WXMsgType.Video)
  318. {
  319. string video_dir = Path.Combine(UserBakConfig.UserWorkspacePath, "Video");
  320. if(!Directory.Exists(video_dir))
  321. Directory.CreateDirectory(video_dir);
  322. FileInfo fileInfo = new FileInfo(path);
  323. string video_file_path = Path.Combine(video_dir, fileInfo.Name);
  324. // 视频的路径是相对路径,需要加上资源目录
  325. path = Path.Combine(UserBakConfig.UserResPath, path);
  326. if(!File.Exists(video_file_path))
  327. File.Copy(path, video_file_path);
  328. path = video_file_path;
  329. }
  330. if (path == null)
  331. return null;
  332. // 改相对路径
  333. path = path.Replace(UserBakConfig.UserWorkspacePath + "\\", "");
  334. return path;
  335. }
  336. public string? DecryptAttachment(WXMsgType type, string path)
  337. {
  338. if (UserBakConfig == null)
  339. return null;
  340. string? file_path = null;
  341. switch (type)
  342. {
  343. case WXMsgType.Image:
  344. string img_dir = Path.Combine(UserBakConfig.UserWorkspacePath, "Image");
  345. if (!Directory.Exists(img_dir))
  346. Directory.CreateDirectory(img_dir);
  347. // 图片的路径是相对路径,需要加上资源目录
  348. path = Path.Combine(UserBakConfig.UserResPath, path);
  349. byte[] decFileByte = DecryptionHelper.DecImage(path);
  350. string decFiletype = DecryptionHelper.CheckFileType(decFileByte);
  351. file_path = DecryptionHelper.SaveDecImage(decFileByte, path, img_dir, decFiletype);
  352. break;
  353. case WXMsgType.Audio:
  354. string audio_dir = Path.Combine(UserBakConfig.UserWorkspacePath, "Audio");
  355. if (!Directory.Exists(audio_dir))
  356. Directory.CreateDirectory(audio_dir);
  357. FileInfo fileInfo = new FileInfo(path);
  358. string audio_file_dir = Path.Combine(audio_dir, fileInfo.Name + ".mp3");
  359. ToolsHelper.DecodeVoice(path, path + ".pcm", audio_file_dir);
  360. file_path = audio_file_dir;
  361. break;
  362. }
  363. return file_path;
  364. }
  365. public List<WXMsgGroup> GetWXMsgGroup()
  366. {
  367. List<WXMsgGroup> g = new List<WXMsgGroup>();
  368. for (int i = 0; i <= 99; i++)
  369. {
  370. if (DBInfo.ContainsKey("MSG" + i.ToString()))
  371. {
  372. SQLiteConnection con = DBInfo["MSG" + i.ToString()];
  373. if (con == null)
  374. return g;
  375. string query = "select StrTalker,Count(localId) as MsgCount from MSG GROUP BY StrTalker";
  376. List<WXMsgGroup> wXMsgs = con.Query<WXMsgGroup>(query);
  377. foreach (WXMsgGroup w in wXMsgs)
  378. {
  379. WXMsgGroup? tmp = g.Find(x => x.UserName == w.UserName);
  380. if (tmp == null)
  381. g.Add(w);
  382. else
  383. tmp.MsgCount += g.Count;
  384. }
  385. }
  386. }
  387. return g;
  388. }
  389. }
  390. public enum WXMsgType
  391. {
  392. Image = 0,
  393. Video = 1,
  394. Audio = 2,
  395. File = 3,
  396. }
  397. }