from os import environ import random import re import time from urllib.parse import urlparse from flask import render_template from sqlalchemy import * from sqlalchemy.orm import relationship, deferred from files.__main__ import Base from files.helpers.const import * from files.helpers.regex import * from files.helpers.lazy import lazy from .flags import Flag from .comment import Comment, normalize_urls_runtime from flask import g from .sub import * from .votes import CommentVote def sort_posts(sort, posts): if sort == "new": return posts.order_by(Submission.created_utc.desc()) elif sort == "old": return posts.order_by(Submission.created_utc) elif sort == "controversial": return posts.order_by((Submission.upvotes+1)/(Submission.downvotes+1) + (Submission.downvotes+1)/(Submission.upvotes+1), Submission.downvotes.desc(), Submission.created_utc.desc()) elif sort == "bottom": return posts.order_by(Submission.realupvotes, Submission.created_utc.desc()) elif sort == "comments": return posts.order_by(Submission.comment_count.desc(), Submission.created_utc.desc()) else: return posts.order_by(Submission.realupvotes.desc(), Submission.created_utc.desc()) 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) 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) 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) author = relationship("User", primaryjoin="Submission.author_id==User.id") oauth_app = relationship("OauthApp", viewonly=True) approved_by = relationship("User", uselist=False, primaryjoin="Submission.is_approved==User.id", viewonly=True) awards = relationship("AwardRelationship", order_by="AwardRelationship.awarded_utc.desc()", viewonly=True) reports = relationship("Flag", viewonly=True) subr = relationship("Sub", primaryjoin="foreign(Submission.sub)==remote(Sub.name)", viewonly=True) 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 @lazy def flags(self, v): flags = g.db.query(Flag).filter_by(post_id=self.id).order_by(Flag.created_utc).all() if not (v and (v.shadowbanned or v.admin_level >= 2)): for flag in flags: if flag.user.shadowbanned: flags.remove(flag) return flags @property @lazy def options(self): return g.db.query(Comment).filter_by(parent_submission = self.id, author_id = AUTOPOLLER_ID, level=1).order_by(Comment.id).all() @property @lazy def choices(self): return g.db.query(Comment).filter_by(parent_submission = self.id, author_id = AUTOCHOICE_ID, level=1).order_by(Comment.id).all() @property @lazy def bet_options(self): return g.db.query(Comment).filter_by(parent_submission = self.id, author_id = AUTOBETTER_ID, level=1).all() @lazy def total_poll_voted(self, v): if v: for option in self.options: if option.poll_voted(v): return True return False @lazy def total_choice_voted(self, v): if v and self.choices: return g.db.query(CommentVote).filter(CommentVote.user_id == v.id, CommentVote.comment_id.in_([x.id for x in self.choices])).count() return False @lazy def total_bet_voted(self, v): if "closed" in self.body.lower(): return True if v: for option in self.bet_options: if option.poll_voted(v): 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 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): age = int(time.time()) - self.created_utc if age < 60: return "just now" elif age < 3600: minutes = int(age / 60) return f"{minutes}m ago" elif age < 86400: hours = int(age / 3600) return f"{hours}hr ago" elif age < 2678400: days = int(age / 86400) return f"{days}d ago" now = time.gmtime() ctd = time.gmtime(self.created_utc) months = now.tm_mon - ctd.tm_mon + 12 * (now.tm_year - ctd.tm_year) if now.tm_mday < ctd.tm_mday: months -= 1 if months < 12: return f"{months}mo ago" else: years = int(months / 12) return f"{years}yr ago" @property @lazy def edited_string(self): age = int(time.time()) - self.edited_utc if age < 60: return "just now" elif age < 3600: minutes = int(age / 60) return f"{minutes}m ago" elif age < 86400: hours = int(age / 3600) return f"{hours}hr ago" elif age < 2678400: days = int(age / 86400) return f"{days}d ago" now = time.gmtime() ctd = time.gmtime(self.edited_utc) months = now.tm_mon - ctd.tm_mon + 12 * (now.tm_year - ctd.tm_year) if now.tm_mday < ctd.tm_mday: months -= 1 if months < 12: return f"{months}mo ago" else: years = int(months / 12) return f"{years}yr ago" @property @lazy def edited_datetime(self): return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.edited_utc))) @property @lazy def score(self): return self.upvotes - self.downvotes @property @lazy def fullname(self): return f"t2_{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 None 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 '👻' else: return self.author.username @property @lazy def is_youtube(self): return self.domain == "youtube.com" and self.embed_url and self.embed_url.startswith('{CC} ONLY

" body = self.body_html or "" body = censor_slurs(body, v) body = normalize_urls_runtime(body, v) if v and v.shadowbanned and v.id == self.author_id and 86400 > time.time() - self.created_utc > 20: ti = max(int((time.time() - self.created_utc)/60), 1) maxupvotes = min(ti, 11) rand = random.randint(0, maxupvotes) if self.upvotes < rand: amount = random.randint(0, 3) if amount == 1: self.views += amount*random.randint(3, 5) self.upvotes += amount g.db.add(self) for c in self.options: body += f'
' if self.choices: curr = self.total_choice_voted(v) if curr: curr = " value=" + str(curr[0].comment_id) else: curr = '' body += f'' for c in self.choices: body += f'''
' for c in self.bet_options: body += f'''
200) or self.total_bet_voted(v) or not v.can_gamble: body += " disabled " body += f'''>" if v and v.admin_level > 2: body += f'''''' body += "
" if self.author.sig_html and (self.author_id == MOOSE_ID or (not self.ghost and not (v and v.sigs_disabled))): body += f"
{self.author.sig_html}" return body @lazy def plainbody(self, v): 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) 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) 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) return title @property @lazy def is_video(self): return self.url and any((self.url.lower().endswith(x) for x in ('.mp4','.webm','.mov'))) and is_safe_url(self.url) @property @lazy def is_audio(self): return self.url and any((self.url.lower().endswith(x) for x in ('.mp3','.wav','.ogg','.aac','.m4a','.flac'))) and is_safe_url(self.url) @property @lazy def is_image(self): if self.url and (self.url.lower().endswith('.webp') or self.url.lower().endswith('.jpg') or self.url.lower().endswith('.png') or self.url.lower().endswith('.gif') or self.url.lower().endswith('.jpeg') or self.url.lower().endswith('?maxwidth=9999') or self.url.lower().endswith('&fidelity=high')) and is_safe_url(self.url): return True return False @lazy def active_flags(self, v): return len(self.flags(v))