aboutsummaryrefslogtreecommitdiff
path: root/backend/utils.py
blob: bab7ebe4e2eecb5d236cafab01994cd52b898997 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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):
	# 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 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