2024-11-12 12:27:04 +00:00
|
|
|
import os
|
|
|
|
from datetime import datetime
|
|
|
|
from typing import List, Type
|
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
from database import db
|
2024-11-12 12:27:04 +00:00
|
|
|
from models import File, Organization, User
|
|
|
|
|
|
|
|
|
|
|
|
class FileService:
|
2024-11-13 02:49:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def create_dummy_file(org: Organization, user: User) -> File:
|
2024-11-12 12:27:04 +00:00
|
|
|
file = File(
|
|
|
|
file_handle = "dummy_file",
|
|
|
|
document_handle = "org/dummy_file.txt",
|
|
|
|
name = "dummy_file",
|
|
|
|
created_at = int(datetime.now().timestamp()),
|
|
|
|
org_id = 1,
|
|
|
|
creator_id = 1,
|
|
|
|
org = org,
|
|
|
|
creator = user
|
|
|
|
)
|
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
file_path = os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "repository"), file.document_handle)
|
2024-11-12 12:27:04 +00:00
|
|
|
with open(file_path, "w") as f:
|
|
|
|
f.write("Dummy file content")
|
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
db.add(file)
|
|
|
|
db.commit()
|
|
|
|
db.refresh(file)
|
2024-11-12 12:27:04 +00:00
|
|
|
return file
|
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_file(file_id: int) -> File | None:
|
|
|
|
return db.query(File).filter(File.id == file_id).first()
|
2024-11-12 12:27:04 +00:00
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_file_by_document_handle(document_handle: str) -> File | None:
|
|
|
|
return db.query(File).filter(File.document_handle == document_handle).first()
|
2024-11-12 12:27:04 +00:00
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_file_by_file_handle(file_handle: str) -> File | None:
|
|
|
|
return db.query(File).filter(File.file_handle == file_handle).first()
|
2024-11-12 12:27:04 +00:00
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def list_files() -> list[Type[File]]:
|
|
|
|
return db.query(File).all()
|
2024-11-12 12:27:04 +00:00
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def list_files_in_org(org: Organization) -> list[Type[File]]:
|
|
|
|
return db.query(File).filter(File.org_id == org.id).all()
|
2024-11-12 12:27:04 +00:00
|
|
|
|
2024-11-13 02:49:43 +00:00
|
|
|
@staticmethod
|
|
|
|
def delete_file(file: File) -> File:
|
|
|
|
file_path = os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "repository"), file.document_handle)
|
2024-11-12 12:27:04 +00:00
|
|
|
os.remove(file_path)
|
|
|
|
file.document_handle = None
|
2024-11-13 02:49:43 +00:00
|
|
|
db.commit()
|
|
|
|
db.refresh(file)
|
2024-11-12 12:27:04 +00:00
|
|
|
return file
|