{"version":3,"file":"UploadFileTree.mjs","sources":["../../../lib/upload/uploader/UploadFileTree.ts"],"sourcesContent":["/*!\n * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors\n * SPDX-License-Identifier: AGPL-3.0-or-later\n */\n\nimport type PQueue from 'p-queue'\nimport type { IUpload, IUploadOptions, TUploadStatus } from './Upload.ts'\n\nimport axios, { isAxiosError } from '@nextcloud/axios'\nimport { basename } from '@nextcloud/paths'\nimport { UploadCancelledError } from '../errors/UploadCancelledError.ts'\nimport { UploadFailedError } from '../errors/UploadFailedError.ts'\nimport { Directory as FileTree } from '../utils/fileTree.ts'\nimport { getMtimeHeader, isRequestAborted } from '../utils/requests.ts'\nimport { concatUrl, encodeUrl } from '../utils/url.ts'\nimport { Upload, UploadStatus } from './Upload.ts'\nimport { UploadFile } from './UploadFile.ts'\n\n/**\n * Callback type for conflict resolution when uploading a folder tree.\n *\n * The callback receives the nodes in the current folder and the current path to upload to,\n * it should return a mapping of nodes that should be uploaded (e.g. after resolving conflicts by renaming or selecting which files to upload).\n * In case the upload should be cancelled, it should return `false`.\n * The returned mapping allowes to resolve conflicts by renaming files or folders before upload,\n * the key is the original name of the node and the value is the name to upload it as.\n *\n * @param nodes - The nodes to upload (list of filenames)\n * @param currentPath - The current path to upload to\n * @return A promise that resolves to a map of nodes that should be uploaded or false if the upload should be cancelled\n */\nexport type ConflictsCallback = (nodes: string[], currentPath: string) => Promise<false | Record<string, string>>\n\ninterface IUploadFileTreeOptions {\n\t/** The callback to handle conflicts */\n\tcallback?: ConflictsCallback\n}\n\n/**\n * A class representing a single file to be uploaded\n */\nexport class UploadFileTree extends Upload<IUploadFileTreeOptions> implements IUpload {\n\t/** The current file tree to upload */\n\t#directory: FileTree\n\t/** Children uploads of this parent folder upload */\n\t#children: (Upload & IUpload)[] = []\n\n\t/** Whether we need to check for conflicts or not (newly created parent folders = no conflict resolution needed) */\n\tprotected needConflictResolution = true\n\n\tpublic source: string\n\tpublic status: TUploadStatus = UploadStatus.INITIALIZED\n\tpublic startTime?: number\n\tpublic totalBytes: number = 0\n\tpublic uploadedBytes: number = -1\n\n\tconstructor(\n\t\tdestination: string,\n\t\tdirectory: FileTree,\n\t\toptions: Partial<IUploadOptions & IUploadFileTreeOptions> = {},\n\t) {\n\t\tsuper(options)\n\n\t\t// exposed state\n\t\tthis.source = destination\n\t\tthis.#directory = directory\n\n\t\tthis.signal.addEventListener('abort', () => {\n\t\t\tfor (const child of this.#children) {\n\t\t\t\tchild.cancel()\n\t\t\t}\n\t\t\tif (this.status !== UploadStatus.FAILED) {\n\t\t\t\tthis.status = UploadStatus.CANCELLED\n\t\t\t}\n\t\t})\n\t}\n\n\tget isChunked(): boolean {\n\t\treturn false\n\t}\n\n\tget children(): IUpload[] {\n\t\treturn [...this.#children]\n\t}\n\n\t/**\n\t * Move this upload - and all already initialized descendants - to a new destination.\n\t *\n\t * The whole tree is initialized upfront, so renaming a directory while resolving\n\t * conflicts also needs to re-base all of its children.\n\t *\n\t * @param source - The new destination of this upload\n\t */\n\tpublic rebase(source: string): void {\n\t\tfor (const child of this.#children) {\n\t\t\t// read the name before the parent source is updated\n\t\t\tchild.rebase(concatUrl(source, basename(child.source)))\n\t\t}\n\t\tsuper.rebase(source)\n\t}\n\n\t/**\n\t * Set up all child uploads for this upload tree.\n\t */\n\tinitialize(): (Upload & IUpload)[] {\n\t\tconst grandchildren: (Upload & IUpload)[] = []\n\t\tfor (const child of this.#directory.children) {\n\t\t\tif (child instanceof FileTree) {\n\t\t\t\tconst upload = new UploadFileTree(\n\t\t\t\t\tconcatUrl(this.source, child.originalName),\n\t\t\t\t\tchild,\n\t\t\t\t\tthis.options,\n\t\t\t\t)\n\t\t\t\tthis.#children.push(upload)\n\t\t\t\tgrandchildren.push(...upload.initialize())\n\t\t\t} else {\n\t\t\t\tconst upload = new UploadFile(\n\t\t\t\t\tconcatUrl(this.source, child.name),\n\t\t\t\t\tchild,\n\t\t\t\t\tthis.options,\n\t\t\t\t)\n\t\t\t\tthis.#children.push(upload)\n\t\t\t}\n\t\t}\n\t\treturn [...this.#children, ...grandchildren]\n\t}\n\n\tasync start(queue: PQueue): Promise<void> {\n\t\tif (this.status !== UploadStatus.INITIALIZED) {\n\t\t\tthrow new Error('Upload already started')\n\t\t}\n\t\tthis.status = UploadStatus.SCHEDULED\n\t\tthis.startTime = Date.now()\n\t\tthis.uploadedBytes = 0\n\n\t\tthis.status = UploadStatus.UPLOADING\n\t\tawait this.#createDirectory(queue)\n\n\t\tif (this.needConflictResolution && this.options.callback) {\n\t\t\tconst nodes = await this.options.callback(\n\t\t\t\tthis.#directory.children.map((node) => basename(node.name)),\n\t\t\t\tthis.source,\n\t\t\t)\n\t\t\tif (nodes === false) {\n\t\t\t\tthis.cancel()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor (const childUpload of this.#children) {\n\t\t\t\tconst originalName = basename(childUpload.source)\n\t\t\t\tconst newName = nodes[originalName]\n\t\t\t\tif (newName === undefined) {\n\t\t\t\t\tchildUpload.cancel()\n\t\t\t\t} else if (newName !== originalName) {\n\t\t\t\t\t// for directories this also re-bases all of their children\n\t\t\t\t\tchildUpload.rebase(concatUrl(this.source, newName))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst uploads: Promise<void>[] = []\n\t\tfor (const upload of this.#children) {\n\t\t\tif (upload.signal.aborted) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// for folder tree uploads store the conflict resolution state to prevent useless requests\n\t\t\tif (upload instanceof UploadFileTree) {\n\t\t\t\tupload.needConflictResolution = this.needConflictResolution\n\t\t\t}\n\n\t\t\tuploads.push(upload.start(queue))\n\t\t}\n\n\t\ttry {\n\t\t\tawait Promise.all(uploads)\n\t\t\tthis.status = UploadStatus.FINISHED\n\t\t} catch (error) {\n\t\t\tthis.cancel()\n\t\t\tif (isRequestAborted(error)) {\n\t\t\t\tthis.status = UploadStatus.CANCELLED\n\t\t\t\tthrow new UploadCancelledError(error)\n\t\t\t} else if (error instanceof UploadCancelledError) {\n\t\t\t\tthis.status = UploadStatus.CANCELLED\n\t\t\t\tthrow error\n\t\t\t} else if (error instanceof UploadFailedError) {\n\t\t\t\tthis.status = UploadStatus.FAILED\n\t\t\t\tthrow error\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.dispatchTypedEvent('finished', new CustomEvent('finished', { detail: this }))\n\t\t}\n\t}\n\n\t/**\n\t * Helper to create the directory for this tree.\n\t *\n\t * @param queue - The job queue\n\t */\n\tasync #createDirectory(queue: PQueue): Promise<void> {\n\t\tawait queue.add(async () => {\n\t\t\ttry {\n\t\t\t\tawait axios.head(encodeUrl(this.source), {\n\t\t\t\t\tsignal: this.signal,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t...this.options.headers,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\treturn // directory already exists, no need to create it\n\t\t\t} catch (error) {\n\t\t\t\tif (isRequestAborted(error)) {\n\t\t\t\t\tthis.cancel()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// directory does not exist, we need to create it\n\t\t\ttry {\n\t\t\t\tawait axios.request({\n\t\t\t\t\tmethod: 'MKCOL',\n\t\t\t\t\turl: encodeUrl(this.source),\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t...this.options.headers,\n\t\t\t\t\t\t...getMtimeHeader(this.#directory),\n\t\t\t\t\t},\n\t\t\t\t\tsignal: this.signal,\n\t\t\t\t})\n\t\t\t\t// MKCOL worked so this is a new directory, no conflict resolution needed\n\t\t\t\tthis.needConflictResolution = false\n\t\t\t} catch (error) {\n\t\t\t\t// ignore 405 Method Not Allowed as it means the directory already exists and we can continue with uploading the children\n\t\t\t\tif (isAxiosError(error) && error.response?.status === 405) {\n\t\t\t\t\tthis.needConflictResolution = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t})\n\t}\n}\n"],"names":["FileTree"],"mappings":";;;;;;;;;AAAA;AAAA;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