-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreadJson.py
69 lines (49 loc) · 1.96 KB
/
readJson.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
#coding = utf-8
from io import open
import os, json, time, shutil
def readJson(downloadtime = None, magnet = None, type = None, torrent_file_name = None):
jsonFile = None
with open(os.path.join(os.getcwd(), 'torrentfiles', 'history.json'), 'r', encoding='utf8') as f:
jsonFile = json.loads(f.read())
rst = False
if type == 'store':
expire = downloadtime + 21600
fname = '%s.torrent' % int(downloadtime * 1000000)
jsonFile.append({
'fname': fname,
'expire': expire,
'magnet': magnet,
'torrent_file_name': torrent_file_name
})
rst = {
'fname': '/file/%s' % fname,
'torrent_file_name': torrent_file_name
}
elif type== 'get':
for item in jsonFile:
if item['magnet'] == magnet:
rst = {
'fname': '/file/%s' % item['fname'],
'torrent_file_name': item['torrent_file_name']
}
break
toRemove = []
nowtime = time.time()
for idx in range(len(jsonFile)):
if nowtime > jsonFile[idx]['expire']:
if os.path.exists(os.path.join(os.getcwd(), 'torrentfiles', jsonFile[idx]['fname'])):
os.remove(os.path.join(os.getcwd(), 'torrentfiles', jsonFile[idx]['fname']))
toRemove.append(idx)
for i in toRemove:
jsonFile.remove(i)
with open(os.path.join(os.getcwd(), 'torrentfiles', 'history.json'), 'w', encoding='utf8') as f:
f.write(unicode(json.dumps(jsonFile, ensure_ascii=False)))
return rst
def clearData():
for i in os.listdir(os.path.join(os.getcwd(), 'torrentfiles')):
filepath = os.path.join(os.getcwd(), 'torrentfiles', i)
if not i == 'history.json' and not i.split('.')[-1] == 'torrent':
if os.path.isdir(filepath):
shutil.rmtree(filepath)
else:
os.remove(filepath)