file-tree-upload-doc.tsx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import { useTranslation } from 'react-i18next'
  2. import { Button } from 'react-bootstrap'
  3. import { useCallback, useEffect, useState } from 'react'
  4. import Uppy from '@uppy/core'
  5. import XHRUpload from '@uppy/xhr-upload'
  6. import { Dashboard } from '@uppy/react'
  7. import { useFileTreeActionable } from '../../../contexts/file-tree-actionable'
  8. import { useProjectContext } from '../../../../../shared/context/project-context'
  9. import * as eventTracking from '../../../../../infrastructure/event-tracking'
  10. import '@uppy/core/dist/style.css'
  11. import '@uppy/dashboard/dist/style.css'
  12. import { refreshProjectMetadata } from '../../../util/api'
  13. import ErrorMessage from '../error-message'
  14. import { debugConsole } from '@/utils/debugging'
  15. export default function FileTreeUploadDoc() {
  16. const { parentFolderId, cancel, isDuplicate, droppedFiles, setDroppedFiles } =
  17. useFileTreeActionable()
  18. const { _id: projectId } = useProjectContext()
  19. const [error, setError] = useState<string>()
  20. const [conflicts, setConflicts] = useState<any[]>([])
  21. const [overwrite, setOverwrite] = useState(false)
  22. const maxNumberOfFiles = 40
  23. const maxFileSize = window.ExposedSettings.maxUploadSize
  24. // calculate conflicts
  25. const buildConflicts = (files: Record<string, any>) =>
  26. Object.values(files).filter(file =>
  27. isDuplicate(file.meta.targetFolderId ?? parentFolderId, file.meta.name)
  28. )
  29. const buildEndpoint = (projectId: string, targetFolderId: string) => {
  30. let endpoint = `/project/${projectId}/upload`
  31. if (targetFolderId) {
  32. endpoint += `?folder_id=${targetFolderId}`
  33. }
  34. return endpoint
  35. }
  36. // initialise the Uppy object
  37. const [uppy] = useState(() => {
  38. const endpoint = buildEndpoint(projectId, parentFolderId)
  39. return (
  40. new Uppy({
  41. // logger: Uppy.debugLogger,
  42. allowMultipleUploadBatches: false,
  43. restrictions: {
  44. maxNumberOfFiles,
  45. maxFileSize: maxFileSize || null,
  46. },
  47. onBeforeUpload: files => {
  48. let result = true
  49. setOverwrite(overwrite => {
  50. if (!overwrite) {
  51. setConflicts(() => {
  52. const conflicts = buildConflicts(files)
  53. result = conflicts.length === 0
  54. return conflicts
  55. })
  56. }
  57. return overwrite
  58. })
  59. return result
  60. },
  61. autoProceed: true,
  62. })
  63. // use the basic XHR uploader
  64. .use(XHRUpload, {
  65. endpoint,
  66. headers: {
  67. 'X-CSRF-TOKEN': window.csrfToken,
  68. },
  69. // limit: maxConnections || 1,
  70. limit: 1,
  71. fieldName: 'qqfile', // "qqfile" field inherited from FineUploader
  72. })
  73. // close the modal when all the uploads completed successfully
  74. .on('complete', result => {
  75. if (!result.failed.length) {
  76. // $scope.$emit('done', { name: name })
  77. cancel()
  78. }
  79. })
  80. // broadcast doc metadata after each successful upload
  81. .on('upload-success', (file, response) => {
  82. eventTracking.sendMB('new-file-created', { method: 'upload' })
  83. if (response.body.entity_type === 'doc') {
  84. window.setTimeout(() => {
  85. refreshProjectMetadata(projectId, response.body.entity_id)
  86. }, 250)
  87. }
  88. })
  89. // handle upload errors
  90. .on('upload-error', (file, error, response) => {
  91. switch (response?.status) {
  92. case 429:
  93. setError('rate-limit-hit')
  94. break
  95. case 403:
  96. setError('not-logged-in')
  97. break
  98. default:
  99. debugConsole.error(error)
  100. setError(response?.body?.error || 'generic_something_went_wrong')
  101. break
  102. }
  103. })
  104. )
  105. })
  106. useEffect(() => {
  107. if (uppy && droppedFiles) {
  108. uppy.setOptions({
  109. autoProceed: false,
  110. })
  111. for (const file of droppedFiles.files) {
  112. const fileId = uppy.addFile({
  113. name: file.name,
  114. type: file.type,
  115. data: file,
  116. source: 'Local',
  117. isRemote: false,
  118. meta: {
  119. targetFolderId: droppedFiles.targetFolderId,
  120. },
  121. })
  122. const uppyFile = uppy.getFile(fileId)
  123. uppy.setFileState(fileId, {
  124. xhrUpload: {
  125. // @ts-ignore
  126. ...uppyFile.xhrUpload,
  127. endpoint: buildEndpoint(projectId, droppedFiles.targetFolderId),
  128. },
  129. })
  130. }
  131. }
  132. return () => {
  133. setDroppedFiles(null)
  134. }
  135. }, [uppy, droppedFiles, setDroppedFiles, projectId])
  136. // handle forced overwriting of conflicting files
  137. const handleOverwrite = useCallback(() => {
  138. setOverwrite(true)
  139. window.setTimeout(() => {
  140. uppy.upload()
  141. }, 10)
  142. }, [uppy])
  143. // whether to show a message about conflicting files
  144. const showConflicts = !overwrite && conflicts.length > 0
  145. return (
  146. <>
  147. {error && (
  148. <UploadErrorMessage error={error} maxNumberOfFiles={maxNumberOfFiles} />
  149. )}
  150. {showConflicts ? (
  151. <UploadConflicts
  152. cancel={cancel}
  153. conflicts={conflicts}
  154. handleOverwrite={handleOverwrite}
  155. />
  156. ) : (
  157. <Dashboard
  158. uppy={uppy}
  159. showProgressDetails
  160. // note={`Up to ${maxNumberOfFiles} files, up to ${maxFileSize / (1024 * 1024)}MB`}
  161. height={400}
  162. width="100%"
  163. showLinkToFileUploadResult={false}
  164. proudlyDisplayPoweredByUppy={false}
  165. locale={{
  166. strings: {
  167. // Text to show on the droppable area.
  168. // `%{browse}` is replaced with a link that opens the system file selection dialog.
  169. // TODO: 'drag_here' or 'drop_files_here_to_upload'?
  170. // dropHereOr: `${t('drag_here')} ${t('or')} %{browse}`,
  171. dropPasteFiles: `Drag here, paste an image or file, or %{browseFiles}`,
  172. // Used as the label for the link that opens the system file selection dialog.
  173. // browseFiles: t('select_from_your_computer')
  174. browseFiles: 'select from your computer',
  175. },
  176. }}
  177. />
  178. )}
  179. </>
  180. )
  181. }
  182. function UploadErrorMessage({
  183. error,
  184. maxNumberOfFiles,
  185. }: {
  186. error: string
  187. maxNumberOfFiles: number
  188. }) {
  189. const { t } = useTranslation()
  190. switch (error) {
  191. case 'too-many-files':
  192. return (
  193. <>
  194. {t('maximum_files_uploaded_together', {
  195. max: maxNumberOfFiles,
  196. })}
  197. </>
  198. )
  199. default:
  200. return <ErrorMessage error={error} />
  201. }
  202. }
  203. function UploadConflicts({
  204. cancel,
  205. conflicts,
  206. handleOverwrite,
  207. }: {
  208. cancel: () => void
  209. conflicts: any[]
  210. handleOverwrite: () => void
  211. }) {
  212. const { t } = useTranslation()
  213. return (
  214. <div className="small modal-new-file--body-conflict">
  215. <p className="text-center mb-0">
  216. {t('the_following_files_already_exist_in_this_project')}
  217. </p>
  218. <ul className="text-center list-unstyled row-spaced-small mt-1">
  219. {conflicts.map((conflict, index) => (
  220. <li key={index}>
  221. <strong>{conflict.meta.name}</strong>
  222. </li>
  223. ))}
  224. </ul>
  225. <p className="text-center row-spaced-small">
  226. {t('do_you_want_to_overwrite_them')}
  227. </p>
  228. <p className="text-center">
  229. <Button bsStyle={null} className="btn-secondary" onClick={cancel}>
  230. {t('cancel')}
  231. </Button>
  232. &nbsp;
  233. <Button bsStyle="danger" onClick={handleOverwrite}>
  234. {t('overwrite')}
  235. </Button>
  236. </p>
  237. </div>
  238. )
  239. }