77 lines
1.6 KiB
Python
77 lines
1.6 KiB
Python
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
import random
|
|
import os
|
|
import shutil
|
|
import time
|
|
|
|
user_data_lifetime_seconds = 2*60*60
|
|
data_path = "user_data"
|
|
users = dict([])
|
|
|
|
if os.path.exists(data_path):
|
|
shutil.rmtree(data_path)
|
|
|
|
def delete_old_users(session):
|
|
for ID in users.copy():
|
|
elapsed = time.time() - users[ID]["last accessed"]
|
|
|
|
if (elapsed > user_data_lifetime_seconds):
|
|
print(ID, "Hasn't accessed their files in", elapsed, "seconds, removing all user data")
|
|
|
|
shutil.rmtree(users[ID]["path"])
|
|
del users[ID]
|
|
|
|
new_user_handler_func = None
|
|
|
|
|
|
def new_user_handler(func):
|
|
global new_user_handler_func
|
|
new_user_handler_func = func
|
|
return func
|
|
|
|
|
|
def new_user(session):
|
|
while(True):
|
|
ID = random.randint(0, 100000000)
|
|
if not ID in users:
|
|
break
|
|
|
|
users[ID] = {
|
|
"path": data_path + "/" + str(ID),
|
|
"last accessed": time.time()
|
|
}
|
|
|
|
session["ID"] = ID
|
|
|
|
os.makedirs(users[session["ID"]]["path"])
|
|
|
|
if new_user_handler_func:
|
|
new_user_handler_func(session)
|
|
|
|
|
|
def get_file_path(session, filename):
|
|
return os.path.join(get_folder_path(session), filename)
|
|
|
|
|
|
def file_exists(session, filename):
|
|
return os.path.exists(get_file_path(session, filename))
|
|
|
|
|
|
def check_for_new_user(session):
|
|
if not "ID" in session:
|
|
new_user(session)
|
|
elif not session["ID"] in users:
|
|
new_user(session)
|
|
|
|
delete_old_users(session)
|
|
|
|
|
|
def get_folder_path(session):
|
|
check_for_new_user(session)
|
|
ID = session["ID"]
|
|
user = users[ID]
|
|
|
|
user["last accessed"] = time.time()
|
|
|
|
return user["path"]
|
|
|