-
Notifications
You must be signed in to change notification settings - Fork 3
/
store.py
85 lines (72 loc) · 2.32 KB
/
store.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
#!/usr/bin/env python
import json
from Util import Util
import Config
import base64
from errors import *
class Store:
@staticmethod
def GET(svc, session, params, action):
raise WrongArgs('unknown action')
@staticmethod
def POST(svc, session, params, action):
if (session == None): raise Unauthorized('login first')
if not session.CheckScope('bbs'): raise NoPerm("out of scope")
if (action == "new"):
item = svc.get_str(params, 'item')
content = svc.get_str(params, 'content')
store_id = Store.new(item, content)
result = {}
result['id'] = store_id
svc.writedata(json.dumps(result))
else:
raise WrongArgs('unknown action')
@staticmethod
def new(item, content):
if (item != 'attachment'):
raise WrongArgs("unknown item type")
try:
data = base64.b64decode(content)
except:
raise WrongArgs("base64 decoding failure")
filename = Util.RandomStr(16)
filepath = Store.path_from_id(filename)
fp = None
try_count = 16 # good luck!
while (try_count > 0):
while (try_count > 0):
try:
fp = open(filepath, "rb")
# ... success?
filename = Util.RandomStr(16)
filepath = Store.path_from_id(filename)
except:
break
try_count -= 1
# at least we can't open it...
try:
with open(filepath, "wb") as fp:
fp.write(data)
return filename
except:
# ... failed...
filename = Util.RandomStr(16)
filepath = Store.path_from_id(filename)
try_count -= 1
raise ServerError("can't store content")
@staticmethod
def path_from_id(id):
return Config.BBS_ROOT + "/tmp/" + id + ".tmp"
@staticmethod
def verify_id(id):
if (not Util.CheckStr(id)):
return False
if (len(id) != 16):
return False
try:
filepath = Store.path_from_id(id)
with open(filepath, "rb"):
pass
except:
return False
return True