aboutsummaryrefslogtreecommitdiff
path: root/backend/utils.py
blob: 1e23e63a0c879d708389b757301e68cd69305401 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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

def cleanup(user, subdir):
	directory = userdir(user) + subdir + "/"
	print("Cleaning up %s" % (directory, ))
	# TODO
	# Remove contents
	# Remove aliases
	os.rmdir(directory)
	return

def aliases(user, subdir):
	aliases = []
	data = db.cursor().execute("SELECT alias, access, storage, display FROM aliases WHERE user = :user AND real = :dir", {"user": user, "dir": subdir}).fetchall()
	for alias in data:
		aliases.append({"alias": alias[0], "access": alias[1], "storage": alias[2], "display": alias[3]})
	return aliases