film2.0/src/__init__.py

115 lines
2.5 KiB
Python
Raw Normal View History

2024-01-23 16:31:46 +00:00
#!/usr/bin/env python3
import os
from flask import Flask, Response, render_template, send_file, request
2024-01-25 01:19:00 +00:00
from . import file
from . import config
from . import auth
2024-01-23 16:31:46 +00:00
app = Flask(
__name__,
template_folder="../templates",
static_folder="../static",
)
app.jinja_env.globals.update(
config=config,
path_join=os.path.join,
)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
@auth.requires_auth
2024-01-23 16:31:46 +00:00
def index(path):
2024-01-25 01:19:00 +00:00
internal_path = os.path.join(config.get('base_path'), path)
2024-01-23 16:31:46 +00:00
path = '/' + path
# Checks ###################################################
if '..' in path:
return 'Path cannot contain double dots, i.e. "..".'
if not os.path.exists(internal_path):
return (
render_template(
"error.html",
code=404,
2024-01-24 15:59:18 +00:00
msg=f'The path "{path}" does not exist.',
2024-01-23 16:31:46 +00:00
),
404,
)
# Actual serving ###########################################
if os.path.isdir(internal_path):
_, dirs, files = next(os.walk(internal_path))
files = sorted(filter(lambda x: not x.startswith("."), files))
dirs = sorted(filter(lambda x: not x.startswith("."), dirs))
2024-01-23 16:31:46 +00:00
return (
render_template(
"directory.html",
path=path,
dirs=dirs,
files=files,
),
200,
)
# Path exists, not a folder, must be a file, send
return send_file(internal_path)
2024-01-25 01:19:00 +00:00
@app.route('/search')
@auth.requires_auth
2024-01-25 01:19:00 +00:00
def search():
q = request.args.get('q', '')
if q == '':
return (
render_template(
"error.html",
code=400,
msg='No search string provided.',
),
400,
)
ret = file.search(q)
return (
render_template(
"search.html",
list=ret,
q=q,
),
200,
)
@app.route('/auth', methods=['POST'])
def auth_handle():
expected_pass = config.get('password')
if expected_pass is None:
return "You shouldn't be here.", 405
if request.form.get("pass", None) != expected_pass:
return render_template(
'auth.html',
path=request.form.get("location", "/"),
error_msg="Incorrect password",
), 403
return Response(
"Redirecting...",
303,
{
'Location': request.form.get("location", "/"),
'Set-Cookie': 'film_session=To be changed',
}
)