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

tool_file_manager.py 7.6KB

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