in between state before converting to pathlib

This commit is contained in:
Marcel Gansfusz
2025-10-28 19:32:01 +01:00
parent 856c401c06
commit d6508c739d
9 changed files with 104 additions and 51 deletions

View File

@@ -3,7 +3,7 @@ from typing import List, Dict, Tuple, Sequence
from starlette.responses import StreamingResponse
from annotated_types import IsDigit
from fastapi import FastAPI, File, HTTPException, UploadFile, Request, Form
from fastapi import FastAPI, File, HTTPException, Path, UploadFile, Request, Form
from fastapi.responses import FileResponse
# import multiprocessing
@@ -28,6 +28,7 @@ import filetype
import logging
import pathlib
from pathlib import Path
from starlette.types import HTTPExceptionHandler
@@ -54,16 +55,6 @@ info("App Started")
# startup()
app = FastAPI()
app.mount(
"/favicon",
StaticFiles(directory=os.environ.get("FAVICON_PATH", ".app/favicon")),
name="favicon",
)
app.mount(
"/static",
StaticFiles(directory=os.environ.get("STATIC_PATH", "./static")),
name="static",
)
CATEGORIES = [
@@ -75,16 +66,18 @@ CATEGORIES = [
"Zusammenfassungen",
"Multimedia",
]
APP_ROOT_PATH = os.environ.get("APP_ROOT_PATH", "./app")
APP_ROOT_PATH = Path(os.environ.get("APP_ROOT_PATH", "./app"))
SUBCAT_CATEGORIES = ["Klausuren", "Übungen", "Labore"]
SUBCAT_CATEGORIES_I = [1, 2, 3]
EX_DATE_CATEGORIES = ["Prüfungen", "Klausuren"]
EX_DATE_CATEGORIES_I = [0, 1]
UNIZEUG_PATH = os.environ.get("UNIZEUG_PATH", "./app/dest")
FILES_IN_PROGRESS = f"{APP_ROOT_PATH}/files/"
EMPTYFILE = f"{APP_ROOT_PATH}/graphics/empty.pdf"
UNSUPPORTEDFILE = f"{APP_ROOT_PATH}/graphics/unsupported.pdf"
GREETINGFILE = f"{APP_ROOT_PATH}/graphics/greeting.pdf"
UNIZEUG_PATH = Path(os.environ.get("UNIZEUG_PATH", "./app/dest"))
FILES_IN_PROGRESS = APP_ROOT_PATH / "files/"
EMPTYFILE = APP_ROOT_PATH / "graphics/empty.pdf"
UNSUPPORTEDFILE = APP_ROOT_PATH / "graphics/unsupported.pdf"
GREETINGFILE = APP_ROOT_PATH / "graphics/greeting.pdf"
FAVICON = APP_ROOT_PATH / "favicon"
STATIC_FILES = APP_ROOT_PATH / "static"
# cur = db.cursor()
@@ -158,10 +151,22 @@ def sqlT(
# )
app.mount(
"/favicon",
StaticFiles(directory=os.environ.get("FAVICON_PATH", FAVICON)),
name="favicon",
)
app.mount(
"/static",
StaticFiles(directory=os.environ.get("STATIC_PATH", STATIC_FILES)),
name="static",
)
@app.get("/")
async def get_index():
"""gives the Index.html file"""
return FileResponse(f"{APP_ROOT_PATH}/index.html")
return FileResponse(APP_ROOT_PATH / "index.html")
@app.get("/files/{file_id}")
@@ -234,6 +239,9 @@ async def search_lva(
)
# res += cur.fetchall()
res = remove_duplicates(res + zw)
info(
f"LVA Search: {searchterm}; Result: {res[: (searchlim if searchlim != 0 else -1)]}"
)
if searchlim == 0:
return res
else:
@@ -268,6 +276,9 @@ async def search_profs(
)
# res += cur.fetchall()
res = remove_duplicates(res + zw)
info(
f"Prof Search: {searchterm}; Result: {res[: (searchlim if searchlim != 0 else -1)]}"
)
if searchlim == 0:
return res
else:
@@ -308,6 +319,9 @@ async def search_subcats(
)
# res += cur.fetchall()
res = remove_duplicates(res + rest)
info(
f"Subcatrgory Search: {searchterm}; Result: {res[: (searchlim if searchlim != 0 else -1)]}"
)
if searchlim == 0:
return res
else:
@@ -364,7 +378,7 @@ async def create_upload_file(files: List[UploadFile], c2pdf: bool = True):
content = doc.tobytes()
if ft != "dir":
filename = make_filename_unique(filename)
locpath = FILES_IN_PROGRESS + filename
locpath = FILES_IN_PROGRESS / filename
# locpaths.append(locpath)
# cur = db.cursor()
# try:
@@ -448,7 +462,7 @@ async def get_submission(
error(f"User tried to upload a file without specifying the {th[1]}")
raise HTTPException(400, f"You need to specify a {th[1]}")
filepath = "./app/files/" + res[0][0]
filepath = FILES_IN_PROGRESS / res[0][0]
# except mariadb.Error as e:
# print(f"Mariadb Error: {e}")
# raise HTTPException(
@@ -675,7 +689,7 @@ def make_savepath(
ex_date: str,
fname: str,
ftype: str,
) -> str:
) -> os.PathLike:
"""Generates the path, the file is saved to after the upload process is finished. It creates all nessecery directories."""
lv = get_lvpath(lva)
lvpath = lv[1] + "/"
@@ -687,9 +701,9 @@ def make_savepath(
sc = get_subcatpath(subcat, int(cat), pf[0], lv[0])
scpath = sc[1] + "/"
if int(cat) == 6:
savepath = UNIZEUG_PATH + lv[1] + "_Multimedia_only/" + pfpath
savepath = UNIZEUG_PATH / (lv[1] + "_Multimedia_only/") / pfpath
else:
savepath = UNIZEUG_PATH + lvpath + pfpath + catpath + scpath
savepath = UNIZEUG_PATH / lvpath / pfpath / catpath / scpath
os.makedirs(savepath, exist_ok=True)
filename = sem + "_"
if int(cat) in EX_DATE_CATEGORIES_I:
@@ -707,14 +721,14 @@ def make_savepath(
filename += fname
file = filename + "." + ftype
destpath = pathlib.Path(savepath + file)
destpath = savepath / file
i = 0
while destpath.is_file():
file = filename + f"_{i}." + ftype
i += 1
destpath = pathlib.Path(savepath + file)
destpath = savepath / file
destpath.touch()
return savepath + file
return savepath / file
def get_lvpath(lva: str) -> Tuple[int, str]:
@@ -907,10 +921,10 @@ async def save_files_to_folder(files: List[UploadFile]) -> str:
if filename == "":
filename = "None"
filename = make_filename_unique(filename)
os.mkdir(FILES_IN_PROGRESS + filename)
os.mkdir(FILES_IN_PROGRESS / filename)
for idx, file in enumerate(files):
fn = file.filename if file.filename is not None else "None" + str(idx)
with open(FILES_IN_PROGRESS + filename + "/" + fn, "wb") as f:
with open(FILES_IN_PROGRESS / filename / fn, "wb") as f:
f.write(await file.read())
return filename
@@ -938,13 +952,13 @@ async def remove_old_FIP_entrys():
info(f"Remove Files: {files}")
for file in files:
sql("DELETE FROM FIP WHERE id=?", (file["id"]), return_result=False)
os.remove(FILES_IN_PROGRESS + file["filename"])
os.remove(FILES_IN_PROGRESS / file["filename"])
# sql(
# "DELETE FROM FIP WHERE HOUR(TIMEDIFF(NOW(),initTimeStamp)) > 24",
# return_result=False,
# )
db.commit()
return FileResponse("./index.html")
return FileResponse(APP_ROOT_PATH / "/index.html")
def delete_from_FIP(uuid: str):