-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathandroid_jd.py
477 lines (438 loc) · 18.3 KB
/
android_jd.py
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
# -*- coding: utf-8 -*-
import hashlib
import os
import clr
__author__ = "TaoJianping"
clr.AddReference('System.Core')
clr.AddReference('System.Xml.Linq')
clr.AddReference('System.Data.SQLite')
try:
clr.AddReference('unity_c37r')
clr.AddReference('model_eb')
clr.AddReference('model_im')
clr.AddReference('bcp_im')
except Exception as e:
print("debug", e)
import model_eb
import model_im
import PA_runtime
import System
from PA_runtime import *
from System.Data.SQLite import *
from System.Xml.Linq import *
from System.Xml.XPath import Extensions as XPathExtensions
del clr
# CONST
JD_VERSION = 1
# 消息状态
MESSAGE_STATUS_DEFAULT = 0
MESSAGE_STATUS_UNSENT = 1
MESSAGE_STATUS_SENT = 2
MESSAGE_STATUS_UNREAD = 3
MESSAGE_STATUS_READ = 4
# 00未知、01收藏夹、02购物车、03已购买、04普通浏览、99其他
EB_PRODUCT_UNKWON = "0"
EB_PRODUCT_FAVORITE = "1"
EB_PRODUCT_SHOPCART = "2"
EB_PRODCUT_BUIED = "3"
EB_PRODUCT_BROWSE = "4"
EB_PRODUCT_OTHER = "99"
# 消息类型
MESSAGE_CONTENT_TYPE_TEXT = 1 # 文本
MESSAGE_CONTENT_TYPE_IMAGE = 2 # 图片
MESSAGE_CONTENT_TYPE_VOICE = 3 # 语音
MESSAGE_CONTENT_TYPE_VIDEO = 4 # 视频
MESSAGE_CONTENT_TYPE_EMOJI = 5 # 表情
MESSAGE_CONTENT_TYPE_CONTACT_CARD = 6 # 名片
MESSAGE_CONTENT_TYPE_LOCATION = 7 # 坐标
MESSAGE_CONTENT_TYPE_LINK = 8 # 链接
MESSAGE_CONTENT_TYPE_VOIP = 9 # 网络电话
MESSAGE_CONTENT_TYPE_ATTACHMENT = 10 # 附件
MESSAGE_CONTENT_TYPE_RED_ENVELPOE = 11 # 红包
MESSAGE_CONTENT_TYPE_RECEIPT = 12 # 转账
MESSAGE_CONTENT_TYPE_AA_RECEIPT = 13 # 群收款
MESSAGE_CONTENT_TYPE_SYSTEM = 99 # 系统
class ColHelper(object):
def __init__(self, db_path):
self.db_path = db_path
self.conn = System.Data.SQLite.SQLiteConnection(
'Data Source = {}; Readonly = True'.format(db_path))
def __enter__(self):
self.conn.Open()
self.cmd = System.Data.SQLite.SQLiteCommand(self.conn)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.cmd.Dispose()
if hasattr(self, "reader"):
self.reader.Close()
self.conn.Close()
return True
def __repr__(self):
return "this db exists in {path}".format(path=self.db_path)
def execute_sql(self, sql):
self.cmd.CommandText = sql
self.reader = self.cmd.ExecuteReader()
return self.reader
def has_rest(self):
return self.reader.Read()
def get_string(self, idx):
return self.reader.GetString(idx) if not self.reader.IsDBNull(idx) else ""
def get_int64(self, idx):
return self.reader.GetInt64(idx) if not self.reader.IsDBNull(idx) else 0
def get_blob(self, idx):
return self.reader.GetValue(idx) if not self.reader.IsDBNull(idx) else None
def get_float(self, idx):
return self.reader.GetFloat(idx) if not self.reader.IsDBNull(idx) else 0
class JDParser(object):
def __init__(self, root, extract_deleted, extract_source):
self.root = root
self.extract_deleted = extract_deleted
self.extract_source = extract_source
self.cache_db = self.__get_cache_db()
self.eb = model_eb.EB(self.cache_db, JD_VERSION, u'Jingdong')
self.model_im_col = self.eb.im
self.need_parse = self.eb.need_parse
self.jd_db_path, self.user_db_path = self.__get_data_db()
self.jd_db_col = ColHelper(self.jd_db_path)
self.user_db_col = ColHelper(self.user_db_path)
if self.need_parse and all((self.jd_db_path, self.user_db_path)):
self.eb.db_create()
self.using_account = None
def __get_data_db(self):
"""获取需要用到的两张表的地址"""
jd_db_node = self.root.GetByPath("databases/jd.db")
user_db_node = self.root.GetByPath("databases/__icssdk_database.db")
if all((jd_db_node, user_db_node)):
return jd_db_node.PathWithMountPoint, user_db_node.PathWithMountPoint
else:
return None, None
def __get_cache_db(self):
"""获取中间数据库的db路径"""
self.cache_path = ds.OpenCachePath("Jingdong")
m = hashlib.md5()
m.update(self.root.AbsolutePath.encode('utf-8'))
return os.path.join(self.cache_path, m.hexdigest().upper())
def __process_media(self, msg):
try:
sdcard = '/storage/emulated/0/'
searchkey = ''
nodes = list()
if msg.content.find(sdcard) != -1:
searchkey = msg.content[msg.content.find(sdcard) + len(sdcard):]
nodes = self.root.FileSystem.Search(searchkey + '$')
if len(list(nodes)) == 0:
searchkey = msg.content[msg.content.rfind('/') + 1:]
nodes = self.root.FileSystem.Search(searchkey + '$')
for node in nodes:
msg.media_path = node.AbsolutePath
if msg.media_path.endswith('.mp3'):
msg.type = MESSAGE_CONTENT_TYPE_VOICE
elif msg.media_path.endswith('.amr'):
msg.type = MESSAGE_CONTENT_TYPE_VOICE
elif msg.media_path.endswith('.slk'):
msg.type = MESSAGE_CONTENT_TYPE_VOICE
elif msg.media_path.endswith('.mp4'):
msg.type = MESSAGE_CONTENT_TYPE_VIDEO
elif msg.media_path.endswith('.jpg'):
msg.type = MESSAGE_CONTENT_TYPE_IMAGE
elif msg.media_path.endswith('.png'):
msg.type = MESSAGE_CONTENT_TYPE_IMAGE
else:
msg.type = MESSAGE_CONTENT_TYPE_ATTACHMENT
return True
except Exception as e:
print (e)
return False
def __config_using_account(self):
with self.user_db_col as db_col:
sql = """SELECT pin
FROM my_info"""
db_col.execute_sql(sql)
while db_col.has_rest():
self.using_account = db_col.get_string(0)
def _get_account_table(self):
with self.user_db_col as db_col:
sql = """SELECT mypin
FROM my_config"""
db_col.execute_sql(sql)
while db_col.has_rest():
account = model_im.Account()
account.account_id = db_col.get_string(0)
self.model_im_col.db_insert_table_account(account)
self.model_im_col.db_commit()
def _get_friend_table(self):
with self.user_db_col as db_col:
sql = """SELECT _id,
localPin,
venderId,
appId,
venderName,
avatar
FROM _MSG_LIST_"""
db_col.execute_sql(sql)
while db_col.has_rest():
try:
friend = model_im.Friend()
friend.account_id = db_col.get_string(1)
friend.source = self.user_db_path
friend.friend_id = db_col.get_string(2)
friend.nickname = db_col.get_string(4)
friend.photo = db_col.get_string(5)
self.model_im_col.db_insert_table_friend(friend)
except Exception as e:
print("debug error", e)
self.model_im_col.db_commit()
def _get_message_table(self):
with self.user_db_col as db_col:
sql = """SELECT _id,
UUID,
localPin,
type,
datetime,
timestamp,
mid,
from_pin,
body_type,
body_content,
body_url,
readed
FROM _MSG_"""
db_col.execute_sql(sql)
while db_col.has_rest():
try:
message = model_im.Message()
message.account_id = db_col.get_string(2)
message.sender_id = db_col.get_string(7)
message.sender_name = db_col.get_string(7)
message.msg_id = db_col.get_string(6)
message.send_time = self.__convert_timestamp(db_col.get_int64(5))
message.source = self.user_db_path
message_type = db_col.get_string(8)
if message_type == "text":
message.type = MESSAGE_CONTENT_TYPE_TEXT
elif message_type == "image":
message.content = db_col.get_string(10)
self.__process_media(message)
else:
message.type = MESSAGE_CONTENT_TYPE_SYSTEM
message.content = db_col.get_string(9)
message.status = MESSAGE_STATUS_READ if db_col.get_int64(11) == 1 else MESSAGE_STATUS_UNREAD
message.is_sender = 1 if message.account_id == message.sender_id else 0
self.model_im_col.db_insert_table_message(message)
except Exception as e:
print("debug error", e)
self.model_im_col.db_commit()
@staticmethod
def __convert_timestamp(ts):
if isinstance(ts, str):
return ts[:-3]
elif isinstance(ts, int):
ts = str(ts)[:-3]
return int(ts)
else:
ts = str(ts)[:-3]
return int(ts)
def _get_search_table(self):
with self.jd_db_col as db_col:
sql = """SELECT word,
search_time
FROM search_history"""
db_col.execute_sql(sql)
while db_col.has_rest():
search = model_im.Search()
search.key = db_col.get_string(0)
search.create_time = self.__convert_timestamp(db_col.get_int64(1))
search.source = self.jd_db_path
self.model_im_col.db_insert_table_search(search)
self.model_im_col.db_commit()
def _get_product_table(self):
# 购物车的商品
with self.jd_db_col as db_col:
sql = """SELECT id,
name,
productCode,
buyCount
FROM CartTable"""
db_col.execute_sql(sql)
while db_col.has_rest():
product = model_eb.EBProduct()
product.set_value_with_idx(product.account_id, self.using_account)
product.set_value_with_idx(product.product_id, db_col.get_int64(2))
product.set_value_with_idx(product.product_name, db_col.get_string(1))
product.set_value_with_idx(product.source, EB_PRODUCT_SHOPCART)
self.eb.db_insert_table_product(product.get_value())
self.eb.db_commit()
# 普通的浏览记录
with self.jd_db_col as db_col:
sql = """SELECT id,
productCode
FROM BrowseHistoryTable"""
db_col.execute_sql(sql)
while db_col.has_rest():
product = model_eb.EBProduct()
product.set_value_with_idx(product.product_id, db_col.get_int64(1))
product.set_value_with_idx(product.source, EB_PRODUCT_BROWSE)
self.eb.db_insert_table_product(product.get_value())
self.eb.db_commit()
def decode_recover_account(self):
node = self.root.GetByPath("databases/__icssdk_database.db")
if node is None:
return
db = SQLiteParser.Database.FromNode(node, canceller)
if db is None:
return
table = 'my_config'
ts = SQLiteParser.TableSignature(table)
for rec in db.ReadTableDeletedRecords(ts, False):
if canceller.IsCancellationRequested:
return
try:
account = model_im.Account()
account.account_id = rec["mypin"].Value
self.model_im_col.db_insert_table_account(account)
except Exception as e:
print("error happen", e)
self.model_im_col.db_commit()
def decode_recover_friend(self):
node = self.root.GetByPath("databases/__icssdk_database.db")
if node is None:
return
db = SQLiteParser.Database.FromNode(node, canceller)
if db is None:
return
table = '_MSG_LIST_'
ts = SQLiteParser.TableSignature(table)
for rec in db.ReadTableDeletedRecords(ts, False):
if canceller.IsCancellationRequested:
return
try:
friend = model_im.Friend()
friend.account_id = rec["localPin"].Value
friend.source = self.user_db_path
friend.friend_id = rec["venderId"].Value
friend.nickname = rec["venderName"].Value
friend.photo = rec["avatar"].Value
self.model_im_col.db_insert_table_friend(friend)
except Exception as e:
print("error happen", e)
self.model_im_col.db_commit()
def decode_recover_message(self):
node = self.root.GetByPath("databases/__icssdk_database.db")
if node is None:
return
db = SQLiteParser.Database.FromNode(node, canceller)
if db is None:
return
table = '_MSG_'
ts = SQLiteParser.TableSignature(table)
for rec in db.ReadTableDeletedRecords(ts, False):
if canceller.IsCancellationRequested:
return
try:
message = model_im.Message()
message.account_id = rec["localPin"].Value
message.sender_id = rec["from_pin"].Value
message.sender_name = rec["from_pin"].Value
message.msg_id = rec["mid"].Value
message.send_time = self.__convert_timestamp(rec["timestamp"].Value)
message.source = self.user_db_path
message_type = rec["body_type"].Value
if message_type == "text":
message.type = MESSAGE_CONTENT_TYPE_TEXT
elif message_type == "image":
message.content = rec["body_content"].Value
self.__process_media(message)
else:
message.type = MESSAGE_CONTENT_TYPE_SYSTEM
message.content = rec["body_content"].Value
message.status = MESSAGE_STATUS_READ if rec["readed"].Value == 1 else MESSAGE_STATUS_UNREAD
message.is_sender = 1 if message.account_id == message.sender_id else 0
self.model_im_col.db_insert_table_message(message)
except Exception as e:
print("error happen", e)
self.model_im_col.db_commit()
def decode_recover_search(self):
node = self.root.GetByPath("databases/jd.db")
if node is None:
return
db = SQLiteParser.Database.FromNode(node, canceller)
if db is None:
return
table = 'search_history'
ts = SQLiteParser.TableSignature(table)
for rec in db.ReadTableDeletedRecords(ts, False):
if canceller.IsCancellationRequested:
return
try:
search = model_im.Search()
search.key = rec["word"].Value
search.create_time = self.__convert_timestamp(rec["search_time"].Value)
search.source = self.jd_db_path
self.model_im_col.db_insert_table_search(search)
except Exception as e:
print("error happen", e)
self.model_im_col.db_commit()
def decode_recover_product(self):
node = self.root.GetByPath("databases/jd.db")
if node is None:
return
db = SQLiteParser.Database.FromNode(node, canceller)
if db is None:
return
# 购物车
table = 'CartTable'
ts = SQLiteParser.TableSignature(table)
for rec in db.ReadTableDeletedRecords(ts, False):
if canceller.IsCancellationRequested:
return
try:
product = model_eb.EBProduct()
product.set_value_with_idx(product.account_id, self.using_account)
product.set_value_with_idx(product.product_id, rec["productCode"].Value)
product.set_value_with_idx(product.product_name, rec["name"].Value)
product.set_value_with_idx(product.source, EB_PRODUCT_SHOPCART)
self.eb.db_insert_table_product(product.get_value())
except Exception as e:
print("error happen", e)
# 浏览记录
table = 'BrowseHistoryTable'
ts = SQLiteParser.TableSignature(table)
for rec in db.ReadTableDeletedRecords(ts, False):
if canceller.IsCancellationRequested:
return
try:
product = model_eb.EBProduct()
product.set_value_with_idx(product.product_id, rec["productCode"].Value)
product.set_value_with_idx(product.source, EB_PRODUCT_BROWSE)
self.eb.db_insert_table_product(product.get_value())
except Exception as e:
print("error happen", e)
self.eb.db_commit()
def parse(self):
"""解析的主函数"""
if not all((self.user_db_path, self.jd_db_path)):
return
# 配置当前正在使用的用户
self.__config_using_account()
# 获取缓存数据
self._get_account_table()
self._get_friend_table()
self._get_message_table()
self._get_product_table()
self._get_search_table()
self.decode_recover_account()
self.decode_recover_friend()
self.decode_recover_message()
self.decode_recover_search()
self.decode_recover_product()
generate = model_eb.GenerateModel(self.cache_db)
results = generate.get_models()
return results
def parse_jd(root, extract_deleted, extract_source):
pr = ParserResults()
pr.Categories = DescripCategories.JingDong
results = JDParser(root, extract_deleted, extract_source).parse()
if results:
pr.Models.AddRange(results)
pr.Build("京东")
return pr