-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathapi.py
2947 lines (2288 loc) · 82.4 KB
/
api.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
import re
import time
from app import app
from commons import *
from api_commons import *
from flask import g, make_response
from session import save_session,load_session
from recently import *
def create_all_necessary_collections():
aqlc.create_collection('admins')
aqlc.create_collection('operations')
aqlc.create_collection('aliases')
aqlc.create_collection('histories')
aqlc.create_collection('votes')
aqlc.create_collection('messages')
aqlc.create_collection('conversations')
aqlc.create_collection('notifications')
aqlc.create_collection('tags')
aqlc.create_collection('comments')
aqlc.create_collection('followings')
aqlc.create_collection('favorites')
aqlc.create_collection('blacklist')
aqlc.create_collection('polls')
aqlc.create_collection('poll_votes')
aqlc.create_collection('punchcards')
# def make_notification(to_uid, from_uid, why, url, **kw):
# d = dict(
# to_uid=to_uid,
# from_uid=from_uid,
# why=why,
# url=url,
# t_c=time_iso_now(),
# **kw,
# )
#
# aql('insert @k into notifications', k=d, silent=True)
class IndexCreator:
# create index
@classmethod
def create_indices(cls,coll,aa):
for a in aa:
qprint('creating index on',coll,a)
aqlc.create_index(coll, type='persistent', fields=a,
unique=False,sparse=False)
# create index with unique=True
@classmethod
def create_index_unique_true(cls, coll, a, unique=True):
for ai in a:
qprint('creating index on',coll,[ai])
aqlc.create_index(coll, type='persistent', fields=[ai], unique=unique, sparse=False)
def get_uidlist_by_namelist(names):
uids = aql('''
let uidlist = (
for n in @names
let user = (for i in users filter i.name==n return i)[0]
return user.uid
)
let uids = remove_value(uidlist, null)
return uids
''', names=names, silent=True)[0]
return uids
def make_notification_names(names, from_uid, why, url, **kw):
# names is a list of usernames
uids = get_uidlist_by_namelist(names)
return make_notification_uids(uids, from_uid, why, url, **kw)
def make_notification_uids(uids, from_uid, why, url, **kw):
if not len(uids): return
if "no_notifications" in g:
print_err('likely spam, no notifications sent')
return
haters = get_reversed_blacklist(from_uid) + get_blacklist(from_uid)
haters = [i['uid'] for i in haters]
uids = [i for i in uids if i not in haters]
# same as above but with uids
d = dict(
# to_uid=to_uid,
from_uid=from_uid,
why=why,
url=url,
t_c=time_iso_now(),
**kw,
)
aql('''
let uidlist = @uids
let uids = remove_value(uidlist, null)
for i in uids
let d = merge({to_uid:i}, @k)
upsert {to_uid:d.to_uid, from_uid:d.from_uid, why:d.why, url:d.url}
insert d update {} into notifications
''', uids=uids, k=d, silent=True)
aql('''
let uidlist = @uids
let uids = remove_value(uidlist, null)
for uid in uids
let user = (for u in users filter u.uid==uid return u)[0]
update user with {
nnotif: length(for n in notifications filter n.to_uid==user.uid and n.t_c>user.t_notif return n),
} in users
''', uids=uids, silent=True)
def get_url_to_post(pid):
# 1. get tid
pobj = aql('for p in posts filter p._key==@k return p',k=pid,silent=True)
if len(pobj)==0:
raise Exception('no such post')
pobj = pobj[0]
tid = pobj['tid']
# 2. check rank of post in thread
# see how much posts before this one in thread
rank = aql('''
return length(
for p in posts
filter p.tid==@tid and p.t_c <= @tc
return 1
)
''', tid=tid, tc=pobj['t_c'], silent=True)[0]
return get_url_to_post_given_details(tid, pid, rank)
def get_url_to_post_given_details(tid, pid, rank): # assume you know rank
# 3. calculate page number
pnum = ((rank - 1) // post_list_defaults['pagesize']) + 1
# 4. assemble url
if pnum>1:
url = '/t/{}?page={}#{}'.format(tid, pnum, pid)
else:
url = '/t/{}#{}'.format(tid, pid)
return url
@stale_cache(6,1800)
def get_bigcats():
return aql("return document('counters/bigcats')",silent=True)[0]
@stale_cache(6,1800)
def get_bigcats_w_cid():
bigcats = aql('''return document('counters/bigcats')
''',silent=True)[0]
for k in bigcats['briefs']:
bigcats['briefs'][k]['cid']=k
return bigcats
def get_categories_info():
return get_categories_info_withuid(show_empty=0 or is_self_admin())
def cats_into_lines(cats):
bc = get_bigcats()
res = cats
catd = {c['cid']:c for c in res}
catl = []
singles = []
def lasttrue(l):
# if len(l):
# l[-1]['last']=True
# return l
l.append(None)
return l
# sort by bigcats
briefs, cats = bc['briefs'], bc['cats']
for bck in briefs:
cntr = []
if bck=='main' or bck.startswith('-'):
continue
bccats = key(cats, bck) or [] #cats[bck]
for ck in catd.copy():
if ck in bccats:
cntr.append(catd[ck])
del catd[ck]
if cntr:
if len(cntr)>1:
lasttrue(cntr)
catl+=cntr
else:
singles+=cntr
leftovers = sorted(catd.values(), key=lambda n:-n['count'])
singles = sorted(singles, key=lambda n:-n['count'])
catl += lasttrue(singles+leftovers) # + lasttrue(leftovers)
return catl
# def get_raw_categories_info():
# return get_raw_categories_info_raw()
@stale_cache(ttr=5, ttl=1800)
def get_raw_categories_info():
return aql('''
for c in categories
let cnt = length(for i in threads filter i.cid==c.cid return i)
sort cnt desc
return merge(c, {count:cnt})
''', silent=True)
@stale_cache(ttr=10, ttl=1200)
def get_categories_info_withuid(show_empty=False):
res = get_raw_categories_info()
res = [i for i in cats_into_lines(res) if i is not None]
if show_empty:
return res
else:
return [i for i in res if i['count']>0]
@stale_cache(ttr=15, ttl=1200)
def get_categories_info_twoparts(cid, mode='cat'):
res = get_raw_categories_info()
bc = get_bigcats()
all_upper = False
if mode == 'cat':
bcid = None
for k,v in bc['cats'].items():
if cid in v:
bcid = k
break
# upper = [i for i in res if i['cid']==cid]
# lower = [i for i in res if i['cid']!=cid]
if bcid is not None:
cid = bcid
else:
all_upper = True
if not all_upper:
bc = get_bigcats()
lcats = set(bc['cats'][cid])
upper = [i for i in res if i['cid'] in lcats]
lower = [i for i in res if i['cid'] not in lcats]
upper = cats_into_lines(upper)
lower = cats_into_lines(lower)
return upper, lower
else:
upper = cats_into_lines(res)
return upper,
def get_current_salt():
salt = g.session['salt'] if 'salt' in g.session else '==nosalt=='
return salt
# json apis sharing a common endpoint
api_registry = {}
def register(name):
def k(f):
api_registry[name] = f
return k
def es(k):
j = g.j
return (str(j[k]) if ((k in j) and (k is not None)) else None)
def eb(k):
j = g.j
return ((True if j[k] else False) if k in j else False)
def ei(k):
j = g.j
return (int(j[k]) if ((k in j) and (k is not None)) else None)
def get_user_by_name(name):
res = aql('for u in users filter u.name==@n sort u.uid asc return u', n=name, silent=True)
if len(res)>0:
return res[0]
else:
return None
def get_user_by_id(id):
try:
id = int(id)
except:
print_err('personal_party_wrongly_set', id)
return None
res = aql('for u in users filter u.uid==@n return u', n=id, silent=True)
if len(res)>0:
return res[0]
else:
return None
def get_user_by_id_admin(uid):
uo = aql('for i in users filter i.uid==@k \
let admin = length(for a in admins filter a.name==i.name return a)\
return merge(i, {admin})',
k=uid, silent=True)
return uo[0] if uo else False
@stale_cache(ttr=10, ttl=1800, maxsize=8192)
def get_user_by_id_cached(uid):
return get_user_by_id(uid)
@register('test')
def _():
# raise Exception('ouch')
return {'double':int(g.j['a'])*2}
def get_public_key_by_uid(uid):
pk = aql('''
for i in entities filter i.uid==@uid and i.type=='public_key' sort i.t_c desc limit 1 return i
''', uid=uid, silent=True)
if pk and 'doc' in pk[0]:
s = pk[0]['doc']
if isinstance(s, str):
return s
return None
from pgp_stuff import verify_publickey_message
@register('login_pgp')
def _():
msg = es('message')
# find username in message
groups = re.findall(username_regex_pgp, msg)
if len(groups)<1:
groups = re.findall(username_regex_pgp_new, msg)
if len(groups)<1:
raise Exception('No username found in message')
else:
uname = base64.b64decode(groups[0][0]).decode('utf-8')
else:
uname = groups[0][0]
timestamp = groups[0][1] # GMT +0
print_down('attempt pgp login:', uname, timestamp)
user = get_user_by_name(uname)
if not user:
raise Exception('no user named '+uname)
if not login_time_validation(timestamp):
raise Exception('timestamp too old, try with a more current one')
# find public_key
pk = get_public_key_by_uid(user['uid'])
if not pk:
raise Exception('user does not have a public key')
n = 3
while n:
try:
result = verify_publickey_message(pk, msg)
if not result:
raise Exception('verification failed')
except Exception as e:
n-=1
if n:
print_err('Error:',n,e)
time.sleep(0.3)
continue
else:
raise e
else:
break
# user sucessfully logged in with pgp
aql('update @u with {pgp_login:true} in users', u=user)
return {'error':False, 'message':'login success', 'setuid':user['uid']}
@register('login')
def _():
uname = es('username')
pwh = es('password_hash')
# find user
u = get_user_by_name(uname)
if not u:
raise Exception('username not found')
if key(u, 'delete'):
raise Exception('your account has been banned')
# find password object
p = aql('for p in passwords filter p.uid==@uid return p', uid=u['uid'])
if len(p)==0:
raise Exception('password record not found.')
p = p[0]
hashstr = p['hashstr']
saltstr = p['saltstr']
# hash incoming with salt and check
verified = check_hash_salt_pw(hashstr, saltstr, pwh)
if not verified:
raise Exception('wrong password')
# there's one more possibility: user has alias
alias = aql('for i in aliases filter i.is==@n return i', n=u['name'])
if len(alias)>=1:
alias = alias[0]['name']
au = aql('for u in users filter u.name==@n return u',n=alias)
if len(au)!=0:
# don't log into the aliasing account
# if the aliasing account got its own password
have_password = aql('for p in passwords filter p.uid==@uid return p', uid=au[0]['uid'])
if not have_password:
u = au[0]
return {'error':False, 'message':'login success', 'setuid':u['uid']}
def insert_new_password_object(uid, pwh):
# generate salt, hash the pw
hashstr, saltstr = hash_w_salt(pwh)
pwobj = dict(
uid=uid,
hashstr=hashstr,
saltstr=saltstr,
)
aql('''insert @i into passwords''', i=pwobj)
@stale_cache(ttr=30, ttl=1860)
def get_banned_salts():
return aql('''for u in users sort u.t_c desc
limit 100
filter u.delete==true
let inv = (for i in invitations filter i._key==u.invitation return i)[0]
let invsalt = inv.salt
return invsalt
''', silent=True)
def get_salt_registration():
inv = key(g.current_user, 'invitation')
if inv:
isalts = aql('for i in invitations filter i._key==@inv return i.salt', inv=inv,
silent=True)
if len(isalts):
return isalts[0]
return 'salt not found'
def has_banned_friends():
# check if salty friends are banned
banned_friends = get_banned_salts()
salt = get_current_salt()
salt2 = get_salt_registration()
has = salt in banned_friends
if has: print_err(salt, 'has banned friends')
has2 = salt2 in banned_friends
if has2: print_err(salt2, '(during invitation) has_banned_friends')
return has or has2
@register('register')
def _():
uname = es('username')
pwh = es('password_hash')
ik = es('invitation_code')
if 'salt' not in g.session:
raise Exception('to register you must enable cookies / use a browser.')
salt = g.session['salt']
# check if user name is legal
m = re.fullmatch(username_regex, uname)
if m is None:
raise Exception('username doesnt match requirement')
# check if username occupied
if len(aql('for u in users filter u.name==@n return 1',n=uname))>0:
raise Exception('username occupied')
# assert len(pwh) == 32 # sanity
# check if invitation code exist and valid
invitation = aql('''
for i in invitations
filter i._key == @ik and i.active != false return i
''',ik=ik)
if len(invitation) == 0:
raise Exception('invitation code not exist or already used by someone else')
# check if inviting user is banned
invu = aql('''for u in users filter u.uid==@invuid return u''', invuid=invitation[0]['uid'])
if len(invu)!=0:
invu = invu[0]
if 'delete' in invu and invu['delete']:
raise Exception('registration is closed, please try again tomorrow')
# obtain a new uid
uid = obtain_new_id('uid')
newuser = dict(
uid=uid,
name=uname,
t_c=time_iso_now(),
brief='',
invitation=ik,
)
# generate salt, hash the pw
insert_new_password_object(uid, pwh)
# hashstr, saltstr = hash_w_salt(pwh)
#
# pwobj = dict(
# uid=uid,
# hashstr=hashstr,
# saltstr=saltstr,
# )
#
# aql('''insert @i into passwords''', i=pwobj)
aql('''insert @i into users''', i=newuser)
aql('''for i in invitations filter i._key==@ik
update i with {active:false, ip_addr:@ip, salt:@salt} in invitations''', ik=ik, ip=g.display_ip_address, salt=salt)
return newuser
def obtain_new_id(name):
# obtain a new uid
uid = aql('''
let c = document('counters/counters')
update c with {{ {d}:c.{d}+1}} in counters return NEW.{d}
'''.format(d=name))[0]
return uid
def increment_view_counter(target_type, _id):
if target_type=='thread' or target_type=='user':
_id = int(_id)
keyname=target_type[0]+'id'
elif target_type=='post':
_id = str(_id)
keyname='_key'
else:
raise Exception('unsupported tt for vc increment')
aql('''
for i in {collname} filter i.{keyname}=={_id}
update i with {{ vc:i.vc+1 }} in {collname}
'''.format(
collname = target_type+'s',
keyname = keyname,
_id = _id,
),
silent=True)
@register('logout')
def _():
return {'logout':True}
def get_thread(tid):
thread = aql('for t in threads filter t.tid==@k return t',
k=int(tid),silent=True)
if len(thread)==0:
raise Exception('tid not exist')
return thread[0]
def get_post(pid):
post = aqlc.from_filter('posts','i._key==@k', k=str(pid), silent=True)
if len(post) == 0:
raise Exception('pid not found')
return post[0]
def banned_check():
if 'delete' in g.current_user and g.current_user['delete']:
raise Exception('your account has been banned')
def get_comment(k):
c = aqlc.from_filter('comments', 'i._key==@k', k=str(k), silent=True)
if len(c) == 0: raise Exception('comment id not found')
return c[0]
@register('comment')
def _():
must_be_logged_in()
uid = g.selfuid
op = es('op')
t_c = time_iso_now()
if op=='add':
content = es('content').strip()
parent = es('parent').strip()
parent_object = aql('return document(@parent)', parent=parent, silent=True)
if not parent_object:
raise Exception('parent object not found')
# check if user repeatedly submitted the same content
lp = aql('for p in comments filter p.uid==@k sort p.t_c desc limit 1 return p',k=uid, silent=True)
if len(lp) >= 1:
if lp[0]['content'] == content:
raise Exception('repeatedly posting same content')
coid = str(obtain_new_id('pid'))
content_length_check(content, allow_short=True)
newcomment = dict(
_key = coid,
content = content,
parent = parent,
t_c = t_c,
uid = uid,
)
aql('insert @k in comments', k=newcomment)
elif op=='edit':
content = es('content').strip()
key = es('key').strip()
comm = get_comment(key)
if not can_do_to(g.current_user, 'edit', comm['uid']):
raise Exception('insufficient priviledge')
content_length_check(content)
newcomment = dict(
_key = key,
content = content,
t_e = t_c,
editor = uid,
)
aql('update @k with @k in comments', k=newcomment)
else:
raise Exception('unsupported op on comments')
return {'error':False}
def get_comments(parent):
comments = aql('''for i in comments filter i.parent==@p
sort i.t_c asc
let user = (for u in users filter u.uid==i.uid return u)[0]
return merge(i, {user})''', p=parent, silent=True)
html = render_template_g(
'comment_section.html.jinja',
comments = comments,
parent = parent,
)
return html
@register('render_comments')
def _():
j = g.j
parent = es('parent').strip()
html = get_comments(parent)
return {'error':False, 'html':html}
@app.route('/comments/<string:k1>/<string:k2>')
def getcomments(k1,k2):
parent = k1+'/'+k2
html = get_comments(parent)
return html
def current_user_doesnt_have_enough_likes():
return g.current_user['nlikes'] < 3 if 'nlikes' in g.current_user else True
def current_user_posted_baodao():
uid = g.selfuid
if uid:
lp = aqls('''for i in posts
filter i.uid==@uid and i.tid==14636 and i.delete!=true
limit 1
return i
''', uid=uid)
lp2 = aqls('''for i in threads
filter i.uid==@uid and i.cid==4 and i.delete!=true
limit 1
return i
''', uid=uid)
return True if (lp+lp2) else False
return False
def current_user_can_post_outside_baodao():
is_new_user = key(g.current_user, 't_c') > time_iso_now(-86400*42)
return (not is_new_user) or current_user_posted_baodao()
def dlp_ts(ts): return min(70, max(3 +0, int(ts*0.025*2)))
def dlt_ts(ts): return min(10, max(2 +0, int(ts*0.006*2)))
def daily_limit_posts(uid):
user = get_user_by_id_cached(uid)
trust_score = trust_score_format(user)
return dlp_ts(trust_score)
def daily_limit_threads(uid):
user = get_user_by_id_cached(uid)
trust_score = trust_score_format(user)
return dlt_ts(trust_score)
def daily_number_posts(uid):
return aql('''return length(for t in posts
filter t.uid==@k and t.t_c>@t and t.tid!=14636 return t)''',
silent=True, k=uid, t=time_iso_now(-86400*2))[0]
def daily_number_threads(uid):
return aql('''return length(for t in threads
filter t.uid==@k and t.t_c>@t return t)''',
silent=True, k=uid, t=time_iso_now(-86400*2))[0]
@ttl_cache(ttl=10, maxsize=1024)
def daily_limit_posts_cached(uid):return daily_limit_posts(uid)
@ttl_cache(ttl=10, maxsize=1024)
def daily_limit_threads_cached(uid):return daily_limit_threads(uid)
@ttl_cache(ttl=10, maxsize=1024)
def daily_number_posts_cached(uid):return daily_number_posts(uid)
@ttl_cache(ttl=10, maxsize=1024)
def daily_number_threads_cached(uid):return daily_number_threads(uid)
def spam_kill(content):
from antispam import is_spam
spam_detected = False
if is_spam(content):
spam_detected = True
if current_user_doesnt_have_enough_likes():
aql('update @u with @u in users', u={
'_key':g.current_user['_key'],
'delete':True,
})
g.no_notifications = True
return spam_detected
@register('post')
def _():
must_be_logged_in()
banned_check()
# check if salty friends are banned
if has_banned_friends() \
and not is_self_admin() \
and current_user_doesnt_have_enough_likes():
aql('update @u with @u in users', u={
'_key':g.current_user['_key'],
'delete':True,
})
g.no_notifications = True
uid = g.current_user['uid']
target_type, _id = parse_target(es('target'), force_int=False)
# title = es('title').strip()
content = es('content').strip()
content_length_check(content)
pagerank = pagerank_format(g.current_user)
trust_score = trust_score_format(g.current_user)
spam_detected = spam_kill(content)
if target_type=='thread':
_id = int(_id)
# check if tid exists
tid = _id
thread = get_thread(tid)
cid = key(thread, 'cid')
# if not posting to baodao
if tid!=14636:
# check if user haven't baodao yet
if not current_user_can_post_outside_baodao():
raise Exception(zh('新用户需要先去水区新人报道,然后才可以发表回复。'))
# check if user repeatedly submitted the same content
lp = aql('for p in posts filter p.uid==@k sort p.t_c desc limit 1 return p',k=uid, silent=True)
if len(lp) >= 1:
if lp[0]['content'] == content:
raise Exception(en('repeatedly posting same content'))
if tid!=14636:
# daily limit for low pagerank users
# daily_limit = int(pagerank*2+6)
daily_limit = daily_limit_posts(uid)
recent24hs = daily_number_posts(uid)
if recent24hs>=daily_limit:
raise Exception(spf(zh('你在过去$3小时发表了$0个评论,达到或超过了你目前的社会信用分($1) 所允许的值($2)。如果要提高这个限制,请尽量发表受其他用户欢迎的内容,以提高社会信用分。'))(recent24hs, trust_score, daily_limit,48))
# check if user posted too much content in too little time
recents = aql('return length(for t in posts filter t.uid==@k and t.t_c>@t return t)', silent=True, k=uid, t=time_iso_now(-1200))[0]
if recents>=5:
raise Exception(spf(en('too many posts ($0) in the last $1 minute(s)'))(recents, 1200//60))
if lp and lp[0]['t_c'] > time_iso_now(-60):
raise Exception(en('please wait one minute between posts'))
# # new users cannot post outside water in the first hours
# if g.current_user['t_c'] > time_iso_now(-600) and \
# thread['cid']!=4 and current_user_doesnt_have_enough_likes():
# raise Exception('新注册用户前十分钟只能在水区发帖')
# can only post once in questions
if 'mode'in thread and thread['mode']=='question':
nposts_already = len(aql(
'for p in posts filter p.uid==@k and p.tid==@tid return 1',
k=uid, tid=tid, silent=True))
if nposts_already:
raise Exception(zh('(从2021年7月8日开始)每个问题只允许发表一次回答。'))
timenow = time_iso_now()
tu = thread['uid']
if im_in_blacklist_of(tu):
raise Exception(en('you are in the blacklist of the thread owner'))
while 1:
new_pid = str(obtain_new_id('pid'))
exists = aql('for p in posts filter p._key==@pid return p', silent=False, pid=new_pid)
if len(exists):
continue
else:
break
newpost = dict(
uid=uid,
t_c=timenow,
content=content,
tid=tid,
_key=str(new_pid),
)
if spam_detected:
newpost['spam']=True
inserted = aql('insert @p in posts return NEW', p=newpost)[0]
inserted['content']=None
# update thread update time
aql('''
for t in threads filter t.tid==@tid
update t with {t_u:@now} in threads
''',silent=True,tid=tid,now=timenow)
# assemble url to the new post
url = get_url_to_post(str(inserted['_key']))
# url = '/p/{}'.format(inserted['_key'])
inserted['url'] = url
# notifications
# extract_ats
ats = extract_ats(content)
ats = [name for name in ats if name!=g.current_user['name']]
if len(ats):
make_notification_names(
names=ats,
why='at_post',
url=url,
from_uid=uid,
)
# replies
publisher = get_user_by_id(thread['uid'])
if thread['uid']!=uid and (publisher['name'] not in ats):
make_notification_uids(
uids=[thread['uid']],
why='reply_thread',
url=url,
from_uid=uid,
)
update_thread_votecount(thread['tid'])
update_user_votecount(g.current_user['uid'])
return inserted
elif target_type=='username' or target_type=='user': # send another user a new message
if target_type=='username':
_id = _id
target_user = get_user_by_name(_id)
if not target_user:
raise Exception('username not exist')
target_uid = target_user['uid']
else:
_id = int(_id)
target_uid = _id
target_user = get_user_by_id(target_uid)
if not target_user:
raise Exception('uid not exist')
# new users are not allowed to send pms to other ppl unless they
# got enough likes
if current_user_doesnt_have_enough_likes()\
and target_user['name']!='thphd':
raise Exception(zh("你暂时还是新用户,不可以发信给除了站长(thphd)之外的其他人"))
# content_length_check(content)
url = send_message(uid, target_uid, content)
return {'url':url}
elif target_type=='category':
_id = int(_id)
title = es('title').strip()
title_length_check(title)
mode = es('mode')
mode = None if mode!='question' else mode
assert mode in [None, 'question']
# check if cat exists
cid = _id
cat = aql('for c in categories filter c.cid==@k return c',k=cid,silent=True)
if len(cat)==0:
raise Exception('cid not exist')
cat = cat[0]
# check if user repeatedly submitted the same content
lp = aql('for t in threads filter t.uid==@k sort t.t_c desc limit 1 return t',k=uid, silent=True)
if len(lp) >= 1:
if lp[0]['content'] == content:
raise Exception(en('repeatedly posting same content'))
# check if the same title has been used before
jk = aql('for t in threads filter t.title==@title limit 1 return 1', title=title, silent=True)
if len(jk):
raise Exception(zh('这个标题被别人使用过'))
# # new users cannot post outside water in the first hours
# if g.current_user['t_c'] > time_iso_now(-43200) and \
# cid!=4 and current_user_doesnt_have_enough_likes():
# raise Exception('新注册用户最开始只能在水区发帖')
daily_limit = daily_limit_threads(uid)
recent24hs = daily_number_threads(uid)
if recent24hs>=daily_limit:
raise Exception(spf(zh('你在过去$3小时发表了$0个主题帖或问题,达到或超过了你目前的社会信用分($1) 所允许的值($2)。如果要提高这个限制,请尽量发表受其他用户欢迎的内容,以提高社会信用分。'))(recent24hs, trust_score, daily_limit, 48))
# check if user posted too much content in too little time
recents = aql('return length(for t in threads filter t.uid==@k and t.t_c>@t return t)', silent=True, k=uid, t=time_iso_now(-1200))[0]
if recents>=2 and not g.is_admin:
raise Exception(spf(en('too many threads ($0) in the last $1 minute(s)'))(recents, 1200//60))
# ask for a new tid
tid = obtain_new_id('tid')