You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import datetime
  2. import hashlib
  3. import os
  4. import uuid
  5. from typing import Any, Literal, Union
  6. from flask_login import current_user # type: ignore
  7. from werkzeug.exceptions import NotFound
  8. from configs import dify_config
  9. from constants import (
  10. AUDIO_EXTENSIONS,
  11. DOCUMENT_EXTENSIONS,
  12. IMAGE_EXTENSIONS,
  13. VIDEO_EXTENSIONS,
  14. )
  15. from core.file import helpers as file_helpers
  16. from core.rag.extractor.extract_processor import ExtractProcessor
  17. from extensions.ext_database import db
  18. from extensions.ext_storage import storage
  19. from models.account import Account
  20. from models.enums import CreatedByRole
  21. from models.model import EndUser, UploadFile
  22. from .errors.file import FileTooLargeError, UnsupportedFileTypeError
  23. PREVIEW_WORDS_LIMIT = 3000
  24. class FileService:
  25. @staticmethod
  26. def upload_file(
  27. *,
  28. filename: str,
  29. content: bytes,
  30. mimetype: str,
  31. user: Union[Account, EndUser, Any],
  32. source: Literal["datasets"] | None = None,
  33. source_url: str = "",
  34. ) -> UploadFile:
  35. # get file extension
  36. extension = os.path.splitext(filename)[1].lstrip(".").lower()
  37. # check if filename contains invalid characters
  38. if any(c in filename for c in ["/", "\\", ":", "*", "?", '"', "<", ">", "|"]):
  39. raise ValueError("Filename contains invalid characters")
  40. if len(filename) > 200:
  41. filename = filename.split(".")[0][:200] + "." + extension
  42. if source == "datasets" and extension not in DOCUMENT_EXTENSIONS:
  43. raise UnsupportedFileTypeError()
  44. # get file size
  45. file_size = len(content)
  46. # check if the file size is exceeded
  47. if not FileService.is_file_size_within_limit(extension=extension, file_size=file_size):
  48. raise FileTooLargeError
  49. # generate file key
  50. file_uuid = str(uuid.uuid4())
  51. if isinstance(user, Account):
  52. current_tenant_id = user.current_tenant_id
  53. else:
  54. # end_user
  55. current_tenant_id = user.tenant_id
  56. file_key = "upload_files/" + (current_tenant_id or "") + "/" + file_uuid + "." + extension
  57. # save file to storage
  58. storage.save(file_key, content)
  59. # save file to db
  60. upload_file = UploadFile(
  61. tenant_id=current_tenant_id or "",
  62. storage_type=dify_config.STORAGE_TYPE,
  63. key=file_key,
  64. name=filename,
  65. size=file_size,
  66. extension=extension,
  67. mime_type=mimetype,
  68. created_by_role=(CreatedByRole.ACCOUNT if isinstance(user, Account) else CreatedByRole.END_USER),
  69. created_by=user.id,
  70. created_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  71. used=False,
  72. hash=hashlib.sha3_256(content).hexdigest(),
  73. source_url=source_url,
  74. )
  75. db.session.add(upload_file)
  76. db.session.commit()
  77. return upload_file
  78. @staticmethod
  79. def is_file_size_within_limit(*, extension: str, file_size: int) -> bool:
  80. if extension in IMAGE_EXTENSIONS:
  81. file_size_limit = dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT * 1024 * 1024
  82. elif extension in VIDEO_EXTENSIONS:
  83. file_size_limit = dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT * 1024 * 1024
  84. elif extension in AUDIO_EXTENSIONS:
  85. file_size_limit = dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT * 1024 * 1024
  86. else:
  87. file_size_limit = dify_config.UPLOAD_FILE_SIZE_LIMIT * 1024 * 1024
  88. return file_size <= file_size_limit
  89. @staticmethod
  90. def upload_text(text: str, text_name: str) -> UploadFile:
  91. if len(text_name) > 200:
  92. text_name = text_name[:200]
  93. # user uuid as file name
  94. file_uuid = str(uuid.uuid4())
  95. file_key = "upload_files/" + current_user.current_tenant_id + "/" + file_uuid + ".txt"
  96. # save file to storage
  97. storage.save(file_key, text.encode("utf-8"))
  98. # save file to db
  99. upload_file = UploadFile(
  100. tenant_id=current_user.current_tenant_id,
  101. storage_type=dify_config.STORAGE_TYPE,
  102. key=file_key,
  103. name=text_name,
  104. size=len(text),
  105. extension="txt",
  106. mime_type="text/plain",
  107. created_by=current_user.id,
  108. created_by_role=CreatedByRole.ACCOUNT,
  109. created_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  110. used=True,
  111. used_by=current_user.id,
  112. used_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  113. )
  114. db.session.add(upload_file)
  115. db.session.commit()
  116. return upload_file
  117. @staticmethod
  118. def get_file_preview(file_id: str):
  119. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  120. if not upload_file:
  121. raise NotFound("File not found")
  122. # extract text from file
  123. extension = upload_file.extension
  124. if extension.lower() not in DOCUMENT_EXTENSIONS:
  125. raise UnsupportedFileTypeError()
  126. text = ExtractProcessor.load_from_upload_file(upload_file, return_text=True)
  127. text = text[0:PREVIEW_WORDS_LIMIT] if text else ""
  128. return text
  129. @staticmethod
  130. def get_image_preview(file_id: str, timestamp: str, nonce: str, sign: str):
  131. result = file_helpers.verify_image_signature(
  132. upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign
  133. )
  134. if not result:
  135. raise NotFound("File not found or signature is invalid")
  136. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  137. if not upload_file:
  138. raise NotFound("File not found or signature is invalid")
  139. # extract text from file
  140. extension = upload_file.extension
  141. if extension.lower() not in IMAGE_EXTENSIONS:
  142. raise UnsupportedFileTypeError()
  143. generator = storage.load(upload_file.key, stream=True)
  144. return generator, upload_file.mime_type
  145. @staticmethod
  146. def get_file_generator_by_file_id(file_id: str, timestamp: str, nonce: str, sign: str):
  147. result = file_helpers.verify_file_signature(upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign)
  148. if not result:
  149. raise NotFound("File not found or signature is invalid")
  150. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  151. if not upload_file:
  152. raise NotFound("File not found or signature is invalid")
  153. generator = storage.load(upload_file.key, stream=True)
  154. return generator, upload_file
  155. @staticmethod
  156. def get_public_image_preview(file_id: str):
  157. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  158. if not upload_file:
  159. raise NotFound("File not found or signature is invalid")
  160. # extract text from file
  161. extension = upload_file.extension
  162. if extension.lower() not in IMAGE_EXTENSIONS:
  163. raise UnsupportedFileTypeError()
  164. generator = storage.load(upload_file.key)
  165. return generator, upload_file.mime_type