files.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import logging
  2. import time
  3. from typing import Optional
  4. from open_webui.apps.webui.internal.db import Base, JSONField, get_db
  5. from open_webui.env import SRC_LOG_LEVELS
  6. from pydantic import BaseModel, ConfigDict
  7. from sqlalchemy import BigInteger, Column, String, Text, JSON
  8. log = logging.getLogger(__name__)
  9. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  10. ####################
  11. # Files DB Schema
  12. ####################
  13. class File(Base):
  14. __tablename__ = "file"
  15. id = Column(String, primary_key=True)
  16. user_id = Column(String)
  17. hash = Column(Text, nullable=True)
  18. filename = Column(Text)
  19. data = Column(JSON)
  20. meta = Column(JSONField)
  21. created_at = Column(BigInteger)
  22. updated_at = Column(BigInteger)
  23. class FileModel(BaseModel):
  24. model_config = ConfigDict(from_attributes=True)
  25. id: str
  26. user_id: str
  27. hash: Optional[str] = None
  28. filename: str
  29. data: dict
  30. meta: dict
  31. created_at: int # timestamp in epoch
  32. updated_at: int # timestamp in epoch
  33. ####################
  34. # Forms
  35. ####################
  36. class FileModelResponse(BaseModel):
  37. id: str
  38. user_id: str
  39. hash: Optional[str] = None
  40. filename: str
  41. data: dict
  42. meta: dict
  43. created_at: int # timestamp in epoch
  44. updated_at: int # timestamp in epoch
  45. class FileForm(BaseModel):
  46. id: str
  47. hash: Optional[str] = None
  48. filename: str
  49. meta: dict = {}
  50. class FilesTable:
  51. def insert_new_file(self, user_id: str, form_data: FileForm) -> Optional[FileModel]:
  52. with get_db() as db:
  53. file = FileModel(
  54. **{
  55. **form_data.model_dump(),
  56. "user_id": user_id,
  57. "created_at": int(time.time()),
  58. "updated_at": int(time.time()),
  59. }
  60. )
  61. try:
  62. result = File(**file.model_dump())
  63. db.add(result)
  64. db.commit()
  65. db.refresh(result)
  66. if result:
  67. return FileModel.model_validate(result)
  68. else:
  69. return None
  70. except Exception as e:
  71. print(f"Error creating tool: {e}")
  72. return None
  73. def get_file_by_id(self, id: str) -> Optional[FileModel]:
  74. with get_db() as db:
  75. try:
  76. file = db.get(File, id)
  77. return FileModel.model_validate(file)
  78. except Exception:
  79. return None
  80. def get_files(self) -> list[FileModel]:
  81. with get_db() as db:
  82. return [FileModel.model_validate(file) for file in db.query(File).all()]
  83. def get_files_by_ids(self, ids: list[str]) -> list[FileModel]:
  84. with get_db() as db:
  85. return [
  86. FileModel.model_validate(file)
  87. for file in db.query(File).filter(File.id.in_(ids)).all()
  88. ]
  89. def get_files_by_user_id(self, user_id: str) -> list[FileModel]:
  90. with get_db() as db:
  91. return [
  92. FileModel.model_validate(file)
  93. for file in db.query(File).filter_by(user_id=user_id).all()
  94. ]
  95. def update_file_hash_by_id(self, id: str, hash: str) -> Optional[FileModel]:
  96. with get_db() as db:
  97. try:
  98. file = db.query(File).filter_by(id=id).first()
  99. file.hash = hash
  100. db.commit()
  101. return FileModel.model_validate(file)
  102. except Exception:
  103. return None
  104. def update_file_data_by_id(self, id: str, data: dict) -> Optional[FileModel]:
  105. with get_db() as db:
  106. try:
  107. file = db.query(File).filter_by(id=id).first()
  108. file.data = {**file.data, **data}
  109. db.commit()
  110. return FileModel.model_validate(file)
  111. except Exception:
  112. return None
  113. def update_file_metadata_by_id(self, id: str, meta: dict) -> Optional[FileModel]:
  114. with get_db() as db:
  115. try:
  116. file = db.query(File).filter_by(id=id).first()
  117. file.meta = {**file.meta, **meta}
  118. db.commit()
  119. return FileModel.model_validate(file)
  120. except Exception:
  121. return None
  122. def delete_file_by_id(self, id: str) -> bool:
  123. with get_db() as db:
  124. try:
  125. db.query(File).filter_by(id=id).delete()
  126. db.commit()
  127. return True
  128. except Exception:
  129. return False
  130. def delete_all_files(self) -> bool:
  131. with get_db() as db:
  132. try:
  133. db.query(File).delete()
  134. db.commit()
  135. return True
  136. except Exception:
  137. return False
  138. Files = FilesTable()