file-tree-upload-doc.tsx 8.8 KB

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