import random
import time
from urllib.parse import urlparse
from sqlalchemy import Column, FetchedValue, ForeignKey
from sqlalchemy.orm import deferred, relationship, scoped_session
from sqlalchemy.sql.sqltypes import *
from files.classes import Base
from files.helpers.const import *
from files.helpers.lazy import lazy
from files.helpers.regex import *
from files.helpers.sorting_and_time import make_age_string
from .comment import normalize_urls_runtime
from .polls import *
from .sub import *
from .subscriptions import *
class Submission(Base):
__tablename__ = "submissions"
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey("users.id"))
edited_utc = Column(Integer, default=0)
created_utc = Column(Integer)
thumburl = Column(String)
is_banned = Column(Boolean, default=False)
bannedfor = Column(String)
chuddedfor = Column(String)
ghost = Column(Boolean, default=False)
views = Column(Integer, default=0)
deleted_utc = Column(Integer, default=0)
distinguish_level = Column(Integer, default=0)
stickied = Column(String)
stickied_utc = Column(Integer)
hole_pinned = Column(String)
sub = Column(String, ForeignKey("subs.name"))
is_pinned = Column(Boolean, default=False)
private = Column(Boolean, default=False)
club = Column(Boolean, default=False)
comment_count = Column(Integer, default=0)
is_approved = Column(Integer, ForeignKey("users.id"))
over_18 = Column(Boolean, default=False)
is_bot = Column(Boolean, default=False)
upvotes = Column(Integer, default=1)
downvotes = Column(Integer, default=0)
realupvotes = Column(Integer, default=1)
app_id=Column(Integer, ForeignKey("oauth_apps.id"))
title = Column(String)
title_html = Column(String)
url = Column(String)
body = Column(String)
body_html = Column(String)
flair = Column(String)
ban_reason = Column(String)
embed_url = Column(String)
new = Column(Boolean)
notify = Column(Boolean)
author = relationship("User", primaryjoin="Submission.author_id==User.id")
oauth_app = relationship("OauthApp")
approved_by = relationship("User", uselist=False, primaryjoin="Submission.is_approved==User.id")
awards = relationship("AwardRelationship", order_by="AwardRelationship.awarded_utc.desc()", back_populates="post")
flags = relationship("Flag", order_by="Flag.created_utc")
comments = relationship("Comment", primaryjoin="Comment.parent_submission==Submission.id", back_populates="post")
subr = relationship("Sub", primaryjoin="foreign(Submission.sub)==remote(Sub.name)")
options = relationship("SubmissionOption", order_by="SubmissionOption.id")
bump_utc = deferred(Column(Integer, server_default=FetchedValue()))
def __init__(self, *args, **kwargs):
if "created_utc" not in kwargs: kwargs["created_utc"] = int(time.time())
super().__init__(*args, **kwargs)
def __repr__(self):
return f""
@property
@lazy
def controversial(self):
if self.downvotes > 5 and 0.25 < self.upvotes / self.downvotes < 4: return True
return False
@property
@lazy
def created_datetime(self):
return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)))
@property
@lazy
def age_string(self):
return make_age_string(self.created_utc)
@property
@lazy
def edited_string(self):
return make_age_string(self.edited_utc)
@property
@lazy
def score(self):
return self.upvotes - self.downvotes
@property
@lazy
def fullname(self):
return f"p_{self.id}"
@property
@lazy
def shortlink(self):
link = f"/post/{self.id}"
if self.sub: link = f"/h/{self.sub}{link}"
if self.club: return link + '/-'
output = title_regex.sub('', self.title.lower())
output = output.split()[:6]
output = '-'.join(output)
if not output: output = '-'
return f"{link}/{output}"
@property
@lazy
def permalink(self):
return SITE_FULL + self.shortlink
@property
@lazy
def domain(self):
if not self.url: return ''
if self.url.startswith('/'): return SITE
domain = urlparse(self.url).netloc
if domain.startswith("www."): domain = domain.split("www.")[1]
return domain.replace("old.reddit.com", "reddit.com")
@property
@lazy
def author_name(self):
if self.ghost: return '👻'
return self.author.user_name
@property
@lazy
def is_youtube(self):
return self.domain == "youtube.com" and self.embed_url and self.embed_url.startswith('{CC} ONLY
"
if self.deleted_utc != 0 and not (v and (v.admin_level >= PERMS['POST_COMMENT_MODERATION'] or v.id == self.author.id)): return "[Deleted by user]"
if self.is_banned and not (v and v.admin_level >= PERMS['POST_COMMENT_MODERATION']) and not (v and v.id == self.author.id): return ""
body = self.body_html or ""
body = censor_slurs(body, v)
body = normalize_urls_runtime(body, v)
if self.options:
curr = [x for x in self.options if x.exclusive and x.voted(v)]
if curr: curr = " value=post-" + str(curr[0].id)
else: curr = ''
body += f''
winner = [x for x in self.options if x.exclusive == 3]
for o in self.options:
if o.exclusive > 1:
body += f'''
= POLL_BET_COINS) or self.total_bet_voted(v): body += " disabled "
body += f'''>"
if o.exclusive == 3:
body += " - WINNER!"
if not winner and v and v.admin_level >= PERMS['POST_BETS_DISTRIBUTE']:
body += f''''''
body += "
"
else:
input_type = 'radio' if o.exclusive else 'checkbox'
body += f''''
if not listing and not self.ghost and self.author.show_sig(v):
body += f"{self.author.sig_html}"
return body
@lazy
def plainbody(self, v):
if self.deleted_utc != 0 and not (v and (v.admin_level >= PERMS['POST_COMMENT_MODERATION'] or v.id == self.author.id)): return "[Deleted by user]"
if self.is_banned and not (v and v.admin_level >= PERMS['POST_COMMENT_MODERATION']) and not (v and v.id == self.author.id): return ""
if self.club and not (v and (v.paid_dues or v.id == self.author_id)): return f"
{CC} ONLY
"
body = self.body
if not body: return ""
body = censor_slurs(body, v).replace('', ':marseytrain:')
body = normalize_urls_runtime(body, v)
return body
@lazy
def realtitle(self, v):
if self.club and not (v and (v.paid_dues or v.id == self.author_id)):
if v: return random.choice(TROLLTITLES).format(username=v.username)
elif DUES == -2: return f'Please make an account to see this post'
else: return f'{CC} MEMBERS ONLY'
elif self.title_html: title = self.title_html
else: title = self.title
title = censor_slurs(title, v)
if v:
title = title.replace("!YOU!", v.username)
return title
@lazy
def plaintitle(self, v):
if self.club and not (v and (v.paid_dues or v.id == self.author_id)):
if v: return random.choice(TROLLTITLES).format(username=v.username)
else: return f'{CC} MEMBERS ONLY'
else: title = self.title
title = censor_slurs(title, v).replace('', ':marseytrain:')
if v:
title = title.replace("!YOU!", v.username)
return title
@property
@lazy
def is_video(self):
return self.url and any((self.url.lower().split('?')[0].endswith(f'.{x}') for x in VIDEO_FORMATS)) and is_safe_url(self.url)
@property
@lazy
def is_audio(self):
return self.url and any((self.url.lower().split('?')[0].endswith(f'.{x}') for x in AUDIO_FORMATS)) and is_safe_url(self.url)
@property
@lazy
def is_image(self):
return self.url and any((self.url.lower().split('?')[0].endswith(f'.{x}') for x in IMAGE_FORMATS)) and is_safe_url(self.url)
@lazy
def filtered_flags(self, v):
return [f for f in self.flags if (v and v.shadowbanned) or not f.user.shadowbanned]
@lazy
def active_flags(self, v):
return len(self.filtered_flags(v))