file-tree-upload-doc.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 = 180
  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', {
  131. method: 'upload',
  132. extension:
  133. file?.name && file?.name.split('.').length > 1
  134. ? file?.name.split('.').pop()
  135. : '',
  136. })
  137. if (response.body.entity_type === 'doc') {
  138. window.setTimeout(() => {
  139. refreshProjectMetadata(projectId, response.body.entity_id)
  140. }, 250)
  141. }
  142. })
  143. // handle upload errors
  144. .on('upload-error', (file, error, response) => {
  145. switch (response?.status) {
  146. case 429:
  147. setError('rate-limit-hit')
  148. break
  149. case 403:
  150. setError('not-logged-in')
  151. break
  152. default:
  153. debugConsole.error(error)
  154. setError(response?.body?.error || 'generic_something_went_wrong')
  155. break
  156. }
  157. })
  158. )
  159. })
  160. useEffect(() => {
  161. if (uppy && droppedFiles) {
  162. uppy.setOptions({
  163. autoProceed: false,
  164. })
  165. for (const file of droppedFiles.files) {
  166. const fileId = uppy.addFile({
  167. name: file.name,
  168. type: file.type,
  169. data: file,
  170. source: 'Local',
  171. isRemote: false,
  172. meta: {
  173. relativePath: (file as any).relativePath,
  174. targetFolderId: droppedFiles.targetFolderId,
  175. },
  176. })
  177. const uppyFile = uppy.getFile(fileId)
  178. uppy.setFileState(fileId, {
  179. xhrUpload: {
  180. ...(uppyFile as any).xhrUpload,
  181. endpoint: buildEndpoint(projectId, droppedFiles.targetFolderId),
  182. },
  183. })
  184. }
  185. }
  186. return () => {
  187. setDroppedFiles(null)
  188. }
  189. }, [uppy, droppedFiles, setDroppedFiles, projectId])
  190. // handle forced overwriting of conflicting files
  191. const handleOverwrite = useCallback(() => {
  192. setOverwrite(true)
  193. window.setTimeout(() => {
  194. uppy.upload()
  195. }, 10)
  196. }, [uppy])
  197. // whether to show a message about conflicting files
  198. const showConflicts =
  199. !overwrite && (conflicts.length > 0 || folderConflicts.length > 0)
  200. return (
  201. <>
  202. {error && (
  203. <UploadErrorMessage error={error} maxNumberOfFiles={maxNumberOfFiles} />
  204. )}
  205. {showConflicts ? (
  206. <UploadConflicts
  207. cancel={cancel}
  208. conflicts={conflicts}
  209. folderConflicts={folderConflicts}
  210. handleOverwrite={handleOverwrite}
  211. setError={setError}
  212. />
  213. ) : (
  214. <Dashboard
  215. uppy={uppy}
  216. showProgressDetails
  217. // note={`Up to ${maxNumberOfFiles} files, up to ${maxFileSize / (1024 * 1024)}MB`}
  218. height={400}
  219. width="100%"
  220. showLinkToFileUploadResult={false}
  221. proudlyDisplayPoweredByUppy={false}
  222. // allow files or folders to be selected
  223. fileManagerSelectionType="both"
  224. locale={{
  225. strings: {
  226. // Text to show on the droppable area.
  227. // `%{browse}` is replaced with a link that opens the system file selection dialog.
  228. // TODO: 'drag_here' or 'drop_files_here_to_upload'?
  229. // dropHereOr: `${t('drag_here')} ${t('or')} %{browse}`,
  230. dropPasteBoth: `Drop or paste your files, folder, or images here. %{browseFiles} or %{browseFolders} from your computer.`,
  231. // Used as the label for the link that opens the system file selection dialog.
  232. // browseFiles: t('select_from_your_computer')
  233. browseFiles: 'Select files',
  234. browseFolders: 'select a folder',
  235. },
  236. }}
  237. />
  238. )}
  239. </>
  240. )
  241. }
  242. function UploadErrorMessage({
  243. error,
  244. maxNumberOfFiles,
  245. }: {
  246. error: string
  247. maxNumberOfFiles: number
  248. }) {
  249. const { t } = useTranslation()
  250. switch (error) {
  251. case 'too-many-files':
  252. return (
  253. <>
  254. {t('maximum_files_uploaded_together', {
  255. max: maxNumberOfFiles,
  256. })}
  257. </>
  258. )
  259. default:
  260. return <ErrorMessage error={error} />
  261. }
  262. }