file-tree-upload-doc.tsx 9.7 KB

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