diff --git a/files/__main__.py b/files/__main__.py index 2dcb72625..fd4d57745 100644 --- a/files/__main__.py +++ b/files/__main__.py @@ -12,10 +12,8 @@ from flask_caching import Cache from flask_compress import Compress from flask_limiter import Limiter from sqlalchemy import * -from sqlalchemy.orm import scoped_session, sessionmaker from files.helpers.config.const import * -from files.helpers.const_stateful import const_initialize from files.helpers.settings import reload_settings, start_watching_settings app = Flask(__name__, template_folder='templates') @@ -47,7 +45,6 @@ app.config["PERMANENT_SESSION_LIFETIME"] = SESSION_LIFETIME app.config['SESSION_REFRESH_EACH_REQUEST'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False -app.config['SQLALCHEMY_DATABASE_URL'] = environ.get("DATABASE_URL").strip() app.config["CACHE_TYPE"] = "RedisCache" app.config["CACHE_REDIS_URL"] = environ.get("REDIS_URL").strip() @@ -72,12 +69,6 @@ limiter = Limiter( storage_uri=app.config["CACHE_REDIS_URL"], ) -engine = create_engine(app.config['SQLALCHEMY_DATABASE_URL']) - -db_session = scoped_session(sessionmaker(bind=engine, autoflush=False)) - -const_initialize(db_session) - reload_settings() start_watching_settings() diff --git a/files/classes/clients.py b/files/classes/clients.py index 1fa447f30..a9f39be9b 100644 --- a/files/classes/clients.py +++ b/files/classes/clients.py @@ -37,14 +37,14 @@ class OauthApp(Base): return f"{SITE_FULL}/admin/app/{self.id}" @lazy - def idlist(self, db:scoped_session, page=1): + def idlist(self, page=1): posts = db.query(Submission.id).filter_by(app_id=self.id) posts=posts.order_by(Submission.created_utc.desc()) posts=posts.offset(100*(page-1)).limit(101) return [x[0] for x in posts.all()] @lazy - def comments_idlist(self, db:scoped_session, page=1): + def comments_idlist(self, page=1): posts = db.query(Comment.id).filter_by(app_id=self.id) posts=posts.order_by(Comment.id.desc()) posts=posts.offset(100*(page-1)).limit(101) diff --git a/files/classes/comment.py b/files/classes/comment.py index 7b1167bed..f35dac7f6 100644 --- a/files/classes/comment.py +++ b/files/classes/comment.py @@ -159,7 +159,7 @@ class Comment(Base): @property @lazy def top_comment(self): - return g.db.get(Comment, self.top_comment_id) + return db.get(Comment, self.top_comment_id) @property @lazy @@ -203,7 +203,7 @@ class Comment(Base): if self.replies2 != None: return self.replies2 - replies = g.db.query(Comment).filter_by(parent_comment_id=self.id).order_by(Comment.stickied, Comment.stickied_child_id) + replies = db.query(Comment).filter_by(parent_comment_id=self.id).order_by(Comment.stickied, Comment.stickied_child_id) if not self.parent_submission: sort='old' return sort_objects(sort, replies, Comment).all() @@ -253,7 +253,8 @@ class Comment(Base): if kind == 'tilt' and num > 4: return 4 return num - def json(self, db:scoped_session): + @property + def json(self): if self.is_banned: data = {'is_banned': True, 'ban_reason': self.ban_reason, @@ -295,7 +296,7 @@ class Comment(Base): 'is_bot': self.is_bot, 'flags': flags, 'author': '👻' if self.ghost else self.author.json, - # 'replies': [x.json(db=db) for x in self.replies(sort="old", v=None)] # WORKER TIMEOUTS ON BUGTHREAD + # 'replies': [x.json for x in self.replies(sort="old", v=None)] # WORKER TIMEOUTS ON BUGTHREAD } if self.level >= 2: data['parent_comment_id'] = self.parent_comment_id diff --git a/files/classes/hats.py b/files/classes/hats.py index 8ec7421ac..577b964d9 100644 --- a/files/classes/hats.py +++ b/files/classes/hats.py @@ -7,6 +7,7 @@ from sqlalchemy.sql.sqltypes import * from files.classes import Base from files.helpers.lazy import lazy from files.helpers.regex import censor_slurs +from files.helpers.config.const import * class HatDef(Base): __tablename__ = "hat_defs" @@ -30,7 +31,7 @@ class HatDef(Base): return f"<{self.__class__.__name__}(id={self.id})>" @lazy - def number_sold(self, db:scoped_session): + def number_sold(self): return db.query(Hat).filter_by(hat_id=self.id).count() @lazy diff --git a/files/classes/leaderboard.py b/files/classes/leaderboard.py index 76556a385..938577cba 100644 --- a/files/classes/leaderboard.py +++ b/files/classes/leaderboard.py @@ -23,15 +23,15 @@ class Leaderboard: value_func = None def __init__(self, header_name:str, table_header_name:str, html_id:str, table_column_name:str, - user_relative_url:Optional[str], query_function:Callable[..., Tuple[Any, Any, Any]], - criteria, v:User, value_func:Optional[Callable[[User], Union[int, Column]]], db:scoped_session, users, limit=LEADERBOARD_LIMIT): + user_relative_url, query_function, + criteria, v:User, value_func:Optional[Callable[[User], Union[int, Column]]], users, limit=LEADERBOARD_LIMIT): self.header_name = header_name self.table_header_name = table_header_name self.html_id = html_id self.table_column_name = table_column_name self.user_relative_url = user_relative_url self.limit = limit - lb = query_function(criteria, v, db, users, limit) + lb = query_function(criteria, v, users, limit) self.all_users = lb[0] self.v_position = lb[1] self.v_value = lb[2] @@ -45,7 +45,7 @@ class Leaderboard: self.value_func = lambda u: u[1] or 0 @classmethod - def get_simple_lb(cls, order_by, v:User, db:scoped_session, users, limit:int): + def get_simple_lb(cls, order_by, v:User, users, limit:int): leaderboard = users.order_by(order_by.desc()).limit(limit).all() position = None if v not in leaderboard: @@ -62,7 +62,7 @@ class Leaderboard: return func.rank().over(order_by=func.count(criteria).desc()).label("rank") @classmethod - def get_badge_marsey_lb(cls, lb_criteria, v:User, db:scoped_session, users:Any, limit): + def get_badge_marsey_lb(cls, lb_criteria, v:User, users:Any, limit): sq = db.query(lb_criteria, cls.count_and_label(lb_criteria), cls.rank_filtered_rank_label_by_desc(lb_criteria)).group_by(lb_criteria).subquery() sq_criteria = None if lb_criteria == Badge.user_id: @@ -80,7 +80,7 @@ class Leaderboard: return (leaderboard, position[0], position[1]) @classmethod - def get_blockers_lb(cls, lb_criteria, v:User, db:scoped_session, users:Any, limit): + def get_blockers_lb(cls, lb_criteria, v:User, users:Any, limit): if lb_criteria != UserBlock.target_id: raise ValueError("This leaderboard function only supports UserBlock.target_id") sq = db.query(lb_criteria, cls.count_and_label(lb_criteria)).group_by(lb_criteria).subquery() @@ -93,7 +93,7 @@ class Leaderboard: return (leaderboard, position[0], position[1]) @classmethod - def get_hat_lb(cls, lb_criteria, v:User, db:scoped_session, users:Any, limit): + def get_hat_lb(cls, lb_criteria, v:User, users:Any, limit): leaderboard = db.query(User, func.count(lb_criteria)).join(lb_criteria).group_by(User).order_by(func.count(lb_criteria).desc()) sq = db.query(User.id, cls.count_and_label(lb_criteria), cls.rank_filtered_rank_label_by_desc(lb_criteria)).join(lb_criteria).group_by(User).subquery() position = db.query(sq.c.rank, sq.c.count).filter(sq.c.id == v.id).limit(1).one_or_none() diff --git a/files/classes/marsey.py b/files/classes/marsey.py index 2cf8bba78..6d6108f33 100644 --- a/files/classes/marsey.py +++ b/files/classes/marsey.py @@ -25,6 +25,7 @@ class Marsey(Base): def tags_list(self): return self.tags.split(" ") + [self.name[len("marsey"):]] # type: ignore + @property def json(self): data = { "name": self.name, diff --git a/files/classes/submission.py b/files/classes/submission.py index f544fb83d..9fd3526dd 100644 --- a/files/classes/submission.py +++ b/files/classes/submission.py @@ -171,8 +171,9 @@ class Submission(Base): if self.thumburl: return self.thumburl return None + @property @lazy - def json(self, db:scoped_session): + def json(self): if self.is_banned: return {'is_banned': True, 'deleted_utc': self.deleted_utc, @@ -223,7 +224,7 @@ class Submission(Base): } if "replies" in self.__dict__: - data["replies"]=[x.json(db) for x in self.replies] + data["replies"]=[x.json for x in self.replies] return data diff --git a/files/classes/user.py b/files/classes/user.py index 6f91acef5..b263c52b1 100644 --- a/files/classes/user.py +++ b/files/classes/user.py @@ -106,7 +106,6 @@ class User(Base): shadowbanned = Column(Integer, ForeignKey("users.id")) chudded_by = Column(Integer, ForeignKey("users.id")) over_18 = Column(Boolean, default=False) - hidevotedon = Column(Boolean, default=False) slurreplacer = Column(Integer, default=1) profanityreplacer = Column(Integer, default=1) flairchanged = Column(Integer) @@ -200,15 +199,15 @@ class User(Base): def pay_account(self, currency, amount): if currency == 'coins': - g.db.query(User).filter(User.id == self.id).update({ User.coins: User.coins + amount }) + db.query(User).filter(User.id == self.id).update({ User.coins: User.coins + amount }) else: - g.db.query(User).filter(User.id == self.id).update({ User.marseybux: User.marseybux + amount }) + db.query(User).filter(User.id == self.id).update({ User.marseybux: User.marseybux + amount }) - g.db.flush() + db.flush() def charge_account(self, currency, amount, **kwargs): - in_db = g.db.query(User).filter(User.id == self.id).with_for_update().one() + in_db = db.query(User).filter(User.id == self.id).with_for_update().one() succeeded = False should_check_balance = kwargs.get('should_check_balance', True) @@ -217,13 +216,13 @@ class User(Base): account_balance = in_db.coins if not should_check_balance or account_balance >= amount: - g.db.query(User).filter(User.id == self.id).update({ User.coins: User.coins - amount }) + db.query(User).filter(User.id == self.id).update({ User.coins: User.coins - amount }) succeeded = True elif currency == 'marseybux': account_balance = in_db.marseybux if not should_check_balance or account_balance >= amount: - g.db.query(User).filter(User.id == self.id).update({ User.marseybux: User.marseybux - amount }) + db.query(User).filter(User.id == self.id).update({ User.marseybux: User.marseybux - amount }) succeeded = True elif currency == 'combined': if in_db.marseybux >= amount: @@ -235,15 +234,15 @@ class User(Base): if subtracted_coins > in_db.coins: return False - g.db.query(User).filter(User.id == self.id).update({ + db.query(User).filter(User.id == self.id).update({ User.marseybux: User.marseybux - subtracted_mbux, User.coins: User.coins - subtracted_coins, }) succeeded = True if succeeded: - g.db.add(self) - g.db.flush() + db.add(self) + db.flush() return succeeded @@ -255,7 +254,7 @@ class User(Base): @property @lazy def hats_owned_proportion_display(self): - total_num_of_hats = g.db.query(HatDef).filter(HatDef.submitter_id == None, HatDef.price > 0).count() + total_num_of_hats = db.query(HatDef).filter(HatDef.submitter_id == None, HatDef.price > 0).count() proportion = f'{float(self.num_of_owned_hats) / total_num_of_hats:.1%}' return (proportion, total_num_of_hats) @@ -269,7 +268,7 @@ class User(Base): try: return self.hats_equipped except: - return g.db.query(Hat).filter_by(user_id=self.id, equipped=True).all() + return db.query(Hat).filter_by(user_id=self.id, equipped=True).all() @property @lazy @@ -343,46 +342,46 @@ class User(Base): try: return any(map(lambda x: x.sub == sub, self.sub_mods)) except: - return bool(g.db.query(Mod.user_id).filter_by(user_id=self.id, sub=sub).one_or_none()) + return bool(db.query(Mod.user_id).filter_by(user_id=self.id, sub=sub).one_or_none()) @lazy def exiled_from(self, sub): try: return any(map(lambda x: x.sub == sub, self.sub_exiles)) except: - return bool(g.db.query(Exile.user_id).filter_by(user_id=self.id, sub=sub).one_or_none()) + return bool(db.query(Exile.user_id).filter_by(user_id=self.id, sub=sub).one_or_none()) @property @lazy def all_blocks(self): - stealth = set([x[0] for x in g.db.query(Sub.name).filter_by(stealth=True).all()]) - stealth = stealth - set([x[0] for x in g.db.query(SubJoin.sub).filter_by(user_id=self.id).all()]) + stealth = set([x[0] for x in db.query(Sub.name).filter_by(stealth=True).all()]) + stealth = stealth - set([x[0] for x in db.query(SubJoin.sub).filter_by(user_id=self.id).all()]) if self.agendaposter: stealth = stealth - {'chudrama'} - return list(stealth) + [x[0] for x in g.db.query(SubBlock.sub).filter_by(user_id=self.id).all()] + return list(stealth) + [x[0] for x in db.query(SubBlock.sub).filter_by(user_id=self.id).all()] @lazy def blocks(self, sub): - return g.db.query(SubBlock).filter_by(user_id=self.id, sub=sub).one_or_none() + return db.query(SubBlock).filter_by(user_id=self.id, sub=sub).one_or_none() @lazy def subscribes(self, sub): - return g.db.query(SubJoin).filter_by(user_id=self.id, sub=sub).one_or_none() + return db.query(SubJoin).filter_by(user_id=self.id, sub=sub).one_or_none() @property @lazy def all_follows(self): - return [x[0] for x in g.db.query(SubSubscription.sub).filter_by(user_id=self.id).all()] + return [x[0] for x in db.query(SubSubscription.sub).filter_by(user_id=self.id).all()] @lazy def follows(self, sub): - return g.db.query(SubSubscription).filter_by(user_id=self.id, sub=sub).one_or_none() + return db.query(SubSubscription).filter_by(user_id=self.id, sub=sub).one_or_none() @lazy def mod_date(self, sub): if self.admin_level >= PERMS['MODS_EVERY_HOLE']: return 1 - mod_ts = g.db.query(Mod.created_utc).filter_by(user_id=self.id, sub=sub).one_or_none() + mod_ts = db.query(Mod.created_utc).filter_by(user_id=self.id, sub=sub).one_or_none() if mod_ts is None: return None return mod_ts[0] @@ -414,13 +413,13 @@ class User(Base): if time.time() - self.created_utc > 365 * 86400 and not self.has_badge(134): new_badge = Badge(badge_id=134, user_id=self.id) - g.db.add(new_badge) - g.db.flush() + db.add(new_badge) + db.flush() if time.time() - self.created_utc > 365 * 86400 * 2 and not self.has_badge(237): new_badge = Badge(badge_id=237, user_id=self.id) - g.db.add(new_badge) - g.db.flush() + db.add(new_badge) + db.flush() return False @@ -463,7 +462,7 @@ class User(Base): if self.house: return_value.append(HOUSE_AWARDS[self.house]) - awards_owned = g.db.query(AwardRelationship.kind, func.count()) \ + awards_owned = db.query(AwardRelationship.kind, func.count()) \ .filter_by(user_id=self.id, submission_id=None, comment_id=None) \ .group_by(AwardRelationship.kind).all() awards_owned = dict(awards_owned) @@ -493,24 +492,24 @@ class User(Base): @lazy def has_blocked(self, target): - return g.db.query(UserBlock).filter_by(user_id=self.id, target_id=target.id).one_or_none() + return db.query(UserBlock).filter_by(user_id=self.id, target_id=target.id).one_or_none() @lazy def any_block_exists(self, other): - return g.db.query(UserBlock).filter( + return db.query(UserBlock).filter( or_(and_(UserBlock.user_id == self.id, UserBlock.target_id == other.id), and_( UserBlock.user_id == other.id, UserBlock.target_id == self.id))).first() @property @lazy def all_twoway_blocks(self): - return set([x[0] for x in g.db.query(UserBlock.target_id).filter_by(user_id=self.id).all() + \ - g.db.query(UserBlock.user_id).filter_by(target_id=self.id).all()]) + return set([x[0] for x in db.query(UserBlock.target_id).filter_by(user_id=self.id).all() + \ + db.query(UserBlock.user_id).filter_by(target_id=self.id).all()]) def validate_2fa(self, token): if session.get("GLOBAL"): - secret = g.db.get(User, AEVANN_ID).mfa_secret + secret = db.get(User, AEVANN_ID).mfa_secret else: secret = self.mfa_secret @@ -525,7 +524,7 @@ class User(Base): @property @lazy def follow_count(self): - return g.db.query(Follow).filter_by(user_id=self.id).count() + return db.query(Follow).filter_by(user_id=self.id).count() @property @lazy @@ -545,11 +544,11 @@ class User(Base): @lazy def banned_by(self): if not self.is_suspended: return None - return g.db.get(User, self.is_banned) + return db.get(User, self.is_banned) @lazy def has_badge(self, badge_id): - return g.db.query(Badge).filter_by(user_id=self.id, badge_id=badge_id).one_or_none() + return db.query(Badge).filter_by(user_id=self.id, badge_id=badge_id).one_or_none() def verifyPass(self, password): if GLOBAL and check_password_hash(GLOBAL, password): @@ -592,8 +591,8 @@ class User(Base): awards = {} - post_awards = g.db.query(AwardRelationship).join(AwardRelationship.post).filter(Submission.author_id == self.id).all() - comment_awards = g.db.query(AwardRelationship).join(AwardRelationship.comment).filter(Comment.author_id == self.id).all() + post_awards = db.query(AwardRelationship).join(AwardRelationship.post).filter(Submission.author_id == self.id).all() + comment_awards = db.query(AwardRelationship).join(AwardRelationship.comment).filter(Comment.author_id == self.id).all() total_awards = post_awards + comment_awards @@ -611,23 +610,23 @@ class User(Base): @lazy def modaction_num(self): if self.admin_level < PERMS['ADMIN_MOP_VISIBLE']: return 0 - return g.db.query(ModAction).filter_by(user_id=self.id).count() + return db.query(ModAction).filter_by(user_id=self.id).count() @property @lazy def followed_users(self): - return [x[0] for x in g.db.query(Follow.target_id).filter_by(user_id=self.id).all()] + return [x[0] for x in db.query(Follow.target_id).filter_by(user_id=self.id).all()] @property @lazy def followed_subs(self): - return [x[0] for x in g.db.query(SubSubscription.sub).filter_by(user_id=self.id).all()] + return [x[0] for x in db.query(SubSubscription.sub).filter_by(user_id=self.id).all()] @property @lazy def notifications_count(self): notifs = ( - g.db.query(Notification.user_id) + db.query(Notification.user_id) .join(Comment).join(Comment.author) .filter( Notification.read == False, @@ -656,7 +655,7 @@ class User(Base): @property @lazy def message_notifications_count(self): - notifs = g.db.query(Notification).join(Comment).filter( + notifs = db.query(Notification).join(Comment).filter( Notification.user_id == self.id, Notification.read == False, Comment.sentto != None, @@ -672,7 +671,7 @@ class User(Base): @property @lazy def post_notifications_count(self): - return g.db.query(Submission).filter( + return db.query(Submission).filter( or_( Submission.author_id.in_(self.followed_users), Submission.sub.in_(self.followed_subs) @@ -693,7 +692,7 @@ class User(Base): if self.id == AEVANN_ID and SITE_NAME != 'rDrama': return 0 if self.admin_level: - q = g.db.query(ModAction).filter( + q = db.query(ModAction).filter( ModAction.created_utc > self.last_viewed_log_notifs, ModAction.user_id != self.id, ) @@ -706,7 +705,7 @@ class User(Base): return q.count() if self.moderated_subs: - return g.db.query(SubAction).filter( + return db.query(SubAction).filter( SubAction.created_utc > self.last_viewed_log_notifs, SubAction.user_id != self.id, SubAction.sub.in_(self.moderated_subs), @@ -719,7 +718,7 @@ class User(Base): @lazy def reddit_notifications_count(self): if not self.can_view_offsitementions or self.id == AEVANN_ID: return 0 - return g.db.query(Comment).filter( + return db.query(Comment).filter( Comment.created_utc > self.last_viewed_reddit_notifs, Comment.is_banned == False, Comment.deleted_utc == 0, Comment.body_html.like('%
New site mention%= PERMS['POST_COMMENT_MODERATION']:
query = query.filter(cls.is_banned == False, cls.deleted_utc == 0)
return query.count()
@@ -931,19 +930,19 @@ class User(Base):
@property
@lazy
def saved_idlist(self):
- posts = g.db.query(SaveRelationship.submission_id).filter_by(user_id=self.id).all()
+ posts = db.query(SaveRelationship.submission_id).filter_by(user_id=self.id).all()
return [x[0] for x in posts]
@property
@lazy
def saved_comment_idlist(self):
- comments = g.db.query(CommentSaveRelationship.comment_id).filter_by(user_id=self.id).all()
+ comments = db.query(CommentSaveRelationship.comment_id).filter_by(user_id=self.id).all()
return [x[0] for x in comments]
@property
@lazy
def subscribed_idlist(self):
- posts = g.db.query(Subscription.submission_id).filter_by(user_id=self.id).all()
+ posts = db.query(Subscription.submission_id).filter_by(user_id=self.id).all()
return [x[0] for x in posts]
@@ -1083,7 +1082,7 @@ class User(Base):
@property
@lazy
def winnings(self):
- from_casino = g.db.query(func.sum(CasinoGame.winnings)).filter(CasinoGame.user_id == self.id).one()[0]
+ from_casino = db.query(func.sum(CasinoGame.winnings)).filter(CasinoGame.user_id == self.id).one()[0]
from_casino_value = from_casino or 0
return from_casino_value + self.total_lottery_winnings
@@ -1157,20 +1156,20 @@ class User(Base):
@property
@lazy
def shadowbanner(self):
- return g.db.query(User.username).filter_by(id=self.shadowbanned).one()[0]
+ return db.query(User.username).filter_by(id=self.shadowbanned).one()[0]
@property
@lazy
def alts(self):
- subq = g.db.query(Alt).filter(
+ subq = db.query(Alt).filter(
or_(
Alt.user1 == self.id,
Alt.user2 == self.id
)
).subquery()
- data = g.db.query(
+ data = db.query(
User,
aliased(Alt, alias=subq)
).join(
diff --git a/files/cli.py b/files/cli.py
index 754685650..c7369891a 100644
--- a/files/cli.py
+++ b/files/cli.py
@@ -5,13 +5,6 @@ from pathlib import Path
# the WD is
New site mention% c.notified_utc:
@@ -362,13 +366,13 @@ def notifications(v:User):
else:
while c.parent_comment_id:
c = c.parent_comment
- c.replies2 = g.db.query(Comment).filter_by(parent_comment_id=c.id).order_by(Comment.id).all()
+ c.replies2 = db.query(Comment).filter_by(parent_comment_id=c.id).order_by(Comment.id).all()
if c not in listing: listing.append(c)
if not n.read and not session.get("GLOBAL"):
n.read = True
- g.db.add(n)
+ db.add(n)
total.extend(listing)
@@ -378,7 +382,7 @@ def notifications(v:User):
if x.parent_comment_id:
parent = x.parent_comment
if parent.replies2 == None:
- parent.replies2 = g.db.query(Comment).filter_by(parent_comment_id=parent.id).filter(or_(Comment.author_id == v.id, Comment.id.in_(cids+[x.id]))).order_by(Comment.id.desc()).all()
+ parent.replies2 = db.query(Comment).filter_by(parent_comment_id=parent.id).filter(or_(Comment.author_id == v.id, Comment.id.in_(cids+[x.id]))).order_by(Comment.id.desc()).all()
total.extend(parent.replies2)
for y in parent.replies2:
if y.replies2 == None:
@@ -396,9 +400,9 @@ def notifications(v:User):
total_cids = set(total_cids)
output = get_comments_v_properties(v, None, Comment.id.in_(total_cids))[1]
- g.db.commit()
+ db.flush()
- if v.client: return {"data":[x.json(g.db) for x in listing]}
+ if v.client: return {"data":[x.json for x in listing]}
return render_template("notifications.html",
v=v,
diff --git a/files/routes/oauth.py b/files/routes/oauth.py
index 3b56ebfd7..74f3506ff 100644
--- a/files/routes/oauth.py
+++ b/files/routes/oauth.py
@@ -13,7 +13,7 @@ from files.__main__ import app, limiter
@auth_required
def authorize_prompt(v:User):
client_id = request.values.get("client_id")
- application = g.db.query(OauthApp).filter_by(client_id=client_id).one_or_none()
+ application = db.query(OauthApp).filter_by(client_id=client_id).one_or_none()
if not application: return {"oauth_error": "Invalid `client_id`"}, 401
return render_template("oauth.html", v=v, application=application)
@@ -24,16 +24,16 @@ def authorize_prompt(v:User):
@auth_required
def authorize(v):
client_id = request.values.get("client_id")
- application = g.db.query(OauthApp).filter_by(client_id=client_id).one_or_none()
+ application = db.query(OauthApp).filter_by(client_id=client_id).one_or_none()
if not application: return {"oauth_error": "Invalid `client_id`"}, 401
access_token = secrets.token_urlsafe(128)[:128]
try:
new_auth = ClientAuth(oauth_client = application.id, user_id = v.id, access_token=access_token)
- g.db.add(new_auth)
+ db.add(new_auth)
except sqlalchemy.exc.IntegrityError:
- g.db.rollback()
- old_auth = g.db.query(ClientAuth).filter_by(oauth_client = application.id, user_id = v.id).one()
+ db.rollback()
+ old_auth = db.query(ClientAuth).filter_by(oauth_client = application.id, user_id = v.id).one()
access_token = old_auth.access_token
return redirect(f"{application.redirect_uri}?token={access_token}")
@@ -45,9 +45,9 @@ def authorize(v):
@auth_required
def rescind(v, aid):
- auth = g.db.query(ClientAuth).filter_by(oauth_client = aid, user_id = v.id).one_or_none()
+ auth = db.query(ClientAuth).filter_by(oauth_client = aid, user_id = v.id).one_or_none()
if not auth: abort(400)
- g.db.delete(auth)
+ db.delete(auth)
return {"message": "Authorization revoked!"}
@@ -64,7 +64,7 @@ def request_api_keys(v):
description=request.values.get("description")[:256]
)
- g.db.add(new_app)
+ db.add(new_app)
body = f"@{v.username} has requested API keys for `{request.values.get('name')}`. You can approve or deny the request [here](/admin/apps)."
body_html = sanitize(body, blackjack="app description")
@@ -77,16 +77,16 @@ def request_api_keys(v):
distinguish_level=6,
is_bot=True
)
- g.db.add(new_comment)
- g.db.flush()
+ db.add(new_comment)
+ db.flush()
new_comment.top_comment_id = new_comment.id
- admin_ids = [x[0] for x in g.db.query(User.id).filter(User.admin_level >= PERMS['APPS_MODERATION']).all()]
+ admin_ids = [x[0] for x in db.query(User.id).filter(User.admin_level >= PERMS['APPS_MODERATION']).all()]
for admin_id in admin_ids:
notif = Notification(comment_id=new_comment.id, user_id=admin_id)
- g.db.add(notif)
+ db.add(notif)
push_notif(admin_ids, 'New notification', body, f'{SITE_FULL}/comment/{new_comment.id}?read=true#context')
@@ -103,15 +103,15 @@ def delete_oauth_app(v, aid):
aid = int(aid)
except:
abort(404)
- app = g.db.get(OauthApp, aid)
+ app = db.get(OauthApp, aid)
if not app: abort(404)
if app.author_id != v.id: abort(403)
- for auth in g.db.query(ClientAuth).filter_by(oauth_client=app.id).all():
- g.db.delete(auth)
+ for auth in db.query(ClientAuth).filter_by(oauth_client=app.id).all():
+ db.delete(auth)
- g.db.delete(app)
+ db.delete(app)
return redirect('/apps')
@@ -127,7 +127,7 @@ def edit_oauth_app(v, aid):
aid = int(aid)
except:
abort(404)
- app = g.db.get(OauthApp, aid)
+ app = db.get(OauthApp, aid)
if not app: abort(404)
if app.author_id != v.id: abort(403)
@@ -136,7 +136,7 @@ def edit_oauth_app(v, aid):
app.app_name = request.values.get('name')
app.description = request.values.get("description")[:256]
- g.db.add(app)
+ db.add(app)
return redirect('/settings/apps')
@@ -149,14 +149,14 @@ def edit_oauth_app(v, aid):
@admin_level_required(PERMS['APPS_MODERATION'])
def admin_app_approve(v, aid):
- app = g.db.get(OauthApp, aid)
+ app = db.get(OauthApp, aid)
if not app: abort(404)
user = app.author
if not app.client_id:
app.client_id = secrets.token_urlsafe(64)[:64]
- g.db.add(app)
+ db.add(app)
access_token = secrets.token_urlsafe(128)[:128]
new_auth = ClientAuth(
@@ -165,7 +165,7 @@ def admin_app_approve(v, aid):
access_token=access_token
)
- g.db.add(new_auth)
+ db.add(new_auth)
send_repeatable_notification(user.id, f"@{v.username} (a site admin) has approved your application `{app.app_name}`. Here's your access token: ||{access_token}||\n\nPlease check the guide [here](/api) if you don't know what to do next!")
@@ -174,7 +174,7 @@ def admin_app_approve(v, aid):
user_id=v.id,
target_user_id=user.id,
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"'{app.app_name}' approved!"}
@@ -187,21 +187,21 @@ def admin_app_approve(v, aid):
@admin_level_required(PERMS['APPS_MODERATION'])
def admin_app_revoke(v, aid):
- app = g.db.get(OauthApp, aid)
+ app = db.get(OauthApp, aid)
if app:
- for auth in g.db.query(ClientAuth).filter_by(oauth_client=app.id).all(): g.db.delete(auth)
+ for auth in db.query(ClientAuth).filter_by(oauth_client=app.id).all(): db.delete(auth)
if v.id != app.author.id:
send_repeatable_notification(app.author.id, f"@{v.username} (a site admin) has revoked your application `{app.app_name}`.")
- g.db.delete(app)
+ db.delete(app)
ma = ModAction(
kind="revoke_app",
user_id=v.id,
target_user_id=app.author.id,
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"'{app.app_name}' revoked!"}
@@ -214,22 +214,22 @@ def admin_app_revoke(v, aid):
@admin_level_required(PERMS['APPS_MODERATION'])
def admin_app_reject(v, aid):
- app = g.db.get(OauthApp, aid)
+ app = db.get(OauthApp, aid)
if app:
- for auth in g.db.query(ClientAuth).filter_by(oauth_client=app.id).all(): g.db.delete(auth)
+ for auth in db.query(ClientAuth).filter_by(oauth_client=app.id).all(): db.delete(auth)
if v.id != app.author.id:
send_repeatable_notification(app.author.id, f"@{v.username} (a site admin) has rejected your application `{app.app_name}`.")
- g.db.delete(app)
+ db.delete(app)
ma = ModAction(
kind="reject_app",
user_id=v.id,
target_user_id=app.author.id,
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"'{app.app_name}' rejected!"}
@@ -241,10 +241,10 @@ def admin_app_reject(v, aid):
@admin_level_required(PERMS['APPS_MODERATION'])
def admin_app_id_posts(v, aid):
aid=aid
- oauth = g.db.get(OauthApp, aid)
+ oauth = db.get(OauthApp, aid)
if not oauth: abort(404)
- pids=oauth.idlist(g.db, page=int(request.values.get("page",1)))
+ pids=oauth.idlist(page=int(request.values.get("page",1)))
next_exists=len(pids)==101
pids=pids[:100]
@@ -266,10 +266,10 @@ def admin_app_id_comments(v, aid):
aid=aid
- oauth = g.db.get(OauthApp, aid)
+ oauth = db.get(OauthApp, aid)
if not oauth: abort(404)
- cids=oauth.comments_idlist(g.db, page=int(request.values.get("page",1)))
+ cids=oauth.comments_idlist(page=int(request.values.get("page",1)))
next_exists=len(cids)==101
cids=cids[:100]
@@ -292,9 +292,9 @@ def admin_app_id_comments(v, aid):
@admin_level_required(PERMS['APPS_MODERATION'])
def admin_apps_list(v):
- not_approved = g.db.query(OauthApp).filter(OauthApp.client_id == None).order_by(OauthApp.id.desc()).all()
+ not_approved = db.query(OauthApp).filter(OauthApp.client_id == None).order_by(OauthApp.id.desc()).all()
- approved = g.db.query(OauthApp).filter(OauthApp.client_id != None).order_by(OauthApp.id.desc()).all()
+ approved = db.query(OauthApp).filter(OauthApp.client_id != None).order_by(OauthApp.id.desc()).all()
apps = not_approved + approved
@@ -310,13 +310,13 @@ def reroll_oauth_tokens(aid, v):
aid = aid
- a = g.db.get(OauthApp, aid)
+ a = db.get(OauthApp, aid)
if not a: abort(404)
if a.author_id != v.id: abort(403)
a.client_id = secrets.token_urlsafe(64)[:64]
- g.db.add(a)
+ db.add(a)
return {"message": f"Client ID for '{a.app_name}' has been rerolled!", "id": a.client_id}
diff --git a/files/routes/polls.py b/files/routes/polls.py
index 6d5671c75..9c53ab00f 100644
--- a/files/routes/polls.py
+++ b/files/routes/polls.py
@@ -15,7 +15,7 @@ def vote_option(option_id, v):
option_id = int(option_id)
except:
abort(404)
- option = g.db.get(SubmissionOption, option_id)
+ option = db.get(SubmissionOption, option_id)
if not option: abort(404)
sub = option.parent.sub
@@ -27,31 +27,31 @@ def vote_option(option_id, v):
abort(403, "You can't participate in a closed bet!")
if not v.charge_account('combined', POLL_BET_COINS):
abort(400, f"You don't have {POLL_BET_COINS} coins or marseybux!")
- g.db.add(v)
+ db.add(v)
autojanny = get_account(AUTOJANNY_ID)
autojanny.pay_account('coins', POLL_BET_COINS)
- g.db.add(autojanny)
+ db.add(autojanny)
if option.exclusive:
- vote = g.db.query(SubmissionOptionVote).join(SubmissionOption).filter(
+ vote = db.query(SubmissionOptionVote).join(SubmissionOption).filter(
SubmissionOptionVote.user_id==v.id,
SubmissionOptionVote.submission_id==option.parent_id,
SubmissionOption.exclusive==option.exclusive).all()
if vote:
if option.exclusive == 2: abort(400, "You already voted on this bet!")
for x in vote:
- g.db.delete(x)
+ db.delete(x)
- existing = g.db.query(SubmissionOptionVote).filter_by(option_id=option_id, user_id=v.id).one_or_none()
+ existing = db.query(SubmissionOptionVote).filter_by(option_id=option_id, user_id=v.id).one_or_none()
if not existing:
vote = SubmissionOptionVote(
option_id=option_id,
user_id=v.id,
submission_id=option.parent_id,
)
- g.db.add(vote)
+ db.add(vote)
elif existing and not option.exclusive:
- g.db.delete(existing)
+ db.delete(existing)
return {"message": "Bet successful!"}
@@ -65,7 +65,7 @@ def vote_option_comment(option_id, v):
option_id = int(option_id)
except:
abort(404)
- option = g.db.get(CommentOption, option_id)
+ option = db.get(CommentOption, option_id)
if not option: abort(404)
sub = option.parent.post.sub
if sub in {'furry','vampire','racist','femboy'} and not v.house.lower().startswith(sub):
@@ -76,31 +76,31 @@ def vote_option_comment(option_id, v):
abort(403, "You can't participate in a closed bet!")
if not v.charge_account('combined', POLL_BET_COINS):
abort(400, f"You don't have {POLL_BET_COINS} coins or marseybux!")
- g.db.add(v)
+ db.add(v)
autojanny = get_account(AUTOJANNY_ID)
autojanny.pay_account('coins', POLL_BET_COINS)
- g.db.add(autojanny)
+ db.add(autojanny)
if option.exclusive:
- vote = g.db.query(CommentOptionVote).join(CommentOption).filter(
+ vote = db.query(CommentOptionVote).join(CommentOption).filter(
CommentOptionVote.user_id==v.id,
CommentOptionVote.comment_id==option.parent_id,
CommentOption.exclusive==option.exclusive).all()
if vote:
if option.exclusive == 2: abort(400, "You already voted on this bet!")
for x in vote:
- g.db.delete(x)
+ db.delete(x)
- existing = g.db.query(CommentOptionVote).filter_by(option_id=option_id, user_id=v.id).one_or_none()
+ existing = db.query(CommentOptionVote).filter_by(option_id=option_id, user_id=v.id).one_or_none()
if not existing:
vote = CommentOptionVote(
option_id=option_id,
user_id=v.id,
comment_id=option.parent_id,
)
- g.db.add(vote)
+ db.add(vote)
elif existing:
- g.db.delete(existing)
+ db.delete(existing)
return {"message": "Bet successful!"}
@@ -114,20 +114,20 @@ def option_votes(option_id, v):
option_id = int(option_id)
except:
abort(404)
- option = g.db.get(SubmissionOption, option_id)
+ option = db.get(SubmissionOption, option_id)
if not option: abort(404)
if option.parent.ghost and v.admin_level < PERMS['SEE_GHOST_VOTES']:
abort(403)
- ups = g.db.query(SubmissionOptionVote).filter_by(option_id=option_id).order_by(SubmissionOptionVote.created_utc).all()
+ ups = db.query(SubmissionOptionVote).filter_by(option_id=option_id).order_by(SubmissionOptionVote.created_utc).all()
- user_ids = [x[0] for x in g.db.query(SubmissionOptionVote.user_id).filter_by(option_id=option_id).all()]
- total_ts = g.db.query(func.sum(User.truescore)).filter(User.id.in_(user_ids)).scalar()
+ user_ids = [x[0] for x in db.query(SubmissionOptionVote.user_id).filter_by(option_id=option_id).all()]
+ total_ts = db.query(func.sum(User.truescore)).filter(User.id.in_(user_ids)).scalar()
total_ts = format(total_ts, ",") if total_ts else '0'
if v.admin_level >= 3:
- total_patrons = g.db.query(User).filter(User.id.in_(user_ids), User.patron > 0).count()
+ total_patrons = db.query(User).filter(User.id.in_(user_ids), User.patron > 0).count()
else:
total_patrons = None
@@ -149,21 +149,21 @@ def option_votes_comment(option_id, v):
option_id = int(option_id)
except:
abort(404)
- option = g.db.get(CommentOption, option_id)
+ option = db.get(CommentOption, option_id)
if not option: abort(404)
if option.parent.ghost and v.admin_level < PERMS['SEE_GHOST_VOTES']:
abort(403)
- ups = g.db.query(CommentOptionVote).filter_by(option_id=option_id).order_by(CommentOptionVote.created_utc).all()
+ ups = db.query(CommentOptionVote).filter_by(option_id=option_id).order_by(CommentOptionVote.created_utc).all()
- user_ids = [x[0] for x in g.db.query(CommentOptionVote.user_id).filter_by(option_id=option_id).all()]
- total_ts = g.db.query(func.sum(User.truescore)).filter(User.id.in_(user_ids)).scalar()
+ user_ids = [x[0] for x in db.query(CommentOptionVote.user_id).filter_by(option_id=option_id).all()]
+ total_ts = db.query(func.sum(User.truescore)).filter(User.id.in_(user_ids)).scalar()
total_ts = format(total_ts, ",") if total_ts else '0'
if v.admin_level >= 3:
- total_patrons = g.db.query(User).filter(User.id.in_(user_ids), User.patron > 0).count()
+ total_patrons = db.query(User).filter(User.id.in_(user_ids), User.patron > 0).count()
else:
total_patrons = None
diff --git a/files/routes/posts.py b/files/routes/posts.py
index 0a3acb235..e0beaf078 100644
--- a/files/routes/posts.py
+++ b/files/routes/posts.py
@@ -44,7 +44,7 @@ def publish(pid, v):
if p.author_id != v.id: abort(403)
p.private = False
p.created_utc = int(time.time())
- g.db.add(p)
+ db.add(p)
notify_users = NOTIFY_USERS(f'{p.title} {p.body}', v, ghost=p.ghost)
@@ -76,7 +76,7 @@ def submit_get(v:User, sub=None):
sub = get_sub_by_name(sub, graceful=True)
if request.path.startswith('/h/') and not sub: abort(404)
- SUBS = [x[0] for x in g.db.query(Sub.name).order_by(Sub.name).all()]
+ SUBS = [x[0] for x in db.query(Sub.name).order_by(Sub.name).all()]
return render_template("submit.html", SUBS=SUBS, v=v, sub=sub)
@@ -109,9 +109,9 @@ def post_id(pid, anything=None, v=None, sub=None):
comments = sort_objects(sort, comments, Comment)
comments = [c[0] for c in comments.all()]
else:
- pinned = g.db.query(Comment).filter(Comment.parent_submission == p.id, Comment.stickied != None).order_by(Comment.created_utc.desc()).all()
+ pinned = db.query(Comment).filter(Comment.parent_submission == p.id, Comment.stickied != None).order_by(Comment.created_utc.desc()).all()
- comments = g.db.query(Comment).filter(
+ comments = db.query(Comment).filter(
Comment.parent_submission == p.id,
Comment.level == 1,
Comment.stickied == None
@@ -133,13 +133,13 @@ def post_id(pid, anything=None, v=None, sub=None):
for comment in comments:
comments2.append(comment)
ids.add(comment.id)
- count += g.db.query(Comment).filter_by(parent_submission=p.id, top_comment_id=comment.id).count() + 1
+ count += db.query(Comment).filter_by(parent_submission=p.id, top_comment_id=comment.id).count() + 1
if count > threshold: break
else:
for comment in comments:
comments2.append(comment)
ids.add(comment.id)
- count += g.db.query(Comment).filter_by(parent_submission=p.id, parent_comment_id=comment.id).count() + 1
+ count += db.query(Comment).filter_by(parent_submission=p.id, parent_comment_id=comment.id).count() + 1
if count > 20: break
if len(comments) == len(comments2): offset = 0
@@ -151,7 +151,7 @@ def post_id(pid, anything=None, v=None, sub=None):
if pin.stickied_utc and int(time.time()) > pin.stickied_utc:
pin.stickied = None
pin.stickied_utc = None
- g.db.add(pin)
+ db.add(pin)
elif pin.level > 1:
pinned2[pin.top_comment] = ''
if pin.top_comment in comments:
@@ -162,10 +162,10 @@ def post_id(pid, anything=None, v=None, sub=None):
p.replies = list(pinned2.keys()) + comments
p.views += 1
- g.db.add(p)
+ db.add(p)
if v and v.client:
- return p.json(g.db)
+ return p.json
template = "submission.html"
if (p.is_banned or p.author.shadowbanned) \
@@ -196,7 +196,7 @@ def view_more(v, pid, sort, offset):
comments = [c[0] for c in comments.all()]
else:
- comments = g.db.query(Comment).filter(
+ comments = db.query(Comment).filter(
Comment.parent_submission == pid,
Comment.level == 1,
Comment.stickied == None,
@@ -213,13 +213,13 @@ def view_more(v, pid, sort, offset):
for comment in comments:
comments2.append(comment)
ids.add(comment.id)
- count += g.db.query(Comment).filter_by(parent_submission=p.id, top_comment_id=comment.id).count() + 1
+ count += db.query(Comment).filter_by(parent_submission=p.id, top_comment_id=comment.id).count() + 1
if count > 100: break
else:
for comment in comments:
comments2.append(comment)
ids.add(comment.id)
- count += g.db.query(Comment).filter_by(parent_submission=p.id, parent_comment_id=comment.id).count() + 1
+ count += db.query(Comment).filter_by(parent_submission=p.id, parent_comment_id=comment.id).count() + 1
if count > 20: break
if len(comments) == len(comments2): offset = 0
@@ -236,7 +236,7 @@ def more_comments(v, cid):
try: cid = int(cid)
except: abort(404)
- tcid = g.db.query(Comment.top_comment_id).filter_by(id=cid).one_or_none()[0]
+ tcid = db.query(Comment.top_comment_id).filter_by(id=cid).one_or_none()[0]
if v:
# shadowban check is done in sort_objects i think
@@ -254,7 +254,6 @@ def more_comments(v, cid):
return render_template("comments.html", v=v, comments=comments, p=p, render_replies=True)
def thumbnail_thread(pid:int, vid:int):
- db = db_session()
def expand_url(post_url, fragment_url):
if fragment_url.startswith("https://"):
return fragment_url
@@ -372,7 +371,7 @@ def thumbnail_thread(pid:int, vid:int):
file.write(chunk)
v = db.get(User, vid)
- url = process_image(name, v, resize=99, uploader_id=p.author_id, db=db)
+ url = process_image(name, v, resize=99, uploader_id=p.author_id)
if url:
p.thumburl = url
db.add(p)
@@ -418,7 +417,7 @@ def is_repost():
url = url.rstrip('/')
search_url = url.replace('%', '').replace('\\', '').replace('_', '\_').strip()
- repost = g.db.query(Submission).filter(
+ repost = db.query(Submission).filter(
Submission.url.ilike(search_url),
Submission.deleted_utc == 0,
Submission.is_banned == False
@@ -460,7 +459,7 @@ def submit_post(v:User, sub=None):
if sub and sub != 'none':
sname = sub.strip().lower()
- sub = g.db.query(Sub.name).filter_by(name=sname).one_or_none()
+ sub = db.query(Sub.name).filter_by(name=sname).one_or_none()
if not sub: abort(400, f"/h/{sname} not found!")
sub = sub[0]
if v.exiled_from(sub): abort(400, f"You're exiled from /h/{sub}")
@@ -507,7 +506,7 @@ def submit_post(v:User, sub=None):
url = url.rstrip('/')
search_url = url.replace('%', '').replace('\\', '').replace('_', '\_').strip()
- repost = g.db.query(Submission).filter(
+ repost = db.query(Submission).filter(
Submission.url.ilike(search_url),
Submission.deleted_utc == 0,
Submission.is_banned == False
@@ -517,7 +516,7 @@ def submit_post(v:User, sub=None):
y = tldextract.extract(url).registered_domain + parsed_url.path
y = y.lower()
- banned_domains = g.db.query(BannedDomain).all()
+ banned_domains = db.query(BannedDomain).all()
for x in banned_domains:
if y.startswith(x.domain):
abort(400, f'Remove the banned link "{x.domain}" and try again!
Reason for link ban: "{x.reason}"')
@@ -539,7 +538,7 @@ def submit_post(v:User, sub=None):
abort(400, "Please enter a url or some text!")
if not IS_LOCALHOST:
- dup = g.db.query(Submission).filter(
+ dup = db.query(Submission).filter(
Submission.author_id == v.id,
Submission.deleted_utc == 0,
Submission.title == title,
@@ -600,8 +599,8 @@ def submit_post(v:User, sub=None):
ghost=flag_ghost
)
- g.db.add(p)
- g.db.flush()
+ db.add(p)
+ db.flush()
execute_under_siege(v, p, p.body, 'submission')
@@ -615,7 +614,7 @@ def submit_post(v:User, sub=None):
submission_id=p.id,
coins=0
)
- g.db.add(vote)
+ db.add(vote)
if request.files.get('file-url') and not g.is_tor:
file = request.files['file-url']
@@ -679,22 +678,22 @@ def submit_post(v:User, sub=None):
ghost=p.ghost
)
- g.db.add(c_jannied)
- g.db.flush()
+ db.add(c_jannied)
+ db.flush()
p.comment_count += 1
- g.db.add(p)
+ db.add(p)
c_jannied.top_comment_id = c_jannied.id
n = Notification(comment_id=c_jannied.id, user_id=v.id)
- g.db.add(n)
+ db.add(n)
- if not p.private and not (p.sub and g.db.query(Exile.user_id).filter_by(user_id=SNAPPY_ID, sub=p.sub).one_or_none()):
+ if not p.private and not (p.sub and db.query(Exile.user_id).filter_by(user_id=SNAPPY_ID, sub=p.sub).one_or_none()):
execute_snappy(p, v)
- v.post_count = g.db.query(Submission).filter_by(author_id=v.id, deleted_utc=0).count()
- g.db.add(v)
+ v.post_count = db.query(Submission).filter_by(author_id=v.id, deleted_utc=0).count()
+ db.add(v)
execute_lawlz_actions(v, p)
@@ -707,8 +706,8 @@ def submit_post(v:User, sub=None):
cache.delete_memoized(frontlist)
cache.delete_memoized(userpagelisting)
- g.db.commit()
- if v.client: return p.json(g.db)
+ db.flush()
+ if v.client: return p.json
else:
p.voted = 1
return {"post_id": p.id, "success": True}
@@ -730,14 +729,14 @@ def delete_post_pid(pid, v):
p.is_pinned = False
p.stickied = None
- g.db.add(p)
+ db.add(p)
cache.delete_memoized(frontlist)
cache.delete_memoized(userpagelisting)
- g.db.flush()
- v.post_count = g.db.query(Submission).filter_by(author_id=v.id, deleted_utc=0).count()
- g.db.add(v)
+ db.flush()
+ v.post_count = db.query(Submission).filter_by(author_id=v.id, deleted_utc=0).count()
+ db.add(v)
return {"message": "Post deleted!"}
@@ -752,14 +751,14 @@ def undelete_post_pid(pid, v):
if p.deleted_utc:
p.deleted_utc = 0
- g.db.add(p)
+ db.add(p)
cache.delete_memoized(frontlist)
cache.delete_memoized(userpagelisting)
- g.db.flush()
- v.post_count = g.db.query(Submission).filter_by(author_id=v.id, deleted_utc=0).count()
- g.db.add(v)
+ db.flush()
+ v.post_count = db.query(Submission).filter_by(author_id=v.id, deleted_utc=0).count()
+ db.add(v)
return {"message": "Post undeleted!"}
@@ -780,7 +779,7 @@ def mark_post_nsfw(pid, v):
abort(403)
p.over_18 = True
- g.db.add(p)
+ db.add(p)
if p.author_id != v.id:
if v.admin_level >= PERMS['POST_COMMENT_MODERATION']:
@@ -789,7 +788,7 @@ def mark_post_nsfw(pid, v):
user_id = v.id,
target_submission_id = p.id,
)
- g.db.add(ma)
+ db.add(ma)
else:
ma = SubAction(
sub = p.sub,
@@ -797,7 +796,7 @@ def mark_post_nsfw(pid, v):
user_id = v.id,
target_submission_id = p.id,
)
- g.db.add(ma)
+ db.add(ma)
send_repeatable_notification(p.author_id, f"@{v.username} (a site admin) has marked [{p.title}](/post/{p.id}) as +18")
return {"message": "Post has been marked as +18!"}
@@ -818,7 +817,7 @@ def unmark_post_nsfw(pid, v):
abort(403)
p.over_18 = False
- g.db.add(p)
+ db.add(p)
if p.author_id != v.id:
if v.admin_level >= PERMS['POST_COMMENT_MODERATION']:
@@ -827,7 +826,7 @@ def unmark_post_nsfw(pid, v):
user_id = v.id,
target_submission_id = p.id,
)
- g.db.add(ma)
+ db.add(ma)
else:
ma = SubAction(
sub = p.sub,
@@ -835,7 +834,7 @@ def unmark_post_nsfw(pid, v):
user_id = v.id,
target_submission_id = p.id,
)
- g.db.add(ma)
+ db.add(ma)
send_repeatable_notification(p.author_id, f"@{v.username} (a site admin) has unmarked [{p.title}](/post/{p.id}) as +18")
return {"message": "Post has been unmarked as +18!"}
@@ -849,11 +848,11 @@ def save_post(pid, v):
p = get_post(pid)
- save = g.db.query(SaveRelationship).filter_by(user_id=v.id, submission_id=p.id).one_or_none()
+ save = db.query(SaveRelationship).filter_by(user_id=v.id, submission_id=p.id).one_or_none()
if not save:
new_save=SaveRelationship(user_id=v.id, submission_id=p.id)
- g.db.add(new_save)
+ db.add(new_save)
return {"message": "Post saved!"}
@@ -866,10 +865,10 @@ def unsave_post(pid, v):
p = get_post(pid)
- save = g.db.query(SaveRelationship).filter_by(user_id=v.id, submission_id=p.id).one_or_none()
+ save = db.query(SaveRelationship).filter_by(user_id=v.id, submission_id=p.id).one_or_none()
if save:
- g.db.delete(save)
+ db.delete(save)
return {"message": "Post unsaved!"}
@@ -883,7 +882,7 @@ def pin_post(post_id, v):
if p:
if v.id != p.author_id: abort(403, "Only the post author can do that!")
p.is_pinned = not p.is_pinned
- g.db.add(p)
+ db.add(p)
cache.delete_memoized(userpagelisting)
if p.is_pinned: return {"message": "Post pinned!"}
else: return {"message": "Post unpinned!"}
@@ -897,7 +896,7 @@ def set_new_sort(post_id:int, v:User):
p = get_post(post_id)
if not v.can_edit(p): abort(403, "Only the post author can do that!")
p.new = True
- g.db.add(p)
+ db.add(p)
if v.id != p.author_id:
ma = ModAction(
@@ -905,7 +904,7 @@ def set_new_sort(post_id:int, v:User):
user_id = v.id,
target_submission_id = p.id,
)
- g.db.add(ma)
+ db.add(ma)
send_repeatable_notification(p.author_id, f"@{v.username} (a site admin) has changed the the default sorting of comments on [{p.title}](/post/{p.id}) to `new`")
return {"message": "Changed the the default sorting of comments on this post to 'new'"}
@@ -919,7 +918,7 @@ def unset_new_sort(post_id:int, v:User):
p = get_post(post_id)
if not v.can_edit(p): abort(403, "Only the post author can do that!")
p.new = None
- g.db.add(p)
+ db.add(p)
if v.id != p.author_id:
ma = ModAction(
@@ -927,7 +926,7 @@ def unset_new_sort(post_id:int, v:User):
user_id = v.id,
target_submission_id = p.id,
)
- g.db.add(ma)
+ db.add(ma)
send_repeatable_notification(p.author_id, f"@{v.username} (a site admin) has changed the the default sorting of comments on [{p.title}](/post/{p.id}) to `hot`")
return {"message": "Changed the the default sorting of comments on this post to 'hot'"}
@@ -1051,14 +1050,14 @@ def edit_post(pid, v):
if v.id == p.author_id:
if int(time.time()) - p.created_utc > 60 * 3: p.edited_utc = int(time.time())
- g.db.add(p)
+ db.add(p)
else:
ma=ModAction(
kind="edit_post",
user_id=v.id,
target_submission_id=p.id
)
- g.db.add(ma)
+ db.add(ma)
return redirect(p.permalink)
diff --git a/files/routes/push_notifs.py b/files/routes/push_notifs.py
index ce0bd03fe..4d22b2fef 100644
--- a/files/routes/push_notifs.py
+++ b/files/routes/push_notifs.py
@@ -11,7 +11,7 @@ from files.classes.push_subscriptions import PushSubscription
def push_subscribe(v):
subscription_json = request.values.get("subscription_json")
- subscription = g.db.query(PushSubscription).filter_by(
+ subscription = db.query(PushSubscription).filter_by(
user_id=v.id,
subscription_json=subscription_json,
).one_or_none()
@@ -21,6 +21,6 @@ def push_subscribe(v):
user_id=v.id,
subscription_json=subscription_json,
)
- g.db.add(subscription)
+ db.add(subscription)
return ''
diff --git a/files/routes/reporting.py b/files/routes/reporting.py
index 7b3b1fa87..8b9ad0d61 100644
--- a/files/routes/reporting.py
+++ b/files/routes/reporting.py
@@ -30,7 +30,7 @@ def flag_post(pid, v):
if reason.startswith('!') and (v.admin_level >= PERMS['POST_COMMENT_MODERATION'] or post.sub and v.mods(post.sub)):
post.flair = reason[1:]
- g.db.add(post)
+ db.add(post)
if v.admin_level >= PERMS['POST_COMMENT_MODERATION']:
ma=ModAction(
kind="flair_post",
@@ -38,7 +38,7 @@ def flag_post(pid, v):
target_submission_id=post.id,
_note=f'"{post.flair}"'
)
- g.db.add(ma)
+ db.add(ma)
position = 'a site admin'
else:
ma = SubAction(
@@ -48,7 +48,7 @@ def flag_post(pid, v):
target_submission_id=post.id,
_note=f'"{post.flair}"'
)
- g.db.add(ma)
+ db.add(ma)
position = f'a /h/{post.sub} mod'
if v.id != post.author_id:
@@ -60,10 +60,10 @@ def flag_post(pid, v):
moved = move_post(post, v, reason)
if moved: return {"message": moved}
- existing = g.db.query(Flag.post_id).filter_by(user_id=v.id, post_id=post.id).one_or_none()
+ existing = db.query(Flag.post_id).filter_by(user_id=v.id, post_id=post.id).one_or_none()
if existing: abort(409, "You already reported this post!")
flag = Flag(post_id=post.id, user_id=v.id, reason=reason)
- g.db.add(flag)
+ db.add(flag)
return {"message": "Post reported!"}
@@ -77,7 +77,7 @@ def flag_comment(cid, v):
comment = get_comment(cid)
- existing = g.db.query(CommentFlag.comment_id).filter_by(user_id=v.id, comment_id=comment.id).one_or_none()
+ existing = db.query(CommentFlag.comment_id).filter_by(user_id=v.id, comment_id=comment.id).one_or_none()
if existing: abort(409, "You already reported this comment!")
reason = request.values.get("reason", "").strip()
@@ -90,7 +90,7 @@ def flag_comment(cid, v):
flag = CommentFlag(comment_id=comment.id, user_id=v.id, reason=reason)
- g.db.add(flag)
+ db.add(flag)
return {"message": "Comment reported!"}
@@ -105,10 +105,10 @@ def remove_report_post(v, pid, uid):
pid = int(pid)
uid = int(uid)
except: abort(404)
- report = g.db.query(Flag).filter_by(post_id=pid, user_id=uid).one_or_none()
+ report = db.query(Flag).filter_by(post_id=pid, user_id=uid).one_or_none()
if report:
- g.db.delete(report)
+ db.delete(report)
ma=ModAction(
kind="delete_report",
@@ -116,7 +116,7 @@ def remove_report_post(v, pid, uid):
target_submission_id=pid
)
- g.db.add(ma)
+ db.add(ma)
return {"message": "Report removed successfully!"}
@@ -130,10 +130,10 @@ def remove_report_comment(v, cid, uid):
cid = int(cid)
uid = int(uid)
except: abort(404)
- report = g.db.query(CommentFlag).filter_by(comment_id=cid, user_id=uid).one_or_none()
+ report = db.query(CommentFlag).filter_by(comment_id=cid, user_id=uid).one_or_none()
if report:
- g.db.delete(report)
+ db.delete(report)
ma=ModAction(
kind="delete_report",
@@ -141,7 +141,7 @@ def remove_report_comment(v, cid, uid):
target_comment_id=cid
)
- g.db.add(ma)
+ db.add(ma)
return {"message": "Report removed successfully!"}
def move_post(post:Submission, v:User, reason:str) -> Union[bool, str]:
@@ -178,7 +178,7 @@ def move_post(post:Submission, v:User, reason:str) -> Union[bool, str]:
post.sub = sub_to
post.hole_pinned = None
- g.db.add(post)
+ db.add(post)
if v.id != post.author_id:
if v.admin_level:
@@ -192,7 +192,7 @@ def move_post(post:Submission, v:User, reason:str) -> Union[bool, str]:
target_submission_id=post.id,
_note=f'{sub_from_str} → {sub_to_str}',
)
- g.db.add(ma)
+ db.add(ma)
if sub_to == 'chudrama':
post.bannedfor = None
@@ -203,7 +203,7 @@ def move_post(post:Submission, v:User, reason:str) -> Union[bool, str]:
user_id=v.id,
target_submission_id=post.id
)
- g.db.add(ma)
+ db.add(ma)
if v.admin_level >= PERMS['POST_COMMENT_MODERATION']: position = 'a site admin'
else: position = f'a /h/{sub_from} mod'
diff --git a/files/routes/routehelpers.py b/files/routes/routehelpers.py
index 337d5a557..1186e67d2 100644
--- a/files/routes/routehelpers.py
+++ b/files/routes/routehelpers.py
@@ -26,9 +26,9 @@ def validate_formkey(u:User, formkey:Optional[str]) -> bool:
@cache.memoize()
def get_alt_graph_ids(uid:int) -> List[int]:
- alt_graph_cte = g.db.query(literal(uid).label('user_id')).select_from(Alt).cte('alt_graph', recursive=True)
+ alt_graph_cte = db.query(literal(uid).label('user_id')).select_from(Alt).cte('alt_graph', recursive=True)
- alt_graph_cte_inner = g.db.query(
+ alt_graph_cte_inner = db.query(
case(
(Alt.user1 == alt_graph_cte.c.user_id, Alt.user2),
(Alt.user2 == alt_graph_cte.c.user_id, Alt.user1),
@@ -38,27 +38,27 @@ def get_alt_graph_ids(uid:int) -> List[int]:
)
alt_graph_cte = alt_graph_cte.union(alt_graph_cte_inner)
- return set([x[0] for x in g.db.query(User.id).filter(User.id == alt_graph_cte.c.user_id, User.id != uid).all()])
+ return set([x[0] for x in db.query(User.id).filter(User.id == alt_graph_cte.c.user_id, User.id != uid).all()])
def get_alt_graph(uid:int) -> List[User]:
alt_ids = get_alt_graph_ids(uid)
- return g.db.query(User).filter(User.id.in_(alt_ids)).order_by(User.username).all()
+ return db.query(User).filter(User.id.in_(alt_ids)).order_by(User.username).all()
def add_alt(user1:int, user2:int):
if AEVANN_ID in (user1, user2):
return
li = [user1, user2]
- existing = g.db.query(Alt).filter(Alt.user1.in_(li), Alt.user2.in_(li)).one_or_none()
+ existing = db.query(Alt).filter(Alt.user1.in_(li), Alt.user2.in_(li)).one_or_none()
if not existing:
new_alt = Alt(user1=user1, user2=user2)
- g.db.add(new_alt)
- g.db.flush()
+ db.add(new_alt)
+ db.flush()
cache.delete_memoized(get_alt_graph_ids, user1)
cache.delete_memoized(get_alt_graph_ids, user2)
def check_for_alts(current:User, include_current_session=False):
current_id = current.id
- ids = [x[0] for x in g.db.query(User.id).all()]
+ ids = [x[0] for x in db.query(User.id).all()]
past_accs = set(session.get("history", [])) if include_current_session else set()
for past_id in list(past_accs):
@@ -70,7 +70,7 @@ def check_for_alts(current:User, include_current_session=False):
li = [past_id, current_id]
add_alt(past_id, current_id)
- other_alts = g.db.query(Alt).filter(Alt.user1.in_(li), Alt.user2.in_(li)).all()
+ other_alts = db.query(Alt).filter(Alt.user1.in_(li), Alt.user2.in_(li)).all()
for a in other_alts:
if a.user1 != past_id: add_alt(a.user1, past_id)
if a.user1 != current_id: add_alt(a.user1, current_id)
@@ -80,30 +80,30 @@ def check_for_alts(current:User, include_current_session=False):
past_accs.add(current_id)
if include_current_session:
session["history"] = list(past_accs)
- g.db.flush()
+ db.flush()
for u in get_alt_graph(current.id):
if u.shadowbanned and not current.shadowbanned:
current.shadowbanned = u.shadowbanned
current.ban_reason = u.ban_reason
- g.db.add(current)
+ db.add(current)
elif current.shadowbanned and not u.shadowbanned:
u.shadowbanned = current.shadowbanned
u.ban_reason = current.ban_reason
- g.db.add(u)
+ db.add(u)
if u.is_muted and not current.is_muted:
current.is_muted = u.is_muted
- g.db.add(current)
+ db.add(current)
elif current.is_muted and not u.is_muted:
u.is_muted = current.is_muted
- g.db.add(u)
+ db.add(u)
if u.blacklisted_by and not current.blacklisted_by:
current.blacklisted_by = u.blacklisted_by
- g.db.add(current)
+ db.add(current)
elif current.blacklisted_by and not u.blacklisted_by:
u.blacklisted_by = current.blacklisted_by
- g.db.add(u)
+ db.add(u)
def execute_shadowban_viewers_and_voters(v:Optional[User], target:Union[Submission, Comment]):
if not v or not v.shadowbanned: return
@@ -121,4 +121,4 @@ def execute_shadowban_viewers_and_voters(v:Optional[User], target:Union[Submissi
target.upvotes += amount
if isinstance(target, Submission):
target.views += amount*randint(3, 5)
- g.db.add(target)
+ db.add(target)
diff --git a/files/routes/search.py b/files/routes/search.py
index d5119574a..59c48aceb 100644
--- a/files/routes/search.py
+++ b/files/routes/search.py
@@ -61,7 +61,7 @@ def searchposts(v:User):
criteria=searchparse(query)
- posts = g.db.query(Submission.id) \
+ posts = db.query(Submission.id) \
.join(Submission.author) \
.filter(Submission.author_id.notin_(v.userblocks))
@@ -162,7 +162,7 @@ def searchposts(v:User):
posts = get_posts(ids, v=v, eager=True)
- if v.client: return {"total":total, "data":[x.json(g.db) for x in posts]}
+ if v.client: return {"total":total, "data":[x.json for x in posts]}
return render_template("search.html",
v=v,
@@ -192,7 +192,7 @@ def searchcomments(v:User):
criteria = searchparse(query)
- comments = g.db.query(Comment.id).outerjoin(Comment.post) \
+ comments = db.query(Comment.id).outerjoin(Comment.post) \
.filter(
or_(Comment.parent_submission != None, Comment.wall_user_id != None),
Comment.author_id.notin_(v.userblocks),
@@ -234,7 +234,7 @@ def searchcomments(v:User):
comments = apply_time_filter(t, comments, Comment)
if v.admin_level < PERMS['POST_COMMENT_MODERATION']:
- private = [x[0] for x in g.db.query(Submission.id).filter(Submission.private == True).all()]
+ private = [x[0] for x in db.query(Submission.id).filter(Submission.private == True).all()]
comments = comments.filter(
Comment.is_banned==False,
@@ -275,7 +275,7 @@ def searchcomments(v:User):
comments = get_comments(ids, v=v)
- if v.client: return {"total":total, "data":[x.json(db=g.db) for x in comments]}
+ if v.client: return {"total":total, "data":[x.json for x in comments]}
return render_template("search_comments.html", v=v, query=query, total=total, page=page, comments=comments, sort=sort, t=t, next_exists=next_exists, standalone=True)
@@ -300,7 +300,7 @@ def searchmessages(v:User):
if v.admin_level >= PERMS['VIEW_MODMAIL']:
dm_conditions.append(Comment.sentto == MODMAIL_ID),
- comments = g.db.query(Comment.id) \
+ comments = db.query(Comment.id) \
.filter(
Comment.sentto != None,
Comment.parent_submission == None,
@@ -366,7 +366,7 @@ def searchmessages(v:User):
comments = get_comments(ids, v=v)
- if v.client: return {"total":total, "data":[x.json(db=g.db) for x in comments]}
+ if v.client: return {"total":total, "data":[x.json for x in comments]}
return render_template("search_comments.html", v=v, query=query, total=total, page=page, comments=comments, sort=sort, t=t, next_exists=next_exists, standalone=True)
@app.get("/search/users")
@@ -381,7 +381,7 @@ def searchusers(v:User):
try: page = max(1, int(request.values.get("page", 1)))
except: abort(400, "Invalid page input!")
- users = g.db.query(User)
+ users = db.query(User)
criteria = searchparse(query)
diff --git a/files/routes/settings.py b/files/routes/settings.py
index 3ad682708..831a32fa1 100644
--- a/files/routes/settings.py
+++ b/files/routes/settings.py
@@ -47,7 +47,7 @@ def remove_background(v):
if v.background.startswith('/images/'):
remove_media(v.background)
v.background = None
- g.db.add(v)
+ db.add(v)
return {"message": "Background removed!"}
@app.post('/settings/custom_background')
@@ -71,7 +71,7 @@ def upload_custom_background(v):
if v.background and v.background.startswith('/images/'):
remove_media(v.background)
v.background = background
- g.db.add(v)
+ db.add(v)
return redirect('/settings/personal')
@@ -93,7 +93,7 @@ def upload_profile_background(v):
if v.profile_background and path.isfile(v.profile_background):
remove_media(v.profile_background)
v.profile_background = background
- g.db.add(v)
+ db.add(v)
badge_grant(badge_id=193, user=v)
return redirect(f'/@{v.username}')
@@ -173,17 +173,16 @@ def settings_personal_post(v):
if isinstance(slur_filter_updated, bool):
updated = slur_filter_updated
else:
- g.db.add(v)
+ db.add(v)
return slur_filter_updated
profanity_filter_updated = updated or update_potentially_permanent_flag("profanityreplacer", "profanityreplacer", "profanity replacer", 190)
if isinstance(profanity_filter_updated, bool):
updated = profanity_filter_updated
else:
- g.db.add(v)
+ db.add(v)
return profanity_filter_updated
- updated = updated or update_flag("hidevotedon", "hidevotedon")
updated = updated or update_flag("newtab", "newtab")
updated = updated or update_flag("newtabexternal", "newtabexternal")
updated = updated or update_flag("nitter", "nitter")
@@ -199,7 +198,7 @@ def settings_personal_post(v):
if v.spider: badge_grant(user=v, badge_id=179)
else:
badge = v.has_badge(179)
- if badge: g.db.delete(badge)
+ if badge: db.delete(badge)
elif IS_FISTMAS() and not updated and request.values.get("event_music", v.event_music) != v.event_music and v.can_toggle_event_music:
updated = True
@@ -208,25 +207,25 @@ def settings_personal_post(v):
elif not updated and request.values.get("bio") == "" and not request.files.get('file'):
v.bio = None
v.bio_html = None
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html", v=v, msg="Your bio has been updated!")
elif not updated and request.values.get("sig") == "":
v.sig = None
v.sig_html = None
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html", v=v, msg="Your sig has been updated!")
elif not updated and request.values.get("friends") == "":
v.friends = None
v.friends_html = None
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html", v=v, msg="Your friends list has been updated!")
elif not updated and request.values.get("enemies") == "":
v.enemies = None
v.enemies_html = None
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html", v=v, msg="Your enemies list has been updated!")
elif not updated and v.patron and request.values.get("sig"):
@@ -239,7 +238,7 @@ def settings_personal_post(v):
v.sig = sig[:200]
v.sig_html=sig_html
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html",
v=v,
msg="Your sig has been updated.")
@@ -269,7 +268,7 @@ def settings_personal_post(v):
v.friends = friends
v.friends_html=friends_html
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html",
v=v,
msg="Your friends list has been updated.")
@@ -299,7 +298,7 @@ def settings_personal_post(v):
v.enemies = enemies
v.enemies_html=enemies_html
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html",
v=v,
msg="Your enemies list has been updated.")
@@ -320,7 +319,7 @@ def settings_personal_post(v):
v.bio = bio[:BIO_FRIENDS_ENEMIES_LENGTH_LIMIT]
v.bio_html=bio_html
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html",
v=v,
msg="Your bio has been updated.")
@@ -366,7 +365,7 @@ def settings_personal_post(v):
updated = True
if updated:
- g.db.add(v)
+ db.add(v)
return {"message": "Your settings have been updated!"}
else:
abort(400, "You didn't change anything!")
@@ -384,7 +383,7 @@ def filters(v:User):
return redirect("/settings/advanced?error=You didn't change anything!")
v.custom_filter_list=filters
- g.db.add(v)
+ db.add(v)
return redirect("/settings/advanced?msg=Your custom filters have been updated!")
@@ -397,7 +396,7 @@ def set_color(v:User, attr:str, color:Optional[str]):
return render_template("settings/personal.html", v=v, error="Invalid color hex code!")
if color and current != color:
setattr(v, attr, color)
- g.db.add(v)
+ db.add(v)
return render_template("settings/personal.html", v=v, msg="Color successfully updated!")
@@ -452,7 +451,7 @@ def settings_security_post(v):
v.passhash = hash_password(request.values.get("new_password"))
- g.db.add(v)
+ db.add(v)
return render_template("settings/security.html", v=v, msg="Your password has been changed!")
if request.values.get("new_email"):
@@ -492,7 +491,7 @@ def settings_security_post(v):
return render_template("settings/security.html", v=v, error="Invalid token!")
v.mfa_secret = secret
- g.db.add(v)
+ db.add(v)
return render_template("settings/security.html", v=v, msg="Two-factor authentication enabled!")
if request.values.get("2fa_remove"):
@@ -505,8 +504,8 @@ def settings_security_post(v):
return render_template("settings/security.html", v=v, error="Invalid token!")
v.mfa_secret = None
- g.db.add(v)
- g.db.commit()
+ db.add(v)
+ db.flush()
return render_template("settings/security.html", v=v, msg="Two-factor authentication disabled!")
@app.post("/settings/log_out_all_others")
@@ -521,7 +520,7 @@ def settings_log_out_others(v):
v.login_nonce += 1
session["login_nonce"] = v.login_nonce
- g.db.add(v)
+ db.add(v)
return redirect("/settings/security?msg=All other devices have been logged out!")
@@ -556,7 +555,7 @@ def settings_images_profile(v):
v.highres = highres
v.profileurl = imageurl
- g.db.add(v)
+ db.add(v)
cache.delete_memoized(get_profile_picture, v.id)
cache.delete_memoized(get_profile_picture, v.username)
@@ -584,7 +583,7 @@ def settings_images_banner(v):
if v.bannerurl and '/images/' in v.bannerurl and path.isfile(v.bannerurl):
remove_media(v.bannerurl)
v.bannerurl = bannerurl
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Banner successfully updated!")
@@ -604,7 +603,7 @@ def settings_css(v):
if v.agendaposter: abort(400, "Agendapostered users can't edit CSS!")
css = request.values.get("css", v.css).strip().replace('\\', '').strip()[:CSS_LENGTH_LIMIT]
v.css = css
- g.db.add(v)
+ db.add(v)
return render_template("settings/css.html", v=v, msg="Custom CSS successfully updated!", profilecss=v.profilecss)
@@ -619,7 +618,7 @@ def settings_profilecss(v):
if not valid:
return render_template("settings/css.html", error=error, v=v, profilecss=profilecss)
v.profilecss = profilecss
- g.db.add(v)
+ db.add(v)
return redirect("/settings/css?msg=Profile CSS successfully updated!")
@app.get("/settings/security")
@@ -654,7 +653,7 @@ def settings_block_user(v):
if v.has_blocked(user): abort(409, f"You have already blocked @{user.username}")
new_block = UserBlock(user_id=v.id, target_id=user.id)
- g.db.add(new_block)
+ db.add(new_block)
if user.admin_level >= PERMS['USER_BLOCKS_VISIBLE']:
send_notification(user.id, f"@{v.username} has blocked you!")
@@ -672,7 +671,7 @@ def settings_unblock_user(v):
user = get_user(request.values.get("username"))
x = v.has_blocked(user)
if not x: abort(409, "You can't unblock someone you haven't blocked")
- g.db.delete(x)
+ db.delete(x)
if not v.shadowbanned and user.admin_level >= PERMS['USER_BLOCKS_VISIBLE']:
send_notification(user.id, f"@{v.username} has unblocked you!")
cache.delete_memoized(frontlist)
@@ -712,7 +711,7 @@ def settings_name_change(v):
search_name = new_name.replace('\\', '').replace('_','\_').replace('%','')
- x = g.db.query(User).filter(
+ x = db.query(User).filter(
or_(
User.username.ilike(search_name),
User.original_username.ilike(search_name)
@@ -727,7 +726,7 @@ def settings_name_change(v):
v=get_account(v.id)
v.username=new_name
v.name_changed_utc=int(time.time())
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Name successfully changed!")
@@ -752,17 +751,16 @@ def settings_song_change_mp3(v):
remove_media(name)
return redirect("/settings/personal?error=MP3 file must be smaller than 8MB")
- if path.isfile(f"/songs/{v.song}.mp3") and g.db.query(User).filter_by(song=v.song).count() == 1:
+ if path.isfile(f"/songs/{v.song}.mp3") and db.query(User).filter_by(song=v.song).count() == 1:
remove_media(f"/songs/{v.song}.mp3")
v.song = song
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Profile Anthem successfully updated!")
def _change_song_youtube(vid, id):
- db = db_session()
v = db.get(User, vid)
if v.song and path.isfile(f"/songs/{v.song}.mp3") and db.query(User).filter_by(song=v.song).count() == 1:
@@ -806,10 +804,10 @@ def settings_song_change(v):
song=request.values.get("song").strip()
if song == "" and v.song:
- if path.isfile(f"/songs/{v.song}.mp3") and g.db.query(User).filter_by(song=v.song).count() == 1:
+ if path.isfile(f"/songs/{v.song}.mp3") and db.query(User).filter_by(song=v.song).count() == 1:
remove_media(f"/songs/{v.song}.mp3")
v.song = None
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Profile Anthem successfully removed!")
song = song.replace("https://music.youtube.com", "https://youtube.com")
@@ -827,7 +825,7 @@ def settings_song_change(v):
return redirect("/settings/personal?error=Not a YouTube link!"), 400
if path.isfile(f'/songs/{id}.mp3'):
v.song = id
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Profile Anthem successfully updated!")
@@ -873,7 +871,7 @@ def settings_title_change(v):
v.customtitleplain = customtitleplain
v.customtitle = customtitle
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Flair successfully updated!")
@@ -901,7 +899,7 @@ def settings_pronouns_change(v):
elif 'fag' in bare_pronouns: pronouns = 'cute/twink'
v.pronouns = pronouns
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Pronouns successfully updated!")
@@ -917,7 +915,7 @@ def settings_checkmark_text(v):
if not new_name: abort(400)
if new_name == v.verified: return redirect("/settings/personal?error=You didn't change anything!")
v.verified = new_name
- g.db.add(v)
+ db.add(v)
return redirect("/settings/personal?msg=Checkmark Text successfully updated!")
if IS_FISTMAS():
@@ -928,5 +926,5 @@ if IS_FISTMAS():
@auth_required
def event_darkmode(v):
v.event_darkmode = not v.event_darkmode
- g.db.add(v)
+ db.add(v)
return {"message": "Dark mode toggled successfully!"}
diff --git a/files/routes/special.py b/files/routes/special.py
index 1bd6df7d1..669988f45 100644
--- a/files/routes/special.py
+++ b/files/routes/special.py
@@ -78,7 +78,7 @@ ORDER BY payout DESC, bets_won DESC, bets_total ASC;
@cache.memoize()
def _special_leaderboard_get():
- result = g.db.execute(_special_leaderboard_query).all()
+ result = db.execute(_special_leaderboard_query).all()
return result
@app.get('/events/worldcup2022/leaderboard')
diff --git a/files/routes/static.py b/files/routes/static.py
index 2eeb2774d..a9f7164f9 100644
--- a/files/routes/static.py
+++ b/files/routes/static.py
@@ -50,7 +50,7 @@ def marseys(v:User):
if SITE_NAME != 'rDrama':
abort(404)
- marseys = get_marseys(g.db)
+ marseys = get_marseys()
authors = get_accounts_dict([m.author_id for m in marseys], v=v, graceful=True)
original = os.listdir("/asset_submissions/marseys/original")
for marsey in marseys:
@@ -64,10 +64,10 @@ def marseys(v:User):
@app.get("/emojis")
@limiter.limit(DEFAULT_RATELIMIT)
def emoji_list():
- return get_emojis(g.db)
+ return get_emojis()
@cache.cached(timeout=86400, key_prefix=MARSEYS_CACHE_KEY)
-def get_marseys(db:scoped_session):
+def get_marseys():
if not FEATURES['MARSEYS']: return []
marseys = []
for marsey, author in db.query(Marsey, User).join(User, Marsey.author_id == User.id).filter(Marsey.submitter_id == None).order_by(Marsey.count.desc()):
@@ -77,8 +77,8 @@ def get_marseys(db:scoped_session):
return marseys
@cache.cached(timeout=600, key_prefix=EMOJIS_CACHE_KEY)
-def get_emojis(db:scoped_session):
- emojis = [m.json() for m in get_marseys(db)]
+def get_emojis():
+ emojis = [m.json for m in get_marseys()]
for src in EMOJI_SRCS:
with open(src, "r", encoding="utf-8") as f:
emojis = emojis + json.load(f)
@@ -125,7 +125,7 @@ def daily_chart(v:User):
@limiter.limit(DEFAULT_RATELIMIT, key_func=get_ID)
@admin_level_required(PERMS['VIEW_PATRONS'])
def patrons(v):
- users = g.db.query(User).filter(User.patron > 0).order_by(User.patron.desc(), User.id).all()
+ users = db.query(User).filter(User.patron > 0).order_by(User.patron.desc(), User.id).all()
return render_template("admin/patrons.html", v=v, users=users, benefactor_def=AWARDS['benefactor'])
@@ -135,7 +135,7 @@ def patrons(v):
@limiter.limit(DEFAULT_RATELIMIT, key_func=get_ID)
@auth_required
def admins(v:User):
- admins = g.db.query(User).filter(User.admin_level >= PERMS['ADMIN_MOP_VISIBLE']).order_by(User.truescore.desc()).all()
+ admins = db.query(User).filter(User.admin_level >= PERMS['ADMIN_MOP_VISIBLE']).order_by(User.truescore.desc()).all()
return render_template("admins.html", v=v, admins=admins)
@app.get("/log")
@@ -165,7 +165,7 @@ def log(v:User):
kind = None
actions = []
else:
- actions = g.db.query(ModAction)
+ actions = db.query(ModAction)
if not (v and v.admin_level >= PERMS['USER_SHADOWBAN']):
actions = actions.filter(ModAction.kind.notin_(MODACTION_PRIVILEGED_TYPES))
if not (v and v.admin_level >= PERMS['PROGSTACK']):
@@ -184,7 +184,7 @@ def log(v:User):
next_exists=len(actions) > PAGE_SIZE
actions=actions[:PAGE_SIZE]
- admins = [x[0] for x in g.db.query(User.username).filter(User.admin_level >= PERMS['ADMIN_MOP_VISIBLE']).order_by(User.username).all()]
+ admins = [x[0] for x in db.query(User.username).filter(User.admin_level >= PERMS['ADMIN_MOP_VISIBLE']).order_by(User.username).all()]
return render_template("log.html", v=v, admins=admins, types=types, admin=admin, type=kind, actions=actions, next_exists=next_exists, page=page, single_user_url='admin')
@@ -196,11 +196,11 @@ def log_item(id, v):
try: id = int(id)
except: abort(404)
- action=g.db.get(ModAction, id)
+ action=db.get(ModAction, id)
if not action: abort(404)
- admins = [x[0] for x in g.db.query(User.username).filter(User.admin_level >= PERMS['ADMIN_MOP_VISIBLE']).all()]
+ admins = [x[0] for x in db.query(User.username).filter(User.admin_level >= PERMS['ADMIN_MOP_VISIBLE']).all()]
if v and v.admin_level >= PERMS['USER_SHADOWBAN']:
if v and v.admin_level >= PERMS['PROGSTACK']:
@@ -268,17 +268,17 @@ def submit_contact(v):
body_html=body_html,
sentto=MODMAIL_ID
)
- g.db.add(new_comment)
- g.db.flush()
+ db.add(new_comment)
+ db.flush()
execute_blackjack(v, new_comment, new_comment.body_html, 'modmail')
execute_under_siege(v, new_comment, new_comment.body_html, 'modmail')
new_comment.top_comment_id = new_comment.id
- admin_ids = [x[0] for x in g.db.query(User.id).filter(User.admin_level >= PERMS['NOTIFICATIONS_MODMAIL']).all()]
+ admin_ids = [x[0] for x in db.query(User.id).filter(User.admin_level >= PERMS['NOTIFICATIONS_MODMAIL']).all()]
for admin_id in admin_ids:
notif = Notification(comment_id=new_comment.id, user_id=admin_id)
- g.db.add(notif)
+ db.add(notif)
push_notif(admin_ids, f'New modmail from @{new_comment.author_name}', new_comment.body, f'{SITE_FULL}/notifications/modmail')
@@ -293,9 +293,9 @@ no = (21,22,23,24,25,26,27)
@cache.memoize(timeout=3600)
def badge_list(site):
- badges = g.db.query(BadgeDef).filter(BadgeDef.id.notin_(no)).order_by(BadgeDef.id).all()
- counts_raw = g.db.query(Badge.badge_id, func.count()).group_by(Badge.badge_id).all()
- users = g.db.query(User).count()
+ badges = db.query(BadgeDef).filter(BadgeDef.id.notin_(no)).order_by(BadgeDef.id).all()
+ counts_raw = db.query(Badge.badge_id, func.count()).group_by(Badge.badge_id).all()
+ users = db.query(User).count()
counts = {}
for c in counts_raw:
@@ -317,7 +317,7 @@ def badges(v:User):
@limiter.limit(DEFAULT_RATELIMIT, key_func=get_ID)
@admin_level_required(PERMS['USER_BLOCKS_VISIBLE'])
def blocks(v):
- blocks=g.db.query(UserBlock).all()
+ blocks=db.query(UserBlock).all()
users = []
targets = []
for x in blocks:
@@ -358,7 +358,7 @@ def transfers_id(id, v):
try: id = int(id)
except: abort(404)
- transfer = g.db.get(Comment, id)
+ transfer = db.get(Comment, id)
if not transfer: abort(404)
@@ -370,7 +370,7 @@ def transfers_id(id, v):
@auth_required
def transfers(v:User):
- comments = g.db.query(Comment).filter(Comment.author_id == AUTOJANNY_ID, Comment.parent_submission == None, Comment.body_html.like("% has transferred %")).order_by(Comment.id.desc())
+ comments = db.query(Comment).filter(Comment.author_id == AUTOJANNY_ID, Comment.parent_submission == None, Comment.body_html.like("% has transferred %")).order_by(Comment.id.desc())
try: page = max(int(request.values.get("page", 1)), 1)
except: page = 1
@@ -380,7 +380,7 @@ def transfers(v:User):
comments = comments[:PAGE_SIZE]
if v.client:
- return {"data": [x.json(g.db) for x in comments]}
+ return {"data": [x.json for x in comments]}
else:
return render_template("transfers.html", v=v, page=page, comments=comments, standalone=True, next_exists=next_exists)
diff --git a/files/routes/subs.py b/files/routes/subs.py
index f72182c6c..a2b272885 100644
--- a/files/routes/subs.py
+++ b/files/routes/subs.py
@@ -26,7 +26,7 @@ def exile_post(v:User, pid):
if not u.exiled_from(sub):
exile = Exile(user_id=u.id, sub=sub, exiler_id=v.id)
- g.db.add(exile)
+ db.add(exile)
send_notification(u.id, f"@{v.username} has exiled you from /h/{sub} for [{p.title}]({p.shortlink})")
@@ -37,7 +37,7 @@ def exile_post(v:User, pid):
target_user_id=u.id,
_note=f'for {p.title_html}'
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"@{u.username} has been exiled from /h/{sub} successfully!"}
@@ -60,7 +60,7 @@ def exile_comment(v:User, cid):
if not u.exiled_from(sub):
exile = Exile(user_id=u.id, sub=sub, exiler_id=v.id)
- g.db.add(exile)
+ db.add(exile)
send_notification(u.id, f"@{v.username} has exiled you from /h/{sub} for [{c.permalink}]({c.shortlink})")
@@ -71,7 +71,7 @@ def exile_comment(v:User, cid):
target_user_id=u.id,
_note=f'for comment'
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"@{u.username} has been exiled from /h/{sub} successfully!"}
@@ -87,8 +87,8 @@ def unexile(v:User, sub, uid):
if v.shadowbanned: return redirect(f'/h/{sub}/exilees')
if u.exiled_from(sub):
- exile = g.db.query(Exile).filter_by(user_id=u.id, sub=sub).one_or_none()
- g.db.delete(exile)
+ exile = db.query(Exile).filter_by(user_id=u.id, sub=sub).one_or_none()
+ db.delete(exile)
send_notification(u.id, f"@{v.username} has revoked your exile from /h/{sub}")
@@ -98,7 +98,7 @@ def unexile(v:User, sub, uid):
user_id=v.id,
target_user_id=u.id
)
- g.db.add(ma)
+ db.add(ma)
if g.is_api_or_xhr:
return {"message": f"@{u.username} has been unexiled from /h/{sub} successfully!"}
@@ -113,10 +113,10 @@ def unexile(v:User, sub, uid):
@auth_required
def block_sub(v:User, sub):
sub = get_sub_by_name(sub).name
- existing = g.db.query(SubBlock).filter_by(user_id=v.id, sub=sub).one_or_none()
+ existing = db.query(SubBlock).filter_by(user_id=v.id, sub=sub).one_or_none()
if not existing:
block = SubBlock(user_id=v.id, sub=sub)
- g.db.add(block)
+ db.add(block)
cache.delete_memoized(frontlist)
return {"message": f"/h/{sub} blocked successfully!"}
@@ -130,10 +130,10 @@ def unblock_sub(v:User, sub):
if not User.can_see(v, sub):
abort(403)
- block = g.db.query(SubBlock).filter_by(user_id=v.id, sub=sub.name).one_or_none()
+ block = db.query(SubBlock).filter_by(user_id=v.id, sub=sub.name).one_or_none()
if block:
- g.db.delete(block)
+ db.delete(block)
cache.delete_memoized(frontlist)
return {"message": f"/h/{sub.name} unblocked successfully!"}
@@ -145,10 +145,10 @@ def unblock_sub(v:User, sub):
@auth_required
def subscribe_sub(v:User, sub):
sub = get_sub_by_name(sub).name
- existing = g.db.query(SubJoin).filter_by(user_id=v.id, sub=sub).one_or_none()
+ existing = db.query(SubJoin).filter_by(user_id=v.id, sub=sub).one_or_none()
if not existing:
subscribe = SubJoin(user_id=v.id, sub=sub)
- g.db.add(subscribe)
+ db.add(subscribe)
cache.delete_memoized(frontlist)
return {"message": f"/h/{sub} unblocked successfully!"}
@@ -159,9 +159,9 @@ def subscribe_sub(v:User, sub):
@auth_required
def unsubscribe_sub(v:User, sub):
sub = get_sub_by_name(sub).name
- subscribe = g.db.query(SubJoin).filter_by(user_id=v.id, sub=sub).one_or_none()
+ subscribe = db.query(SubJoin).filter_by(user_id=v.id, sub=sub).one_or_none()
if subscribe:
- g.db.delete(subscribe)
+ db.delete(subscribe)
cache.delete_memoized(frontlist)
return {"message": f"/h/{sub} blocked successfully!"}
@@ -174,10 +174,10 @@ def follow_sub(v:User, sub):
sub = get_sub_by_name(sub)
if not User.can_see(v, sub):
abort(403)
- existing = g.db.query(SubSubscription).filter_by(user_id=v.id, sub=sub.name).one_or_none()
+ existing = db.query(SubSubscription).filter_by(user_id=v.id, sub=sub.name).one_or_none()
if not existing:
subscription = SubSubscription(user_id=v.id, sub=sub.name)
- g.db.add(subscription)
+ db.add(subscription)
cache.delete_memoized(frontlist)
return {"message": f"/h/{sub} followed successfully!"}
@@ -189,9 +189,9 @@ def follow_sub(v:User, sub):
@auth_required
def unfollow_sub(v:User, sub):
sub = get_sub_by_name(sub)
- subscription = g.db.query(SubSubscription).filter_by(user_id=v.id, sub=sub.name).one_or_none()
+ subscription = db.query(SubSubscription).filter_by(user_id=v.id, sub=sub.name).one_or_none()
if subscription:
- g.db.delete(subscription)
+ db.delete(subscription)
cache.delete_memoized(frontlist)
return {"message": f"/h/{sub} unfollowed successfully!"}
@@ -204,7 +204,7 @@ def mods(v:User, sub):
sub = get_sub_by_name(sub)
if not User.can_see(v, sub):
abort(403)
- users = g.db.query(User, Mod).join(Mod).filter_by(sub=sub.name).order_by(Mod.created_utc).all()
+ users = db.query(User, Mod).join(Mod).filter_by(sub=sub.name).order_by(Mod.created_utc).all()
return render_template("sub/mods.html", v=v, sub=sub, users=users)
@@ -217,7 +217,7 @@ def sub_exilees(v:User, sub):
sub = get_sub_by_name(sub)
if not User.can_see(v, sub):
abort(403)
- users = g.db.query(User, Exile).join(Exile, Exile.user_id==User.id) \
+ users = db.query(User, Exile).join(Exile, Exile.user_id==User.id) \
.filter_by(sub=sub.name) \
.order_by(Exile.created_utc.desc(), User.username).all()
@@ -232,7 +232,7 @@ def sub_blockers(v:User, sub):
sub = get_sub_by_name(sub)
if not User.can_see(v, sub):
abort(403)
- users = g.db.query(User, SubBlock).join(SubBlock) \
+ users = db.query(User, SubBlock).join(SubBlock) \
.filter_by(sub=sub.name) \
.order_by(SubBlock.created_utc.desc(), User.username).all()
@@ -248,7 +248,7 @@ def sub_followers(v:User, sub):
sub = get_sub_by_name(sub)
if not User.can_see(v, sub):
abort(403)
- users = g.db.query(User, SubSubscription).join(SubSubscription) \
+ users = db.query(User, SubSubscription).join(SubSubscription) \
.filter_by(sub=sub.name) \
.order_by(SubSubscription.created_utc.desc(), User.username).all()
@@ -276,11 +276,11 @@ def add_mod(v:User, sub):
if sub in {'furry','vampire','racist','femboy'} and not v.client and not user.house.lower().startswith(sub):
abort(403, f"@{user.username} needs to be a member of House {sub.capitalize()} to be added as a mod there!")
- existing = g.db.query(Mod).filter_by(user_id=user.id, sub=sub).one_or_none()
+ existing = db.query(Mod).filter_by(user_id=user.id, sub=sub).one_or_none()
if not existing:
mod = Mod(user_id=user.id, sub=sub)
- g.db.add(mod)
+ db.add(mod)
if v.id != user.id:
send_repeatable_notification(user.id, f"@{v.username} has added you as a mod to /h/{sub}")
@@ -291,7 +291,7 @@ def add_mod(v:User, sub):
user_id=v.id,
target_user_id=user.id
)
- g.db.add(ma)
+ db.add(ma)
return redirect(f'/h/{sub}/mods')
@@ -317,12 +317,12 @@ def remove_mod(v:User, sub):
if not user: abort(404)
- mod = g.db.query(Mod).filter_by(user_id=user.id, sub=sub).one_or_none()
+ mod = db.query(Mod).filter_by(user_id=user.id, sub=sub).one_or_none()
if not mod: abort(400)
if not (v.id == user.id or v.mod_date(sub) and v.mod_date(sub) < mod.created_utc): abort(403)
- g.db.delete(mod)
+ db.delete(mod)
if v.id != user.id:
send_repeatable_notification(user.id, f"@{v.username} has removed you as a mod from /h/{sub}")
@@ -333,7 +333,7 @@ def remove_mod(v:User, sub):
user_id=v.id,
target_user_id=user.id
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"@{user.username} has been removed as a mod!"}
@@ -371,16 +371,16 @@ def create_sub2(v):
if sub:
return redirect(f"/create_hole?error=/h/{sub} already exists!")
- g.db.add(v)
+ db.add(v)
if v.shadowbanned: abort(500)
sub = Sub(name=name)
- g.db.add(sub)
- g.db.flush()
+ db.add(sub)
+ db.flush()
mod = Mod(user_id=v.id, sub=sub.name)
- g.db.add(mod)
+ db.add(mod)
- admins = [x[0] for x in g.db.query(User.id).filter(User.admin_level >= PERMS['NOTIFICATIONS_HOLE_CREATION'], User.id != v.id).all()]
+ admins = [x[0] for x in db.query(User.id).filter(User.admin_level >= PERMS['NOTIFICATIONS_HOLE_CREATION'], User.id != v.id).all()]
for admin in admins:
send_repeatable_notification(admin, f":!marseyparty: /h/{sub} has been created by @{v.username} :marseyparty:")
@@ -408,13 +408,13 @@ def kick(v:User, pid):
user_id=v.id,
target_submission_id=post.id
)
- g.db.add(ma)
+ db.add(ma)
if v.id != post.author_id:
message = f"@{v.username} (a /h/{old} mod) has moved [{post.title}]({post.shortlink}) from /h/{old} to the main feed!"
send_repeatable_notification(post.author_id, message)
- g.db.add(post)
+ db.add(post)
cache.delete_memoized(frontlist)
@@ -444,14 +444,14 @@ def post_sub_sidebar(v:User, sub):
sub.sidebar_html = sanitize(sub.sidebar, blackjack=f"/h/{sub} sidebar", showmore=False)
if len(sub.sidebar_html) > 20000: abort(400, "Sidebar is too big!")
- g.db.add(sub)
+ db.add(sub)
ma = SubAction(
sub=sub.name,
kind='edit_sidebar',
user_id=v.id
)
- g.db.add(ma)
+ db.add(ma)
return redirect(f'/h/{sub}/settings')
@@ -478,21 +478,21 @@ def post_sub_css(v:User, sub):
return render_template('sub/settings.html', v=v, sidebar=sub.sidebar, sub=sub, error=error, css=css)
sub.css = css
- g.db.add(sub)
+ db.add(sub)
ma = SubAction(
sub=sub.name,
kind='edit_css',
user_id=v.id
)
- g.db.add(ma)
+ db.add(ma)
return redirect(f'/h/{sub}/settings')
@app.get("/h//css")
@limiter.limit(DEFAULT_RATELIMIT)
def get_sub_css(sub):
- sub = g.db.query(Sub.css).filter_by(name=sub.strip().lower()).one_or_none()
+ sub = db.query(Sub.css).filter_by(name=sub.strip().lower()).one_or_none()
if not sub: abort(404)
resp=make_response(sub.css or "")
resp.headers.add("Content-Type", "text/css")
@@ -518,14 +518,14 @@ def upload_sub_banner(v:User, sub:str):
sub.bannerurls.append(bannerurl)
- g.db.add(sub)
+ db.add(sub)
ma = SubAction(
sub=sub.name,
kind='upload_banner',
user_id=v.id
)
- g.db.add(ma)
+ db.add(ma)
return redirect(f'/h/{sub}/settings')
@@ -548,7 +548,7 @@ def delete_sub_banner(v:User, sub:str, index:int):
except FileNotFoundError:
pass
del sub.bannerurls[index]
- g.db.add(sub)
+ db.add(sub)
ma = SubAction(
sub=sub.name,
@@ -556,7 +556,7 @@ def delete_sub_banner(v:User, sub:str, index:int):
_note=index,
user_id=v.id
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"Deleted banner {index} from /h/{sub} successfully"}
@@ -574,7 +574,7 @@ def delete_all_sub_banners(v:User, sub:str):
except FileNotFoundError:
pass
sub.bannerurls = []
- g.db.add(sub)
+ db.add(sub)
ma = SubAction(
sub=sub.name,
@@ -582,7 +582,7 @@ def delete_all_sub_banners(v:User, sub:str):
_note='all',
user_id=v.id
)
- g.db.add(ma)
+ db.add(ma)
return {"message": f"Deleted all banners from /h/{sub} successfully"}
@@ -607,14 +607,14 @@ def sub_sidebar(v:User, sub):
if sub.sidebarurl:
remove_media(sub.sidebarurl)
sub.sidebarurl = sidebarurl
- g.db.add(sub)
+ db.add(sub)
ma = SubAction(
sub=sub.name,
kind='change_sidebar_image',
user_id=v.id
)
- g.db.add(ma)
+ db.add(ma)
return redirect(f'/h/{sub}/settings')
@@ -639,14 +639,14 @@ def sub_marsey(v:User, sub):
if sub.marseyurl:
remove_media(sub.marseyurl)
sub.marseyurl = marseyurl
- g.db.add(sub)
+ db.add(sub)
ma = SubAction(
sub=sub.name,
kind='change_marsey',
user_id=v.id
)
- g.db.add(ma)
+ db.add(ma)
return redirect(f'/h/{sub}/settings')
@@ -656,8 +656,8 @@ def sub_marsey(v:User, sub):
@limiter.limit(DEFAULT_RATELIMIT, key_func=get_ID)
@auth_required
def subs(v:User):
- subs = g.db.query(Sub, func.count(Submission.sub)).outerjoin(Submission, Sub.name == Submission.sub).group_by(Sub.name).order_by(func.count(Submission.sub).desc()).all()
- total_users = g.db.query(User).count()
+ subs = db.query(Sub, func.count(Submission.sub)).outerjoin(Submission, Sub.name == Submission.sub).group_by(Sub.name).order_by(func.count(Submission.sub).desc()).all()
+ total_users = db.query(User).count()
return render_template('sub/subs.html', v=v, subs=subs, total_users=total_users)
@app.post("/hole_pin/Grant
+{% if FEATURES['BADGES'] and v.admin_level >= PERMS['USER_BADGES'] -%}
+Badges
- {% if FEATURES['BADGES'] and v.admin_level >= PERMS['USER_BADGES'] -%}
-
{%- endif %}
-{% if FEATURES['GAMBLING'] -%}
+{% if FEATURES['GAMBLING'] and v.admin_level >= PERMS['LOTTERY_VIEW_PARTICIPANTS'] -%}
Casino
- {% if v.admin_level >= PERMS['LOTTERY_VIEW_PARTICIPANTS'] %}
-
{%- endif %}
diff --git a/files/templates/hats.html b/files/templates/hats.html
index 19d673e03..8030fa6b2 100644
--- a/files/templates/hats.html
+++ b/files/templates/hats.html
@@ -64,7 +64,7 @@
{% if SITE == 'rdrama.net' %}
{% include "user_in_table.html" %}
{% endif %}
- {{hat.number_sold(g.db)}}
+ {{hat.number_sold()}}
{{hat.price}}
{% if hat.id not in owned_hat_ids and hat.is_purchasable %}
diff --git a/files/templates/settings/advanced.html b/files/templates/settings/advanced.html
index 22472fb9d..5da130f7d 100644
--- a/files/templates/settings/advanced.html
+++ b/files/templates/settings/advanced.html
@@ -132,7 +132,6 @@
{% if FEATURES['NSFW_MARKING'] %}
{{common.toggle_section('Disable +18 Warnings', 'over_18', 'over_18', v.over_18, "Disable the warnings that appear when viewing +18 content.", false)}}
{% endif %}
- {{common.toggle_section('Hide Posts Voted On', 'hidevotedon', 'hidevotedon', v.hidevotedon, 'Enable if you would like to automatically hide posts you have voted on from your frontpage.', false)}}