Ada
103479668d
All checks were successful
ci/woodpecker/push/lint Pipeline was successful
Co-authored-by: Ada <ada@gnous.eu> Co-committed-by: Ada <ada@gnous.eu>
98 lines
2.5 KiB
Python
Executable file
98 lines
2.5 KiB
Python
Executable file
"""Manage view and create paste."""
|
|
|
|
from flask import (
|
|
Blueprint,
|
|
abort,
|
|
flash,
|
|
redirect,
|
|
render_template,
|
|
request,
|
|
url_for,
|
|
)
|
|
from werkzeug import Response
|
|
|
|
from paste.db import check_content_exist, connect_redis, insert_content_db
|
|
from paste.utils import generate_id, generate_secret, get_expiration_time
|
|
|
|
home = Blueprint("home", __name__, url_prefix="/")
|
|
|
|
|
|
def create_paste(content: str, time: int) -> dict[str, str]:
|
|
"""
|
|
Create paste in DB.
|
|
:param time: Expiration time in second
|
|
:param content: Content to add in redis.
|
|
:return: A dict with url_id and delete secret.
|
|
"""
|
|
secret = generate_secret()
|
|
url_id = generate_id()
|
|
while check_content_exist(url_id):
|
|
url_id = generate_id()
|
|
insert_content_db(url_id, time, content, secret)
|
|
return {"url_id": url_id, "secret": secret}
|
|
|
|
|
|
@home.route("/")
|
|
def homepage() -> str:
|
|
"""
|
|
Homepage.
|
|
:return: Homepage.
|
|
"""
|
|
return render_template("home.html.j2")
|
|
|
|
|
|
@home.route("/create", methods=["POST"])
|
|
def create() -> Response:
|
|
"""
|
|
Receive POST data for create paste.
|
|
:return: Redirection to homapage.
|
|
"""
|
|
content = request.form.get("content")
|
|
time = request.form.get("time")
|
|
time = 0 if time == "" else int(time)
|
|
|
|
flash_data = create_paste(content, time)
|
|
flash(flash_data["url_id"], category="create")
|
|
flash(flash_data["secret"], category="create")
|
|
|
|
return redirect(url_for("home.homepage"))
|
|
|
|
|
|
@home.route("/delete/<path:path>")
|
|
def delete_paste(path: str) -> Response:
|
|
"""
|
|
Delete a paste
|
|
:param path: path fetched from url
|
|
:return: forbidden (403) or homepage.
|
|
"""
|
|
db = connect_redis()
|
|
secret = request.args.get("secret")
|
|
if db.hget(path, "secret") == secret:
|
|
db.delete(path)
|
|
flash(path, category="delete")
|
|
return redirect(url_for("home.homepage"))
|
|
return abort(403)
|
|
|
|
|
|
@home.route("/<path:path>")
|
|
def get_content(path: str) -> Response | str:
|
|
"""
|
|
Return paste for asked url.
|
|
:param path: Requested path.
|
|
:return: Paste content.
|
|
"""
|
|
db = connect_redis()
|
|
data = db.hgetall(path)
|
|
if check_content_exist(path):
|
|
flash(data["content"])
|
|
cache_time = get_expiration_time(path)
|
|
current_response = Response(render_template("content.html.j2"))
|
|
if cache_time == -1:
|
|
current_response.headers["Cache-Control"] = "public"
|
|
|
|
else:
|
|
current_response.headers["Cache-Control"] = f"public, {cache_time}"
|
|
return current_response
|
|
|
|
return abort(404)
|