From 596d683fc26e18e68f2a7a13520dd2b85674814b Mon Sep 17 00:00:00 2001 From: cbdev Date: Sun, 10 Jul 2022 21:57:27 +0200 Subject: Factor out common functions into utils --- backend/utils.py | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 4 deletions(-) (limited to 'backend/utils.py') diff --git a/backend/utils.py b/backend/utils.py index ddb0adc..bab7ebe 100644 --- a/backend/utils.py +++ b/backend/utils.py @@ -1,12 +1,59 @@ +import sqlite3 +import os + import config +db = sqlite3.connect(config.database, check_same_thread = False) + def redirect(target): return ["", [('Content-Type','text/html'), ("Location", target)], "302 Redirect"] def ensure_user(name): - # TODO + # Add a user directory if configured + if config.user_subdirs: + try: + os.mkdir(config.fileroot + name) + except FileExistsError: + pass + + # Add the user to the database + db.cursor().execute("INSERT OR IGNORE INTO users (name) VALUES (:user)", {"user": name}) + db.commit() return -def is_user(name): - # TODO - return False +def userdir(name): + rootdir = config.fileroot + if config.user_subdirs: + rootdir += name + "/" + return rootdir + +def sanitize_filename(input): + filename = "".join(filter(lambda c: c not in "<>&", os.path.basename(input))) + # os.path.basename still allows `..` as basename + if not filename or filename.startswith("."): + raise ValueError("Invalid filename supplied: " + filename) + return filename + +def target_filename_internal(alias, filename): + target = alias["path"] + "/" + if filename: + target += filename + if config.user_subdirs: + target = alias["user"] + "/" + target + return target + +def target_filename(alias, file): + return config.fileroot + target_filename_internal(alias, file) + +def dirlisting(path, files, dirs): + listing = [] + entries = sorted(os.listdir(path)) + + for entry in entries: + if dirs and os.path.isdir(path + entry): + listing.append({"name": entry}) + if files and os.path.isfile(path + entry): + size = os.path.getsize(path + entry) + listing.append({"name": entry, "size": size}) + + return listing -- cgit v1.2.3