{"version":3,"file":"UploadFile.mjs","sources":["../../../lib/upload/uploader/UploadFile.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 from '@nextcloud/axios'\nimport { join } from '@nextcloud/paths'\nimport { isPublicShare } from '@nextcloud/sharing/public'\nimport { UploadCancelledError } from '../errors/UploadCancelledError.ts'\nimport { UploadFailedError } from '../errors/UploadFailedError.ts'\nimport { getMaxChunksSize, supportsPublicChunking } from '../utils/config.ts'\nimport { getMtimeHeader, isRequestAborted } from '../utils/requests.ts'\nimport { getChunk, initChunkWorkspace, uploadData } from '../utils/upload.ts'\nimport { encodeUrl } from '../utils/url.ts'\nimport { Upload, UploadStatus } from './Upload.ts'\n\n/**\n * A class representing a single file to be uploaded\n */\nexport class UploadFile extends Upload implements IUpload {\n\t#fileHandle: File | FileSystemFileEntry\n\t#file?: File\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\tpublic numberOfChunks: number = 1\n\n\tconstructor(\n\t\tdestination: string,\n\t\tfileHandle: File | FileSystemFileEntry,\n\t\toptions: Partial<IUploadOptions> = {},\n\t) {\n\t\tsuper(options)\n\n\t\t// exposed state\n\t\tthis.source = destination\n\t\tthis.totalBytes = 'size' in fileHandle ? fileHandle.size : -1\n\n\t\t// private state\n\t\tthis.#fileHandle = fileHandle\n\t\tthis.signal.addEventListener('abort', () => {\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\tconst maxChunkSize = getMaxChunksSize('size' in this.#fileHandle ? this.#fileHandle.size : undefined)\n\t\treturn !this.options.noChunking\n\t\t\t&& maxChunkSize > 0\n\t\t\t&& this.totalBytes > maxChunkSize\n\t\t\t&& (!isPublicShare() || supportsPublicChunking())\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\n\t\tthis.startTime = Date.now()\n\t\tthis.#file = await getFile(this.#fileHandle)\n\t\tthis.totalBytes = this.#file.size\n\t\tthis.uploadedBytes = 0\n\t\tthis.status = UploadStatus.SCHEDULED\n\n\t\ttry {\n\t\t\tif (this.isChunked) {\n\t\t\t\tthis.numberOfChunks = Math.ceil(this.totalBytes / getMaxChunksSize(this.totalBytes))\n\t\t\t\tawait this.#uploadChunked(queue)\n\t\t\t} else {\n\t\t\t\tqueue.add(() => this.#upload())\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.cancel()\n\t\t\tif (error instanceof UploadCancelledError || error instanceof UploadFailedError) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.status = UploadStatus.FAILED\n\t\t\tthrow new UploadFailedError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Internal implementation of the upload process for non-chunked uploads.\n\t */\n\tasync #upload() {\n\t\tthis.status = UploadStatus.UPLOADING\n\t\tconst chunk = await getChunk(this.#file!, 0, this.#file!.size)\n\t\ttry {\n\t\t\tawait this.#uploadChunk(chunk, encodeUrl(this.source))\n\t\t\t// Update progress - now we set the uploaded size to 100% of the file size\n\t\t\tthis.uploadedBytes = this.totalBytes\n\t\t\tthis.status = UploadStatus.FINISHED\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof UploadCancelledError)) {\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 * Internal implementation of the upload process for chunked uploads.\n\t *\n\t * @param queue - The job queue to throttle number of concurrent chunk uploads\n\t */\n\tasync #uploadChunked(queue: PQueue) {\n\t\tthis.status = UploadStatus.UPLOADING\n\t\t// The `Destination` header must be a URI, so the source has to be encoded here\n\t\tconst destination = encodeUrl(this.source)\n\t\tconst temporaryUrl = await initChunkWorkspace(destination, this.options.retries, isPublicShare(), this.options.headers)\n\n\t\tconst promises: Promise<void>[] = []\n\t\tconst chunkSize = Math.floor(this.totalBytes / this.numberOfChunks)\n\t\tfor (let i = 0; i < this.numberOfChunks; i++) {\n\t\t\tconst offsetStart = i * chunkSize\n\t\t\tconst chunk = await getChunk(\n\t\t\t\tthis.#file!,\n\t\t\t\toffsetStart,\n\t\t\t\ti === this.numberOfChunks - 1\n\t\t\t\t\t? (this.totalBytes - offsetStart) // last chunk = remaining bytes\n\t\t\t\t\t: chunkSize, // all other chunks = chunkSize\n\t\t\t)\n\t\t\tpromises.push(queue.add(async () => {\n\t\t\t\tawait this.#uploadChunk(chunk, join(temporaryUrl, String(i)))\n\t\t\t}))\n\t\t}\n\t\tthis.status = UploadStatus.UPLOADING\n\n\t\tqueue.add(async () => {\n\t\t\ttry {\n\t\t\t\tawait Promise.all(promises)\n\t\t\t\t// Send the assemble request\n\t\t\t\tthis.status = UploadStatus.ASSEMBLING\n\t\t\t\tawait axios.request({\n\t\t\t\t\tmethod: 'MOVE',\n\t\t\t\t\turl: `${temporaryUrl}/.file`,\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.#file!),\n\t\t\t\t\t\t'OC-Total-Length': this.totalBytes,\n\t\t\t\t\t\tDestination: destination,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tthis.status = UploadStatus.FINISHED\n\t\t\t} catch (error) {\n\t\t\t\tthis.cancel()\n\t\t\t\tif (isRequestAborted(error)) {\n\t\t\t\t\tthis.status = UploadStatus.CANCELLED\n\t\t\t\t\tthrow new UploadCancelledError(error)\n\t\t\t\t}\n\t\t\t\tthis.status = UploadStatus.FAILED\n\t\t\t\tthrow new UploadFailedError(error)\n\t\t\t} finally {\n\t\t\t\tthis.dispatchTypedEvent('finished', new CustomEvent('finished', { detail: this }))\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Internal helper to share logic for uploading a chunk of data for both chunked and non-chunked uploads.\n\t *\n\t * @param chunk - The chunk to upload\n\t * @param url - The target URL\n\t */\n\tasync #uploadChunk(chunk: Blob, url: string) {\n\t\t// Bytes of this chunk that are already accounted for in `this.uploadedBytes`.\n\t\t// This is tracked per chunk as other chunks might be uploaded in parallel.\n\t\tlet accountedBytes = 0\n\t\t// Bytes of this chunk reported as sent by the current try\n\t\tlet sentBytes = 0\n\n\t\ttry {\n\t\t\tawait uploadData(\n\t\t\t\turl,\n\t\t\t\tchunk,\n\t\t\t\t{\n\t\t\t\t\tsignal: this.signal,\n\t\t\t\t\tretries: this.options.retries,\n\t\t\t\t\tonUploadProgress: ({ bytes }) => {\n\t\t\t\t\t\tsentBytes += bytes\n\t\t\t\t\t\t// As this is only the sent bytes not the processed ones we only count 90%.\n\t\t\t\t\t\t// When the chunk is uploaded (server acknowledged the upload) the remaining 10% will be correctly set.\n\t\t\t\t\t\t// Rounding keeps `uploadedBytes` an integer so the accounting stays exact.\n\t\t\t\t\t\tconst accounted = Math.min(Math.round(sentBytes * 0.9), chunk.size)\n\t\t\t\t\t\tthis.uploadedBytes += accounted - accountedBytes\n\t\t\t\t\t\taccountedBytes = accounted\n\t\t\t\t\t\tthis.dispatchTypedEvent('progress', new CustomEvent('progress', { detail: this }))\n\t\t\t\t\t},\n\t\t\t\t\tonUploadRetry: () => {\n\t\t\t\t\t\t// Only discard the progress of this chunk, any other chunk is not affected by this retry\n\t\t\t\t\t\tthis.uploadedBytes -= accountedBytes\n\t\t\t\t\t\taccountedBytes = 0\n\t\t\t\t\t\tsentBytes = 0\n\t\t\t\t\t},\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.#file!),\n\t\t\t\t\t\t'Content-Type': this.#file!.type,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\n\t\t\t// The server acknowledged this chunk, so account the remaining 10% of it\n\t\t\tthis.uploadedBytes += chunk.size - accountedBytes\n\t\t\tthis.dispatchTypedEvent('progress', new CustomEvent('progress', { detail: this }))\n\t\t} catch (error) {\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}\n\n\t\t\tthis.status = UploadStatus.FAILED\n\t\t\tthrow new UploadFailedError(error)\n\t\t}\n\t}\n}\n\n/**\n * Converts a FileSystemFileEntry to a File if needed and returns it.\n *\n * @param fileHandle - The file handle\n */\nasync function getFile(fileHandle: File | FileSystemFileEntry): Promise<File> {\n\tif (fileHandle instanceof File) {\n\t\treturn fileHandle\n\t}\n\n\treturn await new Promise((resolve, reject) => fileHandle.file(resolve, reject))\n}\n"],"names":[],"mappings":";;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAsBO,MAAM,mBAAmB,OAA0B;AAAA,EACzD;AAAA,EACA;AAAA,EAEO;AAAA,EACA,SAAwB,aAAa;AAAA,EACrC;AAAA,EACA,aAAqB;AAAA,EACrB,gBAAwB;AAAA,EACxB,iBAAyB;AAAA,EAEhC,YACC,aACA,YACA,UAAmC,CAAA,GAClC;AACD,UAAM,OAAO;AAGb,SAAK,SAAS;AACd,SAAK,aAAa,UAAU,aAAa,WAAW,OAAO;AAG3D,SAAK,cAAc;AACnB,SAAK,OAAO,iBAAiB,SAAS,MAAM;AAC3C,UAAI,KAAK,WAAW,aAAa,QAAQ;AACxC,aAAK,SAAS,aAAa;AAAA,MAC5B;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,IAAI,YAAqB;AACxB,UAAM,eAAe,iBAAiB,UAAU,KAAK,cAAc,KAAK,YAAY,OAAO,MAAS;AACpG,WAAO,CAAC,KAAK,QAAQ,cACjB,eAAe,KACf,KAAK,aAAa,iBAC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