MarseyWorld/files/routes/static.py

418 lines
14 KiB
Python
Raw Normal View History

2021-10-15 14:08:27 +00:00
from files.mail import *
2022-01-12 02:42:26 +00:00
from files.__main__ import app, limiter, mail
2021-10-15 14:08:27 +00:00
from files.helpers.alerts import *
2021-12-20 12:48:02 +00:00
from files.helpers.const import *
2021-10-15 14:08:27 +00:00
from files.classes.award import AWARDS
from sqlalchemy import func
from os import path
import calendar
import matplotlib.pyplot as plt
2021-11-23 22:54:48 +00:00
from files.classes.mod_logs import ACTIONTYPES, ACTIONTYPES2
2022-01-23 19:51:56 +00:00
from files.classes.badges import BadgeDef
2021-10-15 14:08:27 +00:00
2021-12-28 12:49:52 +00:00
@app.get("/privacy")
2022-01-11 21:54:41 +00:00
@auth_required
2021-12-28 12:49:52 +00:00
def privacy(v):
2022-01-07 21:03:14 +00:00
return render_template("privacy.html", v=v)
2021-12-28 12:49:52 +00:00
2022-01-02 20:20:13 +00:00
@app.get("/marseys")
2022-01-12 02:42:26 +00:00
@auth_required
2022-01-22 14:08:14 +00:00
def marseys(v):
2022-01-23 15:29:13 +00:00
with open("marseys.json", 'r') as f: marsey_count = list(loads(f.read().replace("'",'"')).items())
2022-01-22 14:08:14 +00:00
marsey_count = sorted(marsey_count, key=lambda x: list(x[1].values())[2], reverse=True)
return render_template("marseys.html", v=v, marseys=marsey_count)
2021-12-14 21:32:58 +00:00
2022-01-08 06:41:40 +00:00
@app.get("/terms")
2022-01-14 04:15:41 +00:00
@app.get("/logged_out/terms")
@auth_desired
2022-01-08 06:41:40 +00:00
def terms(v):
2022-01-14 04:15:41 +00:00
if not v and not request.path.startswith('/logged_out'): return redirect(f"/logged_out{request.full_path}")
if v and request.path.startswith('/logged_out'): v = None
2022-01-08 06:41:40 +00:00
return render_template("terms.html", v=v)
2021-12-30 05:27:22 +00:00
@app.get('/sidebar')
2022-01-14 04:15:41 +00:00
@app.get('/logged_out/sidebar')
@auth_desired
2021-12-30 05:27:22 +00:00
def sidebar(v):
2022-01-14 04:15:41 +00:00
if not v and not request.path.startswith('/logged_out'): return redirect(f"/logged_out{request.full_path}")
if v and request.path.startswith('/logged_out'): v = None
2022-01-14 00:14:55 +00:00
return render_template('sidebar.html', v=v)
2021-10-15 14:08:27 +00:00
@app.get("/stats")
@auth_required
def participation_stats(v):
now = int(time.time())
day = now - 86400
2022-01-23 15:29:13 +00:00
with open("marseys.json", 'r') as f: marseys = loads(f.read().replace("'",'"'))
2022-01-22 14:18:11 +00:00
2022-01-03 10:32:31 +00:00
data = {"marseys": len(marseys),
2022-01-03 11:26:30 +00:00
"users": g.db.query(User.id).count(),
2021-11-06 15:52:48 +00:00
"private_users": g.db.query(User.id).filter_by(is_private=True).count(),
2022-01-12 04:22:00 +00:00
"banned_users": g.db.query(User.id).filter(User.is_banned > 0).count(),
2021-11-06 15:52:48 +00:00
"verified_email_users": g.db.query(User.id).filter_by(is_activated=True).count(),
2022-01-22 14:32:02 +00:00
"coins_in_circulation": g.db.query(func.sum(User.coins)).scalar(),
"total_shop_sales": g.db.query(func.sum(User.coins_spent)).scalar(),
2021-11-06 15:52:48 +00:00
"signups_last_24h": g.db.query(User.id).filter(User.created_utc > day).count(),
"total_posts": g.db.query(Submission.id).count(),
"posting_users": g.db.query(Submission.author_id).distinct().count(),
"listed_posts": g.db.query(Submission.id).filter_by(is_banned=False).filter(Submission.deleted_utc == 0).count(),
"removed_posts": g.db.query(Submission.id).filter_by(is_banned=True).count(),
2022-01-12 04:22:00 +00:00
"deleted_posts": g.db.query(Submission.id).filter(Submission.deleted_utc > 0).count(),
2021-11-06 15:52:48 +00:00
"posts_last_24h": g.db.query(Submission.id).filter(Submission.created_utc > day).count(),
2021-12-20 12:48:02 +00:00
"total_comments": g.db.query(Comment.id).filter(Comment.author_id.notin_((AUTOJANNY_ID,NOTIFICATIONS_ID))).count(),
2021-11-06 15:52:48 +00:00
"commenting_users": g.db.query(Comment.author_id).distinct().count(),
"removed_comments": g.db.query(Comment.id).filter_by(is_banned=True).count(),
2022-01-12 04:22:00 +00:00
"deleted_comments": g.db.query(Comment.id).filter(Comment.deleted_utc > 0).count(),
2021-12-20 12:48:02 +00:00
"comments_last_24h": g.db.query(Comment.id).filter(Comment.created_utc > day, Comment.author_id.notin_((AUTOJANNY_ID,NOTIFICATIONS_ID))).count(),
2021-11-06 15:52:48 +00:00
"post_votes": g.db.query(Vote.id).count(),
"post_voting_users": g.db.query(Vote.user_id).distinct().count(),
"comment_votes": g.db.query(CommentVote.id).count(),
"comment_voting_users": g.db.query(CommentVote.user_id).distinct().count(),
2022-01-22 15:21:54 +00:00
"total_upvotes": g.db.query(Vote.id).filter_by(vote_type=1).count() + g.db.query(CommentVote.id).filter_by(vote_type=1).count(),
"total_downvotes": g.db.query(Vote.id).filter_by(vote_type=-1).count() + g.db.query(CommentVote.id).filter_by(vote_type=-1).count(),
2021-11-06 15:52:48 +00:00
"total_awards": g.db.query(AwardRelationship.id).count(),
"awards_given": g.db.query(AwardRelationship.id).filter(or_(AwardRelationship.submission_id != None, AwardRelationship.comment_id != None)).count()
2021-10-15 14:08:27 +00:00
}
2022-01-14 12:04:34 +00:00
return render_template("admin/content_stats.html", v=v, title="Content Statistics", data=data)
2021-10-15 14:08:27 +00:00
@app.get("/chart")
@auth_required
def chart(v):
2021-12-15 22:34:38 +00:00
days = int(request.values.get("days", 0))
2021-12-15 22:32:22 +00:00
file = cached_chart(days)
2021-12-14 22:10:11 +00:00
return send_file(file)
2021-10-15 14:08:27 +00:00
2021-12-15 23:02:34 +00:00
@cache.memoize(timeout=86400)
2021-12-15 22:32:22 +00:00
def cached_chart(days):
2021-10-15 14:08:27 +00:00
now = time.gmtime()
midnight_this_morning = time.struct_time((now.tm_year,
now.tm_mon,
now.tm_mday,
0,
0,
0,
now.tm_wday,
now.tm_yday,
0)
)
today_cutoff = calendar.timegm(midnight_this_morning)
2021-12-15 22:32:22 +00:00
if not days:
2022-01-02 00:15:07 +00:00
firstsignup = g.db.query(User.created_utc).filter(User.created_utc != 0).order_by(User.created_utc).first()[0] - 86400
2021-12-15 22:32:22 +00:00
nowstamp = int(time.time())
days = int((nowstamp - firstsignup) / 86400)
2021-12-15 23:06:02 +00:00
if days > 31:
2021-12-20 23:58:30 +00:00
file = "/weekly_chart.png"
2022-01-07 19:13:01 +00:00
day_cutoffs = [today_cutoff - 86400 * 7 * i for i in range(35)][1:]
2021-12-15 23:06:02 +00:00
else:
2021-12-20 23:58:30 +00:00
file = "/daily_chart.png"
2022-01-07 19:13:01 +00:00
day_cutoffs = [today_cutoff - 86400 * i for i in range(35)][1:]
2021-12-15 22:32:22 +00:00
2021-10-15 14:08:27 +00:00
day_cutoffs.insert(0, calendar.timegm(now))
2021-12-15 22:53:29 +00:00
daily_times = [time.strftime("%d/%m", time.gmtime(day_cutoffs[i + 1])) for i in range(len(day_cutoffs) - 1)][::-1]
2021-10-15 14:08:27 +00:00
2021-12-15 22:53:29 +00:00
daily_signups = [g.db.query(User.id).filter(User.created_utc < day_cutoffs[i], User.created_utc > day_cutoffs[i + 1]).count() for i in range(len(day_cutoffs) - 1)][::-1]
2021-10-15 14:08:27 +00:00
2021-12-15 22:53:29 +00:00
post_stats = [g.db.query(Submission.id).filter(Submission.created_utc < day_cutoffs[i], Submission.created_utc > day_cutoffs[i + 1], Submission.is_banned == False).count() for i in range(len(day_cutoffs) - 1)][::-1]
2021-10-15 14:08:27 +00:00
2021-12-20 12:48:02 +00:00
comment_stats = [g.db.query(Comment.id).filter(Comment.created_utc < day_cutoffs[i], Comment.created_utc > day_cutoffs[i + 1],Comment.is_banned == False, Comment.author_id.notin_((AUTOJANNY_ID,NOTIFICATIONS_ID))).count() for i in range(len(day_cutoffs) - 1)][::-1]
2021-10-15 14:08:27 +00:00
2021-11-18 16:59:05 +00:00
plt.rcParams["figure.figsize"] = (20,20)
2021-10-15 14:08:27 +00:00
signup_chart = plt.subplot2grid((20, 4), (0, 0), rowspan=5, colspan=4)
posts_chart = plt.subplot2grid((20, 4), (7, 0), rowspan=5, colspan=4)
comments_chart = plt.subplot2grid((20, 4), (14, 0), rowspan=5, colspan=4)
signup_chart.grid(), posts_chart.grid(), comments_chart.grid()
signup_chart.plot(
daily_times,
daily_signups,
color='red')
posts_chart.plot(
daily_times,
post_stats,
color='green')
comments_chart.plot(
daily_times,
comment_stats,
color='gold')
2022-01-02 00:05:22 +00:00
signup_chart.set_ylim(ymin=0)
posts_chart.set_ylim(ymin=0)
comments_chart.set_ylim(ymin=0)
2021-10-15 14:08:27 +00:00
signup_chart.set_ylabel("Signups")
posts_chart.set_ylabel("Posts")
comments_chart.set_ylabel("Comments")
comments_chart.set_xlabel("Time (UTC)")
signup_chart.legend(loc='upper left', frameon=True)
posts_chart.legend(loc='upper left', frameon=True)
comments_chart.legend(loc='upper left', frameon=True)
plt.savefig(file)
plt.clf()
return file
@app.get("/patrons")
@app.get("/paypigs")
2021-11-21 18:54:36 +00:00
@admin_level_required(3)
2021-10-15 14:08:27 +00:00
def patrons(v):
2022-01-12 04:22:00 +00:00
users = g.db.query(User).filter(User.patron > 0).order_by(User.patron.desc(), User.id).all()
2021-11-24 12:20:52 +00:00
2022-01-14 12:04:34 +00:00
return render_template("patrons.html", v=v, users=users)
2021-10-15 14:08:27 +00:00
@app.get("/admins")
2021-10-19 15:42:58 +00:00
@app.get("/badmins")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def admins(v):
2021-12-26 01:03:21 +00:00
if v and v.admin_level > 2:
admins = g.db.query(User).filter(User.admin_level>1).order_by(User.truecoins.desc()).all()
admins += g.db.query(User).filter(User.admin_level==1).order_by(User.truecoins.desc()).all()
else: admins = g.db.query(User).filter(User.admin_level>0).order_by(User.truecoins.desc()).all()
2022-01-14 12:04:34 +00:00
return render_template("admins.html", v=v, admins=admins)
2021-10-15 14:08:27 +00:00
@app.get("/log")
2021-10-19 15:42:58 +00:00
@app.get("/modlog")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def log(v):
2021-12-20 15:17:43 +00:00
page = int(request.values.get("page",1))
admin = request.values.get("admin")
2021-11-23 00:04:13 +00:00
if admin: admin_id = get_id(admin)
else: admin_id = 0
2021-10-15 14:08:27 +00:00
2021-12-20 15:17:43 +00:00
kind = request.values.get("kind")
2021-10-15 14:08:27 +00:00
2021-11-23 21:58:46 +00:00
if v and v.admin_level > 1: types = ACTIONTYPES
else: types = ACTIONTYPES2
if kind not in types: kind = None
2021-11-22 23:25:33 +00:00
2021-11-23 21:58:46 +00:00
actions = g.db.query(ModAction)
2021-11-23 21:54:07 +00:00
if not (v and v.admin_level > 1):
2022-01-02 14:14:12 +00:00
actions = actions.filter(ModAction.kind.notin_(["shadowban","unshadowban"]))
2021-11-23 21:58:46 +00:00
if admin_id: actions = actions.filter_by(user_id=admin_id)
2021-11-23 23:01:50 +00:00
if kind: actions = actions.filter_by(kind=kind)
2021-11-23 21:54:07 +00:00
2021-11-22 23:25:33 +00:00
actions = actions.order_by(ModAction.id.desc()).offset(25*(page-1)).limit(26).all()
2021-10-15 14:08:27 +00:00
next_exists=len(actions)>25
actions=actions[:25]
2021-11-23 00:04:13 +00:00
admins = [x[0] for x in g.db.query(User.username).filter(User.admin_level > 1).all()]
2021-11-23 00:09:11 +00:00
2022-01-14 12:04:34 +00:00
return render_template("log.html", v=v, admins=admins, types=types, admin=admin, type=kind, actions=actions, next_exists=next_exists, page=page)
2021-10-15 14:08:27 +00:00
@app.get("/log/<id>")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def log_item(id, v):
try: id = int(id)
except:
try: id = int(id, 36)
except: abort(404)
2022-01-02 00:06:46 +00:00
action=g.db.query(ModAction).filter_by(id=id).one_or_none()
2021-10-15 14:08:27 +00:00
if not action:
abort(404)
if request.path != action.permalink:
return redirect(action.permalink)
2021-11-23 21:54:07 +00:00
admins = [x[0] for x in g.db.query(User.username).filter(User.admin_level > 1).all()]
2021-11-23 21:58:46 +00:00
if v and v.admin_level > 1: types = ACTIONTYPES
else: types = ACTIONTYPES2
2022-01-14 12:04:34 +00:00
return render_template("log.html", v=v, actions=[action], next_exists=False, page=1, action=action, admins=admins, types=types)
2021-10-15 14:08:27 +00:00
2021-12-24 23:00:09 +00:00
@app.get("/static/assets/favicon.ico")
2022-01-11 23:00:10 +00:00
def favicon():
2022-01-19 09:07:16 +00:00
return send_file(f"./assets/images/{SITE_NAME}/icon.webp")
2021-10-15 14:08:27 +00:00
@app.get("/api")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def api(v):
2022-01-14 12:04:34 +00:00
return render_template("api.html", v=v)
2021-10-15 14:08:27 +00:00
@app.get("/contact")
2021-10-19 15:42:58 +00:00
@app.get("/press")
@app.get("/media")
2021-10-15 14:08:27 +00:00
@auth_required
def contact(v):
2022-01-14 12:04:34 +00:00
return render_template("contact.html", v=v)
2021-10-15 14:08:27 +00:00
2022-01-06 21:38:54 +00:00
@app.post("/send_admin")
2022-01-15 06:31:17 +00:00
@limiter.limit("1/second;2/minute;6/hour;10/day")
2021-10-15 14:08:27 +00:00
@auth_required
def submit_contact(v):
2022-01-14 06:40:30 +00:00
body = request.values.get("message")
if not body: abort(400)
body = f'This message has been sent automatically to all admins via [/contact](/contact), user email is "{v.email}"\n\nMessage:\n\n' + body
body_html = sanitize(body, noimages=True)
if request.files.get("file") and request.headers.get("cf-ipcountry") != "T1":
file=request.files["file"]
if file.content_type.startswith('image/'):
2022-01-21 23:37:56 +00:00
body_html += f'<img data-bs-target="#expandImageModal" data-bs-toggle="modal" onclick="expandDesktopImage(this.src)" class="in-comment-image" src="{process_image(file)}" loading="lazy">'
2022-01-14 06:40:30 +00:00
elif file.content_type.startswith('video/'):
file.save("video.mp4")
with open("video.mp4", 'rb') as f:
try: url = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)]).json()['data']['link']
except: return {"error": "Imgur error"}, 400
if url.endswith('.'): url += 'mp4'
body_html += f"<p>{url}</p>"
else: return {"error": "Image/Video files only"}, 400
new_comment = Comment(author_id=v.id,
parent_submission=None,
level=1,
sentto=0,
body_html=body_html,
)
g.db.add(new_comment)
g.db.flush()
admins = g.db.query(User).filter(User.admin_level > 2).all()
for admin in admins:
notif = Notification(comment_id=new_comment.id, user_id=admin.id)
g.db.add(notif)
2021-10-15 14:08:27 +00:00
g.db.commit()
2022-01-14 12:04:34 +00:00
return render_template("contact.html", v=v, msg="Your message has been sent.")
2021-10-15 14:08:27 +00:00
@app.get('/archives')
2022-01-11 21:54:41 +00:00
@auth_required
2022-01-11 21:53:49 +00:00
def archivesindex(v):
2021-10-15 14:08:27 +00:00
return redirect("/archives/index.html")
@app.get('/archives/<path:path>')
2022-01-11 21:54:41 +00:00
@auth_required
2022-01-11 21:53:49 +00:00
def archives(v, path):
2021-10-15 14:08:27 +00:00
resp = make_response(send_from_directory('/archives', path))
if request.path.endswith('.css'): resp.headers.add("Content-Type", "text/css")
return resp
@app.get('/assets/<path:path>')
2021-12-23 13:32:17 +00:00
@app.get('/static/assets/<path:path>')
2021-10-15 14:08:27 +00:00
@limiter.exempt
2022-01-11 23:00:10 +00:00
def static_service(path):
2021-12-23 13:32:17 +00:00
if request.path.startswith('/assets/'): return redirect(request.full_path.replace('/assets/', '/static/assets/'))
2021-12-14 21:32:58 +00:00
resp = make_response(send_from_directory('assets', path))
2021-10-15 14:08:27 +00:00
if request.path.endswith('.webp') or request.path.endswith('.gif') or request.path.endswith('.ttf') or request.path.endswith('.woff') or request.path.endswith('.woff2'):
resp.headers.remove("Cache-Control")
resp.headers.add("Cache-Control", "public, max-age=2628000")
2021-11-11 18:58:09 +00:00
if request.path.endswith('.webp'):
resp.headers.remove("Content-Type")
resp.headers.add("Content-Type", "image/webp")
2021-10-15 14:08:27 +00:00
return resp
2021-12-23 13:32:17 +00:00
@app.get('/images/<path>')
@app.get('/hostedimages/<path>')
@app.get("/static/images/<path>")
2021-10-15 14:08:27 +00:00
@limiter.exempt
2022-01-11 23:00:10 +00:00
def images(path):
2021-12-23 13:32:17 +00:00
if request.path.startswith('/images/') or request.path.lower().startswith('/hostedimages/'):
return redirect(request.full_path.replace('/images/', '/static/images/').replace('/hostedimages/', '/static/images/'))
2021-12-13 01:00:08 +00:00
resp = make_response(send_from_directory('/images', path.replace('.WEBP','.webp')))
2021-10-15 14:08:27 +00:00
resp.headers.remove("Cache-Control")
resp.headers.add("Cache-Control", "public, max-age=2628000")
2021-11-11 18:58:09 +00:00
if request.path.endswith('.webp'):
resp.headers.remove("Content-Type")
resp.headers.add("Content-Type", "image/webp")
2021-10-15 14:08:27 +00:00
return resp
@app.get("/robots.txt")
def robots_txt():
2021-12-14 21:32:58 +00:00
return send_file("assets/robots.txt")
2021-10-15 14:08:27 +00:00
@app.get("/settings")
@auth_required
def settings(v):
return redirect("/settings/profile")
@app.get("/settings/profile")
@auth_required
def settings_profile(v):
2022-01-14 12:04:34 +00:00
return render_template("settings_profile.html",
2021-10-15 14:08:27 +00:00
v=v)
@app.get("/badges")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def badges(v):
2022-01-23 19:51:56 +00:00
badges = g.db.query(BadgeDef).all()
2022-01-22 10:43:06 +00:00
2022-01-23 19:51:56 +00:00
return render_template("badges.html", v=v, badges=badges)
2021-10-15 14:08:27 +00:00
2022-01-22 11:54:48 +00:00
@app.get("/marsey_list")
@auth_required
def marsey_list(v):
2022-01-23 15:29:13 +00:00
with open("marseys.json", 'r') as f: return loads(f.read().replace("'",'"'))
2022-01-22 11:54:48 +00:00
2021-10-15 14:08:27 +00:00
@app.get("/blocks")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def blocks(v):
2021-11-06 15:52:48 +00:00
blocks=g.db.query(UserBlock).all()
2021-10-15 14:08:27 +00:00
users = []
targets = []
for x in blocks:
users.append(get_account(x.user_id))
targets.append(get_account(x.target_id))
2022-01-14 12:04:34 +00:00
return render_template("blocks.html", v=v, users=users, targets=targets)
2021-10-15 14:08:27 +00:00
@app.get("/banned")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def banned(v):
2022-01-12 04:22:00 +00:00
users = [x for x in g.db.query(User).filter(User.is_banned > 0, User.unban_utc == 0).all()]
2022-01-14 12:04:34 +00:00
return render_template("banned.html", v=v, users=users)
2021-10-15 14:08:27 +00:00
@app.get("/formatting")
2022-01-11 21:54:41 +00:00
@auth_required
2021-10-15 14:08:27 +00:00
def formatting(v):
2022-01-14 12:04:34 +00:00
return render_template("formatting.html", v=v)
2021-10-15 14:08:27 +00:00
@app.get("/service-worker.js")
2022-01-11 21:54:41 +00:00
@auth_required
2022-01-11 21:53:49 +00:00
def serviceworker(v):
2021-12-24 23:09:08 +00:00
with open("files/assets/js/service-worker.js", "r") as f: return Response(f.read(), mimetype='application/javascript')
2021-10-15 14:08:27 +00:00
@app.get("/settings/security")
@auth_required
def settings_security(v):
2022-01-14 12:04:34 +00:00
return render_template("settings_security.html",
2021-10-15 14:08:27 +00:00
v=v,
2021-12-28 14:11:50 +00:00
mfa_secret=pyotp.random_base32() if not v.mfa_secret else None
2022-01-11 21:53:49 +00:00
)