tool_file_manager.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import base64
  2. import hashlib
  3. import hmac
  4. import logging
  5. import os
  6. import time
  7. from mimetypes import guess_extension, guess_type
  8. from typing import Optional, Union
  9. from uuid import uuid4
  10. import httpx
  11. from configs import dify_config
  12. from core.helper import ssrf_proxy
  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. file_url: str,
  79. conversation_id: Optional[str] = None,
  80. ) -> ToolFile:
  81. # try to download image
  82. try:
  83. response = ssrf_proxy.get(file_url)
  84. response.raise_for_status()
  85. blob = response.content
  86. except httpx.TimeoutException:
  87. raise ValueError(f"timeout when downloading file from {file_url}")
  88. mimetype = guess_type(file_url)[0] or "octet/stream"
  89. extension = guess_extension(mimetype) or ".bin"
  90. unique_name = uuid4().hex
  91. filename = f"{unique_name}{extension}"
  92. filepath = f"tools/{tenant_id}/{filename}"
  93. storage.save(filepath, blob)
  94. tool_file = ToolFile(
  95. user_id=user_id,
  96. tenant_id=tenant_id,
  97. conversation_id=conversation_id,
  98. file_key=filepath,
  99. mimetype=mimetype,
  100. original_url=file_url,
  101. name=filename,
  102. size=len(blob),
  103. )
  104. db.session.add(tool_file)
  105. db.session.commit()
  106. return tool_file
  107. @staticmethod
  108. def get_file_binary(id: str) -> Union[tuple[bytes, str], None]:
  109. """
  110. get file binary
  111. :param id: the id of the file
  112. :return: the binary of the file, mime type
  113. """
  114. tool_file: ToolFile | None = (
  115. db.session.query(ToolFile)
  116. .filter(
  117. ToolFile.id == id,
  118. )
  119. .first()
  120. )
  121. if not tool_file:
  122. return None
  123. blob = storage.load_once(tool_file.file_key)
  124. return blob, tool_file.mimetype
  125. @staticmethod
  126. def get_file_binary_by_message_file_id(id: str) -> Union[tuple[bytes, str], None]:
  127. """
  128. get file binary
  129. :param id: the id of the file
  130. :return: the binary of the file, mime type
  131. """
  132. message_file: MessageFile | None = (
  133. db.session.query(MessageFile)
  134. .filter(
  135. MessageFile.id == id,
  136. )
  137. .first()
  138. )
  139. # Check if message_file is not None
  140. if message_file is not None:
  141. # get tool file id
  142. if message_file.url is not None:
  143. tool_file_id = message_file.url.split("/")[-1]
  144. # trim extension
  145. tool_file_id = tool_file_id.split(".")[0]
  146. else:
  147. tool_file_id = None
  148. else:
  149. tool_file_id = None
  150. tool_file: ToolFile | None = (
  151. db.session.query(ToolFile)
  152. .filter(
  153. ToolFile.id == tool_file_id,
  154. )
  155. .first()
  156. )
  157. if not tool_file:
  158. return None
  159. blob = storage.load_once(tool_file.file_key)
  160. return blob, tool_file.mimetype
  161. @staticmethod
  162. def get_file_generator_by_tool_file_id(tool_file_id: str):
  163. """
  164. get file binary
  165. :param tool_file_id: the id of the tool file
  166. :return: the binary of the file, mime type
  167. """
  168. tool_file: ToolFile | None = (
  169. db.session.query(ToolFile)
  170. .filter(
  171. ToolFile.id == tool_file_id,
  172. )
  173. .first()
  174. )
  175. if not tool_file:
  176. return None, None
  177. stream = storage.load_stream(tool_file.file_key)
  178. return stream, tool_file
  179. # init tool_file_parser
  180. from core.file.tool_file_parser import tool_file_manager
  181. tool_file_manager["manager"] = ToolFileManager