您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

tool_file_manager.py 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import base64
  2. import hashlib
  3. import hmac
  4. import logging
  5. import os
  6. import time
  7. from collections.abc import Generator
  8. from mimetypes import guess_extension, guess_type
  9. from typing import Optional, Union
  10. from uuid import uuid4
  11. from httpx import get
  12. from configs import dify_config
  13. from extensions.ext_database import db
  14. from extensions.ext_storage import storage
  15. from models.model import MessageFile
  16. from models.tools import ToolFile
  17. logger = logging.getLogger(__name__)
  18. class ToolFileManager:
  19. @staticmethod
  20. def sign_file(tool_file_id: str, extension: str) -> str:
  21. """
  22. sign file to get a temporary url
  23. """
  24. base_url = dify_config.FILES_URL
  25. file_preview_url = f"{base_url}/files/tools/{tool_file_id}{extension}"
  26. timestamp = str(int(time.time()))
  27. nonce = os.urandom(16).hex()
  28. data_to_sign = f"file-preview|{tool_file_id}|{timestamp}|{nonce}"
  29. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  30. sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  31. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  32. return f"{file_preview_url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  33. @staticmethod
  34. def verify_file(file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  35. """
  36. verify signature
  37. """
  38. data_to_sign = f"file-preview|{file_id}|{timestamp}|{nonce}"
  39. secret_key = dify_config.SECRET_KEY.encode() if dify_config.SECRET_KEY else b""
  40. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  41. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  42. # verify signature
  43. if sign != recalculated_encoded_sign:
  44. return False
  45. current_time = int(time.time())
  46. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT
  47. @staticmethod
  48. def create_file_by_raw(
  49. *,
  50. user_id: str,
  51. tenant_id: str,
  52. conversation_id: Optional[str],
  53. file_binary: bytes,
  54. mimetype: str,
  55. ) -> ToolFile:
  56. extension = guess_extension(mimetype) or ".bin"
  57. unique_name = uuid4().hex
  58. filename = f"{unique_name}{extension}"
  59. filepath = f"tools/{tenant_id}/{filename}"
  60. storage.save(filepath, file_binary)
  61. tool_file = ToolFile(
  62. user_id=user_id,
  63. tenant_id=tenant_id,
  64. conversation_id=conversation_id,
  65. file_key=filepath,
  66. mimetype=mimetype,
  67. name=filename,
  68. size=len(file_binary),
  69. )
  70. db.session.add(tool_file)
  71. db.session.commit()
  72. db.session.refresh(tool_file)
  73. return tool_file
  74. @staticmethod
  75. def create_file_by_url(
  76. user_id: str,
  77. tenant_id: str,
  78. conversation_id: str | None,
  79. file_url: str,
  80. ) -> ToolFile:
  81. # try to download image
  82. try:
  83. response = get(file_url)
  84. response.raise_for_status()
  85. blob = response.content
  86. except Exception as e:
  87. logger.error(f"Failed to download file from {file_url}: {e}")
  88. raise
  89. mimetype = guess_type(file_url)[0] or "octet/stream"
  90. extension = guess_extension(mimetype) or ".bin"
  91. unique_name = uuid4().hex
  92. filename = f"{unique_name}{extension}"
  93. filepath = f"tools/{tenant_id}/{filename}"
  94. storage.save(filepath, blob)
  95. tool_file = ToolFile(
  96. user_id=user_id,
  97. tenant_id=tenant_id,
  98. conversation_id=conversation_id,
  99. file_key=filepath,
  100. mimetype=mimetype,
  101. original_url=file_url,
  102. name=filename,
  103. size=len(blob),
  104. )
  105. db.session.add(tool_file)
  106. db.session.commit()
  107. return tool_file
  108. @staticmethod
  109. def get_file_binary(id: str) -> Union[tuple[bytes, str], None]:
  110. """
  111. get file binary
  112. :param id: the id of the file
  113. :return: the binary of the file, mime type
  114. """
  115. tool_file = (
  116. db.session.query(ToolFile)
  117. .filter(
  118. ToolFile.id == id,
  119. )
  120. .first()
  121. )
  122. if not tool_file:
  123. return None
  124. blob = storage.load_once(tool_file.file_key)
  125. return blob, tool_file.mimetype
  126. @staticmethod
  127. def get_file_binary_by_message_file_id(id: str) -> Union[tuple[bytes, str], None]:
  128. """
  129. get file binary
  130. :param id: the id of the file
  131. :return: the binary of the file, mime type
  132. """
  133. message_file = (
  134. db.session.query(MessageFile)
  135. .filter(
  136. MessageFile.id == id,
  137. )
  138. .first()
  139. )
  140. # Check if message_file is not None
  141. if message_file is not None:
  142. # get tool file id
  143. if message_file.url is not None:
  144. tool_file_id = message_file.url.split("/")[-1]
  145. # trim extension
  146. tool_file_id = tool_file_id.split(".")[0]
  147. else:
  148. tool_file_id = None
  149. else:
  150. tool_file_id = None
  151. tool_file = (
  152. db.session.query(ToolFile)
  153. .filter(
  154. ToolFile.id == tool_file_id,
  155. )
  156. .first()
  157. )
  158. if not tool_file:
  159. return None
  160. blob = storage.load_once(tool_file.file_key)
  161. return blob, tool_file.mimetype
  162. @staticmethod
  163. def get_file_generator_by_tool_file_id(tool_file_id: str) -> Union[tuple[Generator, str], None]:
  164. """
  165. get file binary
  166. :param tool_file_id: the id of the tool file
  167. :return: the binary of the file, mime type
  168. """
  169. tool_file = (
  170. db.session.query(ToolFile)
  171. .filter(
  172. ToolFile.id == tool_file_id,
  173. )
  174. .first()
  175. )
  176. if not tool_file:
  177. return None
  178. generator = storage.load_stream(tool_file.file_key)
  179. return generator, tool_file.mimetype
  180. # init tool_file_parser
  181. from core.file.tool_file_parser import tool_file_manager
  182. tool_file_manager["manager"] = ToolFileManager