This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
queries.py
1899 lines (1500 loc) · 64.1 KB
/
queries.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
# The contents of this file are subject to the Common Public Attribution
# License Version 1.0. (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, but Sections 14 and 15 have been added to cover use of
# software over a computer network and provide for limited attribution for the
# Original Developer. In addition, Exhibit A has been modified to be consistent
# with Exhibit B.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
#
# The Original Code is reddit.
#
# The Original Developer is the Initial Developer. The Initial Developer of
# the Original Code is reddit Inc.
#
# All portions of the code written by reddit are Copyright (c) 2006-2015 reddit
# Inc. All Rights Reserved.
###############################################################################
from r2.models import Account, Link, Comment, Report, LinksByAccount
from r2.models.vote import cast_vote, get_votes, VotesByAccount
from r2.models import Message, Inbox, Subreddit, ModContribSR, ModeratorInbox, MultiReddit
from r2.lib.db.thing import Thing, Merge
from r2.lib.db.operators import asc, desc, timeago
from r2.lib.db.sorts import epoch_seconds
from r2.lib.db import tdb_cassandra
from r2.lib.utils import fetch_things2, tup, UniqueIterator, set_last_modified
from r2.lib import utils
from r2.lib import amqp, sup, filters
from r2.lib.comment_tree import add_comments, update_comment_votes
from r2.models.promo import PROMOTE_STATUS, PromotionLog
from r2.models.query_cache import (
cached_query,
CachedQuery,
CachedQueryMutator,
filter_thing,
FakeQuery,
merged_cached_query,
MergedCachedQuery,
SubredditQueryCache,
ThingTupleComparator,
UserQueryCache,
)
from r2.models.last_modified import LastModified
from r2.lib.utils import in_chunks, is_subdomain, SimpleSillyStub
import cPickle as pickle
from datetime import datetime
from time import mktime
import pytz
import itertools
import collections
from copy import deepcopy
from r2.lib.db.operators import and_, or_
from pylons import g
query_cache = g.permacache
log = g.log
make_lock = g.make_lock
worker = amqp.worker
stats = g.stats
precompute_limit = 1000
db_sorts = dict(hot = (desc, '_hot'),
new = (desc, '_date'),
top = (desc, '_score'),
controversial = (desc, '_controversy'))
def db_sort(sort):
cls, col = db_sorts[sort]
return cls(col)
db_times = dict(all = None,
hour = Thing.c._date >= timeago('1 hour'),
day = Thing.c._date >= timeago('1 day'),
week = Thing.c._date >= timeago('1 week'),
month = Thing.c._date >= timeago('1 month'),
year = Thing.c._date >= timeago('1 year'))
# sorts for which there can be a time filter (by day, by week,
# etc). All of these but 'all' are done in mr_top, who knows about the
# structure of the stored CachedResults (so changes here may warrant
# changes there)
time_filtered_sorts = set(('top', 'controversial'))
#we need to define the filter functions here so cachedresults can be pickled
def filter_identity(x):
return x
def filter_thing2(x):
"""A filter to apply to the results of a relationship query returns
the object of the relationship."""
return x._thing2
class CachedResults(object):
"""Given a query returns a list-like object that will lazily look up
the query from the persistent cache. """
def __init__(self, query, filter):
self.query = query
self.query._limit = precompute_limit
self.filter = filter
self.iden = self.query._iden()
self.sort_cols = [s.col for s in self.query._sort]
self.data = []
self._fetched = False
@property
def sort(self):
return self.query._sort
def fetch(self, force=False, stale=False):
"""Loads the query from the cache."""
self.fetch_multi([self], force=force, stale=stale)
@classmethod
def fetch_multi(cls, crs, force=False, stale=False):
unfetched = filter(lambda cr: force or not cr._fetched, crs)
if not unfetched:
return
keys = [cr.iden for cr in unfetched]
cached = query_cache.get_multi(keys, allow_local=not force, stale=stale)
for cr in unfetched:
cr.data = cached.get(cr.iden) or []
cr._fetched = True
def make_item_tuple(self, item):
"""Given a single 'item' from the result of a query build the tuple
that will be stored in the query cache. It is effectively the
fullname of the item after passing through the filter plus the
columns of the unfiltered item to sort by."""
filtered_item = self.filter(item)
lst = [filtered_item._fullname]
for col in self.sort_cols:
#take the property of the original
attr = getattr(item, col)
#convert dates to epochs to take less space
if isinstance(attr, datetime):
attr = epoch_seconds(attr)
lst.append(attr)
return tuple(lst)
def can_insert(self):
"""True if a new item can just be inserted rather than
rerunning the query."""
# This is only true in some circumstances: queries where
# eligibility in the list is determined only by its sort
# value (e.g. hot) and where addition/removal from the list
# incurs an insertion/deletion event called on the query. So
# the top hottest items in X some subreddit where the query
# is notified on every submission/banning/unbanning/deleting
# will work, but for queries with a time-component or some
# other eligibility factor, it cannot be inserted this way.
if self.query._sort in ([desc('_date')],
[desc('_hot'), desc('_date')],
[desc('_score'), desc('_date')],
[desc('_controversy'), desc('_date')]):
if not any(r for r in self.query._rules
if r.lval.name == '_date'):
# if no time-rule is specified, then it's 'all'
return True
return False
def can_delete(self):
"True if a item can be removed from the listing, always true for now."
return True
def _mutate(self, fn, willread=True):
self.data = query_cache.mutate(self.iden, fn, default=[], willread=willread)
self._fetched=True
def insert(self, items):
"""Inserts the item into the cached data. This only works
under certain criteria, see can_insert."""
self._insert_tuples([self.make_item_tuple(item) for item in tup(items)])
def _insert_tuples(self, tuples):
def _mutate(data):
data = data or []
item_tuples = tuples or []
existing_fnames = {item[0] for item in data}
new_fnames = {item[0] for item in item_tuples}
mutated_length = len(existing_fnames.union(new_fnames))
would_truncate = mutated_length >= precompute_limit
if would_truncate:
# only insert items that are already stored or new items
# that are large enough that they won't be immediately truncated
# out of storage
# item structure is (name, sortval1[, sortval2, ...])
smallest = data[-1]
item_tuples = [item for item in item_tuples
if (item[0] in existing_fnames or
item[1:] >= smallest[1:])]
if not item_tuples:
return data
# insert the items, remove the duplicates (keeping the
# one being inserted over the stored value if applicable),
# and sort the result
data = filter(lambda x: x[0] not in new_fnames, data)
data.extend(item_tuples)
data.sort(reverse=True, key=lambda x: x[1:])
if len(data) > precompute_limit:
data = data[:precompute_limit]
return data
self._mutate(_mutate)
def delete(self, items):
"""Deletes an item from the cached data."""
fnames = set(self.filter(x)._fullname for x in tup(items))
def _mutate(data):
data = data or []
return filter(lambda x: x[0] not in fnames,
data)
self._mutate(_mutate)
def _replace(self, tuples):
"""Take pre-rendered tuples from mr_top and replace the
contents of the query outright. This should be considered a
private API"""
def _mutate(data):
return tuples
self._mutate(_mutate, willread=False)
def update(self):
"""Runs the query and stores the result in the cache. This is
only run by hand."""
self.data = [self.make_item_tuple(i) for i in self.query]
self._fetched = True
query_cache.set(self.iden, self.data)
def __repr__(self):
return '<CachedResults %s %s>' % (self.query._rules, self.query._sort)
def __iter__(self):
self.fetch()
for x in self.data:
yield x[0]
class MergedCachedResults(object):
"""Given two CachedResults, merges their lists based on the sorts
of their queries."""
# normally we'd do this by having a superclass of CachedResults,
# but we have legacy pickled CachedResults that we don't want to
# break
def __init__(self, results):
self.cached_results = results
CachedResults.fetch_multi([r for r in results
if isinstance(r, CachedResults)])
CachedQuery._fetch_multi([r for r in results
if isinstance(r, CachedQuery)])
self._fetched = True
self.sort = results[0].sort
comparator = ThingTupleComparator(self.sort)
# make sure they're all the same
assert all(r.sort == self.sort for r in results[1:])
all_items = []
for cr in results:
all_items.extend(cr.data)
all_items.sort(cmp=comparator)
self.data = all_items
def __repr__(self):
return '<MergedCachedResults %r>' % (self.cached_results,)
def __iter__(self):
for x in self.data:
yield x[0]
def update(self):
for x in self.cached_results:
x.update()
def make_results(query, filter = filter_identity):
return CachedResults(query, filter)
def merge_results(*results):
if not results:
return []
return MergedCachedResults(results)
def migrating_cached_query(model, filter_fn=filter_identity):
"""Returns a CachedResults object that has a new-style cached query
attached as "new_query". This way, reads will happen from the old
query cache while writes can be made to go to both caches until a
backfill migration is complete."""
decorator = cached_query(model, filter_fn)
def migrating_cached_query_decorator(fn):
wrapped = decorator(fn)
def migrating_cached_query_wrapper(*args):
new_query = wrapped(*args)
old_query = make_results(new_query.query, filter_fn)
old_query.new_query = new_query
return old_query
return migrating_cached_query_wrapper
return migrating_cached_query_decorator
@cached_query(UserQueryCache)
def get_deleted_links(user_id):
return Link._query(Link.c.author_id == user_id,
Link.c._deleted == True,
Link.c._spam == (True, False),
sort=db_sort('new'))
@cached_query(UserQueryCache)
def get_deleted_comments(user_id):
return Comment._query(Comment.c.author_id == user_id,
Comment.c._deleted == True,
Comment.c._spam == (True, False),
sort=db_sort('new'))
@merged_cached_query
def get_deleted(user):
return [get_deleted_links(user),
get_deleted_comments(user)]
def get_links(sr, sort, time):
return _get_links(sr._id, sort, time)
def _get_links(sr_id, sort, time):
"""General link query for a subreddit."""
q = Link._query(Link.c.sr_id == sr_id,
sort = db_sort(sort),
data = True)
if time != 'all':
q._filter(db_times[time])
res = make_results(q)
return res
@cached_query(SubredditQueryCache)
def get_spam_links(sr_id):
return Link._query(Link.c.sr_id == sr_id,
Link.c._spam == True,
sort = db_sort('new'))
@cached_query(SubredditQueryCache)
def get_spam_comments(sr_id):
return Comment._query(Comment.c.sr_id == sr_id,
Comment.c._spam == True,
sort = db_sort('new'))
@cached_query(SubredditQueryCache)
def get_edited_comments(sr_id):
return FakeQuery(sort=[desc("editted")])
@cached_query(SubredditQueryCache)
def get_edited_links(sr_id):
return FakeQuery(sort=[desc("editted")])
@merged_cached_query
def get_edited(sr, user=None, include_links=True, include_comments=True):
sr_ids = moderated_srids(sr, user)
queries = []
if include_links:
queries.append(get_edited_links)
if include_comments:
queries.append(get_edited_comments)
return [query(sr_id) for sr_id, query in itertools.product(sr_ids, queries)]
def moderated_srids(sr, user):
if isinstance(sr, (ModContribSR, MultiReddit)):
srs = Subreddit._byID(sr.sr_ids, return_dict=False)
if user:
srs = [sr for sr in srs
if sr.is_moderator_with_perms(user, 'posts')]
return [sr._id for sr in srs]
else:
return [sr._id]
@merged_cached_query
def get_spam(sr, user=None, include_links=True, include_comments=True):
sr_ids = moderated_srids(sr, user)
queries = []
if include_links:
queries.append(get_spam_links)
if include_comments:
queries.append(get_spam_comments)
return [query(sr_id) for sr_id, query in itertools.product(sr_ids, queries)]
@cached_query(SubredditQueryCache)
def get_spam_filtered_links(sr_id):
""" NOTE: This query will never run unless someone does an "update" on it,
but that will probably timeout. Use insert_spam_filtered_links."""
return Link._query(Link.c.sr_id == sr_id,
Link.c._spam == True,
Link.c.verdict != 'mod-removed',
sort = db_sort('new'))
@cached_query(SubredditQueryCache)
def get_spam_filtered_comments(sr_id):
return Comment._query(Comment.c.sr_id == sr_id,
Comment.c._spam == True,
Comment.c.verdict != 'mod-removed',
sort = db_sort('new'))
@merged_cached_query
def get_spam_filtered(sr):
return [get_spam_filtered_links(sr),
get_spam_filtered_comments(sr)]
@cached_query(SubredditQueryCache)
def get_reported_links(sr_id):
return Link._query(Link.c.reported != 0,
Link.c.sr_id == sr_id,
Link.c._spam == False,
sort = db_sort('new'))
@cached_query(SubredditQueryCache)
def get_reported_comments(sr_id):
return Comment._query(Comment.c.reported != 0,
Comment.c.sr_id == sr_id,
Comment.c._spam == False,
sort = db_sort('new'))
@merged_cached_query
def get_reported(sr, user=None, include_links=True, include_comments=True):
sr_ids = moderated_srids(sr, user)
queries = []
if include_links:
queries.append(get_reported_links)
if include_comments:
queries.append(get_reported_comments)
return [query(sr_id) for sr_id, query in itertools.product(sr_ids, queries)]
@cached_query(SubredditQueryCache)
def get_unmoderated_links(sr_id):
q = Link._query(Link.c.sr_id == sr_id,
Link.c._spam == (True, False),
sort = db_sort('new'))
# Doesn't really work because will not return Links with no verdict
q._filter(or_(and_(Link.c._spam == True, Link.c.verdict != 'mod-removed'),
and_(Link.c._spam == False, Link.c.verdict != 'mod-approved')))
return q
@merged_cached_query
def get_modqueue(sr, user=None, include_links=True, include_comments=True):
sr_ids = moderated_srids(sr, user)
queries = []
if include_links:
queries.append(get_reported_links)
queries.append(get_spam_filtered_links)
if include_comments:
queries.append(get_reported_comments)
queries.append(get_spam_filtered_comments)
return [query(sr_id) for sr_id, query in itertools.product(sr_ids, queries)]
@merged_cached_query
def get_unmoderated(sr, user=None):
sr_ids = moderated_srids(sr, user)
queries = [get_unmoderated_links]
return [query(sr_id) for sr_id, query in itertools.product(sr_ids, queries)]
def get_domain_links(domain, sort, time):
from r2.lib.db import operators
q = Link._query(operators.domain(Link.c.url) == filters._force_utf8(domain),
sort = db_sort(sort),
data = True)
if time != "all":
q._filter(db_times[time])
return make_results(q)
def user_query(kind, user_id, sort, time):
"""General profile-page query."""
q = kind._query(kind.c.author_id == user_id,
kind.c._spam == (True, False),
sort = db_sort(sort))
if time != 'all':
q._filter(db_times[time])
return make_results(q)
def get_all_comments():
"""the master /comments page"""
q = Comment._query(sort = desc('_date'))
return make_results(q)
def get_sr_comments(sr):
return _get_sr_comments(sr._id)
def _get_sr_comments(sr_id):
"""the subreddit /r/foo/comments page"""
q = Comment._query(Comment.c.sr_id == sr_id,
sort = desc('_date'))
return make_results(q)
def _get_comments(user_id, sort, time):
return user_query(Comment, user_id, sort, time)
def get_comments(user, sort, time):
return _get_comments(user._id, sort, time)
def _get_submitted(user_id, sort, time):
return user_query(Link, user_id, sort, time)
def get_submitted(user, sort, time):
return _get_submitted(user._id, sort, time)
def get_user_actions(user, sort, time):
return merge_results(get_comments(user, sort, time),
get_submitted(user, sort, time),
get_liked(user))
def get_overview(user, sort, time):
return merge_results(get_comments(user, sort, time),
get_submitted(user, sort, time))
def rel_query(rel, thing_id, name, filters = []):
"""General relationship query."""
q = rel._query(rel.c._thing1_id == thing_id,
rel.c._t2_deleted == False,
rel.c._name == name,
sort = desc('_date'),
eager_load = True,
)
if filters:
q._filter(*filters)
return q
cached_userrel_query = cached_query(UserQueryCache, filter_thing2)
cached_srrel_query = cached_query(SubredditQueryCache, filter_thing2)
@cached_userrel_query
def get_liked(user):
return FakeQuery(sort=[desc("_date")])
@cached_userrel_query
def get_disliked(user):
return FakeQuery(sort=[desc("_date")])
@cached_query(UserQueryCache)
def get_hidden_links(user_id):
return FakeQuery(sort=[desc("action_date")])
def get_hidden(user):
return get_hidden_links(user)
@cached_query(UserQueryCache)
def get_categorized_saved_links(user_id, sr_id, category):
return FakeQuery(sort=[desc("action_date")])
@cached_query(UserQueryCache)
def get_categorized_saved_comments(user_id, sr_id, category):
return FakeQuery(sort=[desc("action_date")])
@cached_query(UserQueryCache)
def get_saved_links(user_id, sr_id):
return FakeQuery(sort=[desc("action_date")])
@cached_query(UserQueryCache)
def get_saved_comments(user_id, sr_id):
return FakeQuery(sort=[desc("action_date")])
def get_saved(user, sr_id=None, category=None):
sr_id = sr_id or 'none'
if not category:
queries = [get_saved_links(user, sr_id),
get_saved_comments(user, sr_id)]
else:
queries = [get_categorized_saved_links(user, sr_id, category),
get_categorized_saved_comments(user, sr_id, category)]
return MergedCachedQuery(queries)
@cached_srrel_query
def get_subreddit_messages(sr):
return rel_query(ModeratorInbox, sr, 'inbox')
@cached_srrel_query
def get_unread_subreddit_messages(sr):
return rel_query(ModeratorInbox, sr, 'inbox',
filters = [ModeratorInbox.c.new == True])
def get_unread_subreddit_messages_multi(srs):
if not srs:
return []
queries = [get_unread_subreddit_messages(sr) for sr in srs]
return MergedCachedQuery(queries)
inbox_message_rel = Inbox.rel(Account, Message)
@cached_userrel_query
def get_inbox_messages(user):
return rel_query(inbox_message_rel, user, 'inbox')
@cached_userrel_query
def get_unread_messages(user):
return rel_query(inbox_message_rel, user, 'inbox',
filters = [inbox_message_rel.c.new == True])
inbox_comment_rel = Inbox.rel(Account, Comment)
@cached_userrel_query
def get_inbox_comments(user):
return rel_query(inbox_comment_rel, user, 'inbox')
@cached_userrel_query
def get_unread_comments(user):
return rel_query(inbox_comment_rel, user, 'inbox',
filters = [inbox_comment_rel.c.new == True])
@cached_userrel_query
def get_inbox_selfreply(user):
return rel_query(inbox_comment_rel, user, 'selfreply')
@cached_userrel_query
def get_unread_selfreply(user):
return rel_query(inbox_comment_rel, user, 'selfreply',
filters = [inbox_comment_rel.c.new == True])
@cached_userrel_query
def get_inbox_comment_mentions(user):
return rel_query(inbox_comment_rel, user, "mention")
@cached_userrel_query
def get_unread_comment_mentions(user):
return rel_query(inbox_comment_rel, user, "mention",
filters=[inbox_comment_rel.c.new == True])
def get_inbox(user):
return merge_results(get_inbox_comments(user),
get_inbox_messages(user),
get_inbox_comment_mentions(user),
get_inbox_selfreply(user))
@cached_query(UserQueryCache)
def get_sent(user_id):
return Message._query(Message.c.author_id == user_id,
Message.c._spam == (True, False),
sort = desc('_date'))
def get_unread_inbox(user):
return merge_results(get_unread_comments(user),
get_unread_messages(user),
get_unread_comment_mentions(user),
get_unread_selfreply(user))
def _user_reported_query(user_id, thing_cls):
rel_cls = Report.rel(Account, thing_cls)
return rel_query(rel_cls, user_id, ('-1', '0', '1'))
# -1: rejected report
# 0: unactioned report
# 1: accepted report
@cached_userrel_query
def get_user_reported_links(user_id):
return _user_reported_query(user_id, Link)
@cached_userrel_query
def get_user_reported_comments(user_id):
return _user_reported_query(user_id, Comment)
@cached_userrel_query
def get_user_reported_messages(user_id):
return _user_reported_query(user_id, Message)
@merged_cached_query
def get_user_reported(user_id):
return [get_user_reported_links(user_id),
get_user_reported_comments(user_id),
get_user_reported_messages(user_id)]
def set_promote_status(link, promote_status):
all_queries = [promote_query(link.author_id) for promote_query in
(get_unpaid_links, get_unapproved_links,
get_rejected_links, get_live_links, get_accepted_links)]
all_queries.extend([get_all_unpaid_links(), get_all_unapproved_links(),
get_all_rejected_links(), get_all_live_links(),
get_all_accepted_links()])
if promote_status == PROMOTE_STATUS.unpaid:
inserts = [get_unpaid_links(link.author_id), get_all_unpaid_links()]
elif promote_status == PROMOTE_STATUS.unseen:
inserts = [get_unapproved_links(link.author_id),
get_all_unapproved_links()]
elif promote_status == PROMOTE_STATUS.rejected:
inserts = [get_rejected_links(link.author_id), get_all_rejected_links()]
elif promote_status == PROMOTE_STATUS.promoted:
inserts = [get_live_links(link.author_id), get_all_live_links()]
elif promote_status in (PROMOTE_STATUS.accepted, PROMOTE_STATUS.pending,
PROMOTE_STATUS.finished):
inserts = [get_accepted_links(link.author_id), get_all_accepted_links()]
deletes = list(set(all_queries) - set(inserts))
with CachedQueryMutator() as m:
for q in inserts:
m.insert(q, [link])
for q in deletes:
m.delete(q, [link])
link.promote_status = promote_status
link._commit()
text = "set promote status to '%s'" % PROMOTE_STATUS.name[promote_status]
PromotionLog.add(link, text)
def _promoted_link_query(user_id, status):
STATUS_CODES = {'unpaid': PROMOTE_STATUS.unpaid,
'unapproved': PROMOTE_STATUS.unseen,
'rejected': PROMOTE_STATUS.rejected,
'live': PROMOTE_STATUS.promoted,
'accepted': (PROMOTE_STATUS.accepted,
PROMOTE_STATUS.pending,
PROMOTE_STATUS.finished)}
q = Link._query(Link.c.sr_id == Subreddit.get_promote_srid(),
Link.c._spam == (True, False),
Link.c._deleted == (True, False),
Link.c.promote_status == STATUS_CODES[status],
sort=db_sort('new'))
if user_id:
q._filter(Link.c.author_id == user_id)
return q
@cached_query(UserQueryCache)
def get_unpaid_links(user_id):
return _promoted_link_query(user_id, 'unpaid')
@cached_query(UserQueryCache)
def get_all_unpaid_links():
return _promoted_link_query(None, 'unpaid')
@cached_query(UserQueryCache)
def get_unapproved_links(user_id):
return _promoted_link_query(user_id, 'unapproved')
@cached_query(UserQueryCache)
def get_all_unapproved_links():
return _promoted_link_query(None, 'unapproved')
@cached_query(UserQueryCache)
def get_rejected_links(user_id):
return _promoted_link_query(user_id, 'rejected')
@cached_query(UserQueryCache)
def get_all_rejected_links():
return _promoted_link_query(None, 'rejected')
@cached_query(UserQueryCache)
def get_live_links(user_id):
return _promoted_link_query(user_id, 'live')
@cached_query(UserQueryCache)
def get_all_live_links():
return _promoted_link_query(None, 'live')
@cached_query(UserQueryCache)
def get_accepted_links(user_id):
return _promoted_link_query(user_id, 'accepted')
@cached_query(UserQueryCache)
def get_all_accepted_links():
return _promoted_link_query(None, 'accepted')
@cached_query(UserQueryCache)
def get_payment_flagged_links():
return FakeQuery(sort=[desc("_date")])
def set_payment_flagged_link(link):
with CachedQueryMutator() as m:
q = get_payment_flagged_links()
m.insert(q, [link])
def unset_payment_flagged_link(link):
with CachedQueryMutator() as m:
q = get_payment_flagged_links()
m.delete(q, [link])
@cached_query(UserQueryCache)
def get_underdelivered_campaigns():
return FakeQuery(sort=[desc("_date")])
def set_underdelivered_campaigns(campaigns):
campaigns = tup(campaigns)
with CachedQueryMutator() as m:
q = get_underdelivered_campaigns()
m.insert(q, campaigns)
def unset_underdelivered_campaigns(campaigns):
campaigns = tup(campaigns)
with CachedQueryMutator() as m:
q = get_underdelivered_campaigns()
m.delete(q, campaigns)
@merged_cached_query
def get_promoted_links(user_id):
queries = [get_unpaid_links(user_id), get_unapproved_links(user_id),
get_rejected_links(user_id), get_live_links(user_id),
get_accepted_links(user_id)]
return queries
@merged_cached_query
def get_all_promoted_links():
queries = [get_all_unpaid_links(), get_all_unapproved_links(),
get_all_rejected_links(), get_all_live_links(),
get_all_accepted_links()]
return queries
@cached_query(SubredditQueryCache, filter_fn=filter_thing)
def get_all_gilded_comments():
return FakeQuery(sort=[desc("date")])
@cached_query(SubredditQueryCache, filter_fn=filter_thing)
def get_all_gilded_links():
return FakeQuery(sort=[desc("date")])
@merged_cached_query
def get_all_gilded():
return [get_all_gilded_comments(), get_all_gilded_links()]
@cached_query(SubredditQueryCache, filter_fn=filter_thing)
def get_gilded_comments(sr_id):
return FakeQuery(sort=[desc("date")])
@cached_query(SubredditQueryCache, filter_fn=filter_thing)
def get_gilded_links(sr_id):
return FakeQuery(sort=[desc("date")])
@merged_cached_query
def get_gilded(sr_ids):
queries = [get_gilded_links, get_gilded_comments]
return [query(sr_id)
for sr_id, query in itertools.product(tup(sr_ids), queries)]
@cached_query(UserQueryCache, filter_fn=filter_thing)
def get_gilded_user_comments(user_id):
return FakeQuery(sort=[desc("date")])
@cached_query(UserQueryCache, filter_fn=filter_thing)
def get_gilded_user_links(user_id):
return FakeQuery(sort=[desc("date")])
@merged_cached_query
def get_gilded_users(user_ids):
queries = [get_gilded_user_links, get_gilded_user_comments]
return [query(user_id)
for user_id, query in itertools.product(tup(user_ids), queries)]
@cached_query(UserQueryCache, filter_fn=filter_thing)
def get_user_gildings(user_id):
return FakeQuery(sort=[desc("date")])
@merged_cached_query
def get_gilded_user(user):
return [get_gilded_user_comments(user), get_gilded_user_links(user)]
def add_queries(queries, insert_items=None, delete_items=None, foreground=False):
"""Adds multiple queries to the query queue. If insert_items or
delete_items is specified, the query may not need to be
recomputed against the database."""
for q in queries:
if insert_items and q.can_insert():
log.debug("Inserting %s into query %s" % (insert_items, q))
if foreground:
q.insert(insert_items)
else:
worker.do(q.insert, insert_items)
elif delete_items and q.can_delete():
log.debug("Deleting %s from query %s" % (delete_items, q))
if foreground:
q.delete(delete_items)
else:
worker.do(q.delete, delete_items)
else:
raise Exception("Cannot update query %r!" % (q,))
# dual-write any queries that are being migrated to the new query cache
with CachedQueryMutator() as m:
new_queries = [getattr(q, 'new_query') for q in queries if hasattr(q, 'new_query')]
if insert_items:
for query in new_queries:
m.insert(query, tup(insert_items))
if delete_items:
for query in new_queries:
m.delete(query, tup(delete_items))
#can be rewritten to be more efficient
def all_queries(fn, obj, *param_lists):
"""Given a fn and a first argument 'obj', calls the fn(obj, *params)
for every permutation of the parameters in param_lists"""
results = []
params = [[obj]]
for pl in param_lists:
new_params = []
for p in pl:
for c in params:
new_param = list(c)
new_param.append(p)
new_params.append(new_param)
params = new_params
results = [fn(*p) for p in params]
return results
## The following functions should be called after their respective
## actions to update the correct listings.
def new_link(link):
"Called on the submission and deletion of links"
sr = Subreddit._byID(link.sr_id)
author = Account._byID(link.author_id)
results = [get_links(sr, 'new', 'all')]
# we don't have to do hot/top/controversy because new_vote will do
# that
results.append(get_submitted(author, 'new', 'all'))
for domain in utils.UrlParser(link.url).domain_permutations():
results.append(get_domain_links(domain, 'new', "all"))
with CachedQueryMutator() as m:
if link._spam:
m.insert(get_spam_links(sr), [link])
if not (sr.exclude_banned_modqueue and author._spam):
m.insert(get_unmoderated_links(sr), [link])
add_queries(results, insert_items = link)
amqp.add_item('new_link', link._fullname)
def add_to_commentstree_q(comment):
if utils.to36(comment.link_id) in g.live_config["fastlane_links"]:
amqp.add_item('commentstree_fastlane_q', comment._fullname)
elif g.shard_commentstree_queues:
amqp.add_item('commentstree_%d_q' % (comment.link_id % 10),
comment._fullname)
else:
amqp.add_item('commentstree_q', comment._fullname)
def update_comment_notifications(comment, inbox_rels, mutator):
is_visible = not comment._deleted and not comment._spam