files.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. from fastapi import (
  2. Depends,
  3. FastAPI,
  4. HTTPException,
  5. status,
  6. Request,
  7. UploadFile,
  8. File,
  9. Form,
  10. )
  11. from datetime import datetime, timedelta
  12. from typing import List, Union, Optional
  13. from fastapi import APIRouter
  14. from pydantic import BaseModel
  15. import json
  16. from apps.webui.models.files import Files, FileForm, FileModel, FileResponse
  17. from utils.utils import get_verified_user, get_admin_user
  18. from constants import ERROR_MESSAGES
  19. from importlib import util
  20. import os
  21. import uuid
  22. from config import SRC_LOG_LEVELS, UPLOAD_DIR
  23. import logging
  24. log = logging.getLogger(__name__)
  25. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  26. router = APIRouter()
  27. ############################
  28. # Upload File
  29. ############################
  30. @router.post("/")
  31. def upload_file(
  32. file: UploadFile = File(...),
  33. user=Depends(get_verified_user),
  34. ):
  35. log.info(f"file.content_type: {file.content_type}")
  36. try:
  37. unsanitized_filename = file.filename
  38. filename = os.path.basename(unsanitized_filename)
  39. # replace filename with uuid
  40. id = str(uuid.uuid4())
  41. file_path = f"{UPLOAD_DIR}/{filename}"
  42. contents = file.file.read()
  43. with open(file_path, "wb") as f:
  44. f.write(contents)
  45. f.close()
  46. file = Files.insert_new_file(
  47. user.id,
  48. FileForm(
  49. **{
  50. "id": id,
  51. "filename": filename,
  52. "meta": {
  53. "content_type": file.content_type,
  54. "size": len(contents),
  55. "path": file_path,
  56. },
  57. }
  58. ),
  59. )
  60. if file:
  61. return file
  62. else:
  63. raise HTTPException(
  64. status_code=status.HTTP_400_BAD_REQUEST,
  65. detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
  66. )
  67. except Exception as e:
  68. log.exception(e)
  69. raise HTTPException(
  70. status_code=status.HTTP_400_BAD_REQUEST,
  71. detail=ERROR_MESSAGES.DEFAULT(e),
  72. )
  73. ############################
  74. # List Files
  75. ############################
  76. @router.get("/", response_model=List[FileModel])
  77. async def list_files(user=Depends(get_verified_user)):
  78. files = Files.get_files()
  79. return files
  80. ############################
  81. # Get File By Id
  82. ############################
  83. @router.get("/{id}", response_model=Optional[FileModel])
  84. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  85. file = Files.get_file_by_id(id)
  86. if file:
  87. return file
  88. else:
  89. raise HTTPException(
  90. status_code=status.HTTP_401_UNAUTHORIZED,
  91. detail=ERROR_MESSAGES.NOT_FOUND,
  92. )
  93. ############################
  94. # Delete File By Id
  95. ############################
  96. @router.delete("/{id}")
  97. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  98. file = Files.get_file_by_id(id)
  99. if file:
  100. result = Files.delete_file_by_id(id)
  101. if result:
  102. return {"message": "File deleted successfully"}
  103. else:
  104. raise HTTPException(
  105. status_code=status.HTTP_400_BAD_REQUEST,
  106. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  107. )
  108. else:
  109. raise HTTPException(
  110. status_code=status.HTTP_401_UNAUTHORIZED,
  111. detail=ERROR_MESSAGES.NOT_FOUND,
  112. )