file-tree-upload-doc.jsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { Trans, useTranslation } from 'react-i18next'
  2. import { Button } from 'react-bootstrap'
  3. import { useCallback, useEffect, useState } from 'react'
  4. import PropTypes from 'prop-types'
  5. import Uppy from '@uppy/core'
  6. import XHRUpload from '@uppy/xhr-upload'
  7. import { Dashboard, useUppy } from '@uppy/react'
  8. import { useFileTreeActionable } from '../../../contexts/file-tree-actionable'
  9. import { useProjectContext } from '../../../../../shared/context/project-context'
  10. import * as eventTracking from '../../../../../infrastructure/event-tracking'
  11. import '@uppy/core/dist/style.css'
  12. import '@uppy/dashboard/dist/style.css'
  13. import { refreshProjectMetadata } from '../../../util/api'
  14. import ErrorMessage from '../error-message'
  15. import { debugConsole } from '@/utils/debugging'
  16. export default function FileTreeUploadDoc() {
  17. const { parentFolderId, cancel, isDuplicate, droppedFiles, setDroppedFiles } =
  18. useFileTreeActionable()
  19. const { _id: projectId } = useProjectContext(projectContextPropTypes)
  20. const [error, setError] = useState()
  21. const [conflicts, setConflicts] = useState([])
  22. const [overwrite, setOverwrite] = useState(false)
  23. const maxNumberOfFiles = 40
  24. const maxFileSize = window.ExposedSettings.maxUploadSize
  25. // calculate conflicts
  26. const buildConflicts = files =>
  27. Object.values(files).filter(file =>
  28. isDuplicate(file.meta.targetFolderId ?? parentFolderId, file.meta.name)
  29. )
  30. const buildEndpoint = (projectId, targetFolderId) => {
  31. let endpoint = `/project/${projectId}/upload`
  32. if (targetFolderId) {
  33. endpoint += `?folder_id=${targetFolderId}`
  34. }
  35. return endpoint
  36. }
  37. // initialise the Uppy object
  38. const uppy = useUppy(() => {
  39. const endpoint = buildEndpoint(projectId, parentFolderId)
  40. return (
  41. new Uppy({
  42. // logger: Uppy.debugLogger,
  43. allowMultipleUploads: false,
  44. restrictions: {
  45. maxNumberOfFiles,
  46. maxFileSize: maxFileSize || null,
  47. },
  48. onBeforeUpload: files => {
  49. let result = true
  50. setOverwrite(overwrite => {
  51. if (!overwrite) {
  52. setConflicts(() => {
  53. const conflicts = buildConflicts(files)
  54. result = conflicts.length === 0
  55. return conflicts
  56. })
  57. }
  58. return overwrite
  59. })
  60. return result
  61. },
  62. autoProceed: true,
  63. })
  64. // use the basic XHR uploader
  65. .use(XHRUpload, {
  66. endpoint,
  67. headers: {
  68. 'X-CSRF-TOKEN': window.csrfToken,
  69. },
  70. // limit: maxConnections || 1,
  71. limit: 1,
  72. fieldName: 'qqfile', // "qqfile" field inherited from FineUploader
  73. })
  74. // close the modal when all the uploads completed successfully
  75. .on('complete', result => {
  76. if (!result.failed.length) {
  77. // $scope.$emit('done', { name: name })
  78. cancel()
  79. }
  80. })
  81. // broadcast doc metadata after each successful upload
  82. .on('upload-success', (file, response) => {
  83. eventTracking.sendMB('new-file-created', { method: 'upload' })
  84. if (response.body.entity_type === 'doc') {
  85. window.setTimeout(() => {
  86. refreshProjectMetadata(projectId, response.body.entity_id)
  87. }, 250)
  88. }
  89. })
  90. // handle upload errors
  91. .on('upload-error', (file, error, response) => {
  92. switch (response?.status) {
  93. case 429:
  94. setError('rate-limit-hit')
  95. break
  96. case 403:
  97. setError('not-logged-in')
  98. break
  99. default:
  100. debugConsole.error(error)
  101. setError(response?.body?.error || 'generic_something_went_wrong')
  102. break
  103. }
  104. })
  105. )
  106. })
  107. useEffect(() => {
  108. if (uppy && droppedFiles) {
  109. uppy.setOptions({
  110. autoProceed: false,
  111. })
  112. for (const file of droppedFiles.files) {
  113. const fileId = uppy.addFile({
  114. name: file.name,
  115. type: file.type,
  116. data: file,
  117. source: 'Local',
  118. isRemote: false,
  119. meta: {
  120. targetFolderId: droppedFiles.targetFolderId,
  121. },
  122. })
  123. const uppyFile = uppy.getFile(fileId)
  124. uppy.setFileState(fileId, {
  125. xhrUpload: {
  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. const projectContextPropTypes = {
  183. _id: PropTypes.string.isRequired,
  184. }
  185. function UploadErrorMessage({ error, maxNumberOfFiles }) {
  186. switch (error) {
  187. case 'too-many-files':
  188. return (
  189. <Trans
  190. i18nKey="maximum_files_uploaded_together"
  191. values={{ max: maxNumberOfFiles }}
  192. />
  193. )
  194. default:
  195. return <ErrorMessage error={error} />
  196. }
  197. }
  198. UploadErrorMessage.propTypes = {
  199. error: PropTypes.string.isRequired,
  200. maxNumberOfFiles: PropTypes.number.isRequired,
  201. }
  202. function UploadConflicts({ cancel, conflicts, handleOverwrite }) {
  203. const { t } = useTranslation()
  204. return (
  205. <div className="small modal-new-file--body-conflict">
  206. <p className="text-center mb-0">
  207. {t('the_following_files_already_exist_in_this_project')}
  208. </p>
  209. <ul className="text-center list-unstyled row-spaced-small mt-1">
  210. {conflicts.map((conflict, index) => (
  211. <li key={index}>
  212. <strong>{conflict.meta.name}</strong>
  213. </li>
  214. ))}
  215. </ul>
  216. <p className="text-center row-spaced-small">
  217. {t('do_you_want_to_overwrite_them')}
  218. </p>
  219. <p className="text-center">
  220. <Button bsStyle={null} className="btn-secondary" onClick={cancel}>
  221. {t('cancel')}
  222. </Button>
  223. &nbsp;
  224. <Button bsStyle="danger" onClick={handleOverwrite}>
  225. {t('overwrite')}
  226. </Button>
  227. </p>
  228. </div>
  229. )
  230. }
  231. UploadConflicts.propTypes = {
  232. cancel: PropTypes.func.isRequired,
  233. conflicts: PropTypes.array.isRequired,
  234. handleOverwrite: PropTypes.func.isRequired,
  235. }