file_service.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import datetime
  2. import hashlib
  3. import uuid
  4. from typing import Generator, Tuple, Union
  5. from flask import current_app
  6. from flask_login import current_user
  7. from werkzeug.datastructures import FileStorage
  8. from werkzeug.exceptions import NotFound
  9. from core.data_loader.file_extractor import FileExtractor
  10. from core.file.upload_file_parser import UploadFileParser
  11. from extensions.ext_storage import storage
  12. from extensions.ext_database import db
  13. from models.account import Account
  14. from models.model import UploadFile, EndUser
  15. from services.errors.file import FileTooLargeError, UnsupportedFileTypeError
  16. ALLOWED_EXTENSIONS = ['txt', 'markdown', 'md', 'pdf', 'html', 'htm', 'xlsx', 'docx', 'csv',
  17. 'jpg', 'jpeg', 'png', 'webp', 'gif', 'svg']
  18. IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg']
  19. PREVIEW_WORDS_LIMIT = 3000
  20. class FileService:
  21. @staticmethod
  22. def upload_file(file: FileStorage, user: Union[Account, EndUser], only_image: bool = False) -> UploadFile:
  23. extension = file.filename.split('.')[-1]
  24. if extension.lower() not in ALLOWED_EXTENSIONS:
  25. raise UnsupportedFileTypeError()
  26. elif only_image and extension.lower() not in IMAGE_EXTENSIONS:
  27. raise UnsupportedFileTypeError()
  28. # read file content
  29. file_content = file.read()
  30. # get file size
  31. file_size = len(file_content)
  32. if extension.lower() in IMAGE_EXTENSIONS:
  33. file_size_limit = current_app.config.get("UPLOAD_IMAGE_FILE_SIZE_LIMIT") * 1024 * 1024
  34. else:
  35. file_size_limit = current_app.config.get("UPLOAD_FILE_SIZE_LIMIT") * 1024 * 1024
  36. if file_size > file_size_limit:
  37. message = f'File size exceeded. {file_size} > {file_size_limit}'
  38. raise FileTooLargeError(message)
  39. # user uuid as file name
  40. file_uuid = str(uuid.uuid4())
  41. if isinstance(user, Account):
  42. current_tenant_id = user.current_tenant_id
  43. else:
  44. # end_user
  45. current_tenant_id = user.tenant_id
  46. file_key = 'upload_files/' + current_tenant_id + '/' + file_uuid + '.' + extension
  47. # save file to storage
  48. storage.save(file_key, file_content)
  49. # save file to db
  50. config = current_app.config
  51. upload_file = UploadFile(
  52. tenant_id=current_tenant_id,
  53. storage_type=config['STORAGE_TYPE'],
  54. key=file_key,
  55. name=file.filename,
  56. size=file_size,
  57. extension=extension,
  58. mime_type=file.mimetype,
  59. created_by_role=('account' if isinstance(user, Account) else 'end_user'),
  60. created_by=user.id,
  61. created_at=datetime.datetime.utcnow(),
  62. used=False,
  63. hash=hashlib.sha3_256(file_content).hexdigest()
  64. )
  65. db.session.add(upload_file)
  66. db.session.commit()
  67. return upload_file
  68. @staticmethod
  69. def upload_text(text: str, text_name: str) -> UploadFile:
  70. # user uuid as file name
  71. file_uuid = str(uuid.uuid4())
  72. file_key = 'upload_files/' + current_user.current_tenant_id + '/' + file_uuid + '.txt'
  73. # save file to storage
  74. storage.save(file_key, text.encode('utf-8'))
  75. # save file to db
  76. config = current_app.config
  77. upload_file = UploadFile(
  78. tenant_id=current_user.current_tenant_id,
  79. storage_type=config['STORAGE_TYPE'],
  80. key=file_key,
  81. name=text_name + '.txt',
  82. size=len(text),
  83. extension='txt',
  84. mime_type='text/plain',
  85. created_by=current_user.id,
  86. created_at=datetime.datetime.utcnow(),
  87. used=True,
  88. used_by=current_user.id,
  89. used_at=datetime.datetime.utcnow()
  90. )
  91. db.session.add(upload_file)
  92. db.session.commit()
  93. return upload_file
  94. @staticmethod
  95. def get_file_preview(file_id: str) -> str:
  96. upload_file = db.session.query(UploadFile) \
  97. .filter(UploadFile.id == file_id) \
  98. .first()
  99. if not upload_file:
  100. raise NotFound("File not found")
  101. # extract text from file
  102. extension = upload_file.extension
  103. if extension.lower() not in ALLOWED_EXTENSIONS:
  104. raise UnsupportedFileTypeError()
  105. text = FileExtractor.load(upload_file, return_text=True)
  106. text = text[0:PREVIEW_WORDS_LIMIT] if text else ''
  107. return text
  108. @staticmethod
  109. def get_image_preview(file_id: str, timestamp: str, nonce: str, sign: str) -> Tuple[Generator, str]:
  110. result = UploadFileParser.verify_image_file_signature(file_id, timestamp, nonce, sign)
  111. if not result:
  112. raise NotFound("File not found or signature is invalid")
  113. upload_file = db.session.query(UploadFile) \
  114. .filter(UploadFile.id == file_id) \
  115. .first()
  116. if not upload_file:
  117. raise NotFound("File not found or signature is invalid")
  118. # extract text from file
  119. extension = upload_file.extension
  120. if extension.lower() not in IMAGE_EXTENSIONS:
  121. raise UnsupportedFileTypeError()
  122. generator = storage.load(upload_file.key, stream=True)
  123. return generator, upload_file.mime_type
  124. @staticmethod
  125. def get_public_image_preview(file_id: str) -> str:
  126. upload_file = db.session.query(UploadFile) \
  127. .filter(UploadFile.id == file_id) \
  128. .first()
  129. if not upload_file:
  130. raise NotFound("File not found or signature is invalid")
  131. # extract text from file
  132. extension = upload_file.extension
  133. if extension.lower() not in IMAGE_EXTENSIONS:
  134. raise UnsupportedFileTypeError()
  135. generator = storage.load(upload_file.key)
  136. return generator, upload_file.mime_type