file-tree-upload-doc.tsx 10 KB

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