2024-01-23 16:31:46 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import os
|
|
|
|
import tomllib
|
|
|
|
from flask import Flask, render_template, send_file
|
|
|
|
|
|
|
|
with open("config.toml", "rb") as f:
|
|
|
|
config = tomllib.load(f)
|
|
|
|
|
|
|
|
app = Flask(
|
|
|
|
__name__,
|
|
|
|
template_folder="../templates",
|
|
|
|
static_folder="../static",
|
|
|
|
)
|
|
|
|
|
|
|
|
app.jinja_env.globals.update(
|
|
|
|
config=config,
|
|
|
|
path_join=os.path.join,
|
|
|
|
)
|
|
|
|
|
|
|
|
# Catch all
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/', defaults={'path': ''})
|
|
|
|
@app.route('/<path:path>')
|
|
|
|
def index(path):
|
|
|
|
internal_path = os.path.join(config['base_path'], path)
|
|
|
|
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))
|
2024-01-24 22:52:28 +00:00
|
|
|
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)
|