file-tree-upload-doc.js 6.4 KB

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