materia-server: file remove api

This commit is contained in:
L-Nafaryus 2024-07-02 00:47:24 +05:00
parent 1877554bb2
commit 4312d5b5d1
Signed by: L-Nafaryus
GPG Key ID: 553C97999B363D38
2 changed files with 31 additions and 2 deletions

View File

@ -36,6 +36,11 @@ class File(Base):
.where(sa.and_(File.repository_id == repository_id, File.name == name, query_path))) .where(sa.and_(File.repository_id == repository_id, File.name == name, query_path)))
).first() ).first()
async def remove(self, db: database.Database):
async with db.session() as session:
await session.execute(sa.delete(File).where(File.id == self.id))
await session.commit()
class FileLink(Base): class FileLink(Base):
__tablename__ = "file_link" __tablename__ = "file_link"

View File

@ -68,11 +68,35 @@ async def info(path: Path, user: User = Depends(middleware.user), ctx: middlewar
await session.refresh(user, attribute_names = ["repository"]) await session.refresh(user, attribute_names = ["repository"])
if not user.repository: if not user.repository:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Repository is not found") raise HTTPException(status.HTTP_404_NOT_FOUND, "Repository not found")
if not(file := await File.by_path(user.repository.id, None if path.parent == Path() else path.parent, path.name, ctx.database)): if not(file := await File.by_path(user.repository.id, None if path.parent == Path() else path.parent, path.name, ctx.database)):
raise HTTPException(status.HTTP_404_NOT_FOUND, "File is not found") raise HTTPException(status.HTTP_404_NOT_FOUND, "File not found")
info = FileInfo.model_validate(file) info = FileInfo.model_validate(file)
return info return info
@router.delete("/file")
async def remove(path: Path, user: User = Depends(middleware.user), ctx: middleware.Context = Depends()):
async with ctx.database.session() as session:
session.add(user)
await session.refresh(user, attribute_names = ["repository"])
if not user.repository:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Repository not found")
if not(file := await File.by_path(user.repository.id, None if path.parent == Path() else path.parent, path.name, ctx.database)):
raise HTTPException(status.HTTP_404_NOT_FOUND, "File not found")
repository_path = Config.data_dir() / "repository" / user.lower_name
try:
file_path = repository_path.joinpath(path)
if file_path.exists():
file_path.unlink(missing_ok = True)
except OSError:
raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Failed to remove a file")
await file.remove(ctx.database)