This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
link.py
3023 lines (2499 loc) · 105 KB
/
link.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.config import feature
from r2.lib.db.thing import (
Thing, Relation, NotFound, MultiRelation, CreationError)
from r2.lib.db.operators import desc
from r2.lib.errors import RedditError
from r2.lib.utils import (
base_url,
domain,
epoch_timestamp,
strip_www,
timesince,
title_to_url,
tup,
UrlParser,
)
from account import (
Account,
BlockedSubredditsByAccount,
DeletedUser,
SubredditParticipationByAccount,
)
from subreddit import (
DefaultSR,
DomainSR,
FakeSubreddit,
Subreddit,
SubredditsActiveForFrontPage,
)
from printable import Printable
from r2.config import extensions
from r2.lib.memoize import memoize
from r2.lib.wrapped import Wrapped
from r2.lib.filters import _force_utf8, _force_unicode
from r2.lib import hooks, utils
from r2.lib.log import log_text
from mako.filters import url_escape
from r2.lib.strings import strings, Score
from r2.lib.db import tdb_cassandra, sorts
from r2.lib.db.tdb_cassandra import view_of
from r2.lib.utils import sanitize_url
from r2.lib.voting import cast_vote
from r2.models.gold import (
GildedCommentsByAccount,
GildedLinksByAccount,
make_gold_message,
)
from r2.models.modaction import ModAction
from r2.models.subreddit import MultiReddit
from r2.models.trylater import TryLater
from r2.models.query_cache import CachedQueryMutator
from r2.models.promo import PROMOTE_STATUS
from r2.models.vote import Vote
from pylons import request
from pylons import tmpl_context as c
from pylons import app_globals as g
from pylons.i18n import _
from datetime import datetime, timedelta
from hashlib import md5
import simplejson as json
import random, re
import pycassa
from collections import defaultdict
from itertools import cycle
from pycassa.cassandra.ttypes import NotFoundException
from pycassa.system_manager import (
ASCII_TYPE,
DOUBLE_TYPE,
)
import pytz
NOTIFICATION_EMAIL_DELAY = timedelta(hours=1)
class LinkExists(Exception): pass
class Link(Thing, Printable):
_cache = g.link_transitionalcache
_data_int_props = Thing._data_int_props + (
'num_comments', 'reported', 'comment_tree_id', 'gildings')
_defaults = dict(is_self=False,
suggested_sort=None,
over_18=False,
over_18_override=False,
reported=0, num_comments=0,
moderator_banned=False,
banned_before_moderator=False,
media_object=None,
secure_media_object=None,
preview_object=None,
media_url=None,
gifts_embed_url=None,
media_autoplay=False,
domain_override=None,
third_party_tracking=None,
third_party_tracking_2=None,
promoted=None,
payment_flagged_reason="",
fraud=None,
managed_promo=False,
pending=False,
disable_comments=False,
locked=False,
selftext='',
sendreplies=True,
ip='0.0.0.0',
flair_text=None,
flair_css_class=None,
comment_tree_version=1,
comment_tree_id=0,
contest_mode=False,
skip_commentstree_q="",
sticky_comment_id=None,
ignore_reports=False,
gildings=0,
mobile_ad_url="",
admin_takedown=False,
removed_link_child=None,
precomputed_sorts=None,
)
_essentials = ('sr_id', 'author_id')
_nsfw = re.compile(r"\bnsf[wl]\b", re.I)
SELFTEXT_MAX_LENGTH = 40000
is_votable = True
def __init__(self, *a, **kw):
Thing.__init__(self, *a, **kw)
@property
def vote_queue_name(self):
if self._id36 in g.live_config["fastlane_links"]:
return "vote_fastlane_q"
else:
if g.shard_link_vote_queues:
return "vote_link_%s_q" % str(self.sr_id)[-1]
else:
return "vote_link_q"
@property
def affects_karma_type(self):
if self.is_self:
return None
return "link"
@property
def body(self):
if self.is_self:
return self.selftext
else:
raise AttributeError
@property
def has_thumbnail(self):
return self._t.get('has_thumbnail', hasattr(self, 'thumbnail_url'))
@property
def is_nsfw(self):
return self.over_18
@property
def is_embeddable(self):
return not self.is_nsfw and self.subreddit_slow.is_embeddable
@classmethod
def _by_url(cls, url, sr):
if isinstance(sr, FakeSubreddit):
sr = None
link_ids = LinksByUrlAndSubreddit.get_link_ids(url, sr)
links = Link._byID(link_ids, data=True, return_dict=False)
links = [l for l in links if not l._deleted]
if not links:
raise NotFound('Link "%s"' % url)
return links
def already_submitted_link(self, url, title):
permalink = self.make_permalink_slow()
p = UrlParser(permalink)
p.update_query(already_submitted="true", submit_url=url,
submit_title=title)
return p.unparse()
@classmethod
def resubmit_link(cls, url, title):
p = UrlParser("/submit")
p.update_query(resubmit="true", url=url, title=title)
return p.unparse()
@classmethod
def _choose_comment_tree_version(cls):
try:
weights = g.live_config['comment_tree_version_weights']
except KeyError:
return cls._defaults['comment_tree_version']
try:
return int(utils.weighted_lottery(weights))
except ValueError, ex:
g.log.error("error choosing comment tree version: %s", ex.message)
return cls._defaults['comment_tree_version']
@classmethod
def _submit(cls, is_self, title, content, author, sr, ip,
sendreplies=True):
from r2.models import admintools
from r2.models.comment_tree import CommentTree
if is_self:
url = "self"
selftext = content
else:
url = content
selftext = cls._defaults["selftext"]
over_18 = False
if cls._nsfw.search(title):
over_18 = True
# determine whether the post should go straight into spam
spam = author._spam
if is_self:
spam_filter_level = sr.spam_selfposts
else:
spam_filter_level = sr.spam_links
if spam_filter_level == "all" and not sr.is_special(author):
spam = True
l = cls(
_ups=1,
title=title,
url=url,
selftext=selftext,
_spam=spam,
author_id=author._id,
sendreplies=sendreplies,
sr_id=sr._id,
lang=sr.lang,
ip=ip,
comment_tree_version=cls._choose_comment_tree_version(),
is_self=is_self,
over_18=over_18,
)
l._commit()
# Note: this does not provide atomicity, so for self posts when
# a request dies after the previous line but before the next line
# you will have a link whose URL is literally 'self'
if is_self:
l.url = l.make_permalink_slow()
l._commit()
else:
LinksByUrlAndSubreddit.add_link(l)
LinksByAccount.add_link(author, l)
SubredditParticipationByAccount.mark_participated(author, sr)
SubredditsActiveForFrontPage.mark_new_post(sr)
author.last_submit_time = int(epoch_timestamp(datetime.now(g.tz)))
author._commit()
# if the link is coming in removed, we still need to run it through
# admintools.spam() to set data properly and update queries
if l._spam:
if author._spam:
g.stats.simple_event('spam.autoremove.link')
reason = "banned user"
elif spam_filter_level == "all":
reason = "subreddit setting"
admintools.spam(l, banner=reason)
hooks.get_hook('link.new').call(link=l)
CommentTree.on_new_link(l)
cast_vote(author, l, Vote.DIRECTIONS.up)
return l
def set_content(self, is_self, content):
if not self.promoted:
raise ValueError("set_content is only supported for promoted links")
was_self = self.is_self
self.is_self = is_self
if is_self:
if not was_self:
LinksByUrlAndSubreddit.remove_link(self)
self.url = self.make_permalink_slow()
self.selftext = content
else:
if not was_self:
LinksByUrlAndSubreddit.remove_link(self)
self.url = content
self.selftext = self._defaults.get("selftext", "")
LinksByUrlAndSubreddit.add_link(self)
self._commit()
def _save(self, user, category=None):
LinkSavesByAccount._save(user, self, category)
def _unsave(self, user):
LinkSavesByAccount._unsave(user, self)
def _hide(self, user):
LinkHidesByAccount._hide(user, self)
def _unhide(self, user):
LinkHidesByAccount._unhide(user, self)
def _commit(self):
# If we've updated the (denormalized) preview object, we also need to
# update the metadata that keeps track of the denormalizations.
if 'preview_object' in self._dirties:
(old_val, val) = self._dirties['preview_object']
if old_val:
LinksByImage.remove_link(old_val['uid'], self)
if val:
LinksByImage.add_link(val['uid'], self)
Thing._commit(self)
def link_domain(self):
if self.is_self:
return 'self'
else:
return domain(self.url)
@property
def num_comments(self):
# Paper over obviously broken comment counts (those that are negative).
return max(self.__getattr__('num_comments'), 0)
def keep_item(self, wrapped):
user = c.user if c.user_is_loggedin else None
if not c.user_is_admin and self._deleted:
return False
is_mod = wrapped.subreddit.is_moderator(user)
if not (c.user_is_admin or (isinstance(c.site, DomainSR) and is_mod)):
if self._spam and (not user or
(user and self.author_id != user._id)):
return False
if not (c.user_is_admin or is_mod) and wrapped.enemy:
return False
if user and not c.ignore_hide_rules:
if wrapped.hidden:
return False
# determine if the post can be auto-hidden due to voting/score
if self.author_id == user._id:
# not if it's the user's own post
allow_auto_hide = False
elif wrapped.stickied and not wrapped.different_sr:
# not if it's stickied and we're inside the subreddit
allow_auto_hide = False
else:
allow_auto_hide = True
if (allow_auto_hide and
((user.pref_hide_ups and wrapped.likes == True) or
(user.pref_hide_downs and wrapped.likes == False) or
wrapped.score < user.pref_min_link_score)):
return False
# show NSFW to API and RSS users unless obey_over18=true
is_api = c.render_style in extensions.API_TYPES
is_rss = c.render_style in extensions.RSS_TYPES
if (is_api or is_rss) and not c.obey_over18:
return True
is_nsfw = wrapped.over_18 or wrapped.subreddit.over_18
return c.over18 or not is_nsfw
cache_ignore = {
'subreddit',
'num_comments',
'link_child',
'fresh',
'media_object',
'secure_media_object',
}.union(Printable.cache_ignore)
@staticmethod
def wrapped_cache_key(wrapped, style):
s = Printable.wrapped_cache_key(wrapped, style)
if wrapped.promoted is not None:
s.extend([
getattr(wrapped, "promote_status", -1),
getattr(wrapped, "disable_comments", False),
getattr(wrapped, "media_override", False),
c.user_is_sponsor,
wrapped.url,
repr(wrapped.title),
])
if style == "htmllite":
s.extend([
request.GET.has_key('twocolumn'),
c.link_target,
])
elif style == "xml":
s.append(request.GET.has_key("nothumbs"))
elif style == "compact":
s.append(c.permalink_page)
# add link flair to the key if the user and site have enabled it and it
# exists
if (c.user.pref_show_link_flair and
c.site.link_flair_position and
(wrapped.flair_text or wrapped.flair_css_class)):
s.append(wrapped.flair_text)
s.append(wrapped.flair_css_class)
s.append(c.site.link_flair_position)
if wrapped.locked:
s.append('locked')
return s
def make_permalink(self, sr, force_domain=False):
from r2.lib.template_helpers import get_domain
p = "comments/%s/%s/" % (self._id36, title_to_url(self.title))
# promoted links belong to a separate subreddit and shouldn't
# include that in the path
if self.promoted is not None:
if force_domain:
permalink_domain = get_domain(subreddit=False)
res = "%s://%s/%s" % (g.default_scheme, permalink_domain, p)
else:
res = "/%s" % p
elif not force_domain:
res = "/r/%s/%s" % (sr.name, p)
elif sr != c.site or force_domain:
permalink_domain = get_domain(subreddit=False)
res = "%s://%s/r/%s/%s" % (g.default_scheme, permalink_domain,
sr.name, p)
else:
res = "/%s" % p
# WARNING: If we ever decide to add any ?foo=bar&blah parameters
# here, Comment.make_permalink will need to be updated or else
# it will fail.
return res
def make_permalink_slow(self, force_domain=False):
return self.make_permalink(self.subreddit_slow,
force_domain=force_domain)
def markdown_link_slow(self):
title = _force_unicode(self.title)
title = title.replace("[", r"\[")
title = title.replace("]", r"\]")
return "[%s](%s)" % (title, self.make_permalink_slow())
def _gild(self, user):
now = datetime.now(g.tz)
self._incr("gildings")
self.subreddit_slow.add_gilding_seconds()
GildedLinksByAccount.gild(user, self)
from r2.lib.db import queries
with CachedQueryMutator() as m:
gilding = utils.Storage(thing=self, date=now)
m.insert(queries.get_all_gilded_links(), [gilding])
m.insert(queries.get_gilded_links(self.sr_id), [gilding])
m.insert(queries.get_gilded_user_links(self.author_id),
[gilding])
m.insert(queries.get_user_gildings(user), [gilding])
hooks.get_hook('link.gild').call(link=self, gilder=user)
@staticmethod
def _should_expunge_selftext(link):
if not link._spam:
return False
if not c.user_is_loggedin:
return True
if c.user_is_admin:
return False
if c.user == link.author:
return False
if link.can_ban:
return False
return True
@classmethod
def update_nofollow(cls, user, wrapped):
user_is_loggedin = c.user_is_loggedin
for item in wrapped:
if user_is_loggedin and item.author_id == user._id:
item.nofollow = False
elif item._spam or item.author._spam:
item.nofollow = True
else:
item.nofollow = False
hooks.get_hook('link.update_nofollow').call(
user=user,
wrapped=wrapped,
)
@classmethod
def add_props(cls, user, wrapped):
from r2.lib.pages import make_link_child
from r2.lib.count import incr_counts
from r2.lib import media
from r2.lib.utils import timeago
from r2.lib.template_helpers import get_domain, unsafe, format_html
from r2.models.report import Report
from r2.lib.wrapped import CachedVariable
# referencing c's getattr is cheap, but not as cheap when it
# is in a loop that calls it 30 times on 25-200 things.
user_is_admin = c.user_is_admin
user_is_loggedin = c.user_is_loggedin
pref_media = user.pref_media
site = c.site
saved = hidden = visited = {}
if user_is_admin:
# Checking if a domain's banned isn't even cheap
urls = [item.url for item in wrapped if hasattr(item, 'url')]
# bans_for_domain_parts is just a generator; convert to a set for
# easy use of 'intersection'
from r2.models.admintools import bans_for_domain_parts
banned_domains = {ban.domain
for ban in bans_for_domain_parts(urls)}
if user_is_loggedin:
gilded = [thing for thing in wrapped if thing.gildings > 0]
try:
user_gildings = GildedLinksByAccount.fast_query(user, gilded)
except tdb_cassandra.TRANSIENT_EXCEPTIONS as e:
g.log.warning("Cassandra gilding lookup failed: %r", e)
user_gildings = {}
try:
saved = LinkSavesByAccount.fast_query(user, wrapped)
hidden = LinkHidesByAccount.fast_query(user, wrapped)
if user.gold and user.pref_store_visits:
visited = LinkVisitsByAccount.fast_query(user, wrapped)
except tdb_cassandra.TRANSIENT_EXCEPTIONS as e:
# saved or hidden or may have been done properly, so go ahead
# with what we do have
g.log.warning("Cassandra save/hide/visited lookup failed: %r", e)
# determine which subreddits the user could assign link flair in
if user_is_loggedin:
srs = {item.subreddit for item in wrapped
if item.subreddit.link_flair_position}
mod_flair_srids = {sr._id for sr in srs
if (user_is_admin or
sr.is_moderator_with_perms(c.user, 'flair'))}
author_flair_srids = {sr._id for sr in srs
if sr.link_flair_self_assign_enabled}
if user_is_loggedin:
srs = {item.subreddit for item in wrapped}
is_moderator_srids = {sr._id for sr in srs if sr.is_moderator(user)}
else:
is_moderator_srids = set()
# set the nofollow state where needed
cls.update_nofollow(user, wrapped)
for item in wrapped:
show_media = False
if not hasattr(item, "score_fmt"):
item.score_fmt = Score.number_only
if c.render_style in ('compact', extensions.api_type("compact")):
item.score_fmt = Score.safepoints
item.pref_compress = user.pref_compress
if user.pref_compress:
item.extra_css_class = "compressed"
item.score_fmt = Score.safepoints
elif pref_media == 'on' and not user.pref_compress:
show_media = True
elif pref_media == 'subreddit' and item.subreddit.show_media:
show_media = True
elif item.promoted and item.has_thumbnail:
if user_is_loggedin and item.author_id == user._id:
show_media = True
elif pref_media != 'off' and not user.pref_compress:
show_media = True
item.over_18 = item.over_18 or item.subreddit.over_18
item.nsfw = item.over_18 and user.pref_label_nsfw
item.quarantine = item.subreddit.quarantine
item.is_author = (user == item.author)
item.thumbnail_sprited = False
if item.quarantine:
item.thumbnail = ""
item.preview_image = None
# always show a promo author their own thumbnail
elif item.promoted and (user_is_admin or item.is_author) and item.has_thumbnail:
item.thumbnail = media.thumbnail_url(item)
item.preview_image = getattr(item, 'preview_object', None)
elif user.pref_no_profanity and item.over_18 and not c.site.over_18:
if show_media:
item.thumbnail = "nsfw"
item.thumbnail_sprited = True
else:
item.thumbnail = ""
item.preview_image = None
elif not show_media:
item.thumbnail = ""
item.preview_image = None
elif (item._deleted or
item._spam and item._date < timeago("6 hours")):
item.thumbnail = "default"
item.thumbnail_sprited = True
item.preview_image = None
elif item.has_thumbnail:
item.thumbnail = media.thumbnail_url(item)
item.preview_image = getattr(item, 'preview_object', None)
elif item.is_self:
item.thumbnail = "self"
item.thumbnail_sprited = True
item.preview_image = getattr(item, 'preview_object', None)
else:
item.thumbnail = "default"
item.thumbnail_sprited = True
item.preview_image = getattr(item, 'preview_object', None)
item.score = max(0, item.score)
if item.domain_override:
item.domain = item.domain_override
else:
item.domain = (domain(item.url) if not item.is_self
else 'self.' + item.subreddit.name)
if user_is_loggedin:
item.user_gilded = (user, item) in user_gildings
item.saved = (user, item) in saved
item.hidden = (user, item) in hidden
item.visited = (user, item) in visited
else:
item.user_gilded = False
item.saved = item.hidden = item.visited = False
if c.permalink_page or c.profilepage:
item.gilded_message = make_gold_message(item, item.user_gilded)
else:
item.gilded_message = ''
item.can_gild = (
c.user_is_loggedin and
# you can't gild your own submission
not (item.author and
item.author._id == user._id) and
# no point in showing the button for things you've already gilded
not item.user_gilded and
# ick, if the author deleted their account we shouldn't waste gold
not item.author._deleted and
# some subreddits can have gilding disabled
item.subreddit.allow_gilding and
not item._deleted
)
# set an attribute on the Wrapped item so that it will be
# added to the render cache key
if item.can_ban:
item.ignore_reports_key = item.ignore_reports
if c.user_is_loggedin and c.user.in_timeout:
item.mod_reports, item.user_reports = [], []
else:
item.mod_reports, item.user_reports = Report.get_reports(item)
item.num = None
item.permalink = item.make_permalink(item.subreddit)
if item.is_self:
item.url = item.make_permalink(item.subreddit,
force_domain=True)
if g.shortdomain:
item.shortlink = g.shortdomain + '/' + item._id36
item.domain_str = None
if c.user.pref_domain_details:
urlparser = UrlParser(item.url)
if (not item.is_self and urlparser.is_reddit_url() and
urlparser.is_web_safe_url()):
url_subreddit = urlparser.get_subreddit()
if (url_subreddit and
not isinstance(url_subreddit, DefaultSR)):
item.domain_str = ('{0}/r/{1}'
.format(item.domain,
url_subreddit.name))
elif isinstance(item.media_object, dict):
try:
author_url = item.media_object['oembed']['author_url']
if domain(author_url) == item.domain:
urlparser = UrlParser(author_url)
item.domain_str = strip_www(urlparser.hostname)
item.domain_str += urlparser.path
except KeyError:
pass
if not item.domain_str:
try:
author = item.media_object['oembed']['author_name']
author = _force_unicode(author)
item.domain_str = (_force_unicode('{0}: {1}')
.format(item.domain, author))
except KeyError:
pass
if not item.domain_str:
item.domain_str = item.domain
item.user_is_moderator = item.sr_id in is_moderator_srids
# do we hide the score?
if user_is_admin:
item.hide_score = False
elif user_is_loggedin and item.user_is_moderator:
item.hide_score = False
elif item.promoted and item.score <= 0:
item.hide_score = True
elif user == item.author:
item.hide_score = False
elif item._date > timeago("2 hours"):
item.hide_score = True
else:
item.hide_score = False
# is this link a member of a different (non-c.site) subreddit?
item.different_sr = (isinstance(site, FakeSubreddit) or
site.name != item.subreddit.name)
item.stickied = item._fullname in item.subreddit.get_sticky_fullnames()
# we only want to style a sticky specially if we're inside the
# subreddit that it's stickied in (not in places like front page)
item.use_sticky_style = item.stickied and not item.different_sr
item.subreddit_path = item.subreddit.path
item.domain_path = "/domain/%s/" % item.domain
if item.is_self:
item.domain_path = item.subreddit_path
# attach video or selftext as needed
item.link_child, item.editable = make_link_child(item)
if item.is_self and not item.promoted:
item.href_url = item.permalink
else:
item.href_url = item.url
item.fresh = not any((item.likes != None,
item.saved,
item.visited,
item.hidden,
item._deleted,
item._spam))
# bits that we will render stubs (to make the cached
# version more flexible)
item.num_text = CachedVariable("num")
item.commentcls = CachedVariable("commentcls")
item.comment_label = CachedVariable("numcomments")
item.lastedited = CachedVariable("lastedited")
item.as_deleted = False
if item.deleted and not c.user_is_admin:
item.author = DeletedUser()
item.as_deleted = True
item.selftext = '[deleted]'
item.votable = not item.archived
item.expunged = False
if item.is_self:
item.expunged = Link._should_expunge_selftext(item)
item.editted = getattr(item, "editted", False)
if user_is_loggedin:
can_mod_flair = item.subreddit._id in mod_flair_srids
can_author_flair = (item.is_author and
item.subreddit._id in author_flair_srids)
item.can_flair = can_mod_flair or can_author_flair
else:
item.can_flair = False
taglinetext = ''
if item.different_sr:
author_text = format_html(" <span>%s</span>",
_("by %(author)s to %(reddit)s"))
else:
author_text = format_html(" <span>%s</span>",
_("by %(author)s"))
if item.editted:
if item.score_fmt in (Score.points, Score.safepoints):
taglinetext = format_html("<span>%s</span>",
_("%(score)s submitted %(when)s "
"%(lastedited)s"))
taglinetext = unsafe(taglinetext + author_text)
elif item.different_sr:
taglinetext = _("submitted %(when)s %(lastedited)s "
"by %(author)s to %(reddit)s")
else:
taglinetext = _("submitted %(when)s %(lastedited)s "
"by %(author)s")
else:
if item.score_fmt in (Score.points, Score.safepoints):
taglinetext = format_html("<span>%s</span>",
_("%(score)s submitted %(when)s"))
taglinetext = unsafe(taglinetext + author_text)
elif item.different_sr:
taglinetext = _("submitted %(when)s by %(author)s "
"to %(reddit)s")
else:
taglinetext = _("submitted %(when)s by %(author)s")
item.taglinetext = taglinetext
if item.is_author:
item.should_incr_counts = False
if user_is_admin:
# Link notes
url = getattr(item, 'url')
# Pull just the relevant portions out of the url
urlf = sanitize_url(_force_unicode(url))
if urlf:
urlp = UrlParser(urlf)
hostname = urlp.hostname
if hostname:
parts = (hostname.encode("utf-8").rstrip(".").
split("."))
subparts = {".".join(parts[y:])
for y in xrange(len(parts))}
if subparts.intersection(banned_domains):
item.link_notes.append('banned domain')
# This is passed in promotedlink.html
item.ads_auction_enabled = feature.is_enabled('ads_auction')
if user_is_loggedin:
incr_counts(wrapped)
# Run this last
Printable.add_props(user, wrapped)
@property
def post_hint(self):
"""Returns a string that suggests the content of this link.
As a hint, this is lossy and may be inaccurate in some cases.
Currently one of:
* self
* video (a video file, like an mp4)
* image (an image file, like a gif or png)
* rich:video (a video embedded in HTML - like youtube or vimeo)
* link (catch-all)
"""
if self.is_self:
return 'self'
try:
oembed_type = self.media_object['oembed']['type']
except (KeyError, TypeError):
oembed_type = None
if oembed_type == 'photo':
return 'image'
if oembed_type == 'video':
return 'rich:video'
if oembed_type in {'link', 'rich'}:
return 'link'
p = UrlParser(self.url)
if p.has_image_extension():
return 'image'
if p.path_extension().lower() in {'mp4', 'webm'}:
return 'video'
return 'link'
@property
def subreddit_slow(self):
"""Returns the link's subreddit."""
# The subreddit is often already on the wrapped link as .subreddit
# If available, that should be used instead of calling this
return Subreddit._byID(self.sr_id, data=True, return_dict=False)
@property
def author_slow(self):
"""Returns the link's author."""
# The author is often already on the wrapped link as .author
# If available, that should be used instead of calling this
return Account._byID(self.author_id, data=True, return_dict=False)
@property
def responder_ids(self):
"""Returns an iterable of the OP and other official responders in a
thread.
Designed for Q&A-type threads (eg /r/iama).
"""
return (self.author_id,)
@property
def archived(self):
if getattr(self, 'subreddit', None):
sr = self.subreddit
else:
sr = self.subreddit_slow
return self._age >= sr.archive_age
def can_view_promo(self, user):
if self.promoted:
# promos are visible only if the user is either the author
# or the link is live/previously live.
is_author = c.user_is_loggedin and user._id == self.author_id
return (c.user_is_sponsor or
is_author or
self.promote_status >= PROMOTE_STATUS.promoted)
# not a promo, therefore it is visible
# this preserves the original behavior of `visible_promo()`
return True
def can_comment(self, user):
if getattr(self, 'subreddit', None):
sr = self.subreddit
else:
sr = self.subreddit_slow
if self.archived:
return False
if self.locked and not sr.can_distinguish(user):
return False
return sr.can_comment(user) and self.can_view_promo(user)
def sort_if_suggested(self):
"""Returns a sort, if the link or its subreddit has suggested one."""
if self.suggested_sort:
# A suggested sort of "blank" means explicitly empty: Do not obey
# the subreddit's suggested sort, either.
if self.suggested_sort == 'blank':
return None
return self.suggested_sort
sr = self.subreddit_slow
if sr.suggested_comment_sort:
return sr.suggested_comment_sort