-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathScriptUtils.py
2246 lines (1908 loc) · 66.6 KB
/
ScriptUtils.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
import clr
clr.AddReference('System.Core')
clr.AddReference('System.Xml.Linq')
clr.AddReference('System.Data.SQLite')
try:
clr.AddReference('model_im')
clr.AddReference('model_nd')
clr.AddReference('model_eb')
except Exception:
pass
del clr
from PA_runtime import *
from PA.InfraLib.Utils import *
from System.Data.SQLite import *
from System.Xml.Linq import *
from System.Xml.XPath import Extensions as XPathExtensions
from PA.InfraLib.Extensions import PlistHelper
import System.Data.SQLite as sql
import hashlib
import json
import shutil
import logging
import re
import math
import System
import codecs
import os
import plistlib
import sys
import inspect
import collections
reload(sys)
from HTMLParser import HTMLParser
sys.setdefaultencoding("utf8")
import model_im
import model_nd
import model_eb
# 是否为开发调试环境
DEBUG = False
################################################################################################################
## __author__ = "chenfeiyang" ##
################################################################################################################
#
# C# Unity
#
on_c_sharp_platform = True
def format_mac_timestamp(mac_time, v = 10):
"""
from mac-timestamp generate unix time stamp
"""
date = 0
date_2 = mac_time
if mac_time < 1000000000:
date = mac_time + 978307200
else:
date = mac_time
date_2 = date_2 - 978278400 - 8 * 3600
s_ret = date if v > 5 else date_2
return int(s_ret)
#
# C SHARP GET FUCKING
# you must ensure that your scripts code have import sqlite already!
# and reader is a sqlite-reader object!
#
def c_sharp_get_string(reader, idx):
return reader.GetString(idx) if not reader.IsDBNull(idx) else ""
def c_sharp_get_long(reader, idx):
return reader.GetInt64(idx) if not reader.IsDBNull(idx) else 0
def c_sharp_get_blob(reader, idx):
return bytearray(reader.GetValue(idx)) if not reader.IsDBNull(idx) else 0
def c_sharp_get_real(reader, idx):
return reader.GetDouble(idx) if not reader.IsDBNull(idx) else 0.0
def c_sharp_get_time(reader, idx):
return reader.GetInt32(idx) if not reader.IsDBNull(idx) else 0
def c_sharp_try_get_time(reader, idx):
if reader.IsDBNull(idx):
return 0
try:
return int(reader.GetDouble(idx))
except:
pass
try:
return reader.GetInt32(idx)
except:
pass
try:
return reader.GetInt64(idx)
except:
return 0
# using shutils to copy file
def mapping_file_with_copy(src, dst):
if src is None or src is "":
print('file not copied as src is empty!')
return False
if dst is None or dst is "":
print('file not copied as dst is lost!')
return False
shutil.copy(src, dst)
# not implemented right now...
def mapping_file_with_safe_read(src, dst):
pass
def md5(string):
return hashlib.md5(string).hexdigest()
def is_md5(string):
grp = re.search('[a-fA-F0-9]{32,32}', string)
return True if grp is not None else False
def create_connection(src, read_only = True):
cmd = 'DataSource = {}; ReadOnly = True'.format(src) if read_only else 'DataSource = {}'.format(src)
conn = sql.SQLiteConnection(cmd)
conn.Open()
return conn
def create_logger(path, en_cmd, identifier = 'general'):
logger = logging.getLogger(identifier)
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(path)
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
if en_cmd:
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
class SimpleLogger(object):
def __init__(self, path, en_cmd, id):
#self.logger = create_logger(path, en_cmd, id)
self.level = 0
def set_level(self, val):
self.level = val
def m_print(self, msg):
if self.level == 1:
print(msg)
return
self.logger.info(msg)
def m_err(self, msg):
if self.level == 1:
print(msg)
return
self.logger.error(msg)
# only for small filesystem...
# for escape certain fs_name_check...(like xxxx/twitter.db xxxx/message.db)
def search_for_certain(fs, regx):
global on_c_sharp_platform
if not on_c_sharp_platform:
return list()
nodes = fs.Search(regx)
ns = Enumerable.ToList[Node](nodes)
res = list()
abs_path = fs.PathWithMountPoint
res = list()
for n in ns:
r = re.search('{}/(.*)'.format(abs_path), fs, re.I | re.M).group(1) # 返回fs的节点,注意node是否实现Search
res.append(list)
return res
# correct illegal strings in file names under Windows
def correct_isvilid_path(src_node):
if src_node is None:
return
file_path, file_name = os.path.split(src_node.PathWithMountPoint)
isvalid_string = ["\/", "\\", ":", "*", "?", "<", ">", "|"]
if [s for s in isvalid_string if s in file_name]:
cache = ds.OpenCachePath("Logs")
des_file = os.path.join(cache, file_name.replace(":","_"))
f = open(des_file, 'wb+')
data = src_node.Data
sz = src_node.Size
f.write(bytes(data.read(sz)))
f.close()
return des_file
else:
return src_node.PathWithMountPoint
def get_btree_node_str(b, k, d = ""):
if k in b.Children and b.Children[k] is not None:
try:
return str(b.Children[k].Value)
except:
return d
return d
def get_c_sharp_ts(ts):
try:
ts = TimeStamp.FromUnixTime(ts, False)
if not ts.IsValidForSmartphone():
ts = None
return ts
except:
return None
def get_c_sharp_uri(path):
return ConvertHelper.ToUri(path)
# 坐标转换
earthR = 6378137.0
def outOfChina(lat, lng):
return not (72.004 <= lng <= 137.8347 and 0.8293 <= lat <= 55.8271)
def transform(x, y):
xy = x * y
absX = math.sqrt(abs(x))
xPi = x * math.pi
yPi = y * math.pi
d = 20.0*math.sin(6.0*xPi) + 20.0*math.sin(2.0*xPi)
lat = d
lng = d
lat += 20.0*math.sin(yPi) + 40.0*math.sin(yPi/3.0)
lng += 20.0*math.sin(xPi) + 40.0*math.sin(xPi/3.0)
lat += 160.0*math.sin(yPi/12.0) + 320*math.sin(yPi/30.0)
lng += 150.0*math.sin(xPi/12.0) + 300.0*math.sin(xPi/30.0)
lat *= 2.0 / 3.0
lng *= 2.0 / 3.0
lat += -100.0 + 2.0*x + 3.0*y + 0.2*y*y + 0.1*xy + 0.2*absX
lng += 300.0 + x + 2.0*y + 0.1*x*x + 0.1*xy + 0.1*absX
return lat, lng
def delta(lat, lng):
ee = 0.00669342162296594323
dLat, dLng = transform(lng-105.0, lat-35.0)
radLat = lat / 180.0 * math.pi
magic = math.sin(radLat)
magic = 1 - ee * magic * magic
sqrtMagic = math.sqrt(magic)
dLat = (dLat * 180.0) / ((earthR * (1 - ee)) / (magic * sqrtMagic) * math.pi)
dLng = (dLng * 180.0) / (earthR / sqrtMagic * math.cos(radLat) * math.pi)
return dLat, dLng
def wgs2gcj(wgsLat, wgsLng):
if outOfChina(wgsLat, wgsLng):
return wgsLat, wgsLng
else:
dlat, dlng = delta(wgsLat, wgsLng)
return wgsLat + dlat, wgsLng + dlng
def gcj2wgs(gcjLat, gcjLng):
if outOfChina(gcjLat, gcjLng):
return gcjLat, gcjLng
else:
dlat, dlng = delta(gcjLat, gcjLng)
return gcjLat - dlat, gcjLng - dlng
def gcj2wgs_exact(gcjLat, gcjLng):
initDelta = 0.01
threshold = 0.000001
dLat = dLng = initDelta
mLat = gcjLat - dLat
mLng = gcjLng - dLng
pLat = gcjLat + dLat
pLng = gcjLng + dLng
for i in range(30):
wgsLat = (mLat + pLat) / 2
wgsLng = (mLng + pLng) / 2
tmplat, tmplng = wgs2gcj(wgsLat, wgsLng)
dLat = tmplat - gcjLat
dLng = tmplng - gcjLng
if abs(dLat) < threshold and abs(dLng) < threshold:
return wgsLat, wgsLng
if dLat > 0:
pLat = wgsLat
else:
mLat = wgsLat
if dLng > 0:
pLng = wgsLng
else:
mLng = wgsLng
return wgsLat, wgsLng
SQL_TP_TXT = 0
SQL_TP_INT = 1
SQL_TP_BLOB = 2
SQL_TP_REAL = 3
#
# 因为C# sqlite 对于类型有强依赖,这样便于写代码时减少错误
# 这个可能不是很全面,因为我还没有收集SQLITE的全部类型。。。。
#
def get_sqlite_tbl_info(cmd, tbl_name):
res = list()
cmd.CommandText = '''pragma table_info(%s)''' %tbl_name
reader = cmd.ExecuteReader()
while reader.Read():
tp = c_sharp_get_string(reader, 2)
if tp == 'text':
res.append(SQL_TP_TXT)
elif tp == 'int':
res.append(SQL_TP_INT)
elif tp == 'blob':
res.append(SQL_TP_BLOB)
elif tp == 'real':
res.append(SQL_TP_REAL)
return res
def execute_query(cmd, cmd_text, values):
cmd.CommandText = cmd_text
cmd.Parameters.Clear()
for v in values:
p = cmd.CreateParameter()
p.Value = v
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
#
# copy file....
# note, give node, not db path
# it executes a simple command, then read the results, if any error happens, we copy the sqlite file to cache(C37R)
#
def create_connection_tentatively(db_node, read_only = True):
cmd = 'DataSource = {}; ReadOnly = {}'
cmd = cmd.format(db_node.PathWithMountPoint, 'True' if read_only else 'False')
try:
conn = None
dcmd = None
reader = None
conn = sql.SQLiteConnection(cmd)
conn.Open()
dcmd = sql.SQLiteCommand(conn)
dcmd.CommandText = '''
select * from sqlite_master limit 1 offset 0
'''
reader = dcmd.ExecuteReader()
reader.Read()
reader.Close()
dcmd.Dispose()
return conn
except:
traceback.print_exc()
if reader is not None:
reader.Close()
if dcmd is not None:
dcmd.Dispose()
if conn is not None:
conn.Close()
data = db_node.Data
sz = db_node.Size
cache = ds.OpenCachePath('C37R')
if not os.path.exists(cache):
os.mkdir(cache)
cache_db = cache + '/' + md5(db_node.PathWithMountPoint)
f = open(cache_db, 'wb+')
f.write(data.read(sz))
f.close()
cmd = 'DataSource = {}; ReadOnly = {}'.format(cache_db, 'True' if read_only else 'False')
conn = sql.SQLiteConnection(cmd)
conn.Open()
return conn
#
# MACROS
#
WA_FILE_TEXT = 1
WA_FILE_IMAGE = 2
WA_FILE_AUDIO = 3
WA_FILE_VIDEO = 4
WA_FILE_OTHER = 99
#
# 产生用户类型
#
def create_user_intro(uid, name, photo):
usr = Common.UserIntro()
usr.ID.Value = uid
usr.Name.Value = name
usr.Photo.Value = get_c_sharp_uri(photo)
return usr
#
# 所有c37r系列的类型的基类型
#
class C37RBasic(object):
def __init__(self):
self.idx = -1
self.res = list()
def set_value_with_idx(self, idx, val):
if idx >= len(self.res):
return
self.res[idx] = val
def get_value_with_idx(self, idx):
if idx >= len(self.res):
return None
return self.res[idx]
def get_values(self):
return self.res
#
# check db-version is newest version or not
# db_name: sqlite path
# v_key: version key
# v_value: desired version value
# result : false if check version failed, you may delete this sqlite file, then regenerate it.
#
TBL_CREATE_VERSION = '''
create table if not exists tb_version(v_key text, v_val int)
'''
TBL_INSERT_VERSION = '''
insert into tb_version values (?,?)
'''
def CheckVersion(db_name, v_key, v_value):
try:
if not os.path.exists(db_name):
return False
conn = None
cmd = None
reader = None
res = False
conn = create_connection(db_name)
cmd = sql.SQLiteCommand(conn)
cmd.CommandText = '''
select v_val from tb_version where v_key = '{}'
'''.format(v_key)
reader = cmd.ExecuteReader()
if reader.Read():
value = c_sharp_get_long(reader, 0)
if value == v_value:
res = True
else:
res = False
reader.Close()
cmd.Dispose()
conn.Close()
return res
except:
if reader is not None:
reader.Close()
if cmd is not None:
cmd.Dispose()
if conn is not None:
conn.Close()
return False
#
# like unix "strings" command-line tool
# returns readable strings list
#
def py_strings(file):
chars = r"A-Za-z0-9/\-:.,_$%'()[\]<> "
shortestReturnChar = 4
regExp = '[%s]{%d,}' % (chars, shortestReturnChar)
pattern = re.compile(regExp) # accelerate regularexpression match speed.
with open(file, 'rb') as f:
return pattern.findall(f.read())
#
# 检查数据库文件完备性
# input : sqlite_node(not path)
# cache: 用以copy sqlite 文件的文件夹
# 返回: 如果是正常数据库,则返回原始路径,如果异常,则返回拷贝后的路径
#
def check_sqlite_maturity(sqlite_node, cache):
pth = sqlite_node.PathWithMountPoint
ret = 0x0
if os.path.exists(pth + '-shm'):
ret |= 0x2
if os.path.exists(pth + '-wal'):
ret |= 0x1
if ret != 0x3:
hash_code = md5(pth)
out_file = os.path.join(cache, hash_code)
mapping_file_with_copy(pth, out_file)
if ret & 0x1:
mapping_file_with_copy(pth + '-wal', out_file + '-wal')
if ret & 0x2:
mapping_file_with_copy(pth + '-shm', out_file + '-shm')
return out_file
return pth
#
# 恢复数据中的相关内容
#
def try_get_rec_value(rec, key, def_val = None):
try:
if not rec[key].IsDBNull:
return rec[key].Value
else:
return def_val
except:
return def_val
################################################################################################################
## __author__ = "TaoJianping" ##
################################################################################################################
class ModelCol(object):
def __init__(self, db):
# TODO 增加db的判定,增加兼容
db_path = db.PathWithMountPoint
self.db_path = db_path
self.conn = System.Data.SQLite.SQLiteConnection(
'Data Source = {}; Readonly = True'.format(db_path))
self.cmd = None
self.is_opened = False
self.in_context = False
self.current_reader = None
def open(self):
self.conn.Open()
self.cmd = System.Data.SQLite.SQLiteCommand(self.conn)
self.is_opened = True
def close(self):
if self.current_reader is not None:
self.current_reader.Close()
self.cmd.Dispose()
self.conn.Close()
self.is_opened = False
def __enter__(self):
if self.is_opened is False:
self.open()
self.in_context = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
self.in_context = False
return True
def __repr__(self):
return "this db exists in {path}".format(path=self.db_path)
def __call__(self, sql):
self.execute_sql(sql)
return
def execute_sql(self, sql):
self.cmd.CommandText = sql
self.current_reader = self.cmd.ExecuteReader()
return self.current_reader
def fetch_reader(self, sql):
cmd = System.Data.SQLite.SQLiteCommand(self.conn)
cmd.CommandText = sql
return cmd.ExecuteReader()
def has_rest(self):
return self.current_reader.Read()
def get_string(self, idx):
return self.current_reader.GetString(idx) if not self.current_reader.IsDBNull(idx) else ""
def get_int64(self, idx):
return self.current_reader.GetInt64(idx) if not self.current_reader.IsDBNull(idx) else 0
def get_blob(self, idx):
return self.current_reader.GetValue(idx) if not self.current_reader.IsDBNull(idx) else None
def get_float(self, idx):
return self.current_reader.GetFloat(idx) if not self.current_reader.IsDBNull(idx) else 0
@staticmethod
def fetch_string(reader, idx):
return reader.GetString(idx) if not reader.IsDBNull(idx) else ""
@staticmethod
def fetch_int64(reader, idx):
return reader.GetInt64(idx) if not reader.IsDBNull(idx) else 0
@staticmethod
def fetch_blob(reader, idx):
return reader.GetValue(idx) if not reader.IsDBNull(idx) else None
@staticmethod
def fetch_float(reader, idx):
return reader.GetFloat(idx) if not reader.IsDBNull(idx) else 0
# Const
FieldType = SQLiteParser.FieldType
FieldConstraints = SQLiteParser.FieldConstraints
class RecoverTableHelper(object):
def __init__(self, node):
self.db = SQLiteParser.Database.FromNode(node, canceller)
self.db_path = node.PathWithMountPoint
def get_table(self, table_name, table_config):
"""
None = 0,
NotNull = 8,
Text = 1, SQLiteParser.FieldType.Text
Int = 2, SQLiteParser.FieldType.Int
Blob = 3, SQLiteParser.FieldType.Blob
Float = 4 SQLiteParser.FieldType.Float
None = 0,
PrimaryKey = 1,
NotNull = 2
:param table_name: 表的名字
:param table_config: 表的字段的配置
:return:
"""
ts = SQLiteParser.TableSignature(table_name)
for column_name, config in table_config.items():
field_type = config[0]
field_constraint = config[1]
if field_constraint:
SQLiteParser.Tools.AddSignatureToTable(ts, column_name, field_type, field_constraint)
else:
SQLiteParser.Tools.AddSignatureToTable(ts, column_name, field_type)
return ts
def is_valid(self):
return True if self.db else False
def read_records(self, table, read_delete_records=False, deep_carve=False):
return self.db.ReadTableRecords(table, read_delete_records, deep_carve)
def read_deleted_records(self, table, deep_carve=False):
return self.db.ReadTableDeletedRecords(table, deep_carve)
# 为了不破坏兼容性,只是继承RecoverTableHelper,但功能都是一样的
# ModelCol和BaseModel的区别就是前者能写sql语句,而这个不能
class BaseModel(RecoverTableHelper):
pass
class TaoUtils(object):
@staticmethod
def open_file(file_path, encoding="utf-8"):
try:
with codecs.open(file_path, 'r', encoding=encoding) as f:
return f.read()
except Exception as e:
with open(file_path) as f:
return f.read()
@staticmethod
def copy_file(old_path, new_path):
try:
shutil.copyfile(old_path, new_path)
return True
except Exception as e:
return False
@staticmethod
def copy_dir(old_path, new_path):
try:
if os.path.exists(new_path):
shutil.rmtree(new_path)
shutil.copytree(old_path, new_path)
return True
except Exception as e:
print(e)
return False
@staticmethod
def list_dir(path):
return os.listdir(path)
@staticmethod
def convert_timestamp(ts):
try:
if not ts:
return None
ts = str(int(float(ts)))
if len(ts) > 13:
return None
elif float(ts) < 0:
return None
elif len(ts) == 13:
return int(float(ts[:-3]))
elif len(ts) <= 10:
return int(float(ts))
else:
return None
except:
return None
@staticmethod
def convert_ts_for_ios(ts):
try:
dstart = DateTime(1970, 1, 1, 0, 0, 0)
cdate = TimeStampFormats.GetTimeStampEpoch1Jan2001(ts)
return ((cdate - dstart).TotalSeconds)
except Exception as e:
return None
@staticmethod
def convert_ts_for_mac(mac_time, v=10):
"""
from mac-timestamp generate unix time stamp
"""
date = 0
date_2 = mac_time
if mac_time < 1000000000:
date = mac_time + 978307200
else:
date = mac_time
date_2 = date_2 - 978278400 - 8 * 3600
s_ret = date if v > 5 else date_2
return int(s_ret)
@staticmethod
def json_loads(data):
try:
return json.loads(data)
except:
return None
@staticmethod
def calculate_file_size(file_path):
if file_path is None:
return
if not os.path.exists(file_path):
return
return int(os.path.getsize(file_path))
@staticmethod
def hash_md5(words):
m = hashlib.md5()
m.update(words)
return m.hexdigest().upper()
@staticmethod
def create_sub_node(node, rpath, vname):
mem = MemoryRange.CreateFromFile(rpath)
r_node = Node(vname, Files.NodeType.File)
r_node.Data = mem
node.Children.Add(r_node)
return r_node
@staticmethod
def open_plist(file_path):
try:
data = plistlib.readPlist(file_path)
except Exception as e:
print(e)
data = None
return data
class TimeHelper(object):
@staticmethod
def str_to_ts(stringify_time, _format="%Y-%m-%d"):
try:
if not stringify_time:
return
time_tuple = time.strptime(stringify_time, _format)
ts = int(time.mktime(time_tuple))
return ts
except Exception as e:
print (e)
return None
@staticmethod
def convert_timestamp(ts):
try:
if not ts:
return None
ts = str(int(float(ts)))
if len(ts) > 13:
return None
elif float(ts) < 0:
return None
elif len(ts) == 13:
return int(float(ts[:-3]))
elif len(ts) <= 10:
return int(float(ts))
else:
return None
except:
return None
@staticmethod
def convert_ts_for_ios(ts):
try:
dstart = DateTime(1970, 1, 1, 0, 0, 0)
cdate = TimeStampFormats.GetTimeStampEpoch1Jan2001(ts)
return ((cdate - dstart).TotalSeconds)
except Exception as e:
return None
@staticmethod
def convert_ts_for_mac(mac_time, v=10):
"""
from mac-timestamp generate unix time stamp
"""
date = 0
date_2 = mac_time
if mac_time < 1000000000:
date = mac_time + 978307200
else:
date = mac_time
date_2 = date_2 - 978278400 - 8 * 3600
s_ret = date if v > 5 else date_2
return int(s_ret)
@staticmethod
def convert_timestamp_for_c_sharp(timestamp):
"""转换成C# 那边的时间戳格式"""
try:
ts = TimeStamp.FromUnixTime(timestamp, False)
if not ts.IsValidForSmartphone():
ts = None
return ts
except Exception as e:
return None
class Logger(object):
def __init__(self, debug):
self.module = None
self.class_name = None
self.func_name = None
self.debug = debug
def error(self):
if self.debug:
TraceService.Trace(TraceLevel.Error, "{module} error: {class_name} {func} ==> {log_info}".format(
module=self.module,
class_name=self.class_name,
func=self.func_name,
log_info=traceback.format_exc()
))
def info(self, info):
TraceService.Trace(TraceLevel.Info, "{module} info: {class_name} {func} ==> {log_info}".format(
module=self.module,
class_name=self.class_name,
func=self.func_name,
log_info=info
))
class ParserBase(object):
"""解析类的基类,尽量把基础的函数放在这里,真正的解析类只处理业务逻辑"""
def __init__(self, root, extract_deleted, extract_source, app_name=None, app_version=1, debug=False):
self.root = self._get_root_node(root)
self.app_name = app_name
self.app_version = app_version
self.extract_deleted = extract_deleted
self.extract_source = extract_source
self.cache_db = self._get_cache_db()
self.logger = Logger(debug)
self.debug = debug
self._search_nodes = [self.root, self.root.FileSystem]
@staticmethod
def _get_root_node(node, times=0):
"""
根据传入的节点拿到要检测的根节点
:param node: 传入的节点
:param times: 向上返回的次数
:return: 目标节点
"""
for i in range(times):
node = node.Parent
return node
def _get_cache_db(self):
"""获取中间数据库的db路径"""
self.cache_path = ds.OpenCachePath(self.app_name)
m = hashlib.md5()
m.update(self.root.AbsolutePath.encode('utf-8'))
return os.path.join(self.cache_path, m.hexdigest().upper())
def _copy_root(self):
"""
因为数据库打开的时候可能会有一些问题,需要把他拷贝出来
我把它放在了cache目录下
:return:
"""
old_root_path = self.root.PathWithMountPoint
new_root_path = os.path.join(self.cache_path, TaoUtils.hash_md5(old_root_path))
TaoUtils.copy_dir(old_root_path, new_root_path)
node = FileSystem.FromLocalDir(new_root_path)
return node
def _copy_data(self, *dirs):
new_data_path_list = [self._copy_data_dir_files(d) for d in dirs]
return new_data_path_list
def _copy_data_dir_files(self, data_dir):
"""
把这个目录下有关的文件夹一般是数据db文件转移到其他地方方便库使用
:param data_dir:
:return:
"""
node = self.root.GetByPath(data_dir)
if node is None:
print("not found data")
return False
old_dir = node.PathWithMountPoint
new_dir = os.path.join(self.cache_path, TaoUtils.hash_md5(data_dir))
TaoUtils.copy_dir(old_dir, new_dir)
return new_dir
def _generate_nd_models(self):
"""网盘类应用 => 从中间数据库返回models给C#那边"""
generate = model_nd.NDModel(self.cache_db)
nd_results = generate.generate_models()
generate = model_im.GenerateModel(self.cache_db + ".IM")
im_results = generate.get_models()
return nd_results + im_results
def _generate_im_models(self):
generate = model_im.GenerateModel(self.cache_db)
results = generate.get_models()
return results
def _add_media_path(self, obj, file_name):
try:
searchkey = file_name
nodes = self.root.FileSystem.Search(searchkey + '$')
for node in nodes:
obj.media_path = node.AbsolutePath
if obj.media_path.endswith('.mp3'):
obj.type = model_im.MESSAGE_CONTENT_TYPE_VOICE
elif obj.media_path.endswith('.amr'):
obj.type = model_im.MESSAGE_CONTENT_TYPE_VOICE
elif obj.media_path.endswith('.slk'):
obj.type = model_im.MESSAGE_CONTENT_TYPE_VOICE
elif obj.media_path.endswith('.mp4'):
obj.type = model_im.MESSAGE_CONTENT_TYPE_VIDEO
elif obj.media_path.endswith('.jpg'):
obj.type = model_im.MESSAGE_CONTENT_TYPE_IMAGE
elif obj.media_path.endswith('.png'):
obj.type = model_im.MESSAGE_CONTENT_TYPE_IMAGE
else:
obj.type = model_im.MESSAGE_CONTENT_TYPE_ATTACHMENT
return True
except Exception as e:
print (e)
return False
@staticmethod
def load_nd_models(cache_db, app_version):
"""
初始化并返回网盘类应用需要的 model
:param cache_db: 中间数据库的地址
:param app_version: 应用的版本
:return:
"""
model_nd_col = model_nd.NetDisk(cache_db, app_version)
model_im_col = model_nd_col.im
return model_nd_col, model_im_col
@staticmethod
def load_im_model():
model_im_col = model_im.IM()
return model_im_col
@staticmethod
def load_eb_models(cache_db, app_version, app_name):
eb = model_eb.EB(cache_db, app_version, app_name)