file-tree-upload-doc.js 7.4 KB

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