-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethods.py
540 lines (463 loc) · 18.3 KB
/
methods.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
from crypt import methods
from random import randint
import os
from uuid import uuid4
from flask import Flask, request, jsonify, g
from matplotlib.pyplot import vlines
from requests import Response
from sqlalchemy import null
import config
import flask_mail
from exts import mail
from model import *
from tokens import *
def rand_filename():
return str(uuid4())
def id_msg(id, message = ""):
return jsonify({"id":id, "message":message})
def wrap_post(post: Posts, uid = None) -> dict:
userinfo = Users.get_by_id(post.uid)
if type(userinfo) is not Users:
userinfo = Users("已注销用户","","","")
replycount = Replies.count_by_pid(uid, post.pid)
DIANZAN_GET = 16
dianzan_list = Dianzans.get_by_post(post.pid, DIANZAN_GET)
dianzaner_str = ""
for i in range(0, min(DIANZAN_GET - 1, len(dianzan_list))):
if i != 0 :
dianzaner_str += ", "
dianzaner_str += str(Users.get_by_id(dianzan_list[i]).name)
logD(dianzaner_str)
if len(dianzan_list)>=DIANZAN_GET:
dianzaner_str += f", ...等{post.dianzan}人赞了"
else:
dianzaner_str += f"共{post.dianzan}人赞了"
if replycount < 0 :
return None
ret_list = {
"pid":post.pid,
"title":post.title,
"content":post.content,
"uid":post.uid,
"pos":post.pos,
"nreply" : replycount,
"dianzan":post.dianzan,
"dianzandetail":dianzaner_str,
"restype":post.res_type,
"resids":post.res_ids,
"datetime":post.addtime.strftime("%Y-%m-%d %H:%M:%S"),
"username":userinfo.name,
"userprofileid" : userinfo.profile_res_id,
"followed":Follow.get(uid, post.uid),
}
if (uid is not None) and (uid >= 0):
if_zan = Dianzans.get(uid, post.pid)
ret_list['if_zan'] = if_zan
return ret_list
def wrap_post_list(post_list:list, uid = None)->dict:
if type(post_list) is TYPE_ERROR_QUERY:
return None
ret_list = []
max_pid = -1
min_pid = -1
for post in post_list:
post_dict = wrap_post(post, uid)
if post_dict is None:
return None
ret_list.append(post_dict)
max_pid = int(max(max_pid, post.pid))
min_pid = int(post.pid if min_pid < 0 else min(min_pid, post.pid))
return {
"posts":ret_list, "count":len(ret_list),
"min":min_pid, "max":max_pid,
}
def wrap_dict(data:dict)->tuple:
if data is None:
return 500, id_msg(-1, "server internal error")
data['message'] = 'success'
return 200, jsonify(data)
def message_dianzan(uid_sender:int, pid:int):
user = Users.get_by_id(uid_sender)
if user is None: return
post = Posts.get(pid)
if post is None: return
title = f"{user.name:s}点赞了您的帖子#{pid:d}"
content = ""
Message.add(post.uid, uid_sender, title, content, pid)
def message_reply(uid_sender:int, pid:int, content:str):
user = Users.get_by_id(uid_sender)
if user is None: return
post = Posts.get(pid)
if post is None: return
title = f"{user.name:s}回复了您的帖子#{pid:d}"
if len(content)>30:
content = content[:30]+"..."
Message.add(post.uid, uid_sender, title, content, pid)
def message_new_post(uid_sender:int, pid:int, content:str):
user = Users.get_by_id(uid_sender)
if user is None: return
post = Posts.get(pid)
if post is None: return
title = f"您关注的{user.name:s}发布了新帖子#{pid:d}"
if len(content)>30:
content = content[:30]+"..."
follower_list = Follow.get_follower_list(uid_sender)
for follower in follower_list:
Message.add(follower, uid_sender, title, content, pid)
def user_login(username:str, passwd:str):
uid = Users.get_by_login(username, passwd)
if uid < 0:
return 400, id_msg(-1, "login failed")
token = generate_token(uid)
return 200, jsonify({"token": f'JWT {token:s}', 'uid':uid, "message":"success"})
def request_valid_code(content:str):
code = randint(100000, 999999)
Valid.insert(content, code)
msg = flask_mail.Message(f'【草莓波球论坛】新用户注册验证', sender = config.MAIL_USERNAME, recipients=[content,])
msg.body = f"【草莓波球论坛】欢迎注册草莓波球论坛!您的验证码为{code}, 请在5分钟内完成注册。如非本人操作请忽略此邮件。"
logD(f"[EMAIL] sending email{code}")
mail.send(msg)
return 200, id_msg(0, "success")
def user_register(username:str, passwd:str, valid_type:str, valid_content:str, valid_code:int):
# IMPORTANT remove this code when release!!
if valid_code != 884888 and Valid.get_code(valid_content) != valid_code:
return 400, id_msg(11, "wrong validation code")
if type(username)!=str or len(username) > MAXLEN_USERNAME or len(username) < MINLEN_USERNAME:
return 400, id_msg(10, f"username should be shorter than {MAXLEN_USERNAME}")
ret = Users.insert(username, passwd, valid_type, valid_content)
if ret < 0:
if ret == ERROR_USERNAME:
return 400, id_msg(2, "username already exist")
if ret == ERROR_MAIL:
return 400, id_msg(3, "mailbox already exist")
if ret == ERROR_TEL:
return 400, id_msg(4, "telephone already exist")
return 500, ""
return 200, jsonify({"uid":ret, "message":"success"})
def user_getinfo(uid:int):
usr = Users.get_by_id(uid)
if type(usr) is not Users:
return 404, id_msg(-1, "user not found")
user_info_dict = {
'uid' : usr.uid,
'username' : usr.name,
'sig' : usr.sig,
'mail' : usr.mail,
'tel' : usr.tel,
'profileid' : usr.profile_res_id,
"followed": Follow.get(g.uid, uid),
'message' : "success"
}
return 200, jsonify(user_info_dict)
def user_set_info(uid:int, username:str, sig:str, res_id:int):
if type(username)!=str or len(username) > MAXLEN_USERNAME or len(username) < MINLEN_USERNAME:
return 400, id_msg(1, f"username should be shorter than {MAXLEN_USERNAME} and longer than {MINLEN_USERNAME}")
if type(sig)!=str or len(sig)>MAXLEN_USERSIG:
return 400, id_msg(2, f"signature should be shorter than {MAXLEN_USERSIG}")
try:
assert(Users.update_username(uid, username))
assert(Users.update_sig(uid, sig))
assert(Users.update_profile(uid, res_id))
except:
return 500, id_msg(-1, "server internal error, maybe request is invalid")
return 200, id_msg(0, "success")
def user_set_profile(uid:int, res_id:int):
ret = Users.update_profile(uid, res_id)
if not ret:
return 500, id_msg(-1, "server internal error, maybe request res_id invalid")
return 200, id_msg(0, "success")
def user_change_passwd(uid:int, old:str, new:str):
code = Users.update_passwd(uid, old, new)
if code == ERROR_VARIFY_FAILED:
return 400, id_msg(1, "password worong")
if code == CHANGE_PASSWD_SUCCESS:
return 200, id_msg(0, "success")
return 500, id_msg(2, "server error")
def user_ban(uid, ban_uid):
if None in [Users.get_by_id(uid), Users.get_by_id(ban_uid)]:
return 404, id_msg(-2, "Users not found")
status = Ban.add(uid, ban_uid)
if not status:
return 500, id_msg(-1, "server internal error")
return 200, id_msg(1, "success")
def user_unban(uid, ban_uid):
if None in [Users.get_by_id(uid), Users.get_by_id(ban_uid)]:
return 404, id_msg(-2, "Users not found")
status = Ban.remove(uid, ban_uid)
if not status:
return 500, id_msg(-1, "server internal error")
return 200, id_msg(0, "success")
def user_ban_list(uid):
if Users.get_by_id(uid) is None:
return 404, id_msg(-2, "No such user")
ban_list = Ban.get_list(uid)
if ban_list is None:
return 500, id_msg(-1, "server internal error")
info_list = []
for uid in ban_list:
user_info = Users.get_by_id(uid)
if user_info is None:
return 500, id_msg(-1, "server internal error")
info_list.append({
"uid" : uid,
"username" : user_info.name,
'imgid' : user_info.profile_res_id,
})
return 200, jsonify({
'list':info_list,
'id':0,
'message':'success',
})
def post_get_n(uid:int, n:int, start:int, type_order:int = POST_ORDER_NEW, type_filter = POST_FILTER_NONE):
post_list = Posts.get_n_newest(g.uid, n, start, type_order, type_filter)
post_list_dict = wrap_post_list(post_list, uid)
return wrap_dict(post_list_dict)
def post_get_detail(uid:int, pid:int):
post = Posts.get(pid)
if type(post) is not Posts:
return 404, id_msg(-1, f"request post not found")
return wrap_dict(wrap_post(post, uid))
def post_get_users(uid, n, start):
post_list = Posts.get_n_newest_filter_uid(uid, n, start)
post_list_dict = wrap_post_list(post_list, uid)
post_list_dict["uid"] = uid
return wrap_dict(post_list_dict)
def post_search(uid, main_pattern, title_pattern, content_pattern, user_pattern, res_type_list):
user_list = None
if user_pattern is not None:
user_list = Users.search(uid, user_pattern)
if type(user_list) is int:
return 500, id_msg(1, "Failed to get userlist")
if res_type_list is not None:
for res_type in res_type_list:
if (res_type is not None) and (res_type not in RES_TYPE_LIST):
return 400, id_msg(2, "restype invalid")
post_list = Posts.search(uid, main_pattern, title_pattern, content_pattern, user_list, res_type_list)
post_list_dict = wrap_post_list(post_list, uid)
return wrap_dict(post_list_dict)
def post_add(uid, title, content, res_type, res_ids, pos):
if type(title) != str or len(title) > MAXLEN_TITLE or len(title) <=0:
return 400, id_msg(2, f"request title format error(should be string shorter than {MAXLEN_TITLE})")
if type(content) != str or len(content) > MAXLEN_CONTENT or len(content) <=0:
return 400, id_msg(3, f"request content format error(should be string shorter than {MAXLEN_CONTENT})")
if (res_type not in RES_TYPE_LIST) and (res_type is not None):
return 400, id_msg(4, f"request resource file type {res_type} invalid")
new_pid = Posts.insert(uid, title, content, res_type, res_ids, pos) # FIX THIS WHEN ADDING RES TABLE
if new_pid<0:
return 500, id_msg(-1, "inserting failed")
message_new_post(uid, new_pid, title+" "+content)
return 200, jsonify({"pid":new_pid, "message":"success"})
def wrap_dianzan(pid:int, uid:int):
post = Posts.get(pid)
DIANZAN_GET = 16
dianzan_list = Dianzans.get_by_post(post.pid, DIANZAN_GET)
dianzaner_str = ""
for i in range(0, min(DIANZAN_GET - 1, len(dianzan_list))):
if i != 0 :
dianzaner_str += ", "
dianzaner_str += str(Users.get_by_id(dianzan_list[i]).name)
logD(dianzaner_str)
if len(dianzan_list)>=DIANZAN_GET:
dianzaner_str += f", ...等{post.dianzan}人赞了"
else:
dianzaner_str += f"共{post.dianzan}人赞了"
ret_list = {
"pid":pid,
"dianzan":post.dianzan,
"dianzandetail":dianzaner_str
}
if (uid is not None) and (uid >= 0):
if_zan = Dianzans.get(uid, pid)
ret_list['if_zan'] = if_zan
return ret_list
def get_dianzan(uid, pid):
ret = wrap_dianzan(pid, uid)
if type(ret) is TYPE_ERROR_QUERY:
if ret == ERROR_NO_POST:
return 404, id_msg(-1, "request post not found")
return 500, id_msg(-1, "server internal error")
ret['message'] = 'success'
return 200, jsonify(ret)
def post_dianzan(uid, pid, flag):
ret = Posts.zan(uid, pid, flag)
ret2 = wrap_dianzan(pid, uid)
logD(f"pid={pid} uid={uid}")
if type(ret) is TYPE_ERROR_QUERY:
if ret == ERROR_NO_POST:
return 404, id_msg(-1, "request post not found")
return 500, id_msg(-1, "server internal error")
ret2['message'] = 'success'
message_dianzan(uid, pid)
return 200, jsonify(ret2)
def post_remove(uid, pid):
status = Posts.remove_by_pid(uid, pid)
if status == ERROR_UNAUTHORIZED:
return 400, id_msg(2, "post not belong to request user")
if status == ERROR_NOTEXIST:
return 400, id_msg(3, "post not exist")
if status < 0:
return 400, id_msg(1, "fail")
return 200, id_msg(0, "success")
def reply_get_n(uid, pid, n, start):
reply_list = Replies.get_by_pid(uid, pid,n,start)
if type(reply_list) is TYPE_ERROR_QUERY:
if reply_list == ERROR_NO_POST:
return 404, id_msg(-1, "request post not found")
return 500, id_msg(-1, "server internal error")
ret_list = []
max_rid = -1
min_rid = -1
for reply in reply_list:
userinfo = Users.get_by_id(reply.uid)
if type(userinfo) is not Users:
userinfo = Users("未知发布者","","","")
ret_list.append({
"pid" : reply.pid,
"rid" : reply.rid,
"uid" : reply.uid,
"content" : reply.content,
"restype" : reply.res_type,
"resids" : reply.res_ids,
"username" : userinfo.name,
"userprofileid" : userinfo.profile_res_id,
"pos":reply.pos,
"datetime":reply.addtime.strftime("%Y-%m-%d %H:%M:%S"),
"followed":Follow.get(uid, reply.uid),
})
max_rid = max(max_rid, reply.rid)
min_rid = reply.rid if min_rid < 0 else min(min_rid, reply.rid)
return 200, jsonify({
"reply":ret_list, "count":len(ret_list), "message":"success",
"min":min_rid, "max":max_rid,
})
def reply_add(uid, pid, content, res_type, res_content, pos):
if type(content) != str or len(content) > MAXLEN_CONTENT or len(content) <=0:
return 400, id_msg(3, f"request content format error(should be string shorter than {MAXLEN_CONTENT})")
if res_type not in RES_TYPE_LIST and res_type is not None:
return 400, id_msg(4, f"request resource file type invalid")
if Posts.get(pid) is None:
return 400, id_msg(5, f"request post not exist")
new_rid = Replies.insert(uid, pid, content, res_type, res_content, pos) # FIX THIS WHEN ADDING RES TABLE
if new_rid<0:
if new_rid == ERROR_NO_POST:
return 404, id_msg(-1, "request post not found")
return 500, id_msg(-1, "inserting failed")
message_reply(uid, pid, content)
return 200, jsonify({"rid":new_rid, "message":"success", "id":0})
def reply_remove(uid, rid):
status = Replies.remove_by_rid(uid, rid)
if status == ERROR_UNAUTHORIZED:
return 400, id_msg(2, "reply not belong to request user")
if status == ERROR_NOTEXIST:
return 400, id_msg(3, "reply not exist")
if status < 0:
return 400, id_msg(1, "fail")
return 200, id_msg(0, "success")
def follow_add(follower, follows):
if None in [Users.get_by_id(follower), Users.get_by_id(follows)]:
return 404, id_msg(-2, "Users not found")
status = Follow.add(follower, follows)
if not status:
return 500, id_msg(-1, "server internal error")
return 200, id_msg(1, "success")
def follow_remove(follower, follows):
if None in [Users.get_by_id(follower), Users.get_by_id(follows)]:
return 404, id_msg(-2, "Users not found")
status = Follow.remove(follower, follows)
if not status:
return 500, id_msg(-1, "server internal error")
return 200, id_msg(0, "success")
def follow_get_list(follower):
if Users.get_by_id(follower) is None:
return 404, id_msg(-2, "No such user")
follows_list = Follow.get_follow_list(follower)
if follows_list is None:
return 500, id_msg(-1, "server internal error")
follow_ret_list = []
for follow in follows_list:
user = Users.get_by_id(follow)
if user is None: continue
follow_ret_list.append({
'uid':user.uid,
'username':user.name,
"imgid":user.profile_res_id,
})
return 200, jsonify({
'list':follow_ret_list,
'id':0,
'message':'success',
})
def file_upload(file):
filename = str(file.filename)
suffix = filename.split('.')[-1].lower()
if (suffix not in config.ALLOWED_EXTENTIONS):
return 400, jsonify({
'id' : -1,
'message' : 'file extention name not allowed',
})
new_filename = f'{rand_filename():s}.{suffix:s}'
save_dir = config.UPLOAD_PATH
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_path = os.path.join(save_dir, new_filename)
try:
file.save(save_path)
except Exception as e:
logDE(e)
return 500, id_msg(-1, "server failed to save file")
res_id = -1
try:
type_table = {
'IMG':RES_IMG,
'AUD':RES_AUD,
'VID':RES_VID,
}
res_id = ResFile.insert(type_table[config.FILE_TYPE[suffix]], new_filename)
except Exception as e:
logDE(e)
return 500, id_msg(-1, "suffix resolving failed")
if res_id is None:
return 500, id_msg(-1, "Database inserting error")
return 200, jsonify({
'id':0,
'message':'success',
'resid':res_id
})
def file_get_path(res_id:int):
file_name = ResFile.get_filename(res_id)
if file_name is None:
return None
file_path = os.path.join(config.UPLOAD_PATH, file_name)
if os.path.exists(file_path):
return file_path
return None
def message_count_unread(uid:int):
if Users.get_by_id(uid) is None:
return 404, id_msg(-1, "Request user invalid")
n_unread = Message.count_unread(uid)
return 200, jsonify({
'message':'success',
'count':n_unread
})
def message_get_list(uid:int, n:int, start=None):
if Users.get_by_id(uid) is None:
return 404, id_msg(-1, "Request user invalid")
msg_list = Message.get_list(uid, n, start)
if type(msg_list) is int:
return 500, id_msg(-1, "Error query database")
Message.mark_read([_.msg_id for _ in msg_list])
msg_ret_list = []
for msg in msg_list:
msg_ret_list.append({
'msg_id':msg.msg_id,
'sender_id':msg.sender,
'title':msg.title,
'content':msg.abstract,
'pid':msg.linkID,
'addtime':msg.addtime,
})
return 200, jsonify({
'message':'success',
'count': len(msg_ret_list),
'list':msg_ret_list
})