From 1044a3ae23979a881d55c11a309a0a3333e00834 Mon Sep 17 00:00:00 2001 From: Aevann1 Date: Sat, 31 Jul 2021 07:28:05 +0200 Subject: [PATCH] fddfd --- drama/__main__.py | 2 +- drama/helpers/wrappers.py | 2 +- drama/routes/admin.py | 30 +++++---- drama/routes/awards.py | 26 ++++---- drama/routes/comments.py | 48 ++++++-------- drama/routes/discord.py | 2 +- drama/routes/errors.py | 30 ++++----- drama/routes/front.py | 13 +--- drama/routes/oauth.py | 56 ++++++++-------- drama/routes/posts.py | 136 +++++++++----------------------------- drama/routes/search.py | 50 +++----------- drama/routes/settings.py | 26 ++++---- drama/routes/static.py | 4 +- drama/routes/users.py | 40 +++++------ 14 files changed, 169 insertions(+), 296 deletions(-) diff --git a/drama/__main__.py b/drama/__main__.py index 2f5b882ac..a6ac62ef5 100644 --- a/drama/__main__.py +++ b/drama/__main__.py @@ -249,7 +249,7 @@ def drop_connection(): def before_request(): if request.method.lower() != "get" and app.config["READ_ONLY"]: - return jsonify({"error":f"{app.config['SITE_NAME']} is currently in read-only mode."}), 500 + return {"error":f"{app.config['SITE_NAME']} is currently in read-only mode."}, 500 if app.config["BOT_DISABLE"] and request.headers.get("X-User-Type")=="Bot": abort(503) diff --git a/drama/helpers/wrappers.py b/drama/helpers/wrappers.py index b115da721..a1ff5a302 100644 --- a/drama/helpers/wrappers.py +++ b/drama/helpers/wrappers.py @@ -193,7 +193,7 @@ def admin_level_required(x): v, c = get_logged_in_user() if c: - return jsonify({"error": "No admin api access"}), 403 + return {"error": "No admin api access"}, 403 if not v: abort(401) diff --git a/drama/routes/admin.py b/drama/routes/admin.py index 11d1673d7..9dc40ce83 100644 --- a/drama/routes/admin.py +++ b/drama/routes/admin.py @@ -76,15 +76,7 @@ def image_posts_listing(v): posts = get_posts(posts, v=v) - return {'html': lambda: render_template("admin/image_posts.html", - v=v, - listing=posts, - next_exists=next_exists, - page=page, - sort="new" - ), - 'api': lambda: [x.json for x in posts] - } + return render_template("admin/image_posts.html", v=v, listing=posts, next_exists=next_exists, page=page, sort="new") @app.get("/admin/flagged/comments") @@ -703,7 +695,7 @@ def ban_user(user_id, v): if request.args.get("notoast"): return (redirect(user.url), user) - return jsonify({"message": f"@{user.username} was banned"}) + return {"message": f"@{user.username} was banned"} @app.post("/unban_user/") @@ -735,7 +727,7 @@ def unban_user(user_id, v): g.db.commit() if request.args.get("notoast"): return (redirect(user.url), user) - return jsonify({"message": f"@{user.username} was unbanned"}) + return {"message": f"@{user.username} was unbanned"} @app.post("/ban_post/") @admin_level_required(3) @@ -921,14 +913,24 @@ def admin_distinguish_comment(c_id, v): html=str(BeautifulSoup(html, features="html.parser").find(id=f"comment-{comment.id}-only")) - return jsonify({"html":html, "api":html}) + return html + +@app.get("/admin/refund") +@admin_level_required(6) +def refund(v): + for u in g.db.query(User).all(): + posts=sum([x[0]+x[1]-1 for x in g.db.query(Submission.upvotes, Submission.downvotes).options(lazyload('*')).filter_by(author_id = u.id, is_banned = False, deleted_utc = 0).all()]) + comments=sum([x[0]+x[1]-1 for x in g.db.query(Comment.upvotes, Comment.downvotes).options(lazyload('*')).filter_by(author_id = u.id, is_banned = False, deleted_utc = 0).all()]) + u.dramacoins = int(posts+comments) + g.db.add(u) + return "sex" @app.get("/admin/dump_cache") @admin_level_required(6) def admin_dump_cache(v): cache.clear() - return jsonify({"message": "Internal cache cleared."}) + return {"message": "Internal cache cleared."} @app.post("/admin/ban_domain") @@ -1098,7 +1100,7 @@ def user_stat_data(v): "comment_data": comment_stats, } - return jsonify(final) + return final def create_plot(**kwargs): diff --git a/drama/routes/awards.py b/drama/routes/awards.py index 4e9c12084..a0defc34c 100644 --- a/drama/routes/awards.py +++ b/drama/routes/awards.py @@ -43,7 +43,7 @@ def get_awards(v): for val in return_value: val['owned'] = len([x for x in user_awards if x.kind == val['kind'] and not x.given]) - return jsonify(return_value) + return return_value @app.put("/post//awards") @@ -52,12 +52,12 @@ def get_awards(v): def award_post(pid, v): if v.is_suspended and v.unban_utc == 0: - return jsonify({"error": "forbidden"}), 403 + return {"error": "forbidden"}, 403 kind = request.form.get("kind", "") if kind not in AWARDS: - return jsonify({"error": "That award doesn't exist."}), 404 + return {"error": "That award doesn't exist."}, 404 post_award = g.db.query(AwardRelationship).filter( and_( @@ -69,15 +69,15 @@ def award_post(pid, v): ).first() if not post_award: - return jsonify({"error": "You don't have that award."}), 404 + return {"error": "You don't have that award."}, 404 post = g.db.query(Submission).filter_by(id=pid).first() if not post or post.is_banned or post.deleted_utc > 0: - return jsonify({"error": "That post doesn't exist or has been deleted or removed."}), 404 + return {"error": "That post doesn't exist or has been deleted or removed."}, 404 if post.author_id == v.id: - return jsonify({"error": "You can't award yourself."}), 403 + return {"error": "You can't award yourself."}, 403 existing_award = g.db.query(AwardRelationship).filter( and_( @@ -88,7 +88,7 @@ def award_post(pid, v): ).first() if existing_award and kind not in ALLOW_MULTIPLE: - return jsonify({"error": "You can't give that award multiple times to the same post."}), 409 + return {"error": "You can't give that award multiple times to the same post."}, 409 post_award.submission_id = post.id #print(f"give award to pid {post_award.submission_id} ({post.id})") @@ -114,12 +114,12 @@ def award_post(pid, v): def award_comment(cid, v): if v.is_suspended and v.unban_utc == 0: - return jsonify({"error": "forbidden"}), 403 + return {"error": "forbidden"}, 403 kind = request.form.get("kind", "") if kind not in AWARDS: - return jsonify({"error": "That award doesn't exist."}), 404 + return {"error": "That award doesn't exist."}, 404 comment_award = g.db.query(AwardRelationship).filter( and_( @@ -131,15 +131,15 @@ def award_comment(cid, v): ).first() if not comment_award: - return jsonify({"error": "You don't have that award."}), 404 + return {"error": "You don't have that award."}, 404 c = g.db.query(Comment).filter_by(id=cid).first() if not c or c.is_banned or c.deleted_utc > 0: - return jsonify({"error": "That comment doesn't exist or has been deleted or removed."}), 404 + return {"error": "That comment doesn't exist or has been deleted or removed."}, 404 if c.author_id == v.id: - return jsonify({"error": "You can't award yourself."}), 403 + return {"error": "You can't award yourself."}, 403 existing_award = g.db.query(AwardRelationship).filter( and_( @@ -150,7 +150,7 @@ def award_comment(cid, v): ).first() if existing_award and kind not in ALLOW_MULTIPLE: - return jsonify({"error": "You can't give that award multiple times to the same comment."}), 409 + return {"error": "You can't give that award multiple times to the same comment."}, 409 comment_award.comment_id = c.id g.db.add(comment_award) diff --git a/drama/routes/comments.py b/drama/routes/comments.py index bd2f5ce7a..4ebb2aeab 100644 --- a/drama/routes/comments.py +++ b/drama/routes/comments.py @@ -43,12 +43,8 @@ def post_pid_comment_cid(cid, pid=None, anything=None, v=None): post = get_post(pid, v=v) if post.over_18 and not (v and v.over_18) and not session.get('over_18', 0) >= int(time.time()): - return {'html': lambda: render_template("errors/nsfw.html", - v=v, - ), - 'api': lambda: {'error': f'This content is not suitable for some users and situations.'} - - } + if request.headers.get("Authorization"): return {'error': f'This content is not suitable for some users and situations.'} + else: render_template("errors/nsfw.html", v=v) post._preloaded_comments = [comment] @@ -219,7 +215,7 @@ def api_comment(v): body = request.form.get("body", "")[0:10000] body = body.strip() - if not body and not request.files.get('file'): return jsonify({"error":"You need to actually write something!"}), 400 + if not body and not request.files.get('file'): return {"error":"You need to actually write something!"}, 400 for i in re.finditer('^(https:\/\/.*\.(png|jpg|jpeg|gif|PNG|JPG|JPEG|GIF))', body, re.MULTILINE): body = body.replace(i.group(1), f'![]({i.group(1)})') body = body.replace("\n", "\n\n").replace("\n\n\n\n\n\n", "\n\n").replace("\n\n\n\n", "\n\n") @@ -240,7 +236,7 @@ def api_comment(v): v.ban(days=30, reason="Digitally malicious content") if any([x.reason==7 for x in bans]): v.ban( reason="Sexualizing minors") - return jsonify({"error": reason}), 401 + return {"error": reason}, 401 # check existing existing = g.db.query(Comment).join(CommentAux).filter(Comment.author_id == v.id, @@ -250,7 +246,7 @@ def api_comment(v): CommentAux.body == body ).options(contains_eager(Comment.comment_aux)).first() if existing: - return jsonify({"error": f"You already made that comment: {existing.permalink}"}), 409 + return {"error": f"You already made that comment: {existing.permalink}"}, 409 if parent.author.any_block_exists(v) and not v.admin_level>=3: return jsonify( @@ -305,7 +301,7 @@ def api_comment(v): g.db.add(ma) g.db.commit() - return jsonify({"error": "Too much spam!"}), 403 + return {"error": "Too much spam!"}, 403 # check badlinks soup = BeautifulSoup(body_html, features="html.parser") @@ -326,7 +322,7 @@ def api_comment(v): BadLink.link)).first() if badlink: - return jsonify({"error": f"Remove the following link and try again: `{check_url}`. Reason: {badlink.reason_text}"}), 403 + return {"error": f"Remove the following link and try again: `{check_url}`. Reason: {badlink.reason_text}"}, 403 # create comment parent_id = parent_fullname.split("_")[1] c = Comment(author_id=v.id, @@ -343,7 +339,7 @@ def api_comment(v): if request.files.get("file"): file=request.files["file"] if not file.content_type.startswith('image/'): - return jsonify({"error": "That wasn't an image!"}), 400 + return {"error": "That wasn't an image!"}, 400 name = f'comment/{c.id}/{secrets.token_urlsafe(8)}' url = upload_file(file) @@ -579,13 +575,8 @@ def api_comment(v): v.comment_count = v.comments.filter(Comment.parent_submission != None).filter_by(is_banned=False, deleted_utc=0).count() g.db.add(v) - return {"html": lambda: jsonify({"html": render_template("comments.html", - v=v, - comments=[c], - render_replies=False, - )}), - "api": lambda: c.json - } + if request.headers.get("Authorization"): return c.json + else: return render_template("comments.html", v=v, comments=[c], render_replies=False) @@ -616,7 +607,7 @@ def edit_comment(cid, v): #auto ban for digitally malicious content if any([x.reason==4 for x in bans]): v.ban(days=30, reason="Digitally malicious content is not allowed.") - return jsonify({"error":"Digitally malicious content is not allowed."}) + return {"error":"Digitally malicious content is not allowed."} if ban.reason: reason += f" {ban.reason_text}" @@ -650,7 +641,7 @@ def edit_comment(cid, v): BadLink.link)).first() if badlink: - return jsonify({"error": f"Remove the following link and try again: `{check_url}`. Reason: {badlink.reason_text}"}), 403 + return {"error": f"Remove the following link and try again: `{check_url}`. Reason: {badlink.reason_text}"}, 403 # check spam - this should hopefully be faster now = int(time.time()) @@ -688,11 +679,11 @@ def edit_comment(cid, v): g.db.add(comment) g.db.commit() - return jsonify({"error": "Too much spam!"}), 403 + return {"error": "Too much spam!"}, 403 if request.files.get("file"): file=request.files["file"] - if not file.content_type.startswith('image/'): return jsonify({"error": "That wasn't an image!"}), 400 + if not file.content_type.startswith('image/'): return {"error": "That wasn't an image!"}, 400 name = f'comment/{c.id}/{secrets.token_urlsafe(8)}' url = upload_file(file) @@ -777,7 +768,7 @@ def edit_comment(cid, v): n = Notification(comment_id=c.id, user_id=x) g.db.add(n) - return jsonify({"html": c.body_html}) + return c.body_html @app.post("/delete/comment/") @auth_required @@ -799,8 +790,7 @@ def delete_comment(cid, v): cache.delete_memoized(User.commentlisting, v) - return {"html": lambda: ("", 204), - "api": lambda: ("", 204)} + return "", 204 @app.post("/undelete/comment/") @auth_required @@ -821,8 +811,8 @@ def undelete_comment(cid, v): cache.delete_memoized(User.commentlisting, v) - return {"html": lambda: ("", 204), - "api": lambda: ("", 204)} + return "", 204 + @app.post("/comment_pin/") @auth_required @@ -856,7 +846,7 @@ def toggle_comment_pin(cid, v): html=str(BeautifulSoup(html, features="html.parser").find(id=f"comment-{comment.id}-only")) - return jsonify({"html":html}) + return html @app.post("/save_comment/") diff --git a/drama/routes/discord.py b/drama/routes/discord.py index cb519613d..72f7a6d95 100644 --- a/drama/routes/discord.py +++ b/drama/routes/discord.py @@ -130,7 +130,7 @@ def discord_redirect(v): else: add_role(v, "norep") else: - return jsonify(x.json()) + return x.json() #check on if they are already there #print(x.status_code) diff --git a/drama/routes/errors.py b/drama/routes/errors.py index 99c4bd070..2997d3cd4 100644 --- a/drama/routes/errors.py +++ b/drama/routes/errors.py @@ -15,7 +15,7 @@ from drama.__main__ import app @auth_desired def error_400(e, v): return{"html": lambda: (render_template('errors/400.html', v=v), 400), - "api": lambda: (jsonify({"error": "400 Bad Request"}), 400 ) + "api": lambda: ({"error": "400 Bad Request"}, 400 ) } @@ -27,7 +27,7 @@ def error_401(e): argval = quote(f"{path}?{qs}", safe='') output = f"/login?redirect={argval}" - if request.headers.get("Authorization"): return jsonify({"error": "401 Not Authorized"}), 401 + if request.headers.get("Authorization"): return {"error": "401 Not Authorized"}, 401 else: return redirect(output) @@ -35,7 +35,7 @@ def error_401(e): @auth_desired def error_403(e, v): return{"html": lambda: (render_template('errors/403.html', v=v), 403), - "api": lambda: (jsonify({"error": "403 Forbidden"}), 403) + "api": lambda: ({"error": "403 Forbidden"}, 403) } @@ -43,7 +43,7 @@ def error_403(e, v): @auth_desired def error_404(e, v): return{"html": lambda: (render_template('errors/404.html', v=v), 404), - "api": lambda: (jsonify({"error": "404 Not Found"}), 404) + "api": lambda: ({"error": "404 Not Found"}, 404) } @@ -51,7 +51,7 @@ def error_404(e, v): @auth_desired def error_405(e, v): return{"html": lambda: (render_template('errors/405.html', v=v), 405), - "api": lambda: (jsonify({"error": "405 Method Not Allowed"}), 405) + "api": lambda: ({"error": "405 Method Not Allowed"}, 405) } @@ -59,7 +59,7 @@ def error_405(e, v): @auth_desired def error_409(e, v): return{"html": lambda: (render_template('errors/409.html', v=v), 409), - "api": lambda: (jsonify({"error": "409 Conflict"}), 409) + "api": lambda: ({"error": "409 Conflict"}, 409) } @@ -67,21 +67,21 @@ def error_409(e, v): @auth_desired def error_410(e, v): return{"html": lambda: (render_template('errors/410.html', v=v), 410), - "api": lambda: (jsonify({"error": "410 Request Payload Too Large"}), 410) + "api": lambda: ({"error": "410 Request Payload Too Large"}, 410) } @app.errorhandler(413) @auth_desired def error_413(e, v): return{"html": lambda: (render_template('errors/413.html', v=v), 413), - "api": lambda: (jsonify({"error": "413 Image Size Too Large"}), 413) + "api": lambda: ({"error": "413 Image Size Too Large"}, 413) } @app.errorhandler(418) @auth_desired def error_418(e, v): return{"html": lambda: (render_template('errors/418.html', v=v), 418), - "api": lambda: (jsonify({"error": "418 I'm A Teapot"}), 418) + "api": lambda: ({"error": "418 I'm A Teapot"}, 418) } @@ -89,7 +89,7 @@ def error_418(e, v): @auth_desired def error_422(e, v): return{"html": lambda: (render_template('errors/422.html', v=v), 422), - "api": lambda: (jsonify({"error": "422 Unprocessable Entity"}), 422) + "api": lambda: ({"error": "422 Unprocessable Entity"}, 422) } @@ -97,7 +97,7 @@ def error_422(e, v): @auth_desired def error_429(e, v): return{"html": lambda: (render_template('errors/429.html', v=v), 429), - "api": lambda: (jsonify({"error": "429 Too Many Requests"}), 429) + "api": lambda: ({"error": "429 Too Many Requests"}, 429) } @@ -105,7 +105,7 @@ def error_429(e, v): @auth_desired def error_451(e, v): return{"html": lambda: (render_template('errors/451.html', v=v), 451), - "api": lambda: (jsonify({"error": "451 Unavailable For Legal Reasons"}), 451) + "api": lambda: ({"error": "451 Unavailable For Legal Reasons"}, 451) } @@ -118,7 +118,7 @@ def error_500(e, v): pass return{"html": lambda: (render_template('errors/500.html', v=v), 500), - "api": lambda: (jsonify({"error": "500 Internal Server Error"}), 500) + "api": lambda: ({"error": "500 Internal Server Error"}, 500) } @@ -126,7 +126,7 @@ def error_500(e, v): @auth_desired def error_502(e, v): return{"html": lambda: (render_template('errors/502.html', v=v), 502), - "api": lambda: (jsonify({"error": "502 Bad Gateway"}), 502) + "api": lambda: ({"error": "502 Bad Gateway"}, 502) } @@ -134,7 +134,7 @@ def error_502(e, v): @auth_desired def error_503(e, v): return{"html": lambda: (render_template('errors/503.html', v=v), 503), - "api": lambda: (jsonify({"error": "503 Service Unavailable"}), 503) + "api": lambda: ({"error": "503 Service Unavailable"}, 503) } diff --git a/drama/routes/front.py b/drama/routes/front.py index cfba371d3..c264549f2 100644 --- a/drama/routes/front.py +++ b/drama/routes/front.py @@ -214,7 +214,7 @@ def front_all(v): # check if ids exist posts = get_posts(ids, v=v) - if request.headers.get("Authorization"): return jsonify({"data": [x.json for x in posts], "next_exists": next_exists}) + if request.headers.get("Authorization"): return {"data": [x.json for x in posts], "next_exists": next_exists} else: return render_template("home.html", v=v, listing=posts, next_exists=next_exists, sort=sort, t=t, page=page) @cache.memoize(timeout=1500) @@ -424,12 +424,5 @@ def all_comments(v): idlist = idlist[0:25] - return {"html": lambda: render_template("home_comments.html", - v=v, - sort=sort, - t=t, - page=page, - comments=comments, - standalone=True, - next_exists=next_exists), - "api": lambda: jsonify({"data": [x.json for x in comments]})} \ No newline at end of file + if request.headers.get("Authorization"): return [x.json for x in comments] + else: return render_template("home_comments.html", v=v, sort=sort, t=t, page=page, comments=comments, standalone=True, next_exists=next_exists) \ No newline at end of file diff --git a/drama/routes/oauth.py b/drama/routes/oauth.py index e01d9f88c..e60c8b96d 100644 --- a/drama/routes/oauth.py +++ b/drama/routes/oauth.py @@ -32,10 +32,10 @@ def oauth_authorize_prompt(v): application = g.db.query(OauthApp).filter_by(client_id=client_id).first() if not application: - return jsonify({"oauth_error": "Invalid `client_id`"}), 401 + return {"oauth_error": "Invalid `client_id`"}, 401 if application.is_banned: - return jsonify({"oauth_error": f"Application `{application.app_name}` is suspended."}), 403 + return {"oauth_error": f"Application `{application.app_name}` is suspended."}, 403 scopes_txt = request.args.get('scope', "") @@ -46,24 +46,24 @@ def oauth_authorize_prompt(v): for scope in scopes: if scope not in SCOPES: - return jsonify({"oauth_error": f"The provided scope `{scope}` is not valid."}), 400 + return {"oauth_error": f"The provided scope `{scope}` is not valid."}, 400 if any(x in scopes for x in ["create", "update"]) and "identity" not in scopes: - return jsonify({"oauth_error": f"`identity` scope required when requesting `create` or `update` scope."}), 400 + return {"oauth_error": f"`identity` scope required when requesting `create` or `update` scope."}, 400 redirect_uri = request.args.get("redirect_uri") if not redirect_uri: - return jsonify({"oauth_error": f"`redirect_uri` must be provided."}), 400 + return {"oauth_error": f"`redirect_uri` must be provided."}, 400 valid_redirect_uris = [x.strip() for x in application.redirect_uri.split(",")] if redirect_uri not in valid_redirect_uris: - return jsonify({"oauth_error": "Invalid redirect_uri"}), 400 + return {"oauth_error": "Invalid redirect_uri"}, 400 state = request.args.get("state") if not state: - return jsonify({'oauth_error': 'state argument required'}), 400 + return {'oauth_error': 'state argument required'}, 400 permanent = bool(request.args.get("permanent")) @@ -92,14 +92,14 @@ def oauth_authorize_post(v): application = g.db.query(OauthApp).filter_by(client_id=client_id).first() if not application: - return jsonify({"oauth_error": "Invalid `client_id`"}), 401 + return {"oauth_error": "Invalid `client_id`"}, 401 if application.is_banned: - return jsonify({"oauth_error": f"Application `{application.app_name}` is suspended."}), 403 + return {"oauth_error": f"Application `{application.app_name}` is suspended."}, 403 valid_redirect_uris = [x.strip() for x in application.redirect_uri.split(",")] if redirect_uri not in valid_redirect_uris: - return jsonify({"oauth_error": "Invalid redirect_uri"}), 400 + return {"oauth_error": "Invalid redirect_uri"}, 400 scopes = scopes_txt.split(',') if not scopes: @@ -108,13 +108,13 @@ def oauth_authorize_post(v): for scope in scopes: if scope not in SCOPES: - return jsonify({"oauth_error": f"The provided scope `{scope}` is not valid."}), 400 + return {"oauth_error": f"The provided scope `{scope}` is not valid."}, 400 if any(x in scopes for x in ["create", "update"]) and "identity" not in scopes: - return jsonify({"oauth_error": f"`identity` scope required when requesting `create` or `update` scope."}), 400 + return {"oauth_error": f"`identity` scope required when requesting `create` or `update` scope."}, 400 if not state: - return jsonify({'oauth_error': 'state argument required'}), 400 + return {'oauth_error': 'state argument required'}, 400 permanent = bool(int(request.values.get("permanent", 0))) @@ -152,13 +152,13 @@ def oauth_grant(): return jsonify( {"oauth_error": "Invalid `client_id` or `client_secret`"}), 401 if application.is_banned: - return jsonify({"oauth_error": f"Application `{application.app_name}` is suspended."}), 403 + return {"oauth_error": f"Application `{application.app_name}` is suspended."}, 403 if request.values.get("grant_type") == "code": code = request.values.get("code") if not code: - return jsonify({"oauth_error": "code required"}), 400 + return {"oauth_error": "code required"}, 400 auth = g.db.query(ClientAuth).filter_by( oauth_code=code, @@ -167,7 +167,7 @@ def oauth_grant(): ).first() if not auth: - return jsonify({"oauth_error": "Invalid code"}), 401 + return {"oauth_error": "Invalid code"}, 401 auth.oauth_code = None auth.access_token = secrets.token_urlsafe(128)[0:128] @@ -187,13 +187,13 @@ def oauth_grant(): if auth.refresh_token: data["refresh_token"] = auth.refresh_token - return jsonify(data) + return data elif request.values.get("grant_type") == "refresh": refresh_token = request.values.get('refresh_token') if not refresh_token: - return jsonify({"oauth_error": "refresh_token required"}), 401 + return {"oauth_error": "refresh_token required"}, 401 auth = g.db.query(ClientAuth).filter_by( refresh_token=refresh_token, @@ -202,7 +202,7 @@ def oauth_grant(): ).first() if not auth: - return jsonify({"oauth_error": "Invalid refresh_token"}), 401 + return {"oauth_error": "Invalid refresh_token"}, 401 auth.access_token = secrets.token_urlsafe(128)[0:128] auth.access_token_expire_utc = int(time.time()) + 60 * 60 @@ -215,10 +215,10 @@ def oauth_grant(): "expires_at": auth.access_token_expire_utc } - return jsonify(data) + return data else: - return jsonify({"oauth_error": f"Invalid grant_type `{request.values.get('grant_type','')}`. Expected `code` or `refresh`."}), 400 + return {"oauth_error": f"Invalid grant_type `{request.values.get('grant_type',''}`. Expected `code` or `refresh`."}), 400 @app.post("/api_keys") @@ -277,7 +277,7 @@ def edit_oauth_app(v, aid): @app.route("/identity") @auth_required def api_v1_identity(v): - return jsonify(v.json) + return v.json @app.post("/admin/app/approve/") @@ -295,7 +295,7 @@ def admin_app_approve(v, aid): u = get_account(app.author_id, v=v) send_notification(1046, u, f"Your application `{app.app_name}` has been approved.") - return jsonify({"message": f"{app.app_name} approved"}) + return {"message": f"{app.app_name} approved"} @app.post("/admin/app/revoke/") @@ -313,7 +313,7 @@ def admin_app_revoke(v, aid): u = get_account(app.author_id, v=v) send_notification(1046, u, f"Your application `{app.app_name}` has been revoked.") - return jsonify({"message": f"{app.app_name} revoked"}) + return {"message": f"{app.app_name} revoked"} @app.post("/admin/app/reject/") @@ -332,7 +332,7 @@ def admin_app_reject(v, aid): g.db.delete(app) - return jsonify({"message": f"{app.app_name} rejected"}) + return {"message": f"{app.app_name} rejected"} @app.get("/admin/app/") @@ -439,7 +439,7 @@ def oauth_rescind_app(aid, v): g.db.delete(auth) - return jsonify({"message": f"{auth.application.app_name} Revoked"}) + return {"message": f"{auth.application.app_name} Revoked"} @app.post("/release") @auth_required @@ -457,7 +457,7 @@ def oauth_release_auth(v): auth.access_token_expire_utc=0 g.db.add(auth) - return jsonify({"message":"Authorization released"}) + return {"message":"Authorization released"} @app.post("/kill") @auth_required @@ -471,4 +471,4 @@ def oauth_kill_auth(v): g.db.delete(auth) - return jsonify({"message":"Authorization released"}) + return {"message":"Authorization released"} diff --git a/drama/routes/posts.py b/drama/routes/posts.py index 5ab0fb775..950fdf6b0 100644 --- a/drama/routes/posts.py +++ b/drama/routes/posts.py @@ -202,17 +202,15 @@ def post_id(pid, anything=None, v=None): g.db.commit() if isinstance(session.get('over_18', 0), dict): session["over_18"] = 0 if post.over_18 and not (v and v.over_18) and not session.get('over_18', 0) >= int(time.time()): - return {"html":lambda:render_template("errors/nsfw.html", - v=v, - ), - "api":lambda:(jsonify({"error":"Must be 18+ to view"}), 451) - } + if request.headers.get("Authorization"): return {"error":"Must be 18+ to view"}, 451 + else: return render_template("errors/nsfw.html", v=v) + post.tree_comments() return { "html":lambda:post.rendered_page(v=v, sort=sort), - "api":lambda:jsonify(post.json) + "api":lambda:post.json } @app.post("/edit_post/") @@ -354,11 +352,11 @@ def get_post_title(v): try: x = requests.get(url, headers=headers) except BaseException: - return jsonify({"error": "Could not reach page"}), 400 + return {"error": "Could not reach page"}, 400 if not x.status_code == 200: - return jsonify({"error": f"Page returned {x.status_code}"}), x.status_code + return {"error": f"Page returned {x.status_code}"}, x.status_code try: @@ -368,9 +366,9 @@ def get_post_title(v): "title": soup.find('title').string } - return jsonify(data) + return data except BaseException: - return jsonify({"error": f"Could not find a title"}), 400 + return {"error": f"Could not find a title"}, 400 def thumbs(new_post): pid = new_post.id @@ -539,42 +537,22 @@ def submit_post(v): return redirect(repost.permalink) if not title: - return {"html": lambda: (render_template("submit.html", - v=v, - error="Please enter a better title.", - title=title, - url=url, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": "Please enter a better title"}, 400) - } + if request.headers.get("Authorization"): return {"error": "Please enter a better title"}, 400 + else: return render_template("submit.html", v=v, error="Please enter a better title.", title=title, url=url, body=request.form.get("body", "")), 400 + elif len(title) > 500: - return {"html": lambda: (render_template("submit.html", - v=v, - error="500 character limit for titles.", - title=title[0:500], - url=url, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": "500 character limit for titles"}, 400) - } + if request.headers.get("Authorization"): return {"error": "500 character limit for titles"}, 400 + else: render_template("submit.html", v=v, error="500 character limit for titles.", title=title[0:500], url=url, body=request.form.get("body", "")), 400 + parsed_url = urlparse(url) if not (parsed_url.scheme and parsed_url.netloc) and not request.form.get( "body") and not request.files.get("file", None): - return {"html": lambda: (render_template("submit.html", - v=v, - error="Please enter a url or some text.", - title=title, - url=url, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": "`url` or `body` parameter required."}, 400) - } + + if request.headers.get("Authorization"): return {"error": "`url` or `body` parameter required."}, 400 + else: return render_template("submit.html", v=v, error="Please enter a url or some text.", title=title, url=url, body=request.form.get("body", "")), 400 + # sanitize title title = bleach.clean(title, tags=[]) @@ -624,16 +602,8 @@ def submit_post(v): elif domain_obj.reason==7: v.ban(reason="Sexualizing minors") - return {"html": lambda: (render_template("submit.html", - v=v, - error="ToS Violation", - title=title, - url=url, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": "ToS violation"}, 400) - } + if request.headers.get("Authorization"): return {"error":"ToS violation"}, 400 + else: return render_template("submit.html", v=v, error="ToS Violation", title=title, url=url, body=request.form.get("body", "")), 400 # check for embeds if domain_obj.embed_function: @@ -727,29 +697,13 @@ def submit_post(v): # catch too-long body if len(str(body)) > 10000: - return {"html": lambda: (render_template("submit.html", - v=v, - error="10000 character limit for text body.", - title=title, - url=url, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": "10000 character limit for text body."}, 400) - } + if request.headers.get("Authorization"): return {"error":"10000 character limit for text body."}, 400 + else: return render_template("submit.html", v=v, error="10000 character limit for text body.", title=title, url=url, body=request.form.get("body", "")), 400 if len(url) > 2048: - return {"html": lambda: (render_template("submit.html", - v=v, - error="2048 character limit for URLs.", - title=title, - url=url, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": "2048 character limit for URLs."}, 400) - } + if request.headers.get("Authorization"): return {"error":"2048 character limit for URLs."}, 400 + else: return render_template("submit.html", v=v, error="2048 character limit for URLs.", title=title, url=url,body=request.form.get("body", "")), 400 # render text for i in re.finditer('^(https:\/\/.*\.(png|jpg|jpeg|gif|PNG|JPG|JPEG|GIF))', body, re.MULTILINE): body = body.replace(i.group(1), f'![]({i.group(1)})') @@ -771,16 +725,8 @@ def submit_post(v): v.ban(days=30, reason="Digitally malicious content is not allowed.") abort(403) - return {"html": lambda: (render_template("submit.html", - v=v, - error=reason, - title=title, - url=url, - body=request.form.get( - "body", ""), - ), 403), - "api": lambda: ({"error": reason}, 403) - } + if request.headers.get("Authorization"): return {"error": reason}, 403 + else: return render_template("submit.html", v=v, error=reason, title=title, url=url, body=request.form.get("body", "")), 403 # check spam soup = BeautifulSoup(body_html, features="html.parser") @@ -810,17 +756,8 @@ def submit_post(v): return redirect('/notifications') else: - - return {"html": lambda: (render_template("submit.html", - v=v, - error=f"The link `{badlink.link}` is not allowed. Reason: {badlink.reason}.", - title=title, - url=url, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": f"The link `{badlink.link}` is not allowed. Reason: {badlink.reason}"}, 400) - } + if request.headers.get("Authorization"): return {"error": f"The link `{badlink.link}` is not allowed. Reason: {badlink.reason}"}, 400 + else: return render_template("submit.html", v=v, error=f"The link `{badlink.link}` is not allowed. Reason: {badlink.reason}.", title=title, url=url, body=request.form.get("body", "")), 400 # check for embeddable video domain = parsed_url.netloc @@ -876,15 +813,9 @@ def submit_post(v): file = request.files['file'] if not file.content_type.startswith('image/'): - return {"html": lambda: (render_template("submit.html", - v=v, - error=f"Image files only.", - title=title, - body=request.form.get( - "body", ""), - ), 400), - "api": lambda: ({"error": f"Image files only"}, 400) - } + if request.headers.get("Authorization"): return {"error": f"Image files only"}, 400 + else: return render_template("submit.html", v=v, error=f"Image files only.", title=title, body=request.form.get("body", "")), 400 + name = f'post/{new_post.id}/{secrets.token_urlsafe(8)}' new_post.url = upload_file(file) @@ -997,9 +928,8 @@ def submit_post(v): cache.delete_memoized(frontlist) - return {"html": lambda: redirect(new_post.permalink), - "api": lambda: jsonify(new_post.json) - } + if request.headers.get("Authorization"): return new_post.json + else: return redirect(new_post.permalink) @app.post("/delete_post/") diff --git a/drama/routes/search.py b/drama/routes/search.py index a5aa751bb..1835e81bc 100644 --- a/drama/routes/search.py +++ b/drama/routes/search.py @@ -223,21 +223,9 @@ def searchposts(v, search_type="posts"): domain=None domain_obj=None - return {"html":lambda:render_template("search.html", - v=v, - query=query, - total=total, - page=page, - listing=posts, - sort=sort, - t=t, - next_exists=next_exists, - domain=domain, - domain_obj=domain_obj, - reasons=REASONS - ), - "api":lambda:jsonify({"data":[x.json for x in posts]}) - } + if request.headers.get("Authorization"): return [x.json for x in posts] + else: return render_template("search_comments.html", v=v, query=query, total=total, page=page, listing=posts, sort=sort, t=t, next_exists=next_exists, domain=domain, domain_obj=domain_obj, reasons=REASONS) + @app.get("/search/comments") @auth_desired @@ -260,19 +248,10 @@ def searchcomments(v): comments = get_comments(ids, v=v) - return {"html":lambda:render_template("search_comments.html", - v=v, - query=query, - total=total, - page=page, - comments=comments, - sort=sort, - t=t, - next_exists=next_exists, - ), - "api":lambda:jsonify({"data":[x.json for x in comments]}) - } - + if request.headers.get("Authorization"): return [x.json for x in comments] + else: return render_template("search_comments.html", v=v, query=query, total=total, page=page, comments=comments, sort=sort, t=t, next_exists=next_exists) + + @app.get("/search/users") @auth_desired def searchusers(v, search_type="posts"): @@ -299,16 +278,5 @@ def searchusers(v, search_type="posts"): users=users[:25] - - return {"html":lambda:render_template("search_users.html", - v=v, - query=query, - total=total, - page=page, - users=users, - sort=sort, - t=t, - next_exists=next_exists - ), - "api":lambda:jsonify({"data":[x.json for x in users]}) - } \ No newline at end of file + if request.headers.get("Authorization"): return [x.json for x in users] + else: return render_template("search_users.html", v=v, query=query, total=total, page=page, users=users, sort=sort, t=t, next_exists=next_exists) \ No newline at end of file diff --git a/drama/routes/settings.py b/drama/routes/settings.py index 1eca418ef..c3ac1ed78 100644 --- a/drama/routes/settings.py +++ b/drama/routes/settings.py @@ -53,7 +53,7 @@ def settings_profile_post(v): if v.animatedname == False: users = g.db.query(User.id).options(lazyload('*')).order_by(User.dramacoins.desc()).limit(25).all() users = [x[0] for x in users] - if v.id not in users: return jsonify({"error": "You must be in the top 25 leaderboard or be a patron to apply an animated name!"}), 403 + if v.id not in users: return {"error": "You must be in the top 25 leaderboard or be a patron to apply an animated name!"}, 403 updated = True v.animatedname = request.values.get("animatedname", None) == 'true' @@ -87,7 +87,7 @@ def settings_profile_post(v): #auto ban for digitally malicious content if any([x.reason==4 for x in bans]): v.ban(days=30, reason="Digitally malicious content is not allowed.") - return jsonify({"error": reason}), 401 + return {"error": reason}, 401 v.bio = bio v.bio_html=bio_html @@ -148,10 +148,10 @@ def settings_profile_post(v): if updated: g.db.add(v) - return jsonify({"message": "Your settings have been updated."}) + return {"message": "Your settings have been updated."} else: - return jsonify({"error": "You didn't change anything."}), 400 + return {"error": "You didn't change anything."}, 400 @app.post("/changelogsub") @auth_required @@ -447,16 +447,16 @@ def settings_block_user(v): user = get_user(request.values.get("username"), graceful=True) if not user: - return jsonify({"error": "That user doesn't exist."}), 404 + return {"error": "That user doesn't exist."}, 404 if user.id == v.id: - return jsonify({"error": "You can't block yourself."}), 409 + return {"error": "You can't block yourself."}, 409 if v.has_block(user): - return jsonify({"error": f"You have already blocked @{user.username}."}), 409 + return {"error": f"You have already blocked @{user.username}."}, 409 if user.id == 1046: - return jsonify({"error": "You can't block @Drama."}), 409 + return {"error": "You can't block @Drama."}, 409 new_block = UserBlock(user_id=v.id, target_id=user.id, @@ -471,11 +471,11 @@ def settings_block_user(v): if request.args.get("notoast"): return "", 204 - if v.admin_level == 1: return jsonify({"message": f"@{user.username} banned!"}) + if v.admin_level == 1: return {"message": f"@{user.username} banned!"} cache.delete_memoized(frontlist) - return jsonify({"message": f"@{user.username} blocked."}) + return {"message": f"@{user.username} blocked."} @app.post("/settings/unblock") @@ -498,11 +498,11 @@ def settings_unblock_user(v): if request.args.get("notoast"): return "", 204 - if v.admin_level == 1: return jsonify({"message": f"@{user.username} unbanned!"}) + if v.admin_level == 1: return {"message": f"@{user.username} unbanned!"} cache.delete_memoized(frontlist) - return jsonify({"message": f"@{user.username} unblocked."}) + return {"message": f"@{user.username} unblocked."} @app.get("/settings/apps") @@ -705,4 +705,4 @@ def settings_badge_recheck(v): v.refresh_selfset_badges() - return jsonify({"message":"Badges Refreshed"}) \ No newline at end of file + return {"message":"Badges Refreshed"} \ No newline at end of file diff --git a/drama/routes/static.py b/drama/routes/static.py index 09121eb53..ef92b5c7a 100644 --- a/drama/routes/static.py +++ b/drama/routes/static.py @@ -16,7 +16,7 @@ def badmins(v): badmins = g.db.query(User).filter_by(admin_level=6).order_by(User.dramacoins.desc()).all() return { "html":lambda:render_template("badmins.html", v=v, badmins=badmins), - "api":lambda:jsonify({"data":[x.json for x in badmins]}) + "api":lambda:{"data":[x.json for x in badmins]} } @app.get("/log") @@ -39,7 +39,7 @@ def log(v): next_exists=next_exists, page=page ), - "api":lambda:jsonify({"data":[x.json for x in actions]}) + "api":lambda:{"data":[x.json for x in actions]} } @app.get("/log/") diff --git a/drama/routes/users.py b/drama/routes/users.py index 360e77646..3f56baf2a 100644 --- a/drama/routes/users.py +++ b/drama/routes/users.py @@ -127,8 +127,8 @@ def message2(v, username): abort(418) user = get_user(username, v=v) - if user.is_blocking: return jsonify({"error": "You're blocking this user."}), 403 - if user.is_blocked: return jsonify({"error": "This user is blocking you."}), 403 + if user.is_blocking: return {"error": "You're blocking this user."}, 403 + if user.is_blocked: return {"error": "This user is blocking you."}, 403 message = request.form.get("message", "")[:1000].strip() message = message.replace("\n", "\n\n").replace("\n\n\n\n\n\n", "\n\n").replace("\n\n\n\n", "\n\n") @@ -179,7 +179,7 @@ def api_is_available(name, v): name=name.strip() if len(name)<3 or len(name)>25: - return jsonify({name:False}) + return {name:False} name=name.replace('_','\_') @@ -193,9 +193,9 @@ def api_is_available(name, v): ).first() if x: - return jsonify({name: False}) + return {name: False} else: - return jsonify({name: True}) + return {name: True} @app.get("/id/") @@ -341,7 +341,7 @@ def u_username(username, v=None): t=t, next_exists=next_exists, is_following=(v and u.has_follower(v))), - 'api': lambda: jsonify({"data": [x.json for x in listing]}) + 'api': lambda: {"data": [x.json for x in listing]} } return {'html': lambda: render_template("userpage.html", @@ -353,7 +353,7 @@ def u_username(username, v=None): t=t, next_exists=next_exists, is_following=(v and u.has_follower(v))), - 'api': lambda: jsonify({"data": [x.json for x in listing]}) + 'api': lambda: {"data": [x.json for x in listing]} } @@ -434,18 +434,8 @@ def u_username_comments(username, v=None): is_following = (v and user.has_follower(v)) - return {"html": lambda: render_template("userpage_comments.html", - u=user, - v=v, - listing=listing, - page=page, - sort=sort, - t=t, - next_exists=next_exists, - is_following=is_following, - standalone=True), - "api": lambda: jsonify({"data": [c.json for c in listing]}) - } + if request.headers.get("Authorization"): return [c.json for c in listing] + else: return render_template("userpage_comments.html", u=user, v=v, listing=listing, page=page, sort=sort, t=t,next_exists=next_exists, is_following=is_following, standalone=True) @app.get("/@/info") @auth_desired @@ -454,11 +444,11 @@ def u_username_info(username, v=None): user=get_user(username, v=v) if user.is_blocking: - return jsonify({"error": "You're blocking this user."}), 401 + return {"error": "You're blocking this user."}, 401 elif user.is_blocked: - return jsonify({"error": "This user is blocking you."}), 403 + return {"error": "This user is blocking you."}, 403 - return jsonify(user.json) + return user.json @app.post("/follow/") @@ -467,7 +457,7 @@ def follow_user(username, v): target = get_user(username) - if target.id==v.id: return jsonify({"error": "You can't follow yourself!"}), 400 + if target.id==v.id: return {"error": "You can't follow yourself!"}, 400 # check for existing follow if g.db.query(Follow).filter_by(user_id=v.id, target_id=target.id).first(): abort(409) @@ -539,7 +529,7 @@ def saved_posts(v, username): page=page, next_exists=next_exists, ), - 'api': lambda: jsonify({"data": [x.json for x in listing]}) + 'api': lambda: {"data": [x.json for x in listing]} } @@ -565,5 +555,5 @@ def saved_comments(v, username): page=page, next_exists=next_exists, standalone=True), - 'api': lambda: jsonify({"data": [x.json for x in listing]}) + 'api': lambda: {"data": [x.json for x in listing]} }