1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-27 13:34:28 +00:00
royalnet/webserver.py

420 lines
17 KiB
Python
Raw Normal View History

2018-10-07 15:19:42 +00:00
import secrets
from flask import Flask, render_template, request, abort, redirect, url_for, Markup, escape, jsonify
2018-05-07 10:51:24 +00:00
from flask import session as fl_session
2018-10-04 10:46:15 +00:00
from flask import g as fl_g
2018-05-07 10:51:24 +00:00
import db
import bcrypt
import configparser
import markdown2
2018-07-15 12:41:42 +00:00
import datetime
2019-01-03 11:32:59 +00:00
# noinspection PyPackageRequirements
2018-07-15 12:41:42 +00:00
import telegram
2018-07-28 17:58:23 +00:00
import query_discord_music
2018-09-05 17:48:34 +00:00
import random
import re
2019-01-06 22:53:22 +00:00
import functools
2018-09-11 23:46:00 +00:00
from raven.contrib.flask import Sentry
2017-10-25 09:09:06 +00:00
app = Flask(__name__)
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
2018-05-07 10:51:24 +00:00
config = configparser.ConfigParser()
config.read("config.ini")
app.secret_key = config["Flask"]["secret_key"]
2018-07-15 12:41:42 +00:00
telegram_bot = telegram.Bot(config["Telegram"]["bot_token"])
2018-03-12 12:29:12 +00:00
2018-09-11 23:46:00 +00:00
sentry = Sentry(app, dsn=config["Sentry"]["token"])
2018-07-21 20:46:02 +00:00
@app.template_filter()
def markdown(text):
"""Convert a string to markdown."""
converted_md = markdown2.markdown(text.replace("<", "&lt;"),
extras=["spoiler", "tables", "smarty-pants", "fenced-code-blocks"])
converted_md = re.sub(r"{https?://(?:www\.)?(?:youtube\.com/watch\?.*?&?v=|youtu.be/)([0-9A-Za-z-]+).*?}",
r'<div class="youtube-embed">'
r' <iframe src="https://www.youtube-nocookie.com/embed/\1?rel=0&amp;showinfo=0"'
r' frameborder="0"'
r' allow="autoplay; encrypted-media"'
r' allowfullscreen'
r' width="640px"'
r' height="320px">'
r' </iframe>'
r'</div>', converted_md)
converted_md = re.sub(r"{https?://clyp.it/([a-z0-9]+)}",
r'<div class="clyp-embed">'
r' <iframe width="100%" height="160" src="https://clyp.it/\1/widget" frameborder="0">'
r' </iframe>'
r'</div>', converted_md)
return Markup(converted_md)
2019-01-06 22:53:22 +00:00
def require_login(f):
@functools.wraps(f)
def func(*args, **kwargs):
2019-01-08 23:32:22 +00:00
if not fl_g.user:
2019-01-06 22:53:22 +00:00
abort(403)
return
return f(*args, **kwargs)
return func
2018-07-21 20:46:02 +00:00
@app.errorhandler(400)
2018-07-21 20:47:52 +00:00
def error_400(_=None):
2019-01-08 19:28:33 +00:00
return render_template("400.html")
2018-07-21 20:46:02 +00:00
2018-07-21 20:47:52 +00:00
@app.route("/400")
def page_400():
return error_400()
2018-07-21 20:46:02 +00:00
@app.errorhandler(403)
2018-07-21 20:47:52 +00:00
def error_403(_=None):
2019-01-08 19:28:33 +00:00
return render_template("403.html")
2018-07-21 20:46:02 +00:00
2018-07-21 20:47:52 +00:00
@app.route("/403")
def page_403():
return error_403()
2018-07-21 20:46:02 +00:00
@app.errorhandler(500)
2018-07-21 20:47:52 +00:00
def error_500(_=None):
2019-01-08 19:28:33 +00:00
return render_template("500.html")
2018-07-21 20:46:02 +00:00
2018-07-21 20:47:52 +00:00
@app.route("/500")
def page_500():
return error_500()
2018-01-25 14:24:17 +00:00
@app.route("/")
2018-06-01 11:45:45 +00:00
def page_main():
2019-01-08 19:28:33 +00:00
royals = fl_g.session.query(db.Royal).order_by(db.Royal.fiorygi.desc()).all()
wiki_pages = fl_g.session.query(db.WikiEntry).order_by(db.WikiEntry.key).all()
random_diario = fl_g.session.query(db.Diario).order_by(db.func.random()).first()
next_events = fl_g.session.query(db.Event).filter(db.Event.time > datetime.datetime.now()).order_by(
2018-07-26 17:26:03 +00:00
db.Event.time).all()
2019-01-08 19:28:33 +00:00
quests = fl_g.session.query(db.Quest).all()
2018-07-24 17:45:12 +00:00
return render_template("main.html", royals=royals, wiki_pages=wiki_pages, entry=random_diario,
2019-01-08 19:28:33 +00:00
events=next_events, escape=escape, quests=quests)
2018-02-02 10:46:27 +00:00
2017-11-07 17:44:00 +00:00
2018-06-04 09:58:27 +00:00
@app.route("/profile/<name>")
def page_profile(name: str):
2019-01-08 19:28:33 +00:00
user = fl_g.session.query(db.Royal).filter_by(username=name).one_or_none()
2018-06-04 09:58:27 +00:00
if user is None:
abort(404)
return
2019-01-08 19:28:33 +00:00
css = fl_g.session.query(db.ProfileData).filter_by(royal=user).one_or_none()
steam = fl_g.session.query(db.Steam).filter_by(royal=user).one_or_none()
osu = fl_g.session.query(db.Osu).filter_by(royal=user).one_or_none()
dota = fl_g.session.query(db.Dota).join(db.Steam).filter_by(royal=user).one_or_none()
lol = fl_g.session.query(db.LeagueOfLegends).filter_by(royal=user).one_or_none()
ow = fl_g.session.query(db.Overwatch).filter_by(royal=user).one_or_none()
tg = fl_g.session.query(db.Telegram).filter_by(royal=user).one_or_none()
discord = fl_g.session.execute(query_discord_music.one_query, {"royal": user.id}).fetchone()
gamelog = fl_g.session.query(db.GameLog).filter_by(royal=user).one_or_none()
halloween = fl_g.session.query(db.Halloween).filter_by(royal=user).one_or_none()
terraria13 = fl_g.session.query(db.Terraria13).filter_by(royal=user).one_or_none()
2018-09-07 16:58:19 +00:00
if css is not None:
converted_bio = Markup(markdown2.markdown(css.bio.replace("<", "&lt;"),
extras=["spoiler", "tables", "smarty-pants", "fenced-code-blocks"]))
else:
converted_bio = ""
return render_template("profile.html", ryg=user, css=css, osu=osu, dota=dota, lol=lol, steam=steam, ow=ow,
2019-01-08 19:28:33 +00:00
tg=tg, discord=discord, bio=converted_bio, gamelog=gamelog,
2019-01-08 14:54:45 +00:00
halloween=halloween, terraria13=terraria13)
2018-06-04 09:58:27 +00:00
2018-05-07 10:51:24 +00:00
@app.route("/login")
def page_login():
2019-01-08 19:28:33 +00:00
return render_template("login.html")
2018-05-07 10:51:24 +00:00
2018-06-01 11:45:45 +00:00
@app.route("/loggedin", methods=["POST"])
2018-05-07 10:51:24 +00:00
def page_loggedin():
2018-06-01 11:45:45 +00:00
username = request.form.get("username", "")
password = request.form.get("password", "")
2019-01-08 19:28:33 +00:00
user = fl_g.session.query(db.Royal).filter_by(username=username).one_or_none()
2018-10-07 18:16:10 +00:00
fl_session.permanent = True
2018-06-01 11:45:45 +00:00
if user is None:
2019-01-06 22:53:22 +00:00
abort(400)
2018-06-01 11:45:45 +00:00
return
if user.password is None:
2018-06-05 10:31:11 +00:00
fl_session["user_id"] = user.id
2018-07-15 16:40:25 +00:00
fl_session["username"] = username
2018-06-01 11:45:45 +00:00
return redirect(url_for("page_password"))
if bcrypt.checkpw(bytes(password, encoding="utf8"), user.password):
2018-06-05 10:31:11 +00:00
fl_session["user_id"] = user.id
2018-07-15 16:40:25 +00:00
fl_session["username"] = username
2018-06-01 11:45:45 +00:00
return redirect(url_for("page_main"))
2019-01-06 22:53:22 +00:00
return redirect(url_for("page_login"))
2018-05-07 10:51:24 +00:00
2018-07-15 16:40:25 +00:00
@app.route("/logout")
def page_logout():
if "user_id" in fl_session:
del fl_session["user_id"]
del fl_session["username"]
return redirect(url_for("page_main"))
2018-05-07 10:51:24 +00:00
@app.route("/password", methods=["GET", "POST"])
2019-01-06 22:53:22 +00:00
@require_login
2018-05-07 10:51:24 +00:00
def page_password():
if request.method == "GET":
2019-01-06 22:53:22 +00:00
return render_template("password.html")
2018-05-07 10:51:24 +00:00
elif request.method == "POST":
2018-06-01 11:45:45 +00:00
new_password = request.form.get("new", "")
2019-01-08 19:28:33 +00:00
user = fl_g.session.query(db.Royal).filter_by(id=fl_g.user_id).one()
2018-06-01 11:45:45 +00:00
if user.password is None:
2018-05-07 10:51:24 +00:00
user.password = bcrypt.hashpw(bytes(new_password, encoding="utf8"), bcrypt.gensalt())
2018-09-05 17:48:34 +00:00
user.fiorygi += 1
2019-01-08 19:28:33 +00:00
fl_g.session.commit()
2018-06-01 11:45:45 +00:00
return redirect(url_for("page_main"))
2019-01-06 22:53:22 +00:00
abort(403)
2018-06-01 11:45:45 +00:00
2018-08-01 16:05:18 +00:00
@app.route("/editprofile", methods=["GET", "POST"])
2019-01-06 22:53:22 +00:00
@require_login
2018-08-01 16:05:18 +00:00
def page_editprofile():
2019-01-08 19:28:33 +00:00
profile_data = fl_g.session.query(db.ProfileData).filter_by(royal_id=fl_g.user_id).join(db.Royal).one_or_none()
2018-06-05 10:31:11 +00:00
if request.method == "GET":
2019-01-08 19:28:33 +00:00
return render_template("profileedit.html", data=profile_data)
2018-06-05 10:31:11 +00:00
elif request.method == "POST":
2018-06-05 13:11:58 +00:00
css = request.form.get("css", "")
2018-08-01 16:05:18 +00:00
bio = request.form.get("bio", "")
2018-06-07 09:59:15 +00:00
if "</style" in css:
2018-06-05 13:11:58 +00:00
abort(400)
return
2018-08-01 16:05:18 +00:00
if profile_data is None:
2019-01-06 22:53:22 +00:00
profile_data = db.ProfileData(royal_id=fl_g.user_id, css=css, bio=bio)
2019-01-08 19:28:33 +00:00
fl_g.session.add(profile_data)
fl_g.session.flush()
2018-09-07 17:09:48 +00:00
profile_data.royal.fiorygi += 1
try:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-04 12:36:13 +00:00
f'⭐️ {profile_data.royal.username} ha'
f' <a href="http://ryg.steffo.eu/editprofile">configurato la sua bio</a>'
f' su Royalnet e ha ottenuto un fioryg!',
2018-09-07 17:09:48 +00:00
parse_mode="HTML", disable_web_page_preview=True, disable_notification=True)
except Exception:
pass
2018-06-05 10:31:11 +00:00
else:
2018-08-01 16:05:18 +00:00
profile_data.css = css
profile_data.bio = bio
2019-01-08 19:28:33 +00:00
fl_g.session.commit()
royal = fl_g.session.query(db.Royal).filter_by(id=fl_g.user_id).one()
2018-06-05 10:31:11 +00:00
return redirect(url_for("page_profile", name=royal.username))
2018-06-13 21:32:26 +00:00
@app.route("/game/<name>")
def page_game(name: str):
if name == "rl":
game_name = "Rocket League"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.RocketLeague).join(db.Steam).order_by(db.RocketLeague.solo_std_rank).all()
2018-06-13 21:32:26 +00:00
elif name == "dota":
game_name = "Dota 2"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Dota).join(db.Steam).order_by(db.Dota.rank_tier.desc().nullslast(),
db.Dota.wins.desc()).all()
2018-06-13 21:32:26 +00:00
elif name == "lol":
game_name = "League of Legends"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.LeagueOfLegends).order_by(db.LeagueOfLegends.solo_division.desc().nullslast(),
db.LeagueOfLegends.solo_rank,
db.LeagueOfLegends.flex_division.desc().nullslast(),
db.LeagueOfLegends.flex_rank,
db.LeagueOfLegends.twtr_division.desc().nullslast(),
db.LeagueOfLegends.twtr_rank,
db.LeagueOfLegends.level).all()
2018-06-13 21:32:26 +00:00
elif name == "osu":
game_name = "osu!"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Osu).order_by(db.Osu.mania_pp.desc().nullslast()).all()
2018-06-13 21:32:26 +00:00
elif name == "ow":
game_name = "Overwatch"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Overwatch).order_by(db.Overwatch.rank.desc().nullslast()).all()
2018-06-13 21:32:26 +00:00
elif name == "steam":
game_name = "Steam"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Steam).order_by(db.Steam.persona_name).all()
2018-06-13 21:32:26 +00:00
elif name == "ryg":
game_name = "Royalnet"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Royal).order_by(db.Royal.username).all()
2018-07-25 21:52:38 +00:00
elif name == "tg":
game_name = "Telegram"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Telegram).order_by(db.Telegram.telegram_id).all()
2018-07-25 21:52:38 +00:00
elif name == "discord":
game_name = "Discord"
2019-01-08 19:28:33 +00:00
query = [dict(row) for row in fl_g.session.execute(query_discord_music.all_query)]
2019-01-03 11:32:59 +00:00
elif name == "halloween2018":
2018-10-02 22:18:41 +00:00
game_name = "Rituale di Halloween"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Halloween).all()
2019-01-08 14:54:45 +00:00
elif name == "terraria13":
game_name = "Terraria 13"
2019-01-08 19:28:33 +00:00
query = fl_g.session.query(db.Terraria13).all()
2018-07-25 21:52:38 +00:00
else:
abort(404)
return
2019-01-08 19:28:33 +00:00
return render_template("game.html", minis=query, game_name=game_name, game_short_name=name)
2018-06-13 21:32:26 +00:00
2018-07-15 12:41:42 +00:00
@app.route("/wiki/<key>", methods=["GET", "POST"])
def page_wiki(key: str):
2019-01-08 19:28:33 +00:00
fl_g.session = db.Session()
wiki_page = fl_g.session.query(db.WikiEntry).filter_by(key=key).one_or_none()
2018-07-15 12:41:42 +00:00
if request.method == "GET":
2019-01-08 19:28:33 +00:00
wiki_latest_edit = fl_g.session.query(db.WikiLog).filter_by(edited_key=key) \
2018-07-26 17:26:03 +00:00
.order_by(db.WikiLog.timestamp.desc()).first()
2018-07-15 12:41:42 +00:00
if wiki_page is None:
2019-01-08 19:28:33 +00:00
return render_template("wikipage.html", key=key)
# Embed YouTube videos
converted_md = markdown2.markdown(wiki_page.content.replace("<", "&lt;"),
extras=["spoiler", "tables", "smarty-pants", "fenced-code-blocks"])
2019-01-03 11:32:59 +00:00
converted_md = re.sub(r"{https?://(?:www\.)?(?:youtube\.com/watch\?.*?&?v=|youtu.be/)([0-9A-Za-z-]+).*?}",
r'<div class="youtube-embed">'
r' <iframe src="https://www.youtube-nocookie.com/embed/\1?rel=0&amp;showinfo=0"'
r' frameborder="0"'
r' allow="autoplay; encrypted-media"'
r' allowfullscreen'
r' width="640px"'
r' height="320px">'
r' </iframe>'
r'</div>', converted_md)
converted_md = re.sub(r"{https?://clyp.it/([a-z0-9]+)}",
2018-09-13 00:23:39 +00:00
r'<div class="clyp-embed">'
r' <iframe width="100%" height="160" src="https://clyp.it/\1/widget" frameborder="0">'
r' </iframe>'
r'</div>', converted_md)
2018-09-08 11:04:33 +00:00
return render_template("wikipage.html", key=key, wiki_page=wiki_page, converted_md=Markup(converted_md),
2019-01-08 19:28:33 +00:00
wiki_log=wiki_latest_edit)
2018-07-15 12:41:42 +00:00
elif request.method == "POST":
2019-01-08 23:32:22 +00:00
if not fl_g.user:
2018-07-21 20:46:02 +00:00
return redirect(url_for("page_login"))
2019-01-08 23:32:22 +00:00
user = fl_g.session.query(db.Royal).filter_by(id=fl_g.user.id).one()
2018-09-05 17:48:34 +00:00
new_content = request.form.get("content")
# Create new page
2018-07-15 12:41:42 +00:00
if wiki_page is None:
2018-09-05 17:48:34 +00:00
difference = len(new_content)
wiki_page = db.WikiEntry(key=key, content=new_content)
2019-01-08 19:28:33 +00:00
fl_g.session.add(wiki_page)
fl_g.session.flush()
2018-09-05 17:48:34 +00:00
# Edit existing page
2018-07-15 12:41:42 +00:00
else:
2018-09-05 17:48:34 +00:00
difference = len(new_content) - len(wiki_page.content)
wiki_page.content = new_content
# Award fiorygi
if difference > 50:
fioryg_chance = -(5000/difference) + 100
fioryg_roll = random.randrange(0, 100)
if fioryg_roll > fioryg_chance:
user.fiorygi += 1
else:
fioryg_chance = -1
fioryg_roll = -2
2018-07-15 12:41:42 +00:00
edit_reason = request.form.get("reason")
new_log = db.WikiLog(editor=user, edited_key=key, timestamp=datetime.datetime.now(), reason=edit_reason)
2019-01-08 19:28:33 +00:00
fl_g.session.add(new_log)
fl_g.session.commit()
2019-01-03 11:32:59 +00:00
message = f' La pagina wiki <a href="https://ryg.steffo.eu/wiki/{key}">{key}</a> è stata' \
f' modificata da' \
f' <a href="https://ryg.steffo.eu/profile/{user.username}">{user.username}</a>' \
f' {"(" + edit_reason + ")" if edit_reason else ""}' \
f' [{"+" if difference > 0 else ""}{difference}]\n'
if fioryg_roll > fioryg_chance:
message += f"⭐️ {user.username} è stato premiato con 1 fioryg per la modifica!"
2018-07-15 16:14:39 +00:00
try:
2019-01-03 11:32:59 +00:00
telegram_bot.send_message(config["Telegram"]["main_group"], message,
2018-08-08 19:59:47 +00:00
parse_mode="HTML", disable_web_page_preview=True, disable_notification=True)
2018-07-21 20:46:02 +00:00
except Exception:
2018-07-15 16:14:39 +00:00
pass
2018-07-15 12:41:42 +00:00
return redirect(url_for("page_wiki", key=key))
@app.route("/diario")
2019-01-06 22:53:22 +00:00
@require_login
def page_diario():
2019-01-08 19:28:33 +00:00
diario_entries = fl_g.session.query(db.Diario).order_by(db.Diario.timestamp.desc()).all()
return render_template("diario.html", entries=diario_entries)
2018-10-04 10:46:15 +00:00
2018-11-06 22:11:35 +00:00
@app.route("/music")
def page_music():
2019-01-08 19:28:33 +00:00
songs = fl_g.session.execute(query_discord_music.top_songs)
2018-11-06 22:11:35 +00:00
return render_template("topsongs.html", songs=songs)
2018-11-06 22:18:02 +00:00
@app.route("/music/<discord_id>")
def page_music_individual(discord_id: str):
2019-01-08 19:28:33 +00:00
discord = fl_g.session.query(db.Discord).filter_by(discord_id=discord_id).one_or_none()
2018-11-06 22:11:35 +00:00
if discord is None:
abort(404)
return
2019-01-08 19:28:33 +00:00
songs = fl_g.session.execute(query_discord_music.single_top_songs, {"discordid": discord.discord_id})
2018-11-06 22:11:35 +00:00
return render_template("topsongs.html", songs=songs, discord=discord)
2018-11-18 16:58:35 +00:00
@app.route("/activity")
def page_activity():
2019-01-08 19:28:33 +00:00
reports = list(fl_g.session.query(db.ActivityReport).order_by(db.ActivityReport.timestamp.desc()).limit(192).all())
2018-11-18 21:33:58 +00:00
return render_template("activity.html", activityreports=list(reversed(reports)))
2018-11-18 16:58:35 +00:00
2018-10-07 18:16:10 +00:00
@app.route("/ses/identify")
def ses_identify():
response = jsonify({
"username": fl_session.get("username"),
"id": fl_session.get("user_id")
})
2018-11-03 17:42:56 +00:00
response.headers["Access-Control-Allow-Origin"] = "https://steffo.eu"
2018-10-07 18:51:46 +00:00
response.headers["Access-Control-Allow-Credentials"] = "true"
2018-10-07 18:16:10 +00:00
return response
2019-01-02 18:05:01 +00:00
@app.route("/hooks/github", methods=["POST"])
2019-01-02 17:51:20 +00:00
def hooks_github():
try:
j = request.get_json()
except Exception:
abort(400)
return
2019-01-02 18:09:47 +00:00
if j is None:
abort(400)
return
2019-01-02 18:05:01 +00:00
# TODO: add secret check
2019-01-02 18:09:47 +00:00
message = f"🐙 Nuovi aggiornamenti a Royalnet:\n"
2019-01-02 17:51:20 +00:00
for commit in j.get("commits", []):
2019-01-02 18:15:04 +00:00
if commit["distinct"]:
2019-01-03 11:32:59 +00:00
message += f'<a href="{commit["url"]}">{commit["message"]}</a>' \
f' di <b>{commit["author"].get("username", "anonimo")}</b>\n'
2019-01-02 18:12:18 +00:00
telegram_bot.send_message(config["Telegram"]["main_group"], message,
2019-01-02 17:51:20 +00:00
parse_mode="HTML", disable_web_page_preview=True, disable_notification=True)
2019-01-02 18:06:41 +00:00
return "Done."
2019-01-02 17:51:20 +00:00
2018-10-04 10:46:15 +00:00
@app.before_request
def pre_request():
2018-11-03 17:42:56 +00:00
fl_g.css = "nryg.less"
2018-10-07 15:19:42 +00:00
fl_g.rygconf = config
2019-01-08 19:28:33 +00:00
fl_g.session = db.Session()
if fl_session is None:
fl_g.user = None
else:
2019-01-08 19:28:33 +00:00
fl_g.user = fl_g.session.query(db.Royal).filter_by(id=fl_session["user_id"]).one_or_none()
@app.after_request
def after_request(response):
fl_g.session.close()
return response
2018-10-04 10:46:15 +00:00
2017-10-25 09:09:06 +00:00
if __name__ == "__main__":
2017-10-27 09:53:05 +00:00
try:
2018-07-15 12:41:42 +00:00
app.run(host="0.0.0.0", port=1235, debug=__debug__)
2017-10-27 09:53:05 +00:00
except KeyboardInterrupt:
2018-01-25 14:29:38 +00:00
pass