diff options
author | cbdev <cb@cbcdn.com> | 2022-07-10 21:57:27 +0200 |
---|---|---|
committer | cbdev <cb@cbcdn.com> | 2022-07-10 21:57:27 +0200 |
commit | 596d683fc26e18e68f2a7a13520dd2b85674814b (patch) | |
tree | d1ae2ae20a0de40c7435f2ad4be8f3eec9e92e9d /backend/utils.py | |
parent | a52bd5c5e458b102bece92d993f327ab3e311601 (diff) | |
download | cargohold-596d683fc26e18e68f2a7a13520dd2b85674814b.tar.gz cargohold-596d683fc26e18e68f2a7a13520dd2b85674814b.tar.bz2 cargohold-596d683fc26e18e68f2a7a13520dd2b85674814b.zip |
Factor out common functions into utils
Diffstat (limited to 'backend/utils.py')
-rw-r--r-- | backend/utils.py | 55 |
1 files changed, 51 insertions, 4 deletions
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 |