-
Notifications
You must be signed in to change notification settings - Fork 7
/
posts.py
1896 lines (1643 loc) · 63.9 KB
/
posts.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 geweb.db.pgsql as db
from point.util.env import env
from point.core.user import User, AlreadySubscribed, SubscribeError, check_auth
from point.core.post import Post, PostAuthorError, PostTextError, \
PostUpdateError, PostDiffError, PostNotFound
from point.core.post import Comment, CommentAuthorError, CommentNotFound, \
CommentEditingForbiddenError
from point.core.post import RecommendationError, RecommendationNotFound, \
RecommendationExists, PostLimitError, \
PostReadonlyError
from point.core.post import BookmarkExists
from point.util.redispool import RedisPool, publish
from point.util import uniqify, b26, unb26, diff_ratio, timestamp
from point.util import cache_get, cache_store, cache_del
from point.util.imgproc import make_thumbnail
from datetime import datetime, timedelta
from psycopg2 import IntegrityError
import settings
try:
import re2 as re
except ImportError:
import re
_user_re = re.compile(r'(?<!\w)@([-a-z]+)', re.I)
def check_last_action(fn):
def _fn(*args, **kwargs):
author = None
if 'author' in kwargs and kwargs['author']:
if isinstance(kwargs['author'], (str, unicode)):
author = User('login')
elif isinstance(kwargs['author'], User):
author = kwargs['author']
if not author:
author = env.user
d = cache_get('last_action:%s' % author.id)
if d:
d = datetime.fromtimestamp(int(d))
if datetime.now() < d+timedelta(seconds=settings.actions_interval):
raise PostLimitError
d = timestamp(datetime.now())
cache_store('last_action:%s' % author.id, d)
return fn(*args, **kwargs)
return _fn
def _get_last():
key = 'last:%s' % env.user.id
try:
post_id = filter(lambda s: '/' not in s, cache_get(key))[-1]
except (IndexError, TypeError):
return None
return post_id
def _store_last(inst):
if isinstance(inst, Post):
item = inst.id
elif isinstance(inst, Comment):
item = '%s/%s' % (inst.post.id, inst.id)
key = 'last:%s' % inst.author.id
items = cache_get(key)
if not items:
items = []
elif not isinstance(items, (list, tuple)):
items = [items]
items.append(item)
cache_store(key, items[-10:])
def _thumbnails(text):
urls = re.finditer(ur'(?P<url>(?P<proto>\w+)://(?:[\w\.\-%\:]*\@)?(?P<host>[\w\.\-%]+)(?::(?P<port>\d+))?(?P<path>(?:/[^\s\?\u0002\u0003]*)*)(?P<qs>\?[^#\s\u0002\u0003]*)?(?:#(?P<hash>\S+))?)',
text)
for m in urls:
url = m.group('url')
imgm = re.search(r'\.(?P<ext>jpe?g|png|gif)(:large)?$', m.group('path'), re.I)
if (imgm \
or re.search("^http://ompldr.org/v[A-Z][a-zA-Z0-9]+$", url, re.I) \
or url.startswith("http://img.leprosorium.com") \
or url.startswith("http://pics.livejournal.com/")) \
and not re.search(r'https?://(www\.)?dropbox.com', url, re.I):
make_thumbnail(url)
return
if re.search(r'https?://(www\.)?dropbox.com', url, re.I):
make_thumbnail('%s://dl.dropboxusercontent.com%s' % \
(m.group('proto'), m.group('path')))
#@check_auth
def show_post(post_id):
"""
Return Post instance
"""
if isinstance(post_id, Post):
post = post_id
post_id = post.id
else:
tz = env.user.get_profile('tz') if env.user.id else settings.timezone
post = Post(post_id, tz=tz)
if post.private and not env.user.id:
raise SubscribeError
if post.private and env.user != post.author:
res = db.fetchone("SELECT 1 FROM posts.recipients "
"WHERE post_id=%s AND user_id=%s;",
[unb26(post_id), env.user.id])
if not res:
raise SubscribeError
if post.author.id != env.user.id and post.author.get_profile('private'):
if post.author.check_whitelist(env.user):
return post
res = db.fetchone("SELECT 1 FROM posts.recipients "
"WHERE post_id=%s AND user_id=%s;",
[unb26(post_id), env.user.id])
if not res:
raise SubscribeError
if post.author.get_profile('deny_anonymous') and not env.user.is_authorized():
raise PostAuthorError
return post
@check_last_action
@check_auth
def add_post(post, title=None, link=None, tags=None, author=None, to=None,
private=False, type='post', auto_subscribe=True, files=None):
"""
Add a new post
"""
if isinstance(post, Post):
if post.id:
raise PostUpdateError
elif isinstance(post, (str, unicode)):
if not author:
author = env.user
text = post.strip()
post = Post(None, author=author, title=title, link=link, tags=tags,
private=private, text=text.strip(), type=type)
post.tune = author.get_tune()
if len(post.text) < 3 and not files:
raise PostTextError
m = re.search(r'^\s*(?P<to>(?:@[a-z0-9_-]+[,\s]*)+)(?P<text>.*)', post.text)
if m and len(m.group('text').strip()) < 3:
raise PostTextError
if post.tags:
post.tags = filter(None, post.tags)
to_users = []
subscribers = []
if to:
for login in uniqify(to):
user = User('login', login)
if user.check_blacklist(author):
raise SubscribeError(login)
to_users.append(user)
subscribers = [ u.id for u in to_users ]
if not post.private:
hl = map(lambda l: l.lower(), re.findall(_user_re, post.text))
if hl:
hl_sql = ("UNION "
"SELECT u.id FROM users.logins u "
"JOIN users.profile_im p ON u.id=p.id "
"WHERE lower(u.login)=ANY(public.array_lowercase(%(hl)s)) "
"AND p.highlight=TRUE ")
else:
hl_sql = ""
if post.author.get_profile('private'):
if post.tags:
#if isinstance(post.tags[0], unicode):
# post.tags = map(lambda t: t.encode('utf-8'), post.tags)
#tags = [ t[:64] for t in tags[:10] ]
res = db.fetchall("SELECT user_id FROM subs.users WHERE "
"to_user_id=%(id)s "
"EXCEPT "
"SELECT user_id FROM posts.tags_blacklist "
"WHERE tag = ANY(%(tags)s) "
"AND (to_user_id IS NULL "
"OR to_user_id=%(id)s);",
{'id': post.author.id, 'tags': post.tags})
else:
res = db.fetchall("SELECT user_id FROM subs.users WHERE "
"to_user_id=%s;", [post.author.id])
else:
if post.tags:
#if isinstance(post.tags[0], unicode):
# post.tags = map(lambda t: t.encode('utf-8'), post.tags)
#tags = [ t[:64] for t in tags[:10] ]
res = db.fetchall("SELECT user_id FROM subs.users WHERE "
"to_user_id=%%(id)s "
"UNION "
"SELECT t.user_id FROM subs.tags t "
#"JOIN users.whitelist w ON w.user_id=%%(id)s "
# "AND t.user_id=w.to_user_id "
"WHERE lower(t.tag) = ANY(array_lowercase(%%(tags)s)) "
"AND (t.to_user_id IS NULL "
"OR t.to_user_id=%%(id)s) "
"%s"
"EXCEPT "
"SELECT user_id FROM users.blacklist WHERE "
"to_user_id=%%(id)s "
"EXCEPT "
"SELECT user_id FROM posts.tags_blacklist "
"WHERE lower(tag) = ANY(array_lowercase(%%(tags)s)) "
"AND (to_user_id IS NULL "
"OR to_user_id=%%(id)s);" % hl_sql,
{'id': post.author.id, 'tags': post.tags,
'hl': hl})
else:
res = db.fetchall("SELECT user_id FROM subs.users WHERE "
"to_user_id=%%(id)s "
"%s"
"EXCEPT "
"SELECT user_id FROM users.blacklist WHERE "
"to_user_id=%%(id)s;" % hl_sql,
{'id':post.author.id, 'hl':hl})
subscribers.extend(
filter(lambda u: u!=post.author.id and u not in subscribers,
map(lambda u: u[0], res)))
if isinstance(files, (list, tuple)):
post.files = files
post_id = post.save()
for u in to_users:
try:
db.perform("INSERT INTO posts.recipients (post_id, user_id) "
"VALUES (%s, %s);", [unb26(post_id), u.id])
except IntegrityError:
pass
publish('msg.self', {
'to': [env.user.id],
'a': 'post',
'post_id': post_id,
'type': post.type,
'author': post.author.login,
'author_id': post.author.id,
'author_name': post.author.get_info('name'),
'tags': post.tags,
'private': post.private,
'title': post.title,
'text': post.text,
'link': post.link,
'to_users': [u.login for u in to_users],
'files': files,
'cut': True
})
if subscribers:
publish('msg', {
'to': subscribers,
'a': 'post',
'post_id': post_id,
'type': post.type,
'author': post.author.login,
'author_id': post.author.id,
'author_name': post.author.get_info('name'),
'tags': post.tags,
'private': post.private,
'title': post.title,
'text': post.text,
'link': post.link,
'to_users': [u.login for u in to_users],
'files': files,
'cut': True
})
if post.private:
ptype = 'private'
else:
ptype = post.type
try:
db.batch("INSERT INTO posts.unread_posts "
"(user_id, post_id, type) VALUES (%s, %s, %s)",
[(u, unb26(post_id), ptype) for u in subscribers])
except IntegrityError:
pass
try:
db.batch("INSERT INTO posts.recommendations_recv "
"(post_id, comment_id, user_id) VALUES (%s, %s, %s);",
[(unb26(post_id), 0, u) for u in subscribers])
except IntegrityError:
pass
if post.private:
add_private_unread([env.user.id] + subscribers, unb26(post_id))
if auto_subscribe:
try:
post.author.subscribe(post)
except AlreadySubscribed:
pass
_store_last(post)
_thumbnails(post.text)
return post_id
@check_auth
def delete_post(post_id):
"""
Delete post
"""
post = Post(post_id)
if env.user != post.author:
raise PostAuthorError
post.delete()
# TODO: publish
@check_auth
def edit_post(post_id, text=None, tags=None, private=None, files=None):
if isinstance(post_id, Post):
post = post_id
post_id = post.id
else:
post = show_post(post_id)
if env.user != post.author:
raise PostAuthorError
if post.edited:
raise PostUpdateError
#if post.comments_count() > 0:
# raise PostCommentedError
if datetime.now() - timedelta(seconds=settings.edit_expire) \
> post.created:
raise PostUpdateError
if not text and tags is None and private is None:
return
if text and post.text != text:
m = re.search(r'^\s*(?P<to>(?:@[a-z0-9_-]+[,\s]*)+)(?P<text>.*)', text)
if m and len(m.group('text').strip()) < 3:
raise PostTextError
if not diff_ratio(post.text, text):
raise PostDiffError
post.edited = True
post.text = text.decode('utf-8') if isinstance(text, str) else text
if tags is not None:
update_tags(post, tags, False)
if files is not None and isinstance(files, (list, tuple)):
post.files = files
post.save()
if text and not post.private:
hl = map(lambda l: l.lower(),re.findall(_user_re, text))
if hl:
hl_sql = ("UNION "
"SELECT u.id FROM users.logins u "
"JOIN users.profile_im p ON u.id=p.id "
"WHERE lower(u.login)=ANY(%(hl)s) AND p.highlight=TRUE ")
else:
hl_sql = ""
res = db.fetchall("SELECT user_id FROM subs.users WHERE "
"to_user_id=%%(id)s "
"%s"
"UNION "
"SELECT user_id FROM posts.recipients "
"WHERE post_id=%%(post_id)s "
"EXCEPT "
"SELECT user_id FROM posts.tags_blacklist "
"WHERE tag = ANY(%%(tags)s) "
"AND (to_user_id IS NULL "
"OR to_user_id=%%(id)s)"
"EXCEPT "
"SELECT user_id FROM users.blacklist WHERE "
"to_user_id=%%(id)s;" % hl_sql,
{'id':env.user.id, 'post_id':unb26(post.id),
'hl':hl, 'tags': tags})
subscribers = filter(lambda u: u!=env.user.id, map(lambda u: u[0], res))
else:
subscribers = [ u.id for u in post.recipients() ]
if subscribers:
publish('msg', {
'to': subscribers,
'a': 'post_edited',
'post_id': post.id,
'author': env.user.login,
'author_id': env.user.id,
'tags': tags,
'text': text,
'private': post.private,
'files': files,
'cut': True
})
_thumbnails(text)
cache_del('md:%s' % post.id)
cache_del('mdx:%s' % post.id)
@check_auth
def update_post(post_id, text):
"""
Update an existing post
"""
text = text.strip()
if len(text) < 3 or len(text) > 1048576:
raise PostTextError
post = show_post(post_id)
if env.user != post.author:
raise PostAuthorError
post.update(text)
if not post.private:
hl = map(lambda l: l.lower(),re.findall(_user_re, text))
if hl:
hl_sql = ("UNION "
"SELECT u.id FROM users.logins u "
"JOIN users.profile_im p ON u.id=p.id "
"WHERE lower(u.login)=ANY(%(hl)s) AND p.highlight=TRUE ")
else:
hl_sql = ""
res = db.fetchall("SELECT user_id FROM subs.users WHERE "
"to_user_id=%%(id)s "
"%s"
"UNION "
"SELECT user_id FROM posts.recipients "
"WHERE post_id=%%(post_id)s "
"EXCEPT "
"SELECT user_id FROM users.blacklist WHERE "
"to_user_id=%%(id)s;" % hl_sql,
{'id':env.user.id, 'post_id':unb26(post.id),
'hl':hl})
subscribers = filter(lambda u: u!=env.user.id, map(lambda u: u[0], res))
else:
subscribers = [ u.id for u in post.recipients() ]
if subscribers:
publish('msg', {
'to': subscribers,
'a': 'post_upd',
'id': post_id,
'author': env.user.login,
'author_id': env.user.id,
'text': text
})
@check_auth
def update_tags(post_id, taglist, save=True):
"""
Update tags
"""
if isinstance(post_id, Post):
post = post_id
else:
post = Post(post_id)
if env.user != post.author:
raise PostAuthorError
post.tags = taglist
if save:
post.save()
def select_posts(author=None, author_private=None, deny_anonymous=None, private=None, tags=None,
blacklist=False, limit=10, offset=0, asc=False, before=None):
if author and isinstance(author, (int, long)):
author = User(author)
requesting_key = 'requesting:%s' % (env.user.id)
if cache_get(requesting_key):
raise PostNotFound
cache_store(requesting_key, '1', 5)
if author and author.id != env.user.id:
if author.get_profile('private') and not author.check_whitelist(env.user):
raise PostAuthorError
if author.get_profile('deny_anonymous') and not env.user.is_authorized():
raise PostAuthorError
if before and isinstance(before, (int, long)):
offset = before - 157321
offset_cond = " OFFSET %d" % offset
elif offset:
offset_cond = " OFFSET %d" % int(offset)
else:
offset = 0
offset_cond = ""
joins = []
if tags:
joins.append("JOIN posts.tags t ON p.id=t.post_id")
if tags or author_private is not None:
joins.append("JOIN users.profile up ON up.id=u.id")
if env.user.id:
query = ("SELECT DISTINCT p.id, NULL AS comment_id, "
"p.author, u.login, i.name, i.avatar, "
"u.type AS user_type, "
"p.private, p.created at time zone '%(tz)s' as created, p.resource, "
"p.type, p.title, p.link, p.tags, p.text, "
"(p.edited=false AND p.created+interval '1800 second' >= now()) AS editable, "
"p.archive, p.files, "
"sp.post_id AS subscribed, "
"rp.post_id AS recommended, "
"rb.post_id AS bookmarked "
"FROM posts.posts p JOIN users.logins u ON p.author=u.id "
" %(joins)s "
"JOIN users.info i ON p.author=i.id "
"LEFT OUTER JOIN subs.posts sp ON sp.post_id=p.id "
"AND sp.user_id=%(user_id)s "
"LEFT OUTER JOIN posts.recommendations rp "
"ON %(user_id)s=rp.user_id AND "
"p.id=rp.post_id AND rp.comment_id=0 "
"LEFT OUTER JOIN posts.bookmarks rb "
"ON p.id=rb.post_id AND %(user_id)s=rb.user_id AND "
"rb.comment_id=0 " % \
{'joins': ' '.join(joins), 'user_id': env.user.id, 'tz': env.user.get_profile('tz')})
else:
query = ("SELECT DISTINCT p.id, NULL AS comment_id, "
"p.author, u.login, i.name, i.avatar,"
"p.private, p.created at time zone '%(tz)s' as created, p.resource, "
"p.type, p.title, p.link, p.tags, p.text, "
"p.archive, p.files, "
"false AS editable, "
"false AS subscribed, "
"false AS recommended, "
"false AS bookmarked "
"FROM posts.posts p JOIN users.logins u ON p.author=u.id "
" %(joins)s "
"JOIN users.info i ON p.author=i.id " % \
{'joins': ' '.join(joins), 'tz': settings.timezone})
cond = []
params = []
if author:
cond.append("p.author=%s")
params.append(author.id)
if private is not None:
cond.append("p.private=%s")
params.append(private)
if tags:
cond.append("LOWER(t.tag)=ANY(public.array_lowercase(%s))")
params.append(tags)
if author_private is not None:
cond.append("up.private=%s")
params.append(author_private)
if deny_anonymous is not None:
cond.append('up.deny_anonymous=%s')
params.append(deny_anonymous)
if env.user.id and blacklist:
cond.append("p.author NOT IN (SELECT to_user_id FROM users.blacklist "
"WHERE user_id=%s)")
params.append(env.user.id)
if cond:
query += " WHERE " + " AND ".join(cond)
order = 'ASC' if asc else 'DESC'
#offset = ' OFFSET %d' % offset if offset else ''
limit = ' LIMIT %d' % limit if limit else ''
query += (" ORDER BY created %s %s %s;" % (order, offset_cond, limit))
res = db.fetchall(query, params)
plist = []
for i, r in enumerate(res):
r = dict(r)
r['uid'] = 157321 + offset + i + 1
plist.append(r)
cache_del(requesting_key)
return _plist(plist)
@check_auth
def recent_posts(limit=10, offset=0, asc=False, type=None, unread=False, before=None):
"""
Get recent incoming posts/recommendations
"""
requesting_key = 'requesting:%s' % (env.user.id)
if cache_get(requesting_key):
raise PostNotFound
cache_store(requesting_key, '1', 5)
order = 'ASC' if asc else 'DESC'
type_cond = " AND p.type='%s'" % type if type else ''
if before and isinstance(before, (int, long)):
before_cond = " AND r.id < %d" % before
offset = ""
elif offset:
before_cond = ""
offset = " OFFSET %d" % int(offset)
else:
before_cond = ""
offset = ""
if unread:
res = db.fetchall(
"SELECT "
"r.user_id, r.post_id AS id,"
"p.author,"
"up.login,"
"ip.name,"
"ip.avatar,"
"up.type,"
"p.text,"
"p.archive, p.files, "
"p.tags, p.title, p.link, "
"p.created at time zone %%(tz)s AS created, "
"p.edited, p.type, "
"p.private, "
"(p.edited=false AND p.created+interval '%%(edit_expire)s second' >= now())"
"AS editable, "
"sp.post_id AS subscribed, "
"rp.post_id AS recommended, "
"rb.post_id AS bookmarked "
"FROM posts.unread_posts r "
"LEFT JOIN users.logins ur ON r.user_id=ur.id "
"LEFT JOIN posts.posts p ON r.post_id=p.id "
"LEFT JOIN users.logins up ON p.author=up.id "
"LEFT JOIN users.info ip ON p.author=ip.id "
"LEFT OUTER JOIN subs.posts sp ON sp.post_id=p.id "
"AND sp.user_id=%%(user_id)s "
"LEFT OUTER JOIN posts.recommendations rp "
"ON %%(user_id)s=rp.user_id AND "
"r.post_id=rp.post_id AND rp.comment_id=0 "
"LEFT OUTER JOIN posts.bookmarks rb "
"ON %%(user_id)s=rb.user_id AND "
"r.post_id=rb.post_id AND rb.comment_id=0 "
"WHERE r.user_id=%%(user_id)s %s "
"ORDER BY p.created %s "
"%s LIMIT %%(limit)s;" % (type_cond, order, offset),
{'user_id': env.user.id, 'tz': env.user.get_profile('tz'),
'limit': limit, 'edit_expire': settings.edit_expire})
else:
res = db.fetchall(
"SELECT "
"r.id AS uid, "
"r.user_id, r.is_rec, r.post_id AS id,r.comment_id, "
"rc.text AS r_text, rc.rcid AS r_comment_id,"
"CASE WHEN r.comment_id>0 THEN c.author ELSE p.author END "
"AS author, "
"CASE WHEN r.comment_id>0 THEN uc.login ELSE up.login END "
"AS login, "
"CASE WHEN r.comment_id>0 THEN ic.name ELSE ip.name END "
"AS name, "
"CASE WHEN r.comment_id>0 THEN ic.avatar ELSE ip.avatar END "
"AS avatar, "
"CASE WHEN r.comment_id>0 THEN uc.type ELSE up.type END "
"AS user_type, "
"CASE WHEN r.is_rec THEN ur.id ELSE NULL END "
"AS r_author, "
"CASE WHEN r.is_rec THEN ur.login ELSE NULL END "
"AS r_login, "
"CASE WHEN r.is_rec THEN ir.name ELSE NULL END "
"AS r_name, "
"CASE WHEN r.is_rec THEN ir.avatar ELSE NULL END "
"AS r_avatar, "
"p.private, "
"CASE WHEN r.comment_id>0 THEN c.text ELSE p.text END "
"AS text, "
"p.archive, "
"CASE WHEN r.comment_id>0 THEN c.files ELSE p.files END AS files, "
"sp.post_id AS subscribed, "
"rp.post_id AS recommended, "
"rb.post_id AS bookmarked, "
"p.tags, p.title, p.link, "
"r.created at time zone %%(tz)s AS created, "
"p.edited, p.type, "
"(p.edited=false AND r.created+interval '%%(edit_expire)s second' >= now())"
"AS editable "
"FROM posts.recent r "
"LEFT JOIN users.logins ur ON r.user_id=ur.id "
"LEFT JOIN posts.posts p ON r.post_id=p.id "
"LEFT JOIN users.logins up ON p.author=up.id "
"LEFT JOIN users.info ip ON p.author=ip.id "
"LEFT OUTER JOIN users.info ir ON r.user_id=ir.id "
"LEFT OUTER JOIN posts.recommendations rc "
"ON r.is_rec=true AND r.user_id=rc.user_id AND "
"r.post_id=rc.post_id AND "
"COALESCE(r.comment_id, 0)=rc.comment_id "
"LEFT OUTER JOIN posts.comments c "
"ON r.post_id=c.post_id AND r.comment_id=c.comment_id "
"LEFT OUTER JOIN users.logins uc ON c.author=uc.id "
"LEFT OUTER JOIN users.info ic ON uc.id=ic.id "
"LEFT OUTER JOIN subs.posts sp ON sp.post_id=p.id "
"AND sp.user_id=%%(user_id)s "
"LEFT OUTER JOIN posts.recommendations rp "
"ON %%(user_id)s=rp.user_id AND "
"r.post_id=rp.post_id AND "
"COALESCE(r.comment_id, 0)=rp.comment_id "
"LEFT OUTER JOIN posts.bookmarks rb "
"ON %%(user_id)s=rb.user_id AND "
"r.post_id=rb.post_id AND "
"COALESCE(r.comment_id, 0)=rb.comment_id "
"WHERE r.rcpt_id=%%(user_id)s %s %s "
"ORDER BY r.created %s "
"%s LIMIT %%(limit)s;" % (type_cond, before_cond, order, offset),
{'user_id': env.user.id, 'tz': env.user.get_profile('tz'),
'limit': limit, 'edit_expire': settings.edit_expire})
cache_del(requesting_key)
return _plist(res)
def recent_blog_posts(author=None, limit=10, offset=0, asc=False, before=None):
"""
Get user's recent posts/recommendations
"""
if author and isinstance(author, (int, long)):
author = User(author)
if author and author.id != env.user.id:
if author.get_profile('private') and not author.check_whitelist(env.user):
raise PostAuthorError
if author.get_profile('deny_anonymous') and not env.user.is_authorized():
raise PostAuthorError
order = 'ASC' if asc else 'DESC'
if before and isinstance(before, (int, long)):
before_cond = " AND r.id < %d" % before
offset = ""
elif offset:
before_cond = ""
offset = " OFFSET %d" % int(offset)
else:
before_cond = ""
offset = ""
res = db.fetchall(
"SELECT "
"r.id AS uid,"
"r.user_id, r.is_rec, r.post_id AS id,r.comment_id, "
"rc.text AS r_text, rc.rcid AS r_comment_id,"
"CASE WHEN r.comment_id>0 THEN c.author ELSE p.author END "
"AS author, "
"CASE WHEN r.comment_id>0 THEN uc.login ELSE up.login END "
"AS login, "
"CASE WHEN r.comment_id>0 THEN ic.name ELSE ip.name END "
"AS name, "
"CASE WHEN r.comment_id>0 THEN ic.avatar ELSE ip.avatar END "
"AS avatar, "
"CASE WHEN r.comment_id>0 THEN uc.type ELSE up.type END "
"AS user_type, "
"CASE WHEN r.is_rec THEN ur.id ELSE NULL END "
"AS r_author, "
"CASE WHEN r.is_rec THEN ur.login ELSE NULL END "
"AS r_login, "
"CASE WHEN r.is_rec THEN ir.name ELSE NULL END "
"AS r_name, "
"CASE WHEN r.is_rec THEN ir.avatar ELSE NULL END "
"AS r_avatar, "
"p.private, "
"CASE WHEN r.comment_id>0 THEN c.text ELSE p.text END "
"AS text, "
"CASE WHEN r.comment_id>0 THEN c.files ELSE p.files END AS files, "
"p.archive, p.pinned AS pinned, "
"(CASE WHEN p.author != %%(author_id)s THEN FALSE "
"ELSE p.pinned END) AS pinned_sort, "
"sp.post_id AS subscribed, "
"rp.post_id AS recommended, "
"rb.post_id AS bookmarked, "
"p.tags, p.title, p.link, "
"r.created at time zone %%(tz)s AS created, "
"p.edited, p.type, "
"(p.edited=false AND r.created+interval '%%(edit_expire)s second' >= now())"
"AS editable "
"FROM posts.recent_blog r "
"LEFT JOIN users.logins ur ON r.user_id=ur.id "
"LEFT OUTER JOIN users.info ir ON r.user_id=ir.id "
"LEFT OUTER JOIN posts.recommendations rc "
"ON r.is_rec=true AND r.user_id=rc.user_id AND "
"r.post_id=rc.post_id AND r.comment_id=rc.comment_id "
"LEFT JOIN posts.posts p ON r.post_id=p.id "
"LEFT JOIN users.logins up ON p.author=up.id "
"LEFT OUTER JOIN users.info ip ON p.author=ip.id "
"LEFT OUTER JOIN users.profile pp ON p.author=pp.id "
"LEFT OUTER JOIN users.whitelist w "
"ON w.user_id=p.author AND w.to_user_id=%%(user_id)s "
"LEFT OUTER JOIN posts.comments c "
"ON r.post_id=c.post_id AND r.comment_id=c.comment_id "
"LEFT OUTER JOIN users.logins uc ON c.author=uc.id "
"LEFT OUTER JOIN users.info ic ON uc.id=ic.id "
"LEFT OUTER JOIN subs.posts sp ON sp.post_id=p.id "
"AND sp.user_id=%%(user_id)s "
"LEFT OUTER JOIN posts.recommendations rp "
"ON r.is_rec=true AND %%(user_id)s=rp.user_id AND "
"r.post_id=rp.post_id AND "
"COALESCE(r.comment_id, 0)=rp.comment_id "
"LEFT OUTER JOIN posts.bookmarks rb "
"ON %%(user_id)s=rb.user_id AND "
"r.post_id=rb.post_id AND "
"COALESCE(r.comment_id, 0)=rb.comment_id "
"WHERE r.user_id=%%(author_id)s AND "
"(w.user_id IS NOT NULL OR pp.private=false "
"OR r.user_id=%%(user_id)s) %s "
"ORDER BY pinned_sort DESC, r.created %s "
"%s LIMIT %%(limit)s;"% (before_cond, order, offset),
{'user_id': env.user.id, 'author_id': author.id,
'tz': env.user.get_profile('tz'),
'limit': limit,
'edit_expire': settings.edit_expire})
return _plist(res)
def add_private_unread(users, post_id):
if not isinstance(users, (list, tuple)):
users = [users]
redis = RedisPool(settings.storage_socket)
for u in users:
key = 'private_unread:%s' % u
ids = redis.get(key)
if ids:
ids = [post_id] + filter(lambda id: int(id)!=post_id, ids.split(','))
else:
ids = [post_id]
redis.set(key, ','.join(map(lambda id: str(id), ids[:100])))
def del_private_unread(users, post_id):
if not isinstance(users, (list, tuple)):
users = [users]
redis = RedisPool(settings.storage_socket)
for u in users:
key = 'private_unread:%s' % u
ids = redis.get(key)
if ids:
ids = filter(lambda id: int(id)!=post_id, ids.split(','))
redis.set(key, ','.join(map(lambda id: str(id), ids[:100])))
@check_auth
def private_unread(limit=10, offset=0, asc=False, before=None):
"""
Get recently updated private posts
"""
if before and isinstance(before, (int, long)):
offset = before - 157321
redis = RedisPool(settings.storage_socket)
ids = redis.get('private_unread:%s' % env.user.id)
if not ids:
return []
ids = map(lambda id: int(id), ids.split(','))[offset:offset+limit]
res = db.fetchall(
"SELECT "
"p.id, p.author, u.login, i.name, i.avatar, p.private, "
"p.created at time zone %(tz)s AS created,"
"p.resource, "
"p.type, p.title, p.link, p.tags, p.text, "
"p.edited,"
"(p.edited=false AND p.created+interval '%(edit_expire)s second' >= now())"
"AS editable, "
"p.archive, p.files, "
"sp.post_id AS subscribed, "
"rp.post_id AS recommended, "
"rb.post_id AS bookmarked "
"FROM unnest(%(ids)s) "
"JOIN posts.posts p ON p.id=unnest "
"JOIN users.logins u ON u.id=p.author "
"LEFT OUTER JOIN users.info i ON i.id=p.author "
"LEFT OUTER JOIN posts.recipients rcp ON rcp.post_id=p.id "
"LEFT OUTER JOIN subs.posts sp ON sp.post_id=p.id "
"AND sp.user_id=%(user_id)s "
"LEFT OUTER JOIN posts.recommendations rp "
"ON %(user_id)s=rp.user_id AND "
"p.id=rp.post_id AND rp.comment_id=0 "
"LEFT OUTER JOIN posts.bookmarks rb "
"ON p.id=rb.post_id AND %(user_id)s=rb.user_id AND "
"rb.comment_id=0 "
"WHERE p.private=true;",
{'ids': ids, 'user_id': env.user.id, 'tz': env.user.get_profile('tz'),
'limit': limit, 'edit_expire': settings.edit_expire})
plist = []
for i, r in enumerate(res):
r = dict(r)
r['uid'] = 157321 + offset + i + 1
plist.append(r)
return _plist(plist)
@check_auth
def private_outgoing(limit=10, offset=None, asc=False, before=None):
"""
Get outgoing private posts
"""
order = 'ASC' if asc else 'DESC'
if before and isinstance(before, (int, long)):
offset = before - 157321
offset_cond = " OFFSET %d" % offset
elif offset:
offset_cond = " OFFSET %d" % int(offset)
else:
offset = 0
offset_cond = ""
res = db.fetchall(
"SELECT "
"p.id, p.author, u.login, i.name, i.avatar, p.private, "
"p.created at time zone %%(tz)s AS created,"
"p.resource, "
"p.type, p.title, p.link, p.tags, p.text, "
"p.edited,"
"(p.edited=false AND p.created+interval '%%(edit_expire)s second' >= now())"
"AS editable, "
"p.archive, p.files, "
"sp.post_id AS subscribed, "
"rp.post_id AS recommended, "
"rb.post_id AS bookmarked "
"FROM posts.posts p "
"JOIN users.logins u ON u.id=p.author "
"LEFT OUTER JOIN users.info i ON i.id=p.author "
"LEFT OUTER JOIN posts.recipients rcp ON rcp.post_id=p.id "
"LEFT OUTER JOIN subs.posts sp ON sp.post_id=p.id "
"AND sp.user_id=%%(user_id)s "
"LEFT OUTER JOIN posts.recommendations rp "
"ON %%(user_id)s=rp.user_id AND "
"p.id=rp.post_id AND rp.comment_id=0 "
"LEFT OUTER JOIN posts.bookmarks rb "
"ON p.id=rb.post_id AND %%(user_id)s=rb.user_id AND "
"rb.comment_id=0 "
"WHERE p.author=%%(user_id)s AND p.private=true "
"GROUP BY p.id, u.login, i.name, i.avatar, sp.post_id, rp.post_id, rb.post_id "
"ORDER BY p.created %s "
"%s LIMIT %%(limit)s;"% (order, offset_cond),
{'user_id': env.user.id, 'tz': env.user.get_profile('tz'),
'offset': offset, 'limit': limit,
'edit_expire': settings.edit_expire})
plist = []
for i, r in enumerate(res):
r = dict(r)
r['uid'] = 157321 + offset + i + 1
plist.append(r)
return _plist(plist)
@check_auth
def private_incoming(limit=10, offset=None, asc=False, before=None):
"""
Get incoming private posts
"""
order = 'ASC' if asc else 'DESC'
if before and isinstance(before, (int, long)):
offset = before - 157321
offset_cond = " OFFSET %d" % offset
elif offset:
offset_cond = " OFFSET %d" % int(offset)
else:
offset = 0
offset_cond = ""
res = db.fetchall(
"SELECT "