{"version":3,"file":"upload.mjs","sources":["../../../lib/upload/utils/upload.ts"],"sourcesContent":["/*!\n * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors\n * SPDX-License-Identifier: AGPL-3.0-or-later\n */\n\nimport type { AxiosError, AxiosProgressEvent, AxiosResponse } from 'axios'\n\nimport { getCurrentUser } from '@nextcloud/auth'\nimport axios from '@nextcloud/axios'\nimport { join } from '@nextcloud/paths'\nimport { generateRemoteUrl, getRootUrl } from '@nextcloud/router'\nimport { getSharingToken } from '@nextcloud/sharing/public'\nimport axiosRetry, { exponentialDelay, isNetworkOrIdempotentRequestError } from 'axios-retry'\nimport logger from '../../utils/logger.ts'\n\naxiosRetry(axios, { retries: 0 })\n\ntype UploadData = Blob | (() => Promise<Blob>)\n\ninterface UploadDataOptions {\n\t/** The abort signal */\n\tsignal: AbortSignal\n\t/** Upload progress event callback */\n\tonUploadProgress?: (event: AxiosProgressEvent) => void\n\t/** Request retry callback (e.g. network error of previous try) */\n\tonUploadRetry?: () => void\n\t/** The final destination file (for chunked uploads) */\n\tdestinationFile?: string\n\t/** Additional headers */\n\theaders?: Record<string, string | number>\n\t/** Number of retries */\n\tretries?: number\n}\n\n/**\n * Upload some data to a given path\n *\n * @param url the url to upload to\n * @param uploadData the data to upload\n * @param uploadOptions upload options\n */\nexport async function uploadData(\n\turl: string,\n\tuploadData: UploadData,\n\tuploadOptions: UploadDataOptions,\n): Promise<AxiosResponse> {\n\tconst options = {\n\t\theaders: {},\n\t\tonUploadProgress: () => {},\n\t\tonUploadRetry: () => {},\n\t\tretries: 5,\n\t\t...uploadOptions,\n\t}\n\n\tlet data: Blob\n\n\t// If the upload data is a blob, we can directly use it\n\t// Otherwise, we need to wait for the promise to resolve\n\tif (uploadData instanceof Blob) {\n\t\tdata = uploadData\n\t} else {\n\t\tdata = await uploadData()\n\t}\n\n\t// Helps the server to know what to do with the file afterwards (e.g. chunked upload)\n\tif (options.destinationFile) {\n\t\toptions.headers.Destination = options.destinationFile\n\t}\n\n\t// If no content type is set, we default to octet-stream\n\tif (!options.headers['Content-Type']) {\n\t\toptions.headers['Content-Type'] = 'application/octet-stream'\n\t}\n\n\treturn await axios.request({\n\t\tmethod: 'PUT',\n\t\turl,\n\t\tdata,\n\t\tsignal: options.signal,\n\t\tonUploadProgress: options.onUploadProgress,\n\t\theaders: options.headers,\n\t\t'axios-retry': {\n\t\t\tretries: options.retries,\n\t\t\tretryDelay: (retryCount: number, error: AxiosError) => exponentialDelay(retryCount, error, 1000),\n\t\t\tretryCondition(error: AxiosError): boolean {\n\t\t\t\t// Do not retry on insufficient storage - this is permanent\n\t\t\t\tif (error.status === 507) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\t// Do a retry on locked error as this is often just some preview generation\n\t\t\t\tif (error.status === 423) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\t// Otherwise fallback to default behavior\n\t\t\t\treturn isNetworkOrIdempotentRequestError(error)\n\t\t\t},\n\t\t\tonRetry: options.onUploadRetry,\n\t\t},\n\t})\n}\n\n/**\n * Get chunk of the file.\n * Doing this on the fly give us a big performance boost and proper garbage collection\n *\n * @param file File to upload\n * @param start Offset to start upload\n * @param length Size of chunk to upload\n */\nexport function getChunk(file: File, start: number, length: number): Promise<Blob> {\n\tif (start === 0 && file.size <= length) {\n\t\treturn Promise.resolve(new Blob([file], { type: file.type || 'application/octet-stream' }))\n\t}\n\n\treturn Promise.resolve(new Blob([file.slice(start, Math.min(start + length, file.size))], { type: 'application/octet-stream' }))\n}\n\n/**\n * Create a temporary upload workspace to upload the chunks to\n *\n * @param destinationFile The file name after finishing the chunked upload\n * @param retries number of retries\n * @param isPublic whether this upload is in a public share or not\n * @param customHeaders Custom HTTP headers used when creating the workspace (e.g. X-NC-Nickname for file drops)\n */\nexport async function initChunkWorkspace(destinationFile: string | undefined = undefined, retries: number = 5, isPublic: boolean = false, customHeaders: Record<string, string> = {}): Promise<string> {\n\tlet chunksWorkspace = generateRemoteUrl('/dav/uploads/', { baseURL: getRootUrl() })\n\tif (isPublic) {\n\t\tchunksWorkspace = chunksWorkspace.replace('/remote.php/', '/public.php/')\n\t\tchunksWorkspace = join(chunksWorkspace, getSharingToken()!)\n\t} else {\n\t\tchunksWorkspace = join(chunksWorkspace, getCurrentUser()!.uid)\n\t}\n\n\tconst hash = [...Array(16)].map(() => Math.floor(Math.random() * 16).toString(16)).join('')\n\tchunksWorkspace = join(chunksWorkspace, `web-file-upload-${hash}`)\n\n\tconst headers = customHeaders\n\tif (destinationFile) {\n\t\theaders.Destination = destinationFile\n\t}\n\n\tawait axios.request({\n\t\tmethod: 'MKCOL',\n\t\turl: chunksWorkspace,\n\t\theaders,\n\t\t'axios-retry': {\n\t\t\tretries,\n\t\t\tretryDelay: (retryCount: number, error: AxiosError) => exponentialDelay(retryCount, error, 1000),\n\t\t},\n\t})\n\n\tlogger.debug('Created temporary upload workspace', { url: chunksWorkspace })\n\n\treturn chunksWorkspace\n}\n"],"names":["uploadData"],"mappings":";;;;;;;AAAA;AAAA;AAAA;AAAA;AAeA,WAAW,OAAO,EAAE,SAAS,GAAG;AA0BhC,eAAsB,WACrB,KACAA,aACA,eACyB;AACzB,QAAM,UAAU;AAAA,IACf,SAAS,CAAA;AAAA,IACT,kBAAkB,MAAM;AAAA,IAAC;AAAA,IACzB,eAAe,MAAM;AAAA,IAAC;AAAA,IACtB,SAAS;AAAA,IACT,GAAG;AAAA,EAAA;AAGJ,MAAI;AAIJ,MAAIA,uBAAsB,MAAM;AAC/B,WAAOA;AAAAA,EACR,OAAO;AACN,WAAO,MAAMA,YAAAA;AAAAA,EACd;AAGA,MAAI,QAAQ,iBAAiB;AAC5B,YAAQ,QAAQ,cAAc,QAAQ;AAAA,EACvC;AAGA,MAAI,CAAC,QAAQ,QAAQ,cAAc,GAAG;AACrC,YAAQ,QAAQ,cAAc,IAAI;AAAA,EACnC;AAEA,SAAO,MAAM,MAAM,QAAQ;AAAA,IAC1B,QAAQ;AAAA,IACR;AA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