tool_file_manager.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 flask import current_app
  12. from httpx import get
  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 = current_app.config.get('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 = current_app.config['SECRET_KEY'].encode()
  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 = current_app.config['SECRET_KEY'].encode()
  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) <= 300 # expired after 5 minutes
  47. @staticmethod
  48. def create_file_by_raw(user_id: str, tenant_id: str,
  49. conversation_id: Optional[str], file_binary: bytes,
  50. mimetype: str
  51. ) -> ToolFile:
  52. """
  53. create file
  54. """
  55. extension = guess_extension(mimetype) or '.bin'
  56. unique_name = uuid4().hex
  57. filename = f"tools/{tenant_id}/{unique_name}{extension}"
  58. storage.save(filename, file_binary)
  59. tool_file = ToolFile(user_id=user_id, tenant_id=tenant_id,
  60. conversation_id=conversation_id, file_key=filename, mimetype=mimetype)
  61. db.session.add(tool_file)
  62. db.session.commit()
  63. return tool_file
  64. @staticmethod
  65. def create_file_by_url(user_id: str, tenant_id: str,
  66. conversation_id: str, file_url: str,
  67. ) -> ToolFile:
  68. """
  69. create file
  70. """
  71. # try to download image
  72. response = get(file_url)
  73. response.raise_for_status()
  74. blob = response.content
  75. mimetype = guess_type(file_url)[0] or 'octet/stream'
  76. extension = guess_extension(mimetype) or '.bin'
  77. unique_name = uuid4().hex
  78. filename = f"tools/{tenant_id}/{unique_name}{extension}"
  79. storage.save(filename, blob)
  80. tool_file = ToolFile(user_id=user_id, tenant_id=tenant_id,
  81. conversation_id=conversation_id, file_key=filename,
  82. mimetype=mimetype, original_url=file_url)
  83. db.session.add(tool_file)
  84. db.session.commit()
  85. return tool_file
  86. @staticmethod
  87. def create_file_by_key(user_id: str, tenant_id: str,
  88. conversation_id: str, file_key: str,
  89. mimetype: str
  90. ) -> ToolFile:
  91. """
  92. create file
  93. """
  94. tool_file = ToolFile(user_id=user_id, tenant_id=tenant_id,
  95. conversation_id=conversation_id, file_key=file_key, mimetype=mimetype)
  96. return tool_file
  97. @staticmethod
  98. def get_file_binary(id: str) -> Union[tuple[bytes, str], None]:
  99. """
  100. get file binary
  101. :param id: the id of the file
  102. :return: the binary of the file, mime type
  103. """
  104. tool_file: ToolFile = db.session.query(ToolFile).filter(
  105. ToolFile.id == id,
  106. ).first()
  107. if not tool_file:
  108. return None
  109. blob = storage.load_once(tool_file.file_key)
  110. return blob, tool_file.mimetype
  111. @staticmethod
  112. def get_file_binary_by_message_file_id(id: str) -> Union[tuple[bytes, str], None]:
  113. """
  114. get file binary
  115. :param id: the id of the file
  116. :return: the binary of the file, mime type
  117. """
  118. message_file: MessageFile = db.session.query(MessageFile).filter(
  119. MessageFile.id == id,
  120. ).first()
  121. # get tool file id
  122. tool_file_id = message_file.url.split('/')[-1]
  123. # trim extension
  124. tool_file_id = tool_file_id.split('.')[0]
  125. tool_file: ToolFile = db.session.query(ToolFile).filter(
  126. ToolFile.id == tool_file_id,
  127. ).first()
  128. if not tool_file:
  129. return None
  130. blob = storage.load_once(tool_file.file_key)
  131. return blob, tool_file.mimetype
  132. @staticmethod
  133. def get_file_generator_by_tool_file_id(tool_file_id: str) -> Union[tuple[Generator, str], None]:
  134. """
  135. get file binary
  136. :param tool_file_id: the id of the tool file
  137. :return: the binary of the file, mime type
  138. """
  139. tool_file: ToolFile = db.session.query(ToolFile).filter(
  140. ToolFile.id == tool_file_id,
  141. ).first()
  142. if not tool_file:
  143. return None
  144. generator = storage.load_stream(tool_file.file_key)
  145. return generator, tool_file.mimetype
  146. # init tool_file_parser
  147. from core.file.tool_file_parser import tool_file_manager
  148. tool_file_manager['manager'] = ToolFileManager