file-tree-upload-doc.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. 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. // $scope.$emit('done', { name: name })
  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. return (
  241. <>
  242. {error && (
  243. <UploadErrorMessage error={error} maxNumberOfFiles={maxNumberOfFiles} />
  244. )}
  245. {showFolderUploadConflicts && (
  246. <FolderUploadConflicts
  247. cancel={cancel}
  248. conflicts={folderConflicts}
  249. handleOverwrite={handleOverwrite}
  250. setError={setError}
  251. />
  252. )}
  253. {showFileUploadConfilcts && (
  254. <FileUploadConflicts
  255. cancel={cancel}
  256. conflicts={conflicts}
  257. handleOverwrite={handleOverwrite}
  258. />
  259. )}
  260. {showDashboard && (
  261. <Dashboard
  262. uppy={uppy}
  263. showProgressDetails
  264. // note={`Up to ${maxNumberOfFiles} files, up to ${maxFileSize / (1024 * 1024)}MB`}
  265. height={400}
  266. width="100%"
  267. showLinkToFileUploadResult={false}
  268. proudlyDisplayPoweredByUppy={false}
  269. // allow files or folders to be selected
  270. fileManagerSelectionType="both"
  271. locale={{
  272. strings: {
  273. // Text to show on the droppable area.
  274. // `%{browse}` is replaced with a link that opens the system file selection dialog.
  275. // TODO: 'drag_here' or 'drop_files_here_to_upload'?
  276. // dropHereOr: `${t('drag_here')} ${t('or')} %{browse}`,
  277. dropPasteBoth: `Drop or paste your files, folder, or images here. %{browseFiles} or %{browseFolders} from your computer.`,
  278. // Used as the label for the link that opens the system file selection dialog.
  279. // browseFiles: t('select_from_your_computer')
  280. browseFiles: 'Select files',
  281. browseFolders: 'select a folder',
  282. },
  283. }}
  284. />
  285. )}
  286. </>
  287. )
  288. }
  289. function UploadErrorMessage({
  290. error,
  291. maxNumberOfFiles,
  292. }: {
  293. error: string
  294. maxNumberOfFiles: number
  295. }) {
  296. const { t } = useTranslation()
  297. switch (error) {
  298. case 'too-many-files':
  299. return (
  300. <>
  301. {t('maximum_files_uploaded_together', {
  302. max: maxNumberOfFiles,
  303. })}
  304. </>
  305. )
  306. default:
  307. return <ErrorMessage error={error} />
  308. }
  309. }