file-tree-upload-doc.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 { 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. locale: {
  140. strings: {
  141. youCanOnlyUploadX:
  142. 'You can only upload %{smart_count} files at a time',
  143. },
  144. },
  145. })
  146. // use the basic XHR uploader
  147. .use(XHRUpload, {
  148. endpoint,
  149. headers: {
  150. 'X-CSRF-TOKEN': getMeta('ol-csrfToken'),
  151. },
  152. // limit: maxConnections || 1,
  153. limit: 1,
  154. fieldName: 'qqfile', // "qqfile" field inherited from FineUploader
  155. })
  156. // close the modal when all the uploads completed successfully
  157. .on('complete', result => {
  158. if (!result.failed.length) {
  159. cancel()
  160. }
  161. })
  162. // broadcast doc metadata after each successful upload
  163. .on('upload-success', (file, response) => {
  164. eventTracking.sendMB('new-file-created', {
  165. method: 'upload',
  166. extension:
  167. file?.name && file?.name.split('.').length > 1
  168. ? file?.name.split('.').pop()
  169. : '',
  170. })
  171. if (response.body.entity_type === 'doc') {
  172. window.setTimeout(() => {
  173. refreshProjectMetadata(projectId, response.body.entity_id)
  174. }, 250)
  175. }
  176. })
  177. // handle upload errors
  178. .on('upload-error', (file, error, response) => {
  179. switch (response?.status) {
  180. case 429:
  181. setError('rate-limit-hit')
  182. break
  183. case 403:
  184. setError('not-logged-in')
  185. break
  186. default:
  187. debugConsole.error(error)
  188. setError(response?.body?.error || 'generic_something_went_wrong')
  189. break
  190. }
  191. })
  192. )
  193. })
  194. useEffect(() => {
  195. if (uppy && droppedFiles) {
  196. uppy.setOptions({
  197. autoProceed: false,
  198. })
  199. for (const file of droppedFiles.files) {
  200. const fileId = uppy.addFile({
  201. name: file.name,
  202. type: file.type,
  203. data: file,
  204. source: 'Local',
  205. isRemote: false,
  206. meta: {
  207. relativePath: (file as any).relativePath,
  208. targetFolderId: droppedFiles.targetFolderId,
  209. },
  210. })
  211. const uppyFile = uppy.getFile(fileId)
  212. uppy.setFileState(fileId, {
  213. xhrUpload: {
  214. ...(uppyFile as any).xhrUpload,
  215. endpoint: buildEndpoint(projectId, droppedFiles.targetFolderId),
  216. },
  217. })
  218. }
  219. }
  220. return () => {
  221. setDroppedFiles(null)
  222. }
  223. }, [uppy, droppedFiles, setDroppedFiles, projectId])
  224. // handle forced overwriting of conflicting files
  225. const handleOverwrite = useCallback(() => {
  226. setOverwrite(true)
  227. uppy.setOptions({
  228. onBeforeUpload() {
  229. // don't check for file conflicts
  230. return true
  231. },
  232. })
  233. uppy.upload()
  234. }, [uppy])
  235. const showFolderUploadConflicts = !overwrite && folderConflicts.length > 0
  236. const showFileUploadConfilcts =
  237. !overwrite && !showFolderUploadConflicts && conflicts.length > 0
  238. const showDashboard = !showFileUploadConfilcts && !showFolderUploadConflicts
  239. return (
  240. <>
  241. {error && (
  242. <UploadErrorMessage error={error} maxNumberOfFiles={maxNumberOfFiles} />
  243. )}
  244. {showFolderUploadConflicts && (
  245. <FolderUploadConflicts
  246. cancel={cancel}
  247. conflicts={folderConflicts}
  248. handleOverwrite={handleOverwrite}
  249. setError={setError}
  250. />
  251. )}
  252. {showFileUploadConfilcts && (
  253. <FileUploadConflicts
  254. cancel={cancel}
  255. conflicts={conflicts}
  256. handleOverwrite={handleOverwrite}
  257. />
  258. )}
  259. {showDashboard && (
  260. <Dashboard
  261. uppy={uppy}
  262. showProgressDetails
  263. // note={`Up to ${maxNumberOfFiles} files, up to ${maxFileSize / (1024 * 1024)}MB`}
  264. height={400}
  265. width="100%"
  266. showLinkToFileUploadResult={false}
  267. proudlyDisplayPoweredByUppy={false}
  268. // allow files or folders to be selected
  269. fileManagerSelectionType="both"
  270. locale={{
  271. strings: {
  272. // Text to show on the droppable area.
  273. // `%{browse}` is replaced with a link that opens the system file selection dialog.
  274. // TODO: 'drag_here' or 'drop_files_here_to_upload'?
  275. // dropHereOr: `${t('drag_here')} ${t('or')} %{browse}`,
  276. dropPasteBoth: `Drop or paste your files, folder, or images here. %{browseFiles} or %{browseFolders} from your computer.`,
  277. // Used as the label for the link that opens the system file selection dialog.
  278. // browseFiles: t('select_from_your_computer')
  279. browseFiles: 'Select files',
  280. browseFolders: 'select a folder',
  281. },
  282. }}
  283. />
  284. )}
  285. </>
  286. )
  287. }
  288. function UploadErrorMessage({
  289. error,
  290. maxNumberOfFiles,
  291. }: {
  292. error: string
  293. maxNumberOfFiles: number
  294. }) {
  295. const { t } = useTranslation()
  296. switch (error) {
  297. case 'too-many-files':
  298. return (
  299. <>
  300. {t('maximum_files_uploaded_together', {
  301. max: maxNumberOfFiles,
  302. })}
  303. </>
  304. )
  305. default:
  306. return <ErrorMessage error={error} />
  307. }
  308. }