file-tree-upload-doc.tsx 8.7 KB

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