#!/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('/') 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, msg=f'The path "{path}" does not exist.', ), 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)) 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)