// Metro module 4721 (f4722). import _objectWithoutProperties from "../../_bundle/_objectWithoutProperties"; import _asyncToGenerator from "../../_bundle/_asyncToGenerator"; import DevSettingsStore from "../../modules/devtools/dev_settings/DevSettingsStore"; import UnsyncedUserSettingsStore from "../../modules/user_settings/UnsyncedUserSettingsStore"; import NetworkStore from "../../stores/NetworkStore"; import { AbortCodes, AnalyticEvents } from "../../Constants"; import Logger from "../../modules/debug/Logger"; import { HTTP, HTTPResponseError } from "../../_bundle/sendRequest"; import Upload, { UploadPlatform, UploadOrigin, isResolvedUpload } from "./Upload"; import { DefaultHttpClient, canUploadNatively, LibdiscoreHttpClient } from "./UploadUtils"; import Durations from "../../utils/Durations"; import Backoff from "../../_bundle/Backoff"; import Module12 from "../../_bundle/Module12"; import NetworkUtils from "../../utils/NetworkUtils"; import { getFileSize } from "../../utils/native/UploadUtils"; import * as _CloudUploaderUtils from "./native/CloudUploaderUtils"; import { getUploadTarget } from "./UploadTargets"; import { getKestrelConfig, getEffectiveKestrelLimit } from "../../modules/media_uploads/experiments/KestrelExperiment"; import SentryUtils_native from "../../utils/SentryUtils.native"; import { getAttachmentFile } from "../../utils/AttachmentFile.native"; import { getFileData } from "../../utils/UploadUtils"; import { getImageAttachmentMezzanineV2Config } from "../../modules/media_uploads/experiments/ImageAttachmentMezzanineV2Experiment"; import AnalyticsUtils from "../../utils/AnalyticsUtils"; import { HermesBuiltin, $createGenerator } from "../../_hermes/prelude"; function $mk114602($env) { return () => $env[0]._aborted; } function $mk114603($env) { return () => { $env[0].handleError(500); }; } function $mk114604($env) { return function*() { let env31351 = { $parent: $env }; env31351[1] = 0; env31351[0] = 0; const r13 = env31351.$parent; const r10 = r13[2]; const r12 = r13.$parent[0]; const createAttachmentURL = r10.getCreateAttachmentURL(r12.channelId); return yield HTTP.post({ url: createAttachmentURL, body: { files: [r13[1]] }, ...r12.createAttachmentUrlRetryOpts(), rejectWithError: false }); }; } function $mk114605($env) { return function*() { let env31352 = { $parent: $env }; env31352[1] = 0; env31352[0] = 0; return yield env31352.$parent.$parent[0].uploadFileToCloud(); }; } function $mk118720($env) { return function*() { let env32117 = { $parent: $env }; env32117[1] = 0; env32117[0] = 0; const r10 = env32117.$parent.$parent[3]; return yield r10.getResumePosition(r10.responseUrl); }; } function $mk118721($env) { return (a0) => setTimeout(a0, $env[2]); } let c2879_17, c2879_19, c2879_14, c2879_15, c2879_18, c2879_21, prototype; let env2879 = {}; const _excluded = ["Content-Range"]; const c2879_12 = new Logger("CloudUpload.tsx"); const c2879_13 = new Set([429]); c2879_17 = void 0; export class ResumableUploadError extends Error { constructor(a0, r4 = {}) { let messageShort; const { cause, response } = r4; let r20 = cause; if (r20 == null) { const r11 = Error; let r13 = response?.text; if (r13 == null) { r13 = "Unknown error"; } r20 = new r11(`${r13}`); } const errorKind = c2879_17.getErrorKind(r20, response); if (errorKind !== "server_error" && errorKind !== "client_error") { messageShort = `${a0}:${errorKind}`; } else { let r36 = response?.status; if (r36 == null) { r36 = 0; } messageShort = `${a0}:${errorKind}:status_${r36}`; } const r45 = { cause }; super(messageShort, r45); this.name = "ResumableUploadError"; this.phase = a0; this.kind = errorKind; this.messageShort = messageShort; } static getErrorKind(a0, a1) { let r3 = a1?.status; if (r3 == null) { r3 = 0; } const r12 = c2879_13.has(r3); const r16 = a0.message.toLowerCase().includes("network") || a0.message.toLowerCase().includes("terminated") || a0.message.toLowerCase().includes("offline") || a0.message.toLowerCase().includes("changed"); return r3 >= 500 ? r3 < 600 ? "server_error" : r12 ? "client_error" : r16 ? "network_error" : "unknown" : r12 ? "client_error" : r16 ? "network_error" : "unknown"; } static rejectionHandler(c14388_0) { return (a0) => { if (a0 instanceof HTTPResponseError) { throw new c2879_17(c14388_0, { response: a0 }); } const r18 = a0 instanceof Error; const r20 = { cause: null }; if (r18) { r20.cause = a0; throw new c2879_17(c14388_0, r20); } r20.cause = new Error(String(a0)); throw new c2879_17(c14388_0, r20); }; } canRetry() { return this.kind === "server_error" || this.kind === "network_error" || this.kind === "client_error"; } } c2879_17 = ResumableUploadError; c2879_19 = ResumableUploadError; c2879_14 = ResumableUploadError; c2879_15 = { NOT_STARTED: "NOT_STARTED", STARTED: "STARTED", UPLOADING: "UPLOADING", ERROR: "ERROR", COMPLETED: "COMPLETED", CANCELED: "CANCELED", REMOVED_FROM_MSG_DRAFT: "REMOVED_FROM_MSG_DRAFT" }; class UploadAnalytics { constructor() { return { __proto__: new.target.prototype, timing: {}, uploadResumptionCount: 0, uploadResumptionPosition: 0 }; } } c2879_18 = void 0; export class CloudUpload extends Upload { status = c2879_15.NOT_STARTED; loaded = 0; reactNativeFilePrepped = false; uploadAnalytics = { __proto__: UploadAnalytics.prototype, timing: {}, uploadResumptionCount: 0, uploadResumptionPosition: 0 }; uploadAttempts = 0; _aborted = false; createResumeAwareProgressFn = (c25253_0) => (a0) => { const loaded = a0.loaded; const loaded2 = loaded + c25253_0; const r8 = a0.total + c25253_0; this.emit("progress", loaded2, r8, loaded2 - this.loaded); this.loaded = loaded2; }; constructor(a0, a1, a2, a3) { super(a0); this.channelId = a1; let preCompressionSize = a0.file?.size; if (preCompressionSize == null) { preCompressionSize = 0; } this.preCompressionSize = preCompressionSize; let currentSize2 = a0.file?.size; if (currentSize2 == null) { currentSize2 = 0; } this.currentSize = currentSize2; this.reactNativeFileIndex = a2; if (a3 != null) { this.allowOptimization = a3; } if (a0.platform === UploadPlatform.WEB && a0.compressionMetadata != null) { this.mimeType = a0.compressionMetadata.originalContentType; } this._abortController = new AbortController(); if (this.origin != null) { this.uploadAnalytics.origin = typeof this.origin === "string" ? this.origin : UploadOrigin[this.origin]; } this._uploadHttpClient = new DefaultHttpClient(); this._libdiscoreEnabled = false; } static fromJson(a0) { const r13 = new c2879_18(a0.item, a0.channelId, a0.reactNativeFileIndex); let c14390_0 = r13; Object.entries(a0).forEach((item) => { const [r4, r8] = item; if (!r4.startsWith("_")) { c14390_0[r4] = r8; } }); const status = r13.status; if (status !== c2879_15.COMPLETED) { r13.status = c2879_15.NOT_STARTED; } return r13; } parseRangeHeader(a0) { const r7 = a0.match(/^bytes=(\d+)-(\d+)(?:\/\d+)?$/); return r7 != null ? [parseInt(r7[1], 10), parseInt(r7[2], 10)] : null; } retryOpts() { return this.item.platform === UploadPlatform.REACT_NATIVE ? { timeout: 1 * Durations.Millis.HOUR, backoff: new Backoff(0.5 * Durations.Millis.SECOND, 30 * Durations.Millis.MINUTE), retries: 12 } : { timeout: 1 * Durations.Millis.HOUR, retries: 12, backoff: new Backoff() }; } createAttachmentUrlRetryOpts() { return this.item.platform === UploadPlatform.REACT_NATIVE ? { timeout: { response: 30 * Durations.Millis.SECOND, deadline: 30 * Durations.Millis.MINUTE }, backoff: new Backoff(0.5 * Durations.Millis.SECOND, 60 * Durations.Millis.SECOND), retries: 8 } : this.retryOpts(); } supportsResume() { return this._libdiscoreEnabled || this.item.platform !== UploadPlatform.REACT_NATIVE; } async uploadFileToCloud() { let r83, r84; const _this = this; if (_this.responseUrl == null) { throw new Error("_uploadFileToCloud - responseUrl is not set"); } c2879_12.log(`Uploading ${_this.id}`, _this.item.platform === UploadPlatform.REACT_NATIVE ? `filename=${_this.item.filename}, uri=${_this.item.uri}` : `filename=${_this.item.file.name}`); if (_this.item.platform === UploadPlatform.REACT_NATIVE) { const r73 = { type: _this.item.mimeType, uri: _this.item.uri, name: _this.item.filename }; r84 = r73.type != null ? r73.type !== "application/json" ? r73.type : "application/octet-stream" : "application/octet-stream"; r83 = r73; } else { r83 = _this.item.file; r84 = "application/octet-stream"; } if (canUploadNatively(_this.item)) { _this._uploadHttpClient = new LibdiscoreHttpClient(); _this._libdiscoreEnabled = true; c2879_12.log("Using libdiscore client for file upload"); } return await _this.uploadFileWithResumption(_this.responseUrl, r83, r84); } async getResumePosition(url) { const _this2 = this; return await _this2._uploadHttpClient.doUpload({ url, headers: { "Content-Range": "bytes */*" }, rejectWithError: true, retries: 0, timeout: { deadline: 30 * Durations.Millis.SECOND }, signal: _this2._abortController.signal }).then((result) => result.status !== 200 && result.status !== 201 ? c2879_14.rejectionHandler("status_check")(result) : _this2.currentSize).catch((error) => { if (error instanceof HTTPResponseError && error.status === 308) { let range = error.headers.range; if (range == null) { range = ""; } const r22 = _this2.parseRangeHeader(range); return r22 != null ? r22[1] + 1 : 0; } return c2879_14.rejectionHandler("status_check")(error); }); } async startOrResumeUpload(c14393_0, r5 = 0) { let r54; const start = r5; const _this3 = this; let headers, c25256_2; c25256_2 = void 0; c2879_12.log(`Attempting to upload attachment with resumeFrom: ${start} and attempts: ${_this3.uploadAttempts}`); if (start > 0) { const uploadAnalytics = _this3.uploadAnalytics; uploadAnalytics.uploadResumptionCount = uploadAnalytics.uploadResumptionCount + 1; headers = c14393_0.headers; if (headers == null) { headers = {}; } c14393_0.headers = { ...headers, "Content-Range": `bytes ${start}-${_this3.currentSize - 1}/${_this3.currentSize}` }; r54 = c14393_0; } else { const headers3 = c14393_0.headers; r54 = c14393_0; if (headers3 != null) { const headers4 = c14393_0.headers; headers4["Content-Range"]; c14393_0.headers = _objectWithoutProperties(headers4, _excluded); r54 = c14393_0; } } r54.onRequestProgress = Module12.throttle(_this3.createResumeAwareProgressFn(start), 50); let c29413_0 = await _this3._uploadHttpClient.doUpload(r54, { fileByteRange: { start } }).catch(c2879_14.rejectionHandler("upload")); if (c29413_0.status !== 200 && c29413_0.status !== 201) { throw new c2879_14("upload", { response: c29413_0 }); } return c29413_0; } uploadFileWithResumption(a0, a1, a2) { let env14394 = { $parent: env2879 }; env14394[0] = a0; env14394[1] = a1; env14394[2] = a2; env14394[3] = this; return _asyncToGenerator(function() { let c25257_0, c25257_1, next, c25257_3, c25257_4, c25257_5, c25257_7; let c25257_8 = 0; let c25257_9 = 0; let c25257_6 = 0; return $createGenerator(function() { let r2, r3, r14, r16, r25, r37, r39, r54, r59, r107, r142, method, method2, method3, value3, value5, value6; let env29414; let $pc = 0, $e; while (true) { switch ($pc) { case 0: const r0 = c25257_9; r2 = r0; if (r0 === 2) { $pc = 50; continue; } $pc = 1; continue; case 1: value5 = arguments[1]; r3 = arguments[0]; const r23 = r2; r16 = Symbol; r14 = env14394; if (r23 === 3) { $pc = 45; continue; } $pc = 2; continue; case 2: try { c25257_9 = 2; r37 = c25257_8; if (r37 === 0) { $pc = 24; continue; } $pc = 3; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 3: try { if (r37 === 1) { $pc = 12; continue; } $pc = 4; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 4: try { const r33 = c25257_3; r25 = c25257_7; c25257_6 = 0; method = HermesBuiltin.getMethod(r33, "throw"); if (method === void 0) { $pc = 9; continue; } $pc = 5; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 5: try { r39 = method.call(c25257_3, r25); HermesBuiltin.ensureObject(r39, "iterator.throw() did not return an object"); if (r39.done) { $pc = 8; continue; } $pc = 6; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 6: try { c25257_8 = 1; c25257_9 = 1; $pc = 7; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 7: return r39; case 8: try { c25257_1 = r39; $pc = 32; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 9: try { method3 = HermesBuiltin.getMethod(c25257_3, "return"); if (method3 === void 0) { $pc = 11; continue; } $pc = 10; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 10: try { HermesBuiltin.ensureObject(method3.call(c25257_3), "iterator.return() did not return an object"); $pc = 11; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 11: try { HermesBuiltin.throwTypeError("yield* delegate must have a .throw() method"); $pc = 12; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 12: try { c25257_6 = 1; if (r3 === 1) { $pc = 23; continue; } $pc = 13; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 13: try { c25257_0 = value5; if (r3 === 2) { $pc = 15; continue; } $pc = 14; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 14: try { c25257_6 = 0; r54 = value5; $pc = 29; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 15: try { c25257_0 = value5; c25257_6 = 0; method2 = HermesBuiltin.getMethod(c25257_3, "return"); if (method2 === void 0) { $pc = 21; continue; } $pc = 16; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 16: try { r59 = method2.call(c25257_3, c25257_0); HermesBuiltin.ensureObject(r59, "iterator.return() did not return an object"); if (r59.done) { $pc = 19; continue; } $pc = 17; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 17: try { c25257_8 = 1; c25257_9 = 1; $pc = 18; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 18: return r59; case 19: try { value3 = r59.value; c25257_9 = 3; $pc = 20; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 20: return { value: value3, done: true }; case 21: try { c25257_9 = 3; $pc = 22; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 22: return { value: value5, done: true }; case 23: try { c25257_9 = 3; throw value5; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 24: try { if (r3 === 1) { $pc = 41; continue; } $pc = 25; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 25: try { if (r3 === 2) { $pc = 39; continue; } $pc = 26; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 26: try { c25257_5 = r14; const r71 = env29414 = { $parent: r14 }; c25257_4 = r71; env29414[0] = void 0; env29414[1] = void 0; env29414[2] = void 0; env29414[3] = void 0; env29414[4] = void 0; env29414[5] = void 0; const r74 = env14394[3].retryOpts(); const timeout = r74.timeout; env29414[1] = r74.backoff; const retries = r74.retries; env29414[2] = retries; env29414[3] = { url: env14394[0], body: env14394[1], headers: { "Content-Type": env14394[2] }, signal: env14394[3]._abortController.signal, onRequestProgress: Module12.throttle(env14394[3].createResumeAwareProgressFn(0), 50), retries: 0, rejectWithError: true, timeout }; env29414[4] = 0; env29414[5] = function* _loop() { let value2, c31350_1, c31350_2, c31350_4; let c31350_3 = 0; const r22 = env29414; const r21 = env14394; try { let env31929; c31350_2 = r22; const r25 = env31929 = { $parent: r21 }; c31350_1 = r25; env31929[0] = void 0; env31929[1] = void 0; env31929[2] = void 0; const r26 = env14394[3]; r26.uploadAttempts = r26.uploadAttempts + 1; env14394[3].uploadAnalytics.numUploadAttempts = env14394[3].uploadAttempts; c31350_3 = 1; env31929[0] = env14394[3].responseUrl; yield env14394[3].ensureFreshResponseUrl(); env29414[3].url = env14394[3].responseUrl; if (env31929[0] !== env14394[3].responseUrl) { env29414[4] = 0; env14394[3].loaded = 0; } else if (env14394[3].uploadAttempts > 1) { env31929[1] = yield env14394[3].trackTime("resumptionCheckTimeMs", (0, _asyncToGenerator)($mk118720(c31350_1))); env14394[3].uploadAnalytics.uploadResumptionPosition = env31929[1]; env29414[4] = env14394[3].supportsResume() ? env31929[1] : 0; env14394[3].loaded = env29414[4]; } value2 = {}; value2.v = yield env14394[3].startOrResumeUpload(env29414[3], env29414[4]); c31350_3 = 0; } catch ($e) { const r50 = $e; let r7 = r50; c31350_4 = r50; if (c31350_3 !== 0) { while (true) { L32: { try { const r202 = c31350_4; c31350_3 = 0; env31929[3] = r202; if (env31929[3] instanceof c2879_14 && env31929[3].canRetry()) { c2879_12.warn(`Error uploading ${env14394[3].id}: ${env31929[3].message}, attempting resumption`); env14394[3].uploadAnalytics.uploadResumptionReason = env31929[3].messageShort; yield NetworkUtils.awaitOnline(); const r274 = c31350_1; env31929[2] = env29414[1].fail(); c2879_12.log(`Waiting ${env31929[2]}ms before attachment upload attempt ${env14394[3].uploadAttempts + 1}`); yield new Promise($mk118721(r274)); break L32; } c2879_12.warn(`Unrecoverable error uploading ${env14394[3].id}: ${env31929[3].message}`); throw env31929[3]; } catch (r198) { r7 = r198; c31350_4 = r198; if (c31350_3 === 0) { break; } continue; } } return void 0; } } throw r7; } return value2; }; if (!(env14394[3].uploadAttempts <= retries)) { $pc = 38; continue; } $pc = 27; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 27: try { if (env14394[3]._aborted) { $pc = 38; continue; } $pc = 28; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 28: try { const r100 = (0, env29414[5])()[r16.iterator](); c25257_3 = r100; HermesBuiltin.ensureObject(r100, "iterator is not an object"); next = r100.next; c25257_0 = void 0; r54 = void 0; $pc = 29; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 29: try { r107 = next.call(c25257_3, r54); HermesBuiltin.ensureObject(r107, "iterator.next() did not return an object"); c25257_1 = r107; if (r107.done) { $pc = 32; continue; } $pc = 30; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 30: try { c25257_8 = 1; c25257_9 = 1; $pc = 31; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 31: return r107; case 32: try { const value4 = c25257_1.value; env29414[0] = value4; if (value4) { $pc = 36; continue; } $pc = 33; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 33: try { if (!(env14394[3].uploadAttempts <= env29414[2])) { $pc = 38; continue; } $pc = 34; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 34: try { if (env14394[3]._aborted) { $pc = 38; continue; } $pc = 35; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 35: try { $pc = 28; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 36: try { value6 = env29414[0].v; c25257_9 = 3; $pc = 37; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 37: return { value: value6, done: true }; case 38: try { throw new Error(`Upload failed after ${env14394[3].uploadAttempts} attempts`); } catch ($caught) { $e = $caught; $pc = 42; continue; } case 39: try { c25257_9 = 3; $pc = 40; continue; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 40: return { value: value5, done: true }; case 41: try { c25257_9 = 3; throw value5; } catch ($caught) { $e = $caught; $pc = 42; continue; } case 42: const r141 = $e; r142 = r141; c25257_7 = r141; if (c25257_6 === 0) { $pc = 44; continue; } $pc = 43; continue; case 43: c25257_8 = 2; $pc = 2; continue; case 44: c25257_9 = 3; throw r142; case 45: if (r3 === 1) { $pc = 49; continue; } $pc = 46; continue; case 46: if (r3 === 2) { $pc = 48; continue; } $pc = 47; continue; case 47: return { value: void 0, done: true }; case 48: return { value: value5, done: true }; case 49: throw value5; case 50: c25257_9 = 3; HermesBuiltin.throwTypeError("Generator functions may not be called on executing generators"); throw new Error("unreachable"); } throw new Error("bad pc " + $pc); } }); })(); } async getSize() { const _this4 = this; const uri = _this4.item.uri; let value = await (getFileSize != null ? getFileSize(uri) : void 0); if (value == null) { value = 0; } return value; } async trackTime(c14396_0, c14396_1) { let r37; const _this5 = this; let c25259_2; let c25259_3 = 0; let c29415_0; try { c29415_0 = void 0; c29415_0 = performance.now(); c25259_3 = 1; r37 = await c14396_1(); c25259_3 = 0; _this5.uploadAnalytics.timing[c14396_0] = performance.now() - c29415_0; } catch ($e) { const r26 = $e; let r8 = r26; c25259_2 = r26; if (c25259_3 !== 0) { while (true) { try { const r65 = c25259_2; c25259_3 = 0; _this5.uploadAnalytics.timing[c14396_0] = performance.now() - c29415_0; throw r65; } catch (r61) { r8 = r61; c25259_2 = r61; if (c25259_3 === 0) { break; } } } } throw r8; } return r37; } async upload() { let r131, r225; let env14397 = { $parent: env2879 }; env14397[0] = this; let currentSize, code, c25260_2, c25260_3, c25260_4, c25260_5; let c25260_6 = 0; const r25 = env14397; L57: { L36: { try { let env29416; c25260_4 = r25; const r62 = env29416 = { $parent: r25 }; c25260_3 = r62; env29416[0] = void 0; env29416[1] = void 0; env29416[2] = void 0; env29416[3] = void 0; env29416[4] = void 0; env29416[5] = void 0; env29416[6] = void 0; if (env14397[0].status === c2879_15.COMPLETED) { break L57; } L29: { L18: { L17: { env14397[0].setStatus(c2879_15.STARTED); env14397[0].startTime = performance.now(); env14397[0].trackUploadStart(); if (env14397[0].reactNativeFilePrepped !== false) { const isCancelled2 = env14397[0].isCancelled(); const r89 = env14397[0]; if (isCancelled2) { r89.handleComplete(env14397[0].id); break L57; } if (r89.allowOptimization) { if (env14397[0].item.platform === UploadPlatform.WEB) { const file = env14397[0].item.file; const id = env14397[0].id; r131 = await c2879_18.tryConvertToWebP(file, $mk114602(env14397), id); break L17; } } r225 = await _CloudUploaderUtils.default.getUploadPayload(env14397[0]); break L29; } await env14397[0].reactNativeCompressAndExtractData(); const isCancelled3 = env14397[0].isCancelled(); const r541 = env14397[0]; if (isCancelled3) { r541.handleComplete(env14397[0].id); break L36; } if (!r541.allowOptimization) { break L18; } if (env14397[0].item.platform !== UploadPlatform.WEB) { break L18; } const file2 = env14397[0].item.file; const id2 = env14397[0].id; r131 = await c2879_18.tryConvertToWebP(file2, $mk114602(env14397), id2); } env29416[0] = r131; if (env29416[0] != null) { if (env29416[0].convertedFile != null) { env14397[0].item.file = env29416[0].convertedFile; env14397[0].currentSize = env29416[0].convertedFile.size; } if (env29416[0].convertedMimeType != null) { env14397[0].uploadAnalytics.convertedMimeType = env29416[0].convertedMimeType; } if (env29416[0].hashTimeMs != null) { env14397[0].uploadAnalytics.timing.hashTimeMs = env29416[0].hashTimeMs; } if (env29416[0].conversionFailureReason != null) { env14397[0].uploadAnalytics.conversionFailureReason = env29416[0].conversionFailureReason; } env14397[0].uploadAnalytics.timing.compressTimeMs = env29416[0].compressTimeMs; } } r225 = await _CloudUploaderUtils.default.getUploadPayload(env14397[0]); } env29416[1] = r225; env29416[2] = getUploadTarget(env14397[0].item.target); if (env29416[1].filename != null && env29416[1].filename !== "") { env14397[0].currentSize; if (env14397[0].currentSize !== 0) { env29416[3] = getKestrelConfig({ location: "CloudUpload.upload.postCompressionCheck" }); env29416[4] = getEffectiveKestrelLimit(env29416[3], env29416[2].getMaxFileSize(env14397[0].channelId)); const currentSize2 = env14397[0].currentSize; currentSize = currentSize2; if (currentSize2 == null) { currentSize = 0; } if (currentSize > env29416[4]) { env14397[0].handleError(AbortCodes.ENTITY_TOO_LARGE); break L36; } if (DevSettingsStore.get("upload_fail_50") && Math.random() < 0.5) { setTimeout($mk114603(env14397), 1000); break L36; } const r338 = c25260_3; c25260_6 = 1; c2879_12.log(`Requesting upload url for ${env14397[0].id}`); env29416[5] = await env14397[0].trackTime("getUploadUrlTimeMs", (0, _asyncToGenerator)($mk114604(r338))); env14397[0].setResponseUrl(env29416[5].body.attachments[0].upload_url); env14397[0].setUploadedFilename(env29416[5].body.attachments[0].upload_filename); const r415 = c25260_3; c25260_6 = 2; await env14397[0].trackTime("uploadTimeMs", (0, _asyncToGenerator)($mk114605(r415))); env14397[0].trackUploadFinished(c2879_15.COMPLETED); env14397[0].handleComplete(env14397[0].id); c25260_6 = 0; break L36; } env14397[0].handleError(AbortCodes.ENTITY_EMPTY); break L36; } c2879_12.error("File does not have a filename.", JSON.stringify(env29416[1])); env14397[0].handleError(AbortCodes.INVALID_FILE_ASSET); } catch ($e) { const r60 = $e; let r8 = r60; c25260_5 = r60; let r61 = c25260_6; if (r61 !== 0) { while (true) { if (r61 === 1) { try { const r641 = c25260_5; c25260_6 = 0; env29416[7] = r641; const r643 = env29416[7]; code = r643 == null ? void 0 : r643.body?.code; if (code == null) { code = env29416[7].status; } env29416[6] = code; if (env29416[6] !== AbortCodes.ENTITY_TOO_LARGE) { const r670 = env29416[6]; c25260_2 = r670; if (r670 == null) { c25260_2 = JSON.stringify(env29416[7].body); } c2879_12.error(`Requesting upload url failed with code ${c25260_2} for ${env14397[0].id}`); SentryUtils_native.captureException(env29416[7]); } env14397[0].handleError(env29416[6]); } catch (r639) { r8 = r639; c25260_5 = r639; r61 = c25260_6; if (r61 === 0) { break; } continue; } return void 0; } try { const r610 = c25260_5; c25260_6 = 0; env29416[8] = r610; if (env14397[0].isCancelled()) { env14397[0].handleComplete(env29416[8]); break L36; } c2879_12.info(`Error: status ${env29416[8].status} for ${env14397[0].id}`); env14397[0].handleError(env29416[8]); break L36; } catch (r607) { r8 = r607; c25260_5 = r607; r61 = c25260_6; if (r61 === 0) { break; } } } } throw r8; } return void 0; } return void 0; } } async reactNativeCompressAndExtractData() { let r79, r124, r461; let env14398 = { $parent: env2879 }; env14398[0] = this; let size, c25261_1, c25261_2; L44: { L43: { L40: { let env29417; const r48 = env14398; c25261_2 = r48; const r12 = env29417 = { $parent: r48 }; c25261_1 = r12; env29417[0] = void 0; env29417[1] = void 0; env29417[2] = void 0; env29417[3] = void 0; env29417[4] = void 0; env29417[5] = void 0; env29417[6] = void 0; const shouldReactNativeCompressUploads = getUploadTarget(env14398[0].item.target).shouldReactNativeCompressUploads; const r57 = env14398[0]; if (shouldReactNativeCompressUploads) { if (r57.reactNativeFilePrepped === true) { env14398[0].uploadAnalytics.fileAlreadyPrepped = true; c2879_12.log(`reactNativeCompressAndExtractData() file already prepped - ${env14398[0].id}`); r79 = env14398[0]; break L44; } c2879_12.log(`Starting compression/conversion for ${env14398[0].id}`); env29417[0] = await env14398[0].trackTime("compressTimeMs", async () => { const r29 = env14398[0]; const reactNativeFileIndex2 = r29.reactNativeFileIndex; let reactNativeFileIndex = reactNativeFileIndex2; if (reactNativeFileIndex2 == null) { reactNativeFileIndex = 0; } return await getAttachmentFile(r29, reactNativeFileIndex); }); if (env29417[0] != null && env29417[0].file != null) { env29417[1] = env29417[0].uri; env29417[2] = env29417[0].file.name; if (isResolvedUpload(env29417[0].file)) { env14398[0].uploadAnalytics.imageCompressionQuality = env29417[0].file.imageCompressionQuality; env14398[0].uploadAnalytics.videoCompressionQuality = env29417[0].file.videoCompressionQuality; env14398[0].uploadAnalytics.imageEncoderType = env29417[0].file.imageEncoderType; if (env29417[0].file.isImage) { env14398[0].uploadAnalytics.sourceMediaWidth = env29417[0].file.sourceWidth; env14398[0].uploadAnalytics.sourceMediaHeight = env29417[0].file.sourceHeight; env14398[0].uploadAnalytics.uploadedImageWidth = env29417[0].file.uploadedImageWidth; env14398[0].uploadAnalytics.uploadedImageHeight = env29417[0].file.uploadedImageHeight; } if (env29417[0].file.videoMetadata !== void 0) { env14398[0].uploadAnalytics.sourceMediaWidth = env29417[0].file.videoMetadata.width; env14398[0].uploadAnalytics.sourceMediaHeight = env29417[0].file.videoMetadata.height; env14398[0].uploadAnalytics.sourceMediaFormat = env29417[0].file.videoMetadata.format; env14398[0].uploadAnalytics.sourceVideoBitrate = env29417[0].file.videoMetadata.bitRate; env14398[0].uploadAnalytics.sourceVideoFramerate = env29417[0].file.videoMetadata.frameRate; env14398[0].uploadAnalytics.videoDurationMs = env29417[0].file.videoMetadata.durationMs; env14398[0].uploadAnalytics.sourceVideoProfile = env29417[0].file.videoMetadata.sourceProfile; env14398[0].uploadAnalytics.sourceVideoLevel = env29417[0].file.videoMetadata.sourceLevel; } if (env29417[0].file.encodingConfig !== void 0) { env14398[0].uploadAnalytics.targetVideoWidth = env29417[0].file.encodingConfig.targetWidth; env14398[0].uploadAnalytics.targetVideoHeight = env29417[0].file.encodingConfig.targetHeight; env14398[0].uploadAnalytics.targetVideoBitrate = env29417[0].file.encodingConfig.targetBitrate; env14398[0].uploadAnalytics.targetVideoCodec = env29417[0].file.encodingConfig.useHEVC ? "hvc1" : "avc1"; env14398[0].uploadAnalytics.targetVideoFramerate = env29417[0].file.encodingConfig.frameRate; env14398[0].uploadAnalytics.targetVideoIsHdr = env29417[0].file.encodingConfig.createHDR; env14398[0].uploadAnalytics.hevcIsSupported = env29417[0].file.encodingConfig.hevcIsSupported; env14398[0].uploadAnalytics.progressUpdateGranularity = env29417[0].file.encodingConfig.progressUpdateGranularity; } env14398[0].uploadAnalytics.psnr = env29417[0].file.psnr; env14398[0].uploadAnalytics.ssim = env29417[0].file.ssim; env14398[0].uploadAnalytics.origin = env29417[0].file.origin; env14398[0].uploadAnalytics.psnrMeasurementLatencyMs = env29417[0].file.psnrMeasurementLatencyMs; env14398[0].uploadAnalytics.ssimMeasurementLatencyMs = env29417[0].file.ssimMeasurementLatencyMs; } env14398[0].filename = env29417[2]; if (env29417[2] != null && env29417[1] != null && env29417[0].file.type != null) { const r375 = env29417[2].split(".").pop(); env29417[3] = r375 == null ? void 0 : r375.toLowerCase(); env29417[4] = env29417[3] !== "jpg" ? env29417[3] !== "jpeg" ? env29417[0].file.type : "image/jpeg" : "image/jpeg"; env14398[0].uploadAnalytics.convertedMimeType = env29417[4]; size = env29417[0].fileSize; if (size == null) { size = (await getFileData(env29417[1])).size; } env29417[5] = size; env14398[0].postCompressionSize = env29417[5]; env14398[0].currentSize = env29417[5]; if (env29417[5] == null) { c2879_12.error(`Size missing from file data for ${env14398[0].id}`); throw new Error("Size missing from file data"); } c2879_12.log(`Completed compression and conversion. Output size=${env29417[5]} bytes; filename=${env29417[2]}; uri=${env29417[1]}; originalMimeType=${env14398[0].mimeType}; mimeType=${env29417[4]} for ${env14398[0].id}`); env29417[6] = { uri: env29417[1], filename: env29417[2], mimeType: env29417[4] }; env14398[0].item = { ...env14398[0].item, ...env29417[6] }; env14398[0].reactNativeFilePrepped = true; r461 = env14398[0]; break L40; } c2879_12.error(`Insufficient file data: ${{ filename: env29417[2], uri: env29417[1], type: env29417[0].file.type }} for ${env14398[0].id}`); throw new Error(`Insufficient file data: ${{ filename: env29417[2], uri: env29417[1], type: env29417[0].file.type }}`); } c2879_12.error(`Failed to get compressed file for ${env14398[0].id}`); r124 = env14398[0]; break L43; } r57.uploadAnalytics.compressAndExtractDisabled = true; c2879_12.log("reactNativeCompressAndExtractData() disabled by upload target"); return env14398[0]; } return r461; } return r124; } return r79; } static async tryConvertToWebP(c14399_0, c14399_1, c14399_2) { let r233; let UNKNOWN_ERROR, compressTimeMs, hashTimeMs, reason, c25262_6; let c25262_7 = 0; let c29418_0, c29418_1, c29418_2, c29418_3, c29418_4, c29418_5, c29418_6, c29418_7; L40: { L35: { L39: { L38: { L15: { try { c29418_0 = void 0; c29418_1 = void 0; c29418_2 = void 0; c29418_3 = void 0; c29418_4 = void 0; c29418_5 = void 0; c29418_6 = void 0; const imageAttachmentMezzanineV2Config = getImageAttachmentMezzanineV2Config({ location: "CloudUpload.maybeConvertToWebP" }); if (imageAttachmentMezzanineV2Config.enabled) { if (c14399_0 == null) { c2879_12.warn(`webp conversion skipped for ${c14399_2}: no file`); break L40; } if (imageAttachmentMezzanineV2Config.maxFileSizeBytes != null && c14399_0.size > imageAttachmentMezzanineV2Config.maxFileSizeBytes) { c2879_12.warn(`webp conversion skipped for ${c14399_2}: too big`); break L15; } if (c14399_1()) { break L39; } c29418_2 = performance.now(); c29418_3 = { compressTimeMs: 0 }; c25262_7 = 1; c29418_4 = await import("./webpConversion"); c29418_1 = c29418_4.ConversionFailureReason; c29418_0 = await c29418_4.maybeConvertToWebP(c14399_0); if ((0, c14399_1)()) { c25262_7 = 0; break L38; } if (c29418_0.success && c29418_0.convertedBlob != null) { c2879_12.log(`webp conversion worked for ${c14399_2}: ${c29418_0.sizeBefore} -> ${c29418_0.sizeAfter} bytes (${c29418_0.compressionRatio.toFixed(2)}x)`); c29418_3.convertedFile = new File([c29418_0.convertedBlob], c14399_0.name, { type: "image/webp", lastModified: c14399_0.lastModified }); c29418_3.convertedMimeType = "image/webp"; const r214 = c29418_3; hashTimeMs = c29418_0.hashTimeMs; if (hashTimeMs == null) { hashTimeMs = void 0; } r214.hashTimeMs = hashTimeMs; } else { reason = c29418_0.reason; if (reason == null) { reason = c29418_1.UNKNOWN_ERROR; } c29418_5 = reason; c2879_12.log(`webp conversion skipped for ${c14399_2}: ${c29418_5}`); c29418_3.conversionFailureReason = c29418_5; } c25262_7 = 0; c29418_6 = Math.round(performance.now() - c29418_2); const r227 = c29418_3; const compressTimeMs2 = c29418_0?.compressTimeMs; compressTimeMs = compressTimeMs2; if (compressTimeMs2 == null) { compressTimeMs = c29418_6; } r227.compressTimeMs = compressTimeMs; r233 = c29418_3; break L35; } c2879_12.warn(`webp conversion skipped for ${c14399_2}: not enabled`); } catch ($e) { const r54 = $e; let r8 = r54; c25262_6 = r54; if (c25262_7 !== 0) { while (true) { try { const r261 = c25262_6; c25262_7 = 0; c29418_7 = r261; c2879_12.warn(`webp conversion failed for ${c14399_2}:`, c29418_7); const r272 = c29418_3; const UNKNOWN_ERROR2 = c29418_1?.UNKNOWN_ERROR; UNKNOWN_ERROR = UNKNOWN_ERROR2; if (UNKNOWN_ERROR2 == null) { UNKNOWN_ERROR = "unknown_error"; } r272.conversionFailureReason = UNKNOWN_ERROR; c29418_6 = Math.round(performance.now() - c29418_2); const r286 = c29418_3; const compressTimeMs3 = c29418_0?.compressTimeMs; compressTimeMs = compressTimeMs3; if (compressTimeMs3 == null) { compressTimeMs = c29418_6; } r286.compressTimeMs = compressTimeMs; r233 = c29418_3; break L35; } catch (r257) { r8 = r257; c25262_6 = r257; if (c25262_7 === 0) { break; } } } } throw r8; } return null; } return null; } return null; } return null; } return r233; } return null; } handleError(a0) { const setStatus2 = this.setStatus; setStatus2.call(this, c2879_15.ERROR); this.error = a0; this.trackUploadFinished(c2879_15.ERROR); try { this.emit("error", a0); } catch ($e) {} this.removeAllListeners(); } handleComplete(a0) { this.setStatus(c2879_15.COMPLETED); c2879_12.log(`Upload complete for ${this.id}`); this.emit("complete", a0); this.removeAllListeners(); } _cancel(a0, a1) { c2879_12.log(a1); this._aborted = true; this._abortController.abort(); this.trackUploadFinished(a0); if (this.status === c2879_15.COMPLETED) { this.delete(); } this.setStatus(a0); this.emit("complete"); this.removeAllListeners(); } cancel() { this._cancel(c2879_15.CANCELED, `Cancelled called for ${this.id}`); } removeFromMsgDraft() { this._cancel(c2879_15.REMOVED_FROM_MSG_DRAFT, `Removed from draft for ${this.id}`); } isCancelled() { const status = this.status; return status === c2879_15.CANCELED || this.status === c2879_15.REMOVED_FROM_MSG_DRAFT; } resetState() { this.status = c2879_15.NOT_STARTED; this.uploadedFilename = void 0; this.responseUrl = void 0; this.responseUrlSetAt = void 0; this.error = void 0; this.startTime = void 0; this.uploadAnalytics = { __proto__: UploadAnalytics.prototype, timing: {}, uploadResumptionCount: 0, uploadResumptionPosition: 0 }; this.uploadAttempts = 0; this._aborted = false; this._abortController = new AbortController(); return Reflect.get(Object.getPrototypeOf(prototype), "resetState", this).call(this); } async delete() { const _this6 = this; let c25263_2 = 0; L13: { try { if (_this6.uploadedFilename != null) { const deleteUploadURL = getUploadTarget(_this6.item.target).getDeleteUploadURL(_this6.uploadedFilename); c25263_2 = 1; await HTTP.del(deleteUploadURL); c25263_2 = 0; break L13; } } catch ($e) { let r25 = $e; if (c25263_2 !== 0) { while (true) { try { c25263_2 = 0; break L13; } catch ($e) { r25 = $e; if (c25263_2 === 0) { break; } } } } throw r25; } return void 0; } } setResponseUrl(a0) { this.responseUrl = a0; this.responseUrlSetAt = Date.now(); } static isResponseUrlStale(a0) { if (a0 == null) { return true; } const r11 = 12 * Durations.Millis.HOUR; return Date.now() - a0 > r11; } async ensureFreshResponseUrl() { const _this7 = this; let c25264_1; let c29419_0, c29419_1, c29419_2; L21: { c25264_1 = void 0; c29419_0 = void 0; c29419_1 = void 0; c29419_2 = void 0; if (c2879_18.isResponseUrlStale(_this7.responseUrlSetAt)) { c29419_0 = await _CloudUploaderUtils.default.getUploadPayload(_this7); c29419_1 = getUploadTarget(_this7.item.target).getCreateAttachmentURL(_this7.channelId); c29419_2 = await HTTP.post({ url: c29419_1, body: { files: [c29419_0] }, ..._this7.createAttachmentUrlRetryOpts(), rejectWithError: false }); if (c29419_2.ok) { const body = c29419_2.body; const r117 = body == null; let r118 = void 0; if (!r117) { const attachments = body.attachments; r118 = attachments == null ? void 0 : attachments[0]; } if (r118 != null) { _this7.setResponseUrl(c29419_2.body.attachments[0].upload_url); _this7.setUploadedFilename(c29419_2.body.attachments[0].upload_filename); break L21; } } throw new c2879_14("upload", { response: c29419_2 }); } return void 0; } } setStatus(a0) { this.status = a0; } setFilename(a0) { this.filename = a0; } setUploadedFilename(a0) { this.uploadedFilename = a0; } trackUploadStart() { const ATTACHMENT_UPLOAD_STARTED = AnalyticEvents.ATTACHMENT_UPLOAD_STARTED; let mimeType = this.mimeType; if (mimeType == null) { mimeType = "unknown"; } AnalyticsUtils.track(ATTACHMENT_UPLOAD_STARTED, { file_size: this.currentSize, mime_type: mimeType, video_upload_quality: UnsyncedUserSettingsStore.videoUploadQuality, data_saving_mode: UnsyncedUserSettingsStore.dataSavingMode, low_quality_image_mode: UnsyncedUserSettingsStore.dataSavingMode, channel_id: this.channelId, connection_type: NetworkStore.getType(), effective_connection_speed: NetworkStore.getEffectiveConnectionSpeed(), service_provider: NetworkStore.getServiceProvider() }); } trackUploadFinished(a0) { const duration_ms = this.startTime != null ? performance.now() - this.startTime : -1; const ATTACHMENT_UPLOAD_FINISHED = AnalyticEvents.ATTACHMENT_UPLOAD_FINISHED; let mimeType = this.mimeType; if (mimeType == null) { mimeType = "unknown"; } let numUploadAttempts = this.uploadAnalytics.numUploadAttempts; if (numUploadAttempts == null) { numUploadAttempts = 1; } let convertedMimeType = this.uploadAnalytics.convertedMimeType; if (convertedMimeType == null) { convertedMimeType = "unknown"; } let imageCompressionQuality = this.uploadAnalytics.imageCompressionQuality; if (imageCompressionQuality == null) { imageCompressionQuality = 0; } let videoCompressionQuality = this.uploadAnalytics.videoCompressionQuality; if (videoCompressionQuality == null) { videoCompressionQuality = "unknown"; } let imageEncoderType = this.uploadAnalytics.imageEncoderType; if (imageEncoderType == null) { imageEncoderType = "unknown"; } AnalyticsUtils.track(ATTACHMENT_UPLOAD_FINISHED, { duration_ms, file_size: this.currentSize, pre_compression_file_size: this.preCompressionSize, final_state: a0, mime_type: mimeType, num_upload_attempts: numUploadAttempts, error_code: this.error, video_upload_quality: UnsyncedUserSettingsStore.videoUploadQuality, data_saving_mode: UnsyncedUserSettingsStore.dataSavingMode, low_quality_image_mode: UnsyncedUserSettingsStore.dataSavingMode, compress_time_ms: this.uploadAnalytics.timing.compressTimeMs, get_upload_url_time_ms: this.uploadAnalytics.timing.getUploadUrlTimeMs, upload_time_ms: this.uploadAnalytics.timing.uploadTimeMs, converted_mime_type: convertedMimeType, image_compression_quality: imageCompressionQuality, video_compression_quality: videoCompressionQuality, image_encoder_type: imageEncoderType, was_converted: this.uploadAnalytics.convertedMimeType != null && this.mimeType !== this.uploadAnalytics.convertedMimeType, was_compressed: this.currentSize < this.preCompressionSize, source_media_width: this.uploadAnalytics.sourceMediaWidth, source_media_height: this.uploadAnalytics.sourceMediaHeight, source_media_format: this.uploadAnalytics.sourceMediaFormat, uploaded_image_width: this.uploadAnalytics.uploadedImageWidth, uploaded_image_height: this.uploadAnalytics.uploadedImageHeight, source_video_bitrate: this.uploadAnalytics.sourceVideoBitrate, video_duration_ms: this.uploadAnalytics.videoDurationMs, source_video_profile_name: this.uploadAnalytics.sourceVideoProfile, source_video_profile_level: this.uploadAnalytics.sourceVideoLevel, target_video_width: this.uploadAnalytics.targetVideoWidth, target_video_height: this.uploadAnalytics.targetVideoHeight, target_video_bitrate: this.uploadAnalytics.targetVideoBitrate, target_video_codec: this.uploadAnalytics.targetVideoCodec, target_video_framerate: this.uploadAnalytics.targetVideoFramerate, target_video_is_hdr: this.uploadAnalytics.targetVideoIsHdr, hevc_is_supported: this.uploadAnalytics.hevcIsSupported, progress_update_granularity: this.uploadAnalytics.progressUpdateGranularity, source_video_framerate: this.uploadAnalytics.sourceVideoFramerate, channel_id: this.channelId, hash_time_ms: this.uploadAnalytics.timing.hashTimeMs, psnr: this.uploadAnalytics.psnr, ssim: this.uploadAnalytics.ssim, origin: this.uploadAnalytics.origin, psnr_measurement_latency_ms: this.uploadAnalytics.psnrMeasurementLatencyMs, ssim_measurement_latency_ms: this.uploadAnalytics.ssimMeasurementLatencyMs, upload_resumption_count: this.uploadAnalytics.uploadResumptionCount, upload_resumption_reason: this.uploadAnalytics.uploadResumptionReason, upload_resumption_position: this.uploadAnalytics.uploadResumptionPosition, upload_resumption_check_time_ms: this.uploadAnalytics.timing.resumptionCheckTimeMs, conversion_failure_reason: this.uploadAnalytics.conversionFailureReason, upload_http_client: this._libdiscoreEnabled ? "libdiscore" : "httputils", connection_type: NetworkStore.getType(), effective_connection_speed: NetworkStore.getEffectiveConnectionSpeed(), service_provider: NetworkStore.getServiceProvider() }); } } const prototype2 = CloudUpload.prototype; c2879_18 = CloudUpload; c2879_21 = CloudUpload; prototype = prototype2; export { c2879_15 as CloudUploadStatus };