app.py
Python script, ASCII text executable
1import datetime 2 3import celery 4import flask 5import sqlalchemy 6from flask_sqlalchemy import SQLAlchemy 7from flask_bcrypt import Bcrypt 8from flask_migrate import Migrate 9 10from sqlalchemy.orm import declarative_base 11from celery import shared_task 12import httpx 13 14app = flask.Flask(__name__) 15from celery import Celery, Task 16 17 18def celery_init_app(app_) -> Celery: 19class FlaskTask(Task): 20def __call__(self, *args: object, **kwargs: object) -> object: 21with app_.app_context(): 22return self.run(*args, **kwargs) 23 24celery_app = Celery(app_.name, task_cls=FlaskTask) 25celery_app.config_from_object(app_.config["CELERY"]) 26celery_app.set_default() 27app_.extensions["celery"] = celery_app 28return celery_app 29 30 31app.config.from_mapping( 32CELERY=dict( 33broker_url="redis://localhost:6379", 34result_backend="redis://localhost:6379" 35), 36) 37celery_app = celery_init_app(app) 38 39app.config["SQLALCHEMY_DATABASE_URI"] = \ 40"postgresql://echo:1234@localhost:5432/echo" 41app.config["SQLALCHEMY_ENGINE_OPTIONS"] = { 42"connect_args": { 43"options": "-c timezone=utc" 44} 45} 46db = SQLAlchemy(app) 47bcrypt = Bcrypt(app) 48migrate = Migrate(app, db) 49app.config["SESSION_TYPE"] = "filesystem" 50app.config["SECRET_KEY"] = "super secret" 51 52with app.app_context(): 53class User(db.Model): 54username = db.Column(db.String(64), unique=True, nullable=False, primary_key=True) 55password = db.Column(db.String(72), nullable=False) 56admin = db.Column(db.Boolean, nullable=False, default=False) 57 58applications = db.relationship("Application", back_populates="owner") 59 60def __init__(self, username, password, admin=False): 61self.username = username 62self.password = bcrypt.generate_password_hash(password).decode("utf-8") 63self.admin = admin 64 65class Application(db.Model): 66id = db.Column(db.Integer, primary_key=True, autoincrement=True, unique=True, default=0) 67name = db.Column(db.String(64), unique=True, nullable=False) 68owner_name = db.Column(db.String(64), db.ForeignKey("user.username"), nullable=False) 69 70owner = db.relationship("User", back_populates="applications") 71 72endpoints = db.relationship("Endpoint", back_populates="application") 73 74def __init__(self, name, owner): 75self.name = name 76self.owner_name = owner.username 77 78class Endpoint(db.Model): 79id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True, autoincrement=True) 80application_id = db.Column(db.Integer, db.ForeignKey("application.id"), nullable=False) 81address = db.Column(db.String(2048), nullable=False) 82name = db.Column(db.String(64), nullable=False) 83comment = db.Column(db.String(2048), nullable=True) 84ping_interval = db.Column(db.Integer, default=300, nullable=False) 85buggy = db.Column(db.Boolean, default=False) 86 87application = db.relationship("Application", back_populates="endpoints") 88statuses = db.relationship("Status", back_populates="endpoint", lazy="dynamic") 89 90def __init__(self, application, name, address, ping_interval, comment=""): 91self.application_id = application.id 92self.name = name 93self.address = address 94self.comment = comment 95self.ping_interval = ping_interval 96 97 98class Status(db.Model): 99id = db.Column(db.Integer, nullable=False, autoincrement=True, primary_key=True) 100endpoint_id = db.Column(db.Integer, db.ForeignKey("endpoint.id"), nullable=False) 101time = db.Column(db.DateTime, default=datetime.datetime.utcnow) 102 103status = db.Column(db.SmallInteger, nullable=False) 104buggy = db.Column(db.Boolean, default=False) 105endpoint = db.relationship("Endpoint", back_populates="statuses") 106 107def __init__(self, endpoint_id, status): 108self.endpoint_id = endpoint_id 109self.status = status 110 111 112@celery.shared_task(name="ping") 113def ping(id, address, next_ping): 114url = address 115print(f"Pinging {url}") 116response = httpx.get(url, verify=False) 117reading = Status(id, response.status_code) 118db.session.add(reading) 119db.session.commit() 120 121# Schedule the next ping 122ping.apply_async(args=(id, address, next_ping), countdown=next_ping) 123 124@celery.shared_task(name="ping_all") 125def ping_all(): 126endpoints = Endpoint.query.all() 127for endpoint in endpoints: 128ping.delay(endpoint.id, endpoint.address, endpoint.ping_interval) 129 130 131task = ping_all.delay() 132 133print() 134print() 135print(task) 136print() 137print() 138 139 140@app.context_processor 141def default(): 142return { 143"session": flask.session, 144} 145 146 147@app.route("/") 148def dashboard(): 149return flask.render_template("dashboard.html", apps=Application.query.all()) 150 151 152@app.route("/login", methods=["GET"]) 153def login(): 154return flask.render_template("login.html") 155 156 157@app.route("/signup", methods=["GET"]) 158def signup(): 159return flask.render_template("signup.html") 160 161 162@app.route("/new-app", methods=["GET"]) 163def new_app(): 164if not flask.session.get("username"): 165return flask.redirect("/login", code=303) 166return flask.render_template("new-app.html") 167 168 169@app.route("/new-app", methods=["POST"]) 170def new_app_post(): 171if not flask.session.get("username"): 172return flask.redirect("/login", code=303) 173if Application.query.filter_by(name=flask.request.form["name"]).first(): 174flask.flash("Application already exists") 175return flask.redirect("/new-app", code=303) 176 177new_app_ = Application( 178flask.request.form["name"], 179db.session.get(User, flask.session["username"]), 180) 181db.session.add(new_app_) 182db.session.commit() 183return flask.redirect("/", code=303) 184 185 186@app.route("/login", methods=["POST"]) 187def login_post(): 188user = db.session.get(User, flask.request.form["username"]) 189if not user: 190flask.flash("Username doesn't exist") 191return flask.redirect("/signup", code=303) 192if not bcrypt.check_password_hash(user.password, flask.request.form["password"]): 193flask.flash("Wrong password") 194return flask.redirect("/signup", code=303) 195 196flask.session["username"] = user.username 197return flask.redirect("/", code=303) 198 199 200@app.route("/logout") 201def logout(): 202flask.session.pop("username", None) 203return flask.redirect("/", code=303) 204 205 206@app.route("/signup", methods=["POST"]) 207def signup_post(): 208if flask.request.form["password"] != flask.request.form["password2"]: 209flask.flash("Passwords do not match") 210return flask.redirect("/signup", code=303) 211if db.session.get(User, flask.request.form["username"]): 212flask.flash("Username already exists") 213return flask.redirect("/signup", code=303) 214if len(flask.request.form["password"]) < 8: 215flask.flash("Password must be at least 8 characters") 216return flask.redirect("/signup", code=303) 217if len(flask.request.form["username"]) < 4: 218flask.flash("Username must be at least 4 characters") 219return flask.redirect("/signup", code=303) 220 221new_user = User( 222flask.request.form["username"], 223flask.request.form["password"], 224) 225db.session.add(new_user) 226db.session.commit() 227flask.session["username"] = new_user.username 228return flask.redirect("/", code=303) 229 230 231# UTC filter 232@app.template_filter("utc") 233def utc_filter(timestamp): 234return datetime.datetime.utcfromtimestamp(timestamp) 235 236 237@app.route("/app/<int:app_id>/") 238def app_info(app_id): 239app_ = db.session.get(Application, app_id) 240 241time_slices = [(datetime.datetime.utcnow() - datetime.timedelta(seconds=int(flask.request.args.get("bar_duration", 30)) * 60 * (i+1)), 242datetime.datetime.utcnow() - datetime.timedelta(seconds=int(flask.request.args.get("bar_duration", 30)) * i)) 243for i in range(int(flask.request.args.get("time_period", 30)) // int(flask.request.args.get("bar_duration", 1)))] 244 245slice_results = [] 246 247for slice_ in time_slices: 248slice_results.append(db.session.query(Status).filter( 249sqlalchemy.and_(Status.endpoint.has(application_id=app_id), 250Status.time >= slice_[0], 251Status.time < slice_[1])).all()) 252 253return flask.render_template("app.html", app=app_, sorted=sorted, list=list, 254sorting=lambda x: x.time, reverse=True, 255is_ok=lambda x: all(status.status in (200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 302, 304, 307) 256for status in x), and_=sqlalchemy.and_, 257bar_duration=int(flask.request.args.get("bar_duration", 30)), int=int, Status=Status, 258time_period=int(flask.request.args.get("time_period", 1440)), 259now=round(datetime.datetime.utcnow().timestamp()), func=sqlalchemy.func, 260reversed=reversed, fromtimestamp=datetime.datetime.utcfromtimestamp, 261slices=slice_results) 262 263 264@app.route("/app/<int:app_id>/edit/") 265def app_editor(app_id): 266if flask.session.get("username") != db.session.get(Application, app_id).owner_name: 267flask.abort(403) 268app_ = db.session.get(Application, app_id) 269return flask.render_template("app-editor.html", app=app_) 270 271 272@app.route("/app/<int:app_id>/edit/<int:endpoint_id>", methods=["POST"]) 273def endpoint_edit(app_id, endpoint_id): 274if flask.session.get("username") != db.session.get(Application, app_id).owner_name: 275flask.abort(403) 276endpoint = db.session.get(Endpoint, endpoint_id) 277if flask.request.form.get("delete") == "delete": 278statuses = db.session.query(Status).filter_by(endpoint_id=endpoint_id).all() 279for status in statuses: 280db.session.delete(status) 281db.session.delete(endpoint) 282db.session.commit() 283else: 284endpoint.name = flask.request.form["name"] 285endpoint.address = flask.request.form["url"] 286endpoint.ping_interval = max(15, int(flask.request.form["ping_interval"])) 287endpoint.comment = flask.request.form["comment"] 288db.session.commit() 289return flask.redirect(f"/app/{app_id}/edit", code=303) 290 291 292@app.route("/app/<int:app_id>/add-endpoint", methods=["POST"]) 293def app_add_endpoint(app_id): 294if flask.session.get("username") != db.session.get(Application, app_id).owner_name: 295flask.abort(403) 296app_ = db.session.get(Application, app_id) 297endpoint = Endpoint(app_, 298flask.request.form["name"], 299flask.request.form["url"], 300max(15, int(flask.request.form["ping_interval"])), 301flask.request.form["comment"]) 302db.session.add(endpoint) 303db.session.commit() 304 305ping.delay(endpoint.id, endpoint.address, endpoint.ping_interval) 306 307return flask.redirect(f"/app/{app_id}/edit", code=303) 308 309