feat(upload): S3 multipart upload with offline resume and wake lock (#391)

* feat(upload): implement S3 multipart upload with offline resume and wake lock

* fix(upload): harden S3 sign and abort authorization, await confirmation, and clean up failed multipart uploads

* fix(webui): resume multipart upload on network recovery and log online event

* fix(webui): remove offline and online toast notifications
This commit is contained in:
Yiling-J
2026-09-07 16:49:00 +08:00
committed by GitHub
parent 62e86b703e
commit 67b767f1e8
23 changed files with 2157 additions and 419 deletions
+45
View File
@@ -151,6 +151,8 @@
"@ai-sdk/replicate": "3.0.34",
"@ai-sdk/togetherai": "3.0.41",
"@ai-sdk/xai": "4.0.49",
"@aws-sdk/client-s3": "3.1121.0",
"@aws-sdk/s3-request-presigner": "3.1121.0",
"@earendil-works/pi-agent-core": "0.82.1",
"@earendil-works/pi-ai": "0.82.1",
"@modelcontextprotocol/client": "2.0.0",
@@ -292,6 +294,9 @@
"@tanstack/react-router": "1.170.11",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.14.10",
"@uppy/aws-s3": "6.0.0",
"@uppy/core": "6.0.0",
"@uppy/xhr-upload": "6.0.0",
"better-auth": "1.6.11",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
@@ -418,8 +423,12 @@
"@aws-crypto/util": ["@aws-crypto/util@5.2.0", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="],
"@aws-sdk/checksums": ["@aws-sdk/checksums@3.1000.29", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Dtu0gr4dnATZAPwEYbpCsG+MpLM7OAliy2gTepEFQwl1vZ6DL3QMH2FveMa3HLvPsOdhJsPRB3KtxVhph9T75A=="],
"@aws-sdk/client-bedrock-runtime": ["@aws-sdk/client-bedrock-runtime@3.1048.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.11", "@aws-sdk/credential-provider-node": "^3.972.42", "@aws-sdk/eventstream-handler-node": "^3.972.16", "@aws-sdk/middleware-eventstream": "^3.972.12", "@aws-sdk/middleware-websocket": "^3.972.19", "@aws-sdk/token-providers": "3.1048.0", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ=="],
"@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.1121.0", "", { "dependencies": { "@aws-sdk/checksums": "^3.1000.29", "@aws-sdk/core": "^3.977.9", "@aws-sdk/credential-provider-node": "^3.972.81", "@aws-sdk/middleware-sdk-s3": "^3.972.75", "@aws-sdk/signature-v4-multi-region": "^3.996.46", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-hBnoqaVBeWdkgXcJElMXA2yUZWkBCBntu2qmN+tfqmzC+j4LzJC3ox8qIgS2WdMS1cb8UwyBogUVrkRXybNm0A=="],
"@aws-sdk/core": ["@aws-sdk/core@3.977.9", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@aws-sdk/xml-builder": "^3.972.40", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.33.3", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-reqPFEQrZxDZpeGj4PFMepBeR5LGYHRqq/L0motTzgFkCRBA4rFdaVXDSLYyGHhxVz7sT2PDnPN9CluGSfgyJA=="],
"@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.70", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-H404B7dJl2mCrBqahDEYsanB0xhdDp6tXnXcTUnXmmpy2Q3J0Ho0bUajZ2jr/RdwzCyS59Gi8xXIFwPLGBl6Uw=="],
@@ -442,10 +451,14 @@
"@aws-sdk/middleware-eventstream": ["@aws-sdk/middleware-eventstream@3.972.29", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-dlRzHCgyB8W6hLuDC5pcT5q+ziPt00n4QGgGBE17ucLVU4zMa6lsbuUdQ2Pm75Z5VA8GF+R/+SgrRcaTdIzSIQ=="],
"@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.75", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/signature-v4-multi-region": "^3.996.46", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-wMIsNumRVKaNMKhvU/s9VrdEwE8S6gSzXp4RygFG5BEMnGkkXf8cjh8zf7cKJBpUDpqTWqwbz5isEgp9rH6Lng=="],
"@aws-sdk/middleware-websocket": ["@aws-sdk/middleware-websocket@3.972.52", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-vsPPM+nMbKJlUCFU+eoGZbdxdxDIAX9LbpjSXaR5Ufpmqgp8TdYQnoExhLu4T3umW/JIIPny1ydbhWidZZYokQ=="],
"@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.44", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/signature-v4-multi-region": "^3.996.46", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-NhEgryjlBF9w38ZXqGymQV28IhkYa1mKhlbYnqIis57AYwWGVYfUPgg/qC2rLRqOUfblxx++irvju10kVTa8Vw=="],
"@aws-sdk/s3-request-presigner": ["@aws-sdk/s3-request-presigner@3.1121.0", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/signature-v4-multi-region": "^3.996.46", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-uudb+S0RTbdmBd2ChRCnDbjK1lbZsBwNtFeCnC1lusWUYpZJ12cYzf7E0HhJzhPV4W83RQgxFNDAh2ZNhuGSJw=="],
"@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.46", "", { "dependencies": { "@aws-sdk/types": "^3.974.5", "@smithy/signature-v4": "^5.6.12", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-L+2xZTye/2T96f3lwCws0Zw6GG2JHZW9e8FpVgGBeeExSKyeoZ6CWRpBml/7DNiK/O26jrgPM9F+Ay8VkgzUWQ=="],
"@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1048.0", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/nested-clients": "^3.997.9", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA=="],
@@ -1224,6 +1237,8 @@
"@testing-library/react": ["@testing-library/react@16.3.3", "", { "dependencies": { "@babel/runtime": "^7.12.5" }, "peerDependencies": { "@testing-library/dom": "^10.0.0", "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg=="],
"@transloadit/prettier-bytes": ["@transloadit/prettier-bytes@2.0.0", "", {}, "sha512-GYzxSL3y9XlhwamBLkHT1y2jFrRsHkZZ1jNctn8NeMNyTtIbMK1Qf0f1koHkDdW+MwOUowCmpm8zP6ZpQ36G5w=="],
"@types/adm-zip": ["@types/adm-zip@0.5.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q=="],
"@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="],
@@ -1338,6 +1353,12 @@
"@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="],
"@uppy/aws-s3": ["@uppy/aws-s3@6.0.0", "", { "peerDependencies": { "@uppy/core": "^6.0.0" } }, "sha512-FnHZr50CgzQInmIfiJjPr7wLXHbTgX6QMkYRIR/Px5rzjwSlacbrnDa2+LrgaJgpFBKGruC++svu+AdotKyxIg=="],
"@uppy/core": ["@uppy/core@6.0.0", "", { "dependencies": { "@transloadit/prettier-bytes": "^2.0.0", "classnames": "^2.5.1", "lodash": "^4.18.1", "mime-match": "^1.0.2", "namespace-emitter": "^2.0.1", "nanoid": "^5.1.11", "p-queue": "^9.3.3", "p-retry": "^6.1.0", "preact": "^10.29.2" } }, "sha512-qaNqf4t2nxnbFFLSVmLr7Jw9TaA4fzvl8paR/ggwiOo5XFgAfbCFzjDzP8l2r5UzR6cCt3wS95QWvrm82UGZ+g=="],
"@uppy/xhr-upload": ["@uppy/xhr-upload@6.0.0", "", { "peerDependencies": { "@uppy/core": "^6.0.0" } }, "sha512-r1EV5LUoMCQjeQVkc+qupCXA5wn8vRV7m3iB5K7z/4nkSj7lEt4Hk0fkudeQ/h4sF9wi3SqAM1x2Syhbt6Ar8A=="],
"@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],
"@videojs/http-streaming": ["@videojs/http-streaming@3.17.5", "", { "dependencies": { "@babel/runtime": "^7.12.5", "@videojs/vhs-utils": "^4.1.2", "aes-decrypter": "^4.0.2", "global": "^4.4.0", "m3u8-parser": "^7.2.0", "mpd-parser": "^1.4.0", "mux.js": "7.1.0", "video.js": "^7 || ^8" } }, "sha512-PRRQVu0hYW5h0XvRWpIyIpEatpMZzZtf7L1avV89Hnu+69f+0c7oLsSL9jwpg2nbvzGkdX5rQxQkz5Vc7tFR9w=="],
@@ -2034,6 +2055,8 @@
"is-negative-zero": ["is-negative-zero@2.0.3", "", {}, "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw=="],
"is-network-error": ["is-network-error@1.3.2", "", {}, "sha512-PhBY86zaxNZUuWP6h13Vu5oFe0XY6/UlKzQnYFELzGVHygP3MxmvTfYSG7GN3aIab/iWudSMgjSnG9Dq+nHrgA=="],
"is-number-object": ["is-number-object@1.1.1", "", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw=="],
"is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
@@ -2238,6 +2261,8 @@
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"mime-match": ["mime-match@1.0.2", "", { "dependencies": { "wildcard": "^1.1.0" } }, "sha512-VXp/ugGDVh3eCLOBCiHZMYWQaTNUHv2IJrut+yXA6+JbLPXHglHwfS/5A5L0ll+jkCY7fIzRJcH6OIunF+c6Cg=="],
"min-document": ["min-document@2.19.2", "", { "dependencies": { "dom-walk": "^0.1.0" } }, "sha512-8S5I8db/uZN8r9HSLFVWPdJCvYOejMcEC82VIzNUc6Zkklf/d1gg2psfE79/vyhWOj4+J8MtwmoOz3TmvaGu5A=="],
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
@@ -2262,6 +2287,8 @@
"named-placeholders": ["named-placeholders@1.1.6", "", { "dependencies": { "lru.min": "^1.1.0" } }, "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w=="],
"namespace-emitter": ["namespace-emitter@2.0.1", "", {}, "sha512-N/sMKHniSDJBjfrkbS/tpkPj4RAbvW3mr8UAzvlMHyun93XEm83IAvhWtJVHo+RHn/oO8Job5YN4b+wRjSVp5g=="],
"nan": ["nan@2.28.0", "", {}, "sha512-fTsDz99OTq2sVePhGdp4qQhggZFtKr64ZNVyVajRKtMOkJxYekplBh577PiJB12v/D3s2E5cGtOI45LWp6rnLQ=="],
"nanoid": ["nanoid@3.3.18", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],
@@ -2320,8 +2347,12 @@
"p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
"p-queue": ["p-queue@9.3.3", "", { "dependencies": { "eventemitter3": "^5.0.4", "p-timeout": "^7.0.0" } }, "sha512-NXAOdnEe5FsZJfT4oK84lE1Y5cFFdWlRuOo5tww8DyNMxyRXwn39fIkUtNLKppcPC+UYU/bXujNCUGDv01y7CA=="],
"p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="],
"p-timeout": ["p-timeout@7.0.1", "", {}, "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg=="],
"package-json-from-dist": ["package-json-from-dist@1.0.1", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="],
"pako": ["pako@0.2.9", "", {}, "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA=="],
@@ -2404,6 +2435,8 @@
"postgres-interval": ["postgres-interval@1.2.0", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="],
"preact": ["preact@10.29.8", "", { "peerDependencies": { "preact-render-to-string": ">=5" }, "optionalPeers": ["preact-render-to-string"] }, "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q=="],
"prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
"prettier": ["prettier@3.9.6", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g=="],
@@ -2814,6 +2847,8 @@
"why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
"wildcard": ["wildcard@1.1.2", "", {}, "sha512-DXukZJxpHA8LuotRwL0pP1+rS6CS7FF2qStDDE1C7DDg2rLud2PXRMuEDYIPhgEezwnlHNL4c+N6MfMTjCGTng=="],
"word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
"wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
@@ -2866,6 +2901,8 @@
"@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
"@aws-sdk/client-s3/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
"@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
"@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1116.0", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-ygIivKqh8aHzNkucOCXHyIBgBpLPfrSI0mCqXF+vLBsPTUKqj0VSqAY0GFPe7lQl4HntjOcQ+KSyS7oUV2C54Q=="],
@@ -2950,6 +2987,10 @@
"@typescript-eslint/typescript-estree/semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"@uppy/core/nanoid": ["nanoid@5.1.16", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],
"@uppy/core/p-retry": ["p-retry@6.2.1", "", { "dependencies": { "@types/retry": "0.12.2", "is-network-error": "^1.0.0", "retry": "^0.13.1" } }, "sha512-hEt02O4hUct5wtwg4H4KcWgDdm+l1bOaEy/hWzd8xtXB9BqxTWBBhb+2ImAtH4Cv4rPjV76xN3Zumqk3k3AhhQ=="],
"@visx/vendor/@types/d3-array": ["@types/d3-array@3.0.3", "", {}, "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ=="],
"@visx/vendor/@types/d3-color": ["@types/d3-color@3.1.0", "", {}, "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA=="],
@@ -3086,6 +3127,10 @@
"@types/ssh2/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
"@uppy/core/p-retry/@types/retry": ["@types/retry@0.12.2", "", {}, "sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow=="],
"@uppy/core/p-retry/retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="],
"@visx/vendor/@types/d3-interpolate/@types/d3-color": ["@types/d3-color@3.1.3", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],
"@visx/vendor/@types/d3-scale/@types/d3-time": ["@types/d3-time@3.0.4", "", {}, "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="],
+1 -1
View File
@@ -22,7 +22,7 @@ const baseNamingConvention = [
filter: {
// Allow CSS variables, common HTTP headers, library-specific names, paths, and hyphenated/numeric keys
regex:
'^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature)$',
'^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature|CopySource|Delete|Objects|Quiet|ResponseContentDisposition|UploadId|PartNumber)$',
match: false,
},
},
+81
View File
@@ -139,4 +139,85 @@ describe('Upload API', () => {
itemId: 'file1',
})
})
it('POST /teams/:teamId/upload/sign', async () => {
vi.spyOn(uploadService, 'signS3Upload').mockResolvedValue({
url: 'http://signed-url.com',
})
const res = await app.request('/teams/team1/upload/sign', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
key: 'files/test.mp4',
method: 'PUT',
fileId: 'file1',
uploadId: 'up1',
partNumber: 1,
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ url: 'http://signed-url.com' })
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'file1',
permission: Permission.Edit,
}),
)
expect(uploadService.signS3Upload).toHaveBeenCalledWith('team1', 'user1', {
key: 'files/test.mp4',
method: 'PUT',
fileId: 'file1',
uploadId: 'up1',
partNumber: 1,
})
})
it('POST /teams/:teamId/upload/sign fails validation when fileId is missing', async () => {
const res = await app.request('/teams/team1/upload/sign', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
key: 'files/test.mp4',
method: 'PUT',
}),
})
expect(res.status).toBe(400)
})
it('POST /teams/:teamId/upload/tasks/:taskId/abort', async () => {
vi.spyOn(uploadService, 'abortUpload').mockResolvedValue({
success: true,
})
const res = await app.request('/teams/team1/upload/tasks/task1/abort', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
body: JSON.stringify({
fileId: 'file1',
uploadId: 'up1',
key: 'files/test.mp4',
}),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ success: true })
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
id: 'file1',
permission: Permission.Edit,
}),
)
expect(uploadService.abortUpload).toHaveBeenCalledWith('team1', 'user1', 'task1', {
fileId: 'file1',
uploadId: 'up1',
key: 'files/test.mp4',
})
})
})
+37
View File
@@ -2,9 +2,11 @@ import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { uploadService } from '@shumai/core/src/upload/upload'
import {
abortUploadRequestSchema,
confirmFileUploadRequestSchema,
createUploadTaskRequestSchema,
localUploadQuerySchema,
s3SignRequestSchema,
} from '@shumai/dtos'
import { paginationParamsSchema, AuditAction } from '@shumai/dtos'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
@@ -124,5 +126,40 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json({ success: true })
},
)
.post('/teams/:teamId/upload/sign', zValidator('json', s3SignRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: req.fileId,
})
const resp = await uploadService.signS3Upload(teamId, user.id, req)
return c.json(resp)
})
.post(
'/teams/:teamId/upload/tasks/:taskId/abort',
zValidator('json', abortUploadRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const taskId = c.req.param('taskId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Edit,
type: ResourceType.Asset,
id: req.fileId,
})
const resp = await uploadService.abortUpload(teamId, user.id, taskId, req)
return c.json(resp)
},
)
export default route
+2
View File
@@ -24,6 +24,8 @@
"@ai-sdk/replicate": "3.0.34",
"@ai-sdk/togetherai": "3.0.41",
"@ai-sdk/xai": "4.0.49",
"@aws-sdk/client-s3": "3.1121.0",
"@aws-sdk/s3-request-presigner": "3.1121.0",
"@earendil-works/pi-agent-core": "0.82.1",
"@earendil-works/pi-ai": "0.82.1",
"@modelcontextprotocol/client": "2.0.0",
+255 -62
View File
@@ -1,43 +1,47 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import {
GetObjectCommand,
PutObjectCommand,
UploadPartCommand,
CreateMultipartUploadCommand,
CompleteMultipartUploadCommand,
ListPartsCommand,
AbortMultipartUploadCommand,
} from '@aws-sdk/client-s3'
import { buildContentDisposition, LocalStorageService, S3StorageService } from './s3'
// Mock Bun S3Client
const s3ClientConstructorSpy = vi.fn()
const s3FileSpy = vi.fn()
const s3WriteSpy = vi.fn()
const s3DeleteSpy = vi.fn()
const s3ListSpy = vi.fn()
const s3ExistsSpy = vi.fn()
const s3PresignSpy = vi.fn()
const s3SendSpy = vi.fn()
const getSignedUrlSpy = vi.fn()
vi.mock('bun', () => {
vi.mock('@aws-sdk/client-s3', async (importOriginal) => {
const actual = await importOriginal<typeof import('@aws-sdk/client-s3')>()
return {
...actual,
S3Client: class {
constructor(params: unknown) {
s3ClientConstructorSpy(params)
}
file = s3FileSpy.mockReturnValue({
size: Promise.resolve(123),
exists: vi.fn().mockResolvedValue(true),
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(10)),
type: 'text/plain',
})
write = s3WriteSpy.mockResolvedValue({})
delete = s3DeleteSpy.mockResolvedValue({})
list = s3ListSpy.mockResolvedValue({ contents: [], isTruncated: false })
exists = s3ExistsSpy.mockResolvedValue(true)
presign = s3PresignSpy.mockReturnValue('http://presigned-url')
send = s3SendSpy
},
}
})
vi.mock('@aws-sdk/s3-request-presigner', () => {
return {
getSignedUrl: vi.fn((client, command, options) => getSignedUrlSpy(client, command, options)),
}
})
describe('S3Service implementations', () => {
beforeEach(async () => {
vi.clearAllMocks()
getSignedUrlSpy.mockReset()
delete process.env.PRESIGNED_URL_EXPIRES_IN
s3PresignSpy.mockReturnValue('http://presigned-url')
getSignedUrlSpy.mockResolvedValue('http://presigned-url')
s3SendSpy.mockResolvedValue({})
})
describe('S3StorageService', () => {
@@ -68,48 +72,53 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
const url = await s3.presign('bucket', 'key', 'GET')
expect(url).toBe('http://presigned-url')
expect(s3PresignSpy).toHaveBeenCalledWith('key', expect.objectContaining({ method: 'GET' }))
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(GetObjectCommand),
expect.objectContaining({ expiresIn: 18000 }),
)
})
it('should cache GET presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockClear()
s3PresignSpy.mockReturnValueOnce('http://presigned-url-1')
s3PresignSpy.mockReturnValueOnce('http://presigned-url-2')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-2')
const url1 = await s3.presign('bucket', 'key', 'GET')
const url2 = await s3.presign('bucket', 'key', 'GET')
expect(url1).toBe('http://presigned-url-1')
expect(url2).toBe('http://presigned-url-1')
expect(s3PresignSpy).toHaveBeenCalledTimes(1)
expect(getSignedUrlSpy).toHaveBeenCalledTimes(1)
})
it('should NOT cache PUT presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockReset()
s3PresignSpy.mockReturnValueOnce('http://unique-put-url-1')
s3PresignSpy.mockReturnValueOnce('http://unique-put-url-2')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://unique-put-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://unique-put-url-2')
const url1 = await s3.presign('bucket', 'key', 'PUT')
const url2 = await s3.presign('bucket', 'key', 'PUT')
expect(url1).toBe('http://unique-put-url-1')
expect(url2).toBe('http://unique-put-url-2')
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
})
it('should respect PRESIGNED_URL_EXPIRES_IN env', async () => {
process.env.PRESIGNED_URL_EXPIRES_IN = '10'
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockClear()
getSignedUrlSpy.mockClear()
await s3.presign('bucket', 'key', 'GET')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(GetObjectCommand),
expect.objectContaining({ expiresIn: 10 * 3600 }),
)
@@ -120,11 +129,14 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect.not.objectContaining({
contentDisposition: expect.anything(),
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
input: expect.not.objectContaining({
ResponseContentDisposition: expect.anything(),
}),
}),
expect.anything(),
)
})
@@ -132,11 +144,14 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true)
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
contentDisposition: 'attachment',
input: expect.objectContaining({
ResponseContentDisposition: 'attachment',
}),
}),
expect.anything(),
)
})
@@ -144,11 +159,15 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true, 'foo.png')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
contentDisposition: 'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
input: expect.objectContaining({
ResponseContentDisposition:
'attachment; filename="foo.png"; filename*=UTF-8\'\'foo.png',
}),
}),
expect.anything(),
)
})
@@ -156,34 +175,35 @@ describe('S3Service implementations', () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
await s3.presign('bucket', 'key', 'GET', true, '报告.png')
expect(s3PresignSpy).toHaveBeenCalledWith(
'key',
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
// Non-ASCII names are conveyed only via filename* (percent-encoded),
// keeping the header value pure ASCII (RFC 7230).
contentDisposition: "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.png",
input: expect.objectContaining({
ResponseContentDisposition: "attachment; filename*=UTF-8''%E6%8A%A5%E5%91%8A.png",
}),
}),
expect.anything(),
)
})
it('should not cache download presign URLs', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3PresignSpy.mockClear()
s3PresignSpy.mockReturnValueOnce('http://download-url-1')
s3PresignSpy.mockReturnValueOnce('http://download-url-2')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://download-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://download-url-2')
const url1 = await s3.presign('bucket', 'key', 'GET', true)
const url2 = await s3.presign('bucket', 'key', 'GET', true)
expect(url1).toBe('http://download-url-1')
expect(url2).toBe('http://download-url-2')
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
})
it('should handle ReadableStream in putObject by wrapping in Response', async () => {
it('should handle ReadableStream in putObject', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3WriteSpy.mockClear()
s3SendSpy.mockClear()
const stream = new ReadableStream({
start(controller) {
@@ -194,25 +214,198 @@ describe('S3Service implementations', () => {
await s3.putObject('test-bucket', 'file.txt', stream, 14, 'text/plain')
expect(s3WriteSpy).toHaveBeenCalledWith(
'file.txt',
expect.any(Response),
expect.objectContaining({ bucket: 'test-bucket', type: 'text/plain' }),
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'file.txt',
ContentType: 'text/plain',
ContentLength: 14,
}),
}),
)
})
it('should handle ArrayBuffer in putObject', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3WriteSpy.mockClear()
s3SendSpy.mockClear()
const arrayBuffer = new TextEncoder().encode('array buffer content').buffer
await s3.putObject('test-bucket', 'file.txt', arrayBuffer, 20, 'text/plain')
expect(s3WriteSpy).toHaveBeenCalledWith(
'file.txt',
arrayBuffer,
expect.objectContaining({ bucket: 'test-bucket', type: 'text/plain' }),
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'file.txt',
ContentType: 'text/plain',
ContentLength: 20,
}),
}),
)
})
it('should presign multipart operations correctly', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
// PUT part
await s3.presignMultipart('bucket', 'key', {
method: 'PUT',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
partNumber: 1,
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(UploadPartCommand),
expect.anything(),
)
// PUT single
await s3.presignMultipart('bucket', 'key', {
method: 'PUT',
key: 'key',
fileId: 'file-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(PutObjectCommand),
expect.anything(),
)
// POST create multipart
await s3.presignMultipart('bucket', 'key', {
method: 'POST',
key: 'key',
fileId: 'file-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(CreateMultipartUploadCommand),
expect.anything(),
)
// POST complete multipart
await s3.presignMultipart('bucket', 'key', {
method: 'POST',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(CompleteMultipartUploadCommand),
expect.anything(),
)
// GET list parts
await s3.presignMultipart('bucket', 'key', {
method: 'GET',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(ListPartsCommand),
expect.anything(),
)
// DELETE abort multipart
await s3.presignMultipart('bucket', 'key', {
method: 'DELETE',
key: 'key',
fileId: 'file-1',
uploadId: 'up-1',
})
expect(getSignedUrlSpy).toHaveBeenCalledWith(
expect.anything(),
expect.any(AbortMultipartUploadCommand),
expect.anything(),
)
// Expect GET without uploadId to throw
await expect(
s3.presignMultipart('bucket', 'key', {
method: 'GET',
key: 'key',
fileId: 'file-1',
}),
).rejects.toThrow('List parts requires uploadId')
// Expect DELETE without uploadId to throw
await expect(
s3.presignMultipart('bucket', 'key', {
method: 'DELETE',
key: 'key',
fileId: 'file-1',
}),
).rejects.toThrow('Abort multipart upload requires uploadId')
})
it('should stream in uploadFileToKey', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3SendSpy.mockClear()
const tmpFile = path.join(process.cwd(), 'data-test-stream.txt')
fs.writeFileSync(tmpFile, 'streaming content from file')
try {
await s3.uploadFileToKey(tmpFile, 'test/key.txt', 'text/plain')
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'test/key.txt',
ContentType: 'text/plain',
ContentLength: 27,
Body: expect.any(fs.ReadStream),
}),
}),
)
// Wait for stream to open and close before unlinking
const callArg = s3SendSpy.mock.calls[0]?.[0]
const stream = callArg?.input?.Body as fs.ReadStream | undefined
if (stream) {
if (!stream.destroyed) {
await new Promise((resolve) => {
if (stream.pending) {
stream.once('open', resolve)
} else {
resolve(null)
}
})
stream.destroy()
await new Promise((resolve) => {
stream.once('close', resolve)
})
}
}
} finally {
if (fs.existsSync(tmpFile)) {
fs.unlinkSync(tmpFile)
}
}
})
it('should abort multipart upload in S3', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
s3SendSpy.mockClear()
await s3.abortMultipartUpload('test-bucket', 'file.txt', 'upload-123')
expect(s3SendSpy).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({
Bucket: 'test-bucket',
Key: 'file.txt',
UploadId: 'upload-123',
}),
}),
)
})
})
+254 -75
View File
@@ -1,8 +1,25 @@
import { ObjectInfo } from '@shumai/dtos'
import { S3Client } from 'bun'
import { ObjectInfo, S3SignRequest } from '@shumai/dtos'
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
HeadObjectCommand,
DeleteObjectCommand,
DeleteObjectsCommand,
ListObjectsV2Command,
ListObjectsV2CommandOutput,
CopyObjectCommand,
CreateMultipartUploadCommand,
UploadPartCommand,
ListPartsCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import * as crypto from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import { Readable } from 'stream'
import { ulid } from 'ulid'
import { LruTtlCache } from '../cache/lru-ttl-cache'
import { detectSupportedMimeType } from '../utils/mime'
@@ -94,6 +111,12 @@ export interface S3Service {
download?: boolean,
filename?: string,
) => Promise<string>
presignMultipart: (
bucket: string,
key: string,
request: S3SignRequest,
) => Promise<{ url: string }>
abortMultipartUpload: (bucket: string, key: string, uploadId: string) => Promise<void>
}
export class S3StorageService implements S3Service {
@@ -111,39 +134,59 @@ export class S3StorageService implements S3Service {
this.client = new S3Client({
region,
endpoint,
accessKeyId,
secretAccessKey,
bucket,
credentials: {
accessKeyId,
secretAccessKey,
},
forcePathStyle: true,
requestChecksumCalculation: 'WHEN_REQUIRED',
responseChecksumValidation: 'WHEN_REQUIRED',
})
this.bucket = bucket
}
async getObjectSize(bucket: string, key: string): Promise<number> {
return await this.client.size(key, { bucket })
const res = await this.client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
return res.ContentLength ?? 0
}
async putObject(
bucket: string,
key: string,
body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream,
_size: number,
body: Buffer | Uint8Array | ArrayBuffer | string | ReadableStream | NodeJS.ReadableStream,
size: number,
contentType?: string,
): Promise<void> {
const payload =
body && typeof body === 'object' && 'getReader' in body
? new Response(body as ReadableStream)
: body
await this.client.write(key, payload, {
bucket,
type: contentType,
})
let payload: string | Uint8Array | Buffer | NodeJS.ReadableStream = ''
if (body && typeof body === 'object' && 'getReader' in body) {
// Convert web ReadableStream to Node stream without buffering into memory
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload = Readable.fromWeb(body as any)
} else if (body && typeof body === 'object' && 'pipe' in body) {
payload = body as NodeJS.ReadableStream
} else if (body instanceof ArrayBuffer) {
payload = Buffer.from(body)
} else if (typeof body === 'string' || body instanceof Uint8Array || Buffer.isBuffer(body)) {
payload = body
}
await this.client.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
// AWS SDK v3 PutObjectCommandInput types differ slightly between Node and Web streams
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Body: payload as any,
ContentLength: size > 0 ? size : undefined,
ContentType: contentType,
}),
)
}
async getObject(bucket: string, key: string): Promise<S3Object> {
const file = this.client.file(key, { bucket })
const arrayBuffer = await file.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
let contentType = file.type
const res = await this.client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
const bytes = await res.Body?.transformToByteArray()
const buffer = bytes ? Buffer.from(bytes) : Buffer.alloc(0)
let contentType = res.ContentType
if (!contentType || contentType === 'application/octet-stream') {
const detected = detectSupportedMimeType(buffer)
if (detected) {
@@ -167,20 +210,26 @@ export class S3StorageService implements S3Service {
destBucket: string,
destKey: string,
): Promise<void> {
const sourceFile = this.client.file(sourceKey, { bucket: sourceBucket })
await this.client.write(destKey, sourceFile, { bucket: destBucket })
await this.client.send(
new CopyObjectCommand({
CopySource: `${sourceBucket}/${sourceKey}`,
Bucket: destBucket,
Key: destKey,
}),
)
}
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
const file = this.client.file(key, { bucket })
await Bun.write(filePath, file)
const res = await this.client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
const bytes = await res.Body?.transformToByteArray()
if (bytes) {
await Bun.write(filePath, bytes)
}
}
async deleteObject(bucket: string, key: string): Promise<number> {
try {
const exists = await this.client.exists(key, { bucket })
if (!exists) return 0
await this.client.delete(key, { bucket })
await this.client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }))
return 1
} catch {
return 0
@@ -189,27 +238,35 @@ export class S3StorageService implements S3Service {
async deletePrefix(bucket: string, prefix: string): Promise<number> {
const keys = await this.listObjects(bucket, prefix)
if (keys.length > 0) {
await Promise.all(keys.map((key) => this.deleteObject(bucket, key)))
if (keys.length === 0) return 0
const chunkSize = 1000
for (let i = 0; i < keys.length; i += chunkSize) {
const batch = keys.slice(i, i + chunkSize)
await this.client.send(
new DeleteObjectsCommand({
Bucket: bucket,
Delete: {
Objects: batch.map((k) => ({ Key: k })),
Quiet: true,
},
}),
)
}
return keys.length
}
async headObject(bucket: string, key: string): Promise<ObjectInfo> {
const file = this.client.file(key, { bucket })
const exists = await file.exists()
if (!exists) {
throw new Error(`NoSuchKey: The specified key does not exist.`)
}
// Bun.S3File doesn't expose lastModified or eTag directly in a way that matches ObjectInfo easily
// but we can try to get them if available. For now, using defaults for fields not provided.
return {
key,
size: await file.size,
lastModified: new Date(), // Bun doesn't expose this yet via S3File
contentType: file.type || 'application/octet-stream',
eTag: '',
try {
const res = await this.client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
return {
key,
size: res.ContentLength ?? 0,
lastModified: res.LastModified ?? new Date(),
contentType: res.ContentType || 'application/octet-stream',
eTag: res.ETag || '',
}
} catch (err: unknown) {
throw new Error(`NoSuchKey: The specified key does not exist.`, { cause: err })
}
}
@@ -219,21 +276,24 @@ export class S3StorageService implements S3Service {
let continuationToken: string | undefined = undefined
while (isTruncated) {
const response = await this.client.list({
prefix,
continuationToken,
})
const response: ListObjectsV2CommandOutput = await this.client.send(
new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
ContinuationToken: continuationToken,
}),
)
if (response.contents) {
for (const item of response.contents) {
if (item.key) {
keys.push(item.key)
if (response.Contents) {
for (const item of response.Contents) {
if (item.Key) {
keys.push(item.Key)
}
}
}
isTruncated = response.isTruncated || false
continuationToken = response.nextContinuationToken
isTruncated = response.IsTruncated || false
continuationToken = response.NextContinuationToken
}
return keys
@@ -246,10 +306,17 @@ export class S3StorageService implements S3Service {
}
async uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void> {
await this.client.write(key, Bun.file(filePath), {
bucket: this.bucket,
type: contentType,
})
const file = Bun.file(filePath)
const stream = fs.createReadStream(filePath)
await this.client.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: stream,
ContentLength: file.size,
ContentType: contentType,
}),
)
}
async presign(
@@ -261,37 +328,125 @@ export class S3StorageService implements S3Service {
): Promise<string> {
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const expiresInSeconds = expireHours * 3600
// Cache time is 2/3 of expire time, rounded to minute
const cacheMinutes = Math.round((expireHours * 60 * 2) / 3)
const cacheTtlMs = cacheMinutes * 60 * 1000
const cacheKey = `${bucket}:${key}`
const cacheTtlMs = expiresInSeconds * 1000
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}`
if (method === 'GET' && !download) {
const cached = this.presignCache.get(cacheKey)
if (cached) return cached
if (cached) {
return cached
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const options: any = {
bucket,
expiresIn: expiresInSeconds,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
method: method as any,
}
let url: string
if (download) {
options.contentDisposition = buildContentDisposition(filename)
if (method === 'GET') {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
ResponseContentDisposition: download ? buildContentDisposition(filename) : undefined,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (method === 'PUT') {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (method === 'DELETE') {
const command = new DeleteObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
throw new Error(`Unsupported method for presign: ${method}`)
}
const url = this.client.presign(key, options)
if (method === 'GET' && !download) {
this.presignCache.set(cacheKey, url, cacheTtlMs)
}
return url
}
async presignMultipart(
bucket: string,
key: string,
request: S3SignRequest,
): Promise<{ url: string }> {
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const expiresInSeconds = expireHours * 3600
let url: string
if (request.method === 'PUT') {
if (request.uploadId && request.partNumber != null) {
const command = new UploadPartCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
PartNumber: request.partNumber,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
}
} else if (request.method === 'POST') {
if (request.uploadId) {
const command = new CompleteMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
const command = new CreateMultipartUploadCommand({
Bucket: bucket,
Key: key,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
}
} else if (request.method === 'GET') {
if (!request.uploadId) {
throw new Error('List parts requires uploadId')
}
const command = new ListPartsCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else if (request.method === 'DELETE') {
if (!request.uploadId) {
throw new Error('Abort multipart upload requires uploadId')
}
const command = new AbortMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: request.uploadId,
})
url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
} else {
throw new Error(`Unsupported method for presignMultipart: ${request.method}`)
}
return { url }
}
async abortMultipartUpload(bucket: string, key: string, uploadId: string): Promise<void> {
await this.client.send(
new AbortMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
}),
)
}
}
export class LocalStorageService implements S3Service {
@@ -527,9 +682,33 @@ export class LocalStorageService implements S3Service {
}
return url
}
async presignMultipart(
bucket: string,
key: string,
request: S3SignRequest,
): Promise<{ url: string }> {
if (request.method === 'PUT') {
return { url: `${this.endpoint}${signLocalUrl(bucket, key)}` }
}
const url = await this.presign(bucket, key, request.method)
return { url }
}
async abortMultipartUpload(
bucket: string,
key: string,
_uploadId: string, // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<void> {
await this.deleteObject(bucket, key)
}
}
const storageBackend = process.env.STORAGE_BACKEND || 'local'
export function getStorageBackend(): 's3' | 'local' {
return (process.env.STORAGE_BACKEND as 's3' | 'local') || 'local'
}
const storageBackend = getStorageBackend()
const port = process.env.SHUMAI_SERVER_PORT || '3000'
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || `http://localhost:${port}`
+294 -1
View File
@@ -4,12 +4,16 @@ import { setupTestDbHooks } from '@shumai/db/test'
import { uploadService } from './upload'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AssetStatus, AssetType, WorkflowTaskType } from '@shumai/db'
import { AssetStatus, AssetType, TaskStatus, WorkflowTaskType } from '@shumai/db'
vi.mock('@shumai/core/src/s3/s3', () => ({
getStorageBackend: vi.fn().mockReturnValue('s3'),
s3Service: {
presign: vi.fn().mockResolvedValue('http://presigned-url.com'),
getObjectSize: vi.fn().mockResolvedValue(100),
presignMultipart: vi.fn().mockResolvedValue({ url: 'http://signed-multipart-url.com' }),
abortMultipartUpload: vi.fn().mockResolvedValue(undefined),
deleteObject: vi.fn().mockResolvedValue(1),
},
}))
@@ -615,4 +619,293 @@ describe('UploadService', () => {
const song2 = await prisma.asset.findFirst({ where: { name: 'other_song.WMA' } })
expect(song2?.mediaType).toBe('audio/x-ms-asf')
})
describe('signS3Upload', () => {
it('should sign multipart request and store uploadId on asset', async () => {
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/video.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'video.mp4',
type: AssetType.file,
projectId,
storageKeyId: storageKey.id,
status: AssetStatus.uploading,
},
})
const res = await uploadService.signS3Upload(teamId, userId, {
key: 'files/test/video.mp4',
method: 'PUT',
uploadId: 'upload-id-xyz',
partNumber: 1,
fileId: asset.id,
})
expect(res.url).toBe('http://signed-multipart-url.com')
const updatedAsset = await prisma.asset.findUnique({
where: { id: asset.id },
})
expect(updatedAsset?.uploadId).toBe('upload-id-xyz')
})
it('should reject signing if requested key does not match asset storage key', async () => {
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/video.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'video.mp4',
type: AssetType.file,
projectId,
storageKeyId: storageKey.id,
status: AssetStatus.uploading,
},
})
await expect(
uploadService.signS3Upload(teamId, userId, {
key: 'files/unauthorized/other.mp4',
method: 'PUT',
fileId: asset.id,
}),
).rejects.toThrow('Requested key does not match asset storage key')
})
it('should reject signing if asset is not in uploading status', async () => {
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/video.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'video.mp4',
type: AssetType.file,
projectId,
storageKeyId: storageKey.id,
status: AssetStatus.uploaded,
},
})
await expect(
uploadService.signS3Upload(teamId, userId, {
key: 'files/test/video.mp4',
method: 'PUT',
fileId: asset.id,
}),
).rejects.toThrow('Asset is not currently uploading')
})
it('should reject signing if asset belongs to another team', async () => {
const otherTeam = await prisma.team.create({ data: { name: 'other-team' } })
const otherProject = await prisma.project.create({
data: { name: 'other-project', teamId: otherTeam.id },
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/other.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'other.mp4',
type: AssetType.file,
projectId: otherProject.id,
storageKeyId: storageKey.id,
status: AssetStatus.uploading,
},
})
await expect(
uploadService.signS3Upload(teamId, userId, {
key: 'files/test/other.mp4',
method: 'PUT',
fileId: asset.id,
}),
).rejects.toThrow('Asset does not belong to team')
})
})
describe('abortUpload', () => {
it('should abort multipart upload, delete asset, and fail task', async () => {
const task = await prisma.task.create({
data: {
creatorId: userId,
type: 'upload',
name: 'task-1',
total: 1,
status: TaskStatus.uploading,
},
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/abort.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'abort.mp4',
type: AssetType.file,
projectId,
storageKeyId: storageKey.id,
taskId: task.id,
uploadId: 'upload-abc',
status: AssetStatus.uploading,
},
})
const res = await uploadService.abortUpload(teamId, userId, task.id, {
fileId: asset.id,
uploadId: 'upload-abc',
key: 'files/test/abort.mp4',
})
expect(res.success).toBe(true)
expect(s3Service.abortMultipartUpload).toHaveBeenCalledWith(
expect.anything(),
'files/test/abort.mp4',
'upload-abc',
)
const deletedAsset = await prisma.asset.findUnique({
where: { id: asset.id },
})
expect(deletedAsset).toBeNull()
const updatedTask = await prisma.task.findUnique({
where: { id: task.id },
})
expect(updatedTask?.status).toBe(TaskStatus.failed)
})
it('should reject aborting if asset taskId does not match', async () => {
const task = await prisma.task.create({
data: {
creatorId: userId,
type: 'upload',
name: 'task-1',
total: 1,
status: TaskStatus.uploading,
},
})
const otherTask = await prisma.task.create({
data: {
creatorId: userId,
type: 'upload',
name: 'other-task',
total: 1,
status: TaskStatus.uploading,
},
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/abort-mismatch.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'abort-mismatch.mp4',
type: AssetType.file,
projectId,
storageKeyId: storageKey.id,
taskId: otherTask.id,
uploadId: 'upload-abc',
status: AssetStatus.uploading,
},
})
await expect(
uploadService.abortUpload(teamId, userId, task.id, {
fileId: asset.id,
uploadId: 'upload-abc',
key: 'files/test/abort-mismatch.mp4',
}),
).rejects.toThrow('Asset does not belong to specified task')
})
it('should delete object from storage when aborting single/local upload without uploadId', async () => {
const task = await prisma.task.create({
data: {
creatorId: userId,
type: 'upload',
name: 'task-2',
total: 1,
status: TaskStatus.uploading,
},
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/single.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'single.mp4',
type: AssetType.file,
projectId,
storageKeyId: storageKey.id,
taskId: task.id,
status: AssetStatus.uploading,
},
})
const res = await uploadService.abortUpload(teamId, userId, task.id, {
fileId: asset.id,
key: 'files/test/single.mp4',
})
expect(res.success).toBe(true)
expect(s3Service.deleteObject).toHaveBeenCalledWith(
expect.anything(),
'files/test/single.mp4',
)
const deletedAsset = await prisma.asset.findUnique({
where: { id: asset.id },
})
expect(deletedAsset).toBeNull()
})
})
describe('confirmFileUpload with errorMessage', () => {
it('should abort multipart upload in S3 and delete asset on failure', async () => {
const task = await prisma.task.create({
data: {
creatorId: userId,
type: 'upload',
name: 'task-err',
total: 1,
status: TaskStatus.uploading,
},
})
const storageKey = await prisma.storageKey.create({
data: { key: 'files/test/fail.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'fail.mp4',
type: AssetType.file,
projectId,
storageKeyId: storageKey.id,
taskId: task.id,
uploadId: 'upload-fail-id',
status: AssetStatus.uploading,
},
})
await uploadService.confirmFileUpload(userId, task.id, {
fileId: asset.id,
errorMessage: 'Network failed',
})
expect(s3Service.abortMultipartUpload).toHaveBeenCalledWith(
expect.anything(),
'files/test/fail.mp4',
'upload-fail-id',
)
const deletedAsset = await prisma.asset.findUnique({
where: { id: asset.id },
})
expect(deletedAsset).toBeNull()
})
})
})
+169 -4
View File
@@ -1,13 +1,17 @@
import { assetService } from '@shumai/core/src/asset/asset'
import { PaginatedData, PaginationParams, paginateQuery } from '@shumai/core/src/pagination'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getStorageBackend, s3Service } from '@shumai/core/src/s3/s3'
import { AssetStatus, AssetType, Prisma, TaskStatus, prisma } from '@shumai/db'
import {
AbortUploadRequest,
AbortUploadResponse,
ConfirmFileUploadRequest,
CreateUploadTaskRequest,
CreateUploadTaskResponse,
FileNode,
PresignedUrl,
S3SignRequest,
S3SignResponse,
TaskInfo,
} from '@shumai/dtos'
import { ImageTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
@@ -16,6 +20,7 @@ import { ulid } from 'ulid'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { getProxyType, isHtmlDocument, isOfficeDocument } from '@shumai/core/src/utils/mime'
import { logger } from '@shumai/core/src/logger'
export class UploadService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
@@ -62,7 +67,7 @@ export class UploadService {
const isParentFile = parentAsset.type === AssetType.file
const targetParentId = isParentFile ? parentAsset.parentId! : parentAsset.id
const createdAssets: { tempId: string; assetId: string }[] = []
const createdAssets: { tempId: string; assetId: string; key?: string }[] = []
await this.prismaClient.$transaction(async (tx) => {
const ids = await this.createAssetsRecursively(
@@ -95,6 +100,7 @@ export class UploadService {
return {
taskId: task.id,
presignedUrls: presignedUrls,
storageBackend: getStorageBackend(),
createdAssets: createdAssets,
}
}
@@ -107,7 +113,7 @@ export class UploadService {
parentId: string,
files: FileNode[],
presignedUrls: PresignedUrl[],
createdAssets: { tempId: string; assetId: string }[],
createdAssets: { tempId: string; assetId: string; key?: string }[],
): Promise<string[]> {
const firstFile = await tx.asset.findFirst({
where: { parentId },
@@ -152,6 +158,7 @@ export class UploadService {
createdAssets.push({
tempId: file.id,
assetId: newAsset.id,
key: key || undefined,
})
if (assetType === AssetType.folder && parentId) {
@@ -202,7 +209,30 @@ export class UploadService {
if (!key) throw new Error('Asset has no key')
if (req.errorMessage) {
await this.prismaClient.asset.delete({ where: { id: asset.id } })
const bucket = process.env.S3_BUCKET || 'shumai'
if (asset.uploadId && key) {
try {
await s3Service.abortMultipartUpload(bucket, key, asset.uploadId)
} catch (err) {
logger.warn(
{ err, key, uploadId: asset.uploadId },
'Failed to abort multipart upload on confirm error',
)
}
} else if (key) {
try {
await s3Service.deleteObject(bucket, key)
} catch (err) {
logger.warn({ err, key }, 'Failed to delete storage object on confirm error')
}
}
await this.prismaClient.asset.delete({ where: { id: asset.id } }).catch(() => {})
if (asset.storageKeyId) {
await this.prismaClient.storageKey
.delete({ where: { id: asset.storageKeyId } })
.catch(() => {})
}
const t = await this.prismaClient.task.findUnique({ where: { id: taskId } })
if (t) {
const updatedTask = await this.prismaClient.task.update({
@@ -373,6 +403,141 @@ export class UploadService {
return { data: infos, pageInfo }
}
async signS3Upload(teamId: string, userId: string, req: S3SignRequest): Promise<S3SignResponse> {
const bucket = process.env.S3_BUCKET || 'shumai'
const asset = await this.prismaClient.asset.findUnique({
where: { id: req.fileId },
include: {
storageKey: true,
project: true,
},
})
if (!asset) {
throw new Error('Asset not found')
}
if (asset.status !== AssetStatus.uploading) {
throw new Error('Asset is not currently uploading')
}
if (asset.project?.teamId !== teamId) {
throw new Error('Asset does not belong to team')
}
const key = asset.storageKey?.key
if (!key) {
throw new Error('Asset has no storage key')
}
if (req.key && req.key !== key) {
throw new Error('Requested key does not match asset storage key')
}
if (req.method === 'GET' || req.method === 'DELETE') {
if (!req.uploadId) {
throw new Error('Operation requires uploadId')
}
}
if (req.uploadId) {
if (asset.uploadId && asset.uploadId !== req.uploadId) {
throw new Error('Upload ID does not match asset upload ID')
}
if (!asset.uploadId) {
await this.prismaClient.asset.update({
where: { id: asset.id },
data: { uploadId: req.uploadId },
})
}
}
const result = await s3Service.presignMultipart(bucket, key, req)
return { url: result.url }
}
async abortUpload(
teamId: string,
userId: string,
taskId: string,
req: AbortUploadRequest,
): Promise<AbortUploadResponse> {
const bucket = process.env.S3_BUCKET || 'shumai'
const asset = await this.prismaClient.asset.findUnique({
where: { id: req.fileId },
include: {
storageKey: true,
project: true,
},
})
if (!asset) {
return { success: true }
}
if (asset.status !== AssetStatus.uploading) {
throw new Error('Asset is not currently uploading')
}
if (asset.taskId !== taskId) {
throw new Error('Asset does not belong to specified task')
}
if (asset.project?.teamId !== teamId) {
throw new Error('Asset does not belong to specified team')
}
const key = asset.storageKey?.key
if (req.key && key && req.key !== key) {
throw new Error('Provided key does not match asset storage key')
}
const uploadId = asset.uploadId || req.uploadId
if (asset.uploadId && req.uploadId && asset.uploadId !== req.uploadId) {
throw new Error('Provided uploadId does not match asset uploadId')
}
if (uploadId && key) {
try {
await s3Service.abortMultipartUpload(bucket, key, uploadId)
} catch (err) {
logger.warn({ err, key, uploadId }, 'Failed to abort multipart upload in S3')
}
} else if (key) {
try {
await s3Service.deleteObject(bucket, key)
} catch (err) {
logger.warn({ err, key }, 'Failed to delete object from storage')
}
}
await this.prismaClient.asset.delete({ where: { id: asset.id } }).catch((err) => {
logger.warn({ err, assetId: asset.id }, 'Failed to delete asset on upload abort')
})
if (asset.storageKeyId) {
await this.prismaClient.storageKey
.delete({ where: { id: asset.storageKeyId } })
.catch(() => {})
}
if (taskId) {
const remaining = await this.prismaClient.asset.count({
where: { taskId, status: AssetStatus.uploading },
})
if (remaining === 0) {
await this.prismaClient.task
.update({
where: { id: taskId },
data: { status: TaskStatus.failed },
})
.catch(() => {})
}
}
return { success: true }
}
}
export const uploadService = new UploadService()
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "assets" ADD COLUMN "upload_id" TEXT;
+1
View File
@@ -522,6 +522,7 @@ model Asset {
sizeByte BigInt @default(0) @map("size_byte")
status AssetStatus
transcodeTaskId String? @map("transcode_task_id")
uploadId String? @map("upload_id")
/// [MediaInfo]
media Json?
isDeleted Boolean @default(false) @map("is_deleted")
File diff suppressed because one or more lines are too long
@@ -4501,6 +4501,7 @@ export const AssetScalarFieldEnum = {
sizeByte: 'sizeByte',
status: 'status',
transcodeTaskId: 'transcodeTaskId',
uploadId: 'uploadId',
media: 'media',
isDeleted: 'isDeleted',
deletedAt: 'deletedAt',
@@ -341,6 +341,7 @@ export const AssetScalarFieldEnum = {
sizeByte: 'sizeByte',
status: 'status',
transcodeTaskId: 'transcodeTaskId',
uploadId: 'uploadId',
media: 'media',
isDeleted: 'isDeleted',
deletedAt: 'deletedAt',
+140 -1
View File
@@ -47,6 +47,7 @@ export type AssetMinAggregateOutputType = {
sizeByte: bigint | null
status: $Enums.AssetStatus | null
transcodeTaskId: string | null
uploadId: string | null
isDeleted: boolean | null
deletedAt: Date | null
sortIndex: string | null
@@ -70,6 +71,7 @@ export type AssetMaxAggregateOutputType = {
sizeByte: bigint | null
status: $Enums.AssetStatus | null
transcodeTaskId: string | null
uploadId: string | null
isDeleted: boolean | null
deletedAt: Date | null
sortIndex: string | null
@@ -94,6 +96,7 @@ export type AssetCountAggregateOutputType = {
sizeByte: number
status: number
transcodeTaskId: number
uploadId: number
media: number
isDeleted: number
deletedAt: number
@@ -130,6 +133,7 @@ export type AssetMinAggregateInputType = {
sizeByte?: true
status?: true
transcodeTaskId?: true
uploadId?: true
isDeleted?: true
deletedAt?: true
sortIndex?: true
@@ -153,6 +157,7 @@ export type AssetMaxAggregateInputType = {
sizeByte?: true
status?: true
transcodeTaskId?: true
uploadId?: true
isDeleted?: true
deletedAt?: true
sortIndex?: true
@@ -177,6 +182,7 @@ export type AssetCountAggregateInputType = {
sizeByte?: true
status?: true
transcodeTaskId?: true
uploadId?: true
media?: true
isDeleted?: true
deletedAt?: true
@@ -289,6 +295,7 @@ export type AssetGroupByOutputType = {
sizeByte: bigint
status: $Enums.AssetStatus
transcodeTaskId: string | null
uploadId: string | null
media:PrismaJson.MediaInfo | null
isDeleted: boolean
deletedAt: Date | null
@@ -337,6 +344,7 @@ export type AssetWhereInput = {
sizeByte?: Prisma.BigIntFilter<"Asset"> | bigint | number
status?: Prisma.EnumAssetStatusFilter<"Asset"> | $Enums.AssetStatus
transcodeTaskId?: Prisma.StringNullableFilter<"Asset"> | string | null
uploadId?: Prisma.StringNullableFilter<"Asset"> | string | null
media?: Prisma.JsonNullableFilter<"Asset">
isDeleted?: Prisma.BoolFilter<"Asset"> | boolean
deletedAt?: Prisma.DateTimeNullableFilter<"Asset"> | Date | string | null
@@ -386,6 +394,7 @@ export type AssetOrderByWithRelationInput = {
sizeByte?: Prisma.SortOrder
status?: Prisma.SortOrder
transcodeTaskId?: Prisma.SortOrderInput | Prisma.SortOrder
uploadId?: Prisma.SortOrderInput | Prisma.SortOrder
media?: Prisma.SortOrderInput | Prisma.SortOrder
isDeleted?: Prisma.SortOrder
deletedAt?: Prisma.SortOrderInput | Prisma.SortOrder
@@ -439,6 +448,7 @@ export type AssetWhereUniqueInput = Prisma.AtLeast<{
sizeByte?: Prisma.BigIntFilter<"Asset"> | bigint | number
status?: Prisma.EnumAssetStatusFilter<"Asset"> | $Enums.AssetStatus
transcodeTaskId?: Prisma.StringNullableFilter<"Asset"> | string | null
uploadId?: Prisma.StringNullableFilter<"Asset"> | string | null
media?: Prisma.JsonNullableFilter<"Asset">
isDeleted?: Prisma.BoolFilter<"Asset"> | boolean
deletedAt?: Prisma.DateTimeNullableFilter<"Asset"> | Date | string | null
@@ -488,6 +498,7 @@ export type AssetOrderByWithAggregationInput = {
sizeByte?: Prisma.SortOrder
status?: Prisma.SortOrder
transcodeTaskId?: Prisma.SortOrderInput | Prisma.SortOrder
uploadId?: Prisma.SortOrderInput | Prisma.SortOrder
media?: Prisma.SortOrderInput | Prisma.SortOrder
isDeleted?: Prisma.SortOrder
deletedAt?: Prisma.SortOrderInput | Prisma.SortOrder
@@ -521,6 +532,7 @@ export type AssetScalarWhereWithAggregatesInput = {
sizeByte?: Prisma.BigIntWithAggregatesFilter<"Asset"> | bigint | number
status?: Prisma.EnumAssetStatusWithAggregatesFilter<"Asset"> | $Enums.AssetStatus
transcodeTaskId?: Prisma.StringNullableWithAggregatesFilter<"Asset"> | string | null
uploadId?: Prisma.StringNullableWithAggregatesFilter<"Asset"> | string | null
media?: Prisma.JsonNullableWithAggregatesFilter<"Asset">
isDeleted?: Prisma.BoolWithAggregatesFilter<"Asset"> | boolean
deletedAt?: Prisma.DateTimeNullableWithAggregatesFilter<"Asset"> | Date | string | null
@@ -546,6 +558,7 @@ export type AssetCreateInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -588,6 +601,7 @@ export type AssetUncheckedCreateInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -630,6 +644,7 @@ export type AssetUpdateInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -672,6 +687,7 @@ export type AssetUncheckedUpdateInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -714,6 +730,7 @@ export type AssetCreateManyInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -739,6 +756,7 @@ export type AssetUpdateManyMutationInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -757,6 +775,7 @@ export type AssetUncheckedUpdateManyInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -807,6 +826,7 @@ export type AssetCountOrderByAggregateInput = {
sizeByte?: Prisma.SortOrder
status?: Prisma.SortOrder
transcodeTaskId?: Prisma.SortOrder
uploadId?: Prisma.SortOrder
media?: Prisma.SortOrder
isDeleted?: Prisma.SortOrder
deletedAt?: Prisma.SortOrder
@@ -836,6 +856,7 @@ export type AssetMaxOrderByAggregateInput = {
sizeByte?: Prisma.SortOrder
status?: Prisma.SortOrder
transcodeTaskId?: Prisma.SortOrder
uploadId?: Prisma.SortOrder
isDeleted?: Prisma.SortOrder
deletedAt?: Prisma.SortOrder
sortIndex?: Prisma.SortOrder
@@ -859,6 +880,7 @@ export type AssetMinOrderByAggregateInput = {
sizeByte?: Prisma.SortOrder
status?: Prisma.SortOrder
transcodeTaskId?: Prisma.SortOrder
uploadId?: Prisma.SortOrder
isDeleted?: Prisma.SortOrder
deletedAt?: Prisma.SortOrder
sortIndex?: Prisma.SortOrder
@@ -1469,6 +1491,7 @@ export type AssetCreateWithoutCreatorInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1510,6 +1533,7 @@ export type AssetUncheckedCreateWithoutCreatorInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1580,6 +1604,7 @@ export type AssetScalarWhereInput = {
sizeByte?: Prisma.BigIntFilter<"Asset"> | bigint | number
status?: Prisma.EnumAssetStatusFilter<"Asset"> | $Enums.AssetStatus
transcodeTaskId?: Prisma.StringNullableFilter<"Asset"> | string | null
uploadId?: Prisma.StringNullableFilter<"Asset"> | string | null
media?: Prisma.JsonNullableFilter<"Asset">
isDeleted?: Prisma.BoolFilter<"Asset"> | boolean
deletedAt?: Prisma.DateTimeNullableFilter<"Asset"> | Date | string | null
@@ -1605,6 +1630,7 @@ export type AssetCreateWithoutTeamRootFolderInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1646,6 +1672,7 @@ export type AssetUncheckedCreateWithoutTeamRootFolderInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1703,6 +1730,7 @@ export type AssetUpdateWithoutTeamRootFolderInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -1744,6 +1772,7 @@ export type AssetUncheckedUpdateWithoutTeamRootFolderInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -1785,6 +1814,7 @@ export type AssetCreateWithoutProjectRootFolderInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1826,6 +1856,7 @@ export type AssetUncheckedCreateWithoutProjectRootFolderInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1872,6 +1903,7 @@ export type AssetCreateWithoutProjectShareRootInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1913,6 +1945,7 @@ export type AssetUncheckedCreateWithoutProjectShareRootInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -1959,6 +1992,7 @@ export type AssetCreateWithoutProjectInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2000,6 +2034,7 @@ export type AssetUncheckedCreateWithoutProjectInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2062,6 +2097,7 @@ export type AssetUpdateWithoutProjectRootFolderInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2103,6 +2139,7 @@ export type AssetUncheckedUpdateWithoutProjectRootFolderInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2155,6 +2192,7 @@ export type AssetUpdateWithoutProjectShareRootInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2196,6 +2234,7 @@ export type AssetUncheckedUpdateWithoutProjectShareRootInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2253,6 +2292,7 @@ export type AssetCreateWithoutShareLinkRootFolderInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2294,6 +2334,7 @@ export type AssetUncheckedCreateWithoutShareLinkRootFolderInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2351,6 +2392,7 @@ export type AssetUpdateWithoutShareLinkRootFolderInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2392,6 +2434,7 @@ export type AssetUncheckedUpdateWithoutShareLinkRootFolderInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2433,6 +2476,7 @@ export type AssetCreateWithoutWatermarkFilesInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2474,6 +2518,7 @@ export type AssetUncheckedCreateWithoutWatermarkFilesInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2531,6 +2576,7 @@ export type AssetUpdateWithoutWatermarkFilesInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2572,6 +2618,7 @@ export type AssetUncheckedUpdateWithoutWatermarkFilesInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -2613,6 +2660,7 @@ export type AssetCreateWithoutChildrenInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2654,6 +2702,7 @@ export type AssetUncheckedCreateWithoutChildrenInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2700,6 +2749,7 @@ export type AssetCreateWithoutParentInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2741,6 +2791,7 @@ export type AssetUncheckedCreateWithoutParentInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2792,6 +2843,7 @@ export type AssetCreateWithoutSymlinksInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2833,6 +2885,7 @@ export type AssetUncheckedCreateWithoutSymlinksInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2879,6 +2932,7 @@ export type AssetCreateWithoutTargetInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2920,6 +2974,7 @@ export type AssetUncheckedCreateWithoutTargetInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -2982,6 +3037,7 @@ export type AssetUpdateWithoutChildrenInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3023,6 +3079,7 @@ export type AssetUncheckedUpdateWithoutChildrenInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3091,6 +3148,7 @@ export type AssetUpdateWithoutSymlinksInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3132,6 +3190,7 @@ export type AssetUncheckedUpdateWithoutSymlinksInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3189,6 +3248,7 @@ export type AssetCreateWithoutStorageKeyInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3230,6 +3290,7 @@ export type AssetUncheckedCreateWithoutStorageKeyInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3297,6 +3358,7 @@ export type AssetCreateWithoutMetadataValuesInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3338,6 +3400,7 @@ export type AssetUncheckedCreateWithoutMetadataValuesInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3395,6 +3458,7 @@ export type AssetUpdateWithoutMetadataValuesInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3436,6 +3500,7 @@ export type AssetUncheckedUpdateWithoutMetadataValuesInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3477,6 +3542,7 @@ export type AssetCreateWithoutAgentMdInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3518,6 +3584,7 @@ export type AssetUncheckedCreateWithoutAgentMdInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3575,6 +3642,7 @@ export type AssetUpdateWithoutAgentMdInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3616,6 +3684,7 @@ export type AssetUncheckedUpdateWithoutAgentMdInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3657,6 +3726,7 @@ export type AssetCreateWithoutCommentsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3698,6 +3768,7 @@ export type AssetUncheckedCreateWithoutCommentsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3755,6 +3826,7 @@ export type AssetUpdateWithoutCommentsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3796,6 +3868,7 @@ export type AssetUncheckedUpdateWithoutCommentsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3837,6 +3910,7 @@ export type AssetCreateWithoutCommentAttachmentsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3878,6 +3952,7 @@ export type AssetUncheckedCreateWithoutCommentAttachmentsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -3935,6 +4010,7 @@ export type AssetUpdateWithoutCommentAttachmentsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -3976,6 +4052,7 @@ export type AssetUncheckedUpdateWithoutCommentAttachmentsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4017,6 +4094,7 @@ export type AssetCreateWithoutEmbeddingsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4058,6 +4136,7 @@ export type AssetUncheckedCreateWithoutEmbeddingsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4115,6 +4194,7 @@ export type AssetUpdateWithoutEmbeddingsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4156,6 +4236,7 @@ export type AssetUncheckedUpdateWithoutEmbeddingsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4197,6 +4278,7 @@ export type AssetCreateWithoutNotificationsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4238,6 +4320,7 @@ export type AssetUncheckedCreateWithoutNotificationsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4295,6 +4378,7 @@ export type AssetUpdateWithoutNotificationsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4336,6 +4420,7 @@ export type AssetUncheckedUpdateWithoutNotificationsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4377,6 +4462,7 @@ export type AssetCreateWithoutTaskInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4418,6 +4504,7 @@ export type AssetUncheckedCreateWithoutTaskInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4485,6 +4572,7 @@ export type AssetCreateWithoutAgentInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4526,6 +4614,7 @@ export type AssetUncheckedCreateWithoutAgentInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4593,6 +4682,7 @@ export type AssetCreateWithoutAgentSessionsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4634,6 +4724,7 @@ export type AssetUncheckedCreateWithoutAgentSessionsInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4691,6 +4782,7 @@ export type AssetUpdateWithoutAgentSessionsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4732,6 +4824,7 @@ export type AssetUncheckedUpdateWithoutAgentSessionsInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4773,6 +4866,7 @@ export type AssetCreateWithoutKanbanTargetTasksInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4814,6 +4908,7 @@ export type AssetUncheckedCreateWithoutKanbanTargetTasksInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4871,6 +4966,7 @@ export type AssetUpdateWithoutKanbanTargetTasksInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4912,6 +5008,7 @@ export type AssetUncheckedUpdateWithoutKanbanTargetTasksInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -4953,6 +5050,7 @@ export type AssetCreateWithoutKanbanTasksInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -4994,6 +5092,7 @@ export type AssetUncheckedCreateWithoutKanbanTasksInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5051,6 +5150,7 @@ export type AssetUpdateWithoutKanbanTasksInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5092,6 +5192,7 @@ export type AssetUncheckedUpdateWithoutKanbanTasksInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5133,6 +5234,7 @@ export type AssetCreateWithoutRecentFilesInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5174,6 +5276,7 @@ export type AssetUncheckedCreateWithoutRecentFilesInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5231,6 +5334,7 @@ export type AssetUpdateWithoutRecentFilesInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5272,6 +5376,7 @@ export type AssetUncheckedUpdateWithoutRecentFilesInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5313,6 +5418,7 @@ export type AssetCreateManyCreatorInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5337,6 +5443,7 @@ export type AssetUpdateWithoutCreatorInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5378,6 +5485,7 @@ export type AssetUncheckedUpdateWithoutCreatorInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5419,6 +5527,7 @@ export type AssetUncheckedUpdateManyWithoutCreatorInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5443,6 +5552,7 @@ export type AssetCreateManyProjectInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5467,6 +5577,7 @@ export type AssetUpdateWithoutProjectInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5508,6 +5619,7 @@ export type AssetUncheckedUpdateWithoutProjectInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5549,6 +5661,7 @@ export type AssetUncheckedUpdateManyWithoutProjectInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5573,6 +5686,7 @@ export type AssetCreateManyParentInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5597,6 +5711,7 @@ export type AssetCreateManyTargetInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5621,6 +5736,7 @@ export type AssetUpdateWithoutParentInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5662,6 +5778,7 @@ export type AssetUncheckedUpdateWithoutParentInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5703,6 +5820,7 @@ export type AssetUncheckedUpdateManyWithoutParentInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5727,6 +5845,7 @@ export type AssetUpdateWithoutTargetInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5768,6 +5887,7 @@ export type AssetUncheckedUpdateWithoutTargetInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5809,6 +5929,7 @@ export type AssetUncheckedUpdateManyWithoutTargetInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5833,6 +5954,7 @@ export type AssetCreateManyStorageKeyInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5857,6 +5979,7 @@ export type AssetUpdateWithoutStorageKeyInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5898,6 +6021,7 @@ export type AssetUncheckedUpdateWithoutStorageKeyInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5939,6 +6063,7 @@ export type AssetUncheckedUpdateManyWithoutStorageKeyInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -5963,6 +6088,7 @@ export type AssetCreateManyTaskInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -5987,6 +6113,7 @@ export type AssetUpdateWithoutTaskInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -6028,6 +6155,7 @@ export type AssetUncheckedUpdateWithoutTaskInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -6069,6 +6197,7 @@ export type AssetUncheckedUpdateManyWithoutTaskInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -6093,6 +6222,7 @@ export type AssetCreateManyAgentInput = {
sizeByte?: bigint | number
status: $Enums.AssetStatus
transcodeTaskId?: string | null
uploadId?: string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: boolean
deletedAt?: Date | string | null
@@ -6117,6 +6247,7 @@ export type AssetUpdateWithoutAgentInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -6158,6 +6289,7 @@ export type AssetUncheckedUpdateWithoutAgentInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -6199,6 +6331,7 @@ export type AssetUncheckedUpdateManyWithoutAgentInput = {
sizeByte?: Prisma.BigIntFieldUpdateOperationsInput | bigint | number
status?: Prisma.EnumAssetStatusFieldUpdateOperationsInput | $Enums.AssetStatus
transcodeTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
uploadId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
media?:PrismaJson.MediaInfo | Prisma.NullableJsonNullValueInput
isDeleted?: Prisma.BoolFieldUpdateOperationsInput | boolean
deletedAt?: Prisma.NullableDateTimeFieldUpdateOperationsInput | Date | string | null
@@ -6353,6 +6486,7 @@ export type AssetSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs =
sizeByte?: boolean
status?: boolean
transcodeTaskId?: boolean
uploadId?: boolean
media?: boolean
isDeleted?: boolean
deletedAt?: boolean
@@ -6403,6 +6537,7 @@ export type AssetSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensi
sizeByte?: boolean
status?: boolean
transcodeTaskId?: boolean
uploadId?: boolean
media?: boolean
isDeleted?: boolean
deletedAt?: boolean
@@ -6435,6 +6570,7 @@ export type AssetSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensi
sizeByte?: boolean
status?: boolean
transcodeTaskId?: boolean
uploadId?: boolean
media?: boolean
isDeleted?: boolean
deletedAt?: boolean
@@ -6467,6 +6603,7 @@ export type AssetSelectScalar = {
sizeByte?: boolean
status?: boolean
transcodeTaskId?: boolean
uploadId?: boolean
media?: boolean
isDeleted?: boolean
deletedAt?: boolean
@@ -6482,7 +6619,7 @@ export type AssetSelectScalar = {
projectId?: boolean
}
export type AssetOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "name" | "nameNgram" | "type" | "mediaType" | "fileCount" | "sizeByte" | "status" | "transcodeTaskId" | "media" | "isDeleted" | "deletedAt" | "sortIndex" | "createdAt" | "updatedAt" | "parentId" | "targetId" | "storageKeyId" | "creatorId" | "agentId" | "taskId" | "projectId", ExtArgs["result"]["asset"]>
export type AssetOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "name" | "nameNgram" | "type" | "mediaType" | "fileCount" | "sizeByte" | "status" | "transcodeTaskId" | "uploadId" | "media" | "isDeleted" | "deletedAt" | "sortIndex" | "createdAt" | "updatedAt" | "parentId" | "targetId" | "storageKeyId" | "creatorId" | "agentId" | "taskId" | "projectId", ExtArgs["result"]["asset"]>
export type AssetInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
parent?: boolean | Prisma.Asset$parentArgs<ExtArgs>
children?: boolean | Prisma.Asset$childrenArgs<ExtArgs>
@@ -6567,6 +6704,7 @@ export type $AssetPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs
sizeByte: bigint
status: $Enums.AssetStatus
transcodeTaskId: string | null
uploadId: string | null
/**
* [MediaInfo]
*/
@@ -7039,6 +7177,7 @@ export interface AssetFieldRefs {
readonly sizeByte: Prisma.FieldRef<"Asset", 'BigInt'>
readonly status: Prisma.FieldRef<"Asset", 'AssetStatus'>
readonly transcodeTaskId: Prisma.FieldRef<"Asset", 'String'>
readonly uploadId: Prisma.FieldRef<"Asset", 'String'>
readonly media: Prisma.FieldRef<"Asset", 'Json'>
readonly isDeleted: Prisma.FieldRef<"Asset", 'Boolean'>
readonly deletedAt: Prisma.FieldRef<"Asset", 'DateTime'>
+28
View File
@@ -36,17 +36,45 @@ export type PresignedUrl = z.infer<typeof presignedUrlSchema>
export const createUploadTaskResponseSchema = z.object({
taskId: z.string(),
presignedUrls: z.array(presignedUrlSchema),
storageBackend: z.enum(['s3', 'local']).default('local'),
createdAssets: z
.array(
z.object({
tempId: z.string(),
assetId: z.string(),
key: z.string().optional(),
}),
)
.optional(),
})
export type CreateUploadTaskResponse = z.infer<typeof createUploadTaskResponseSchema>
export const s3SignRequestSchema = z.object({
key: z.string().min(1),
method: z.enum(['PUT', 'POST', 'GET', 'DELETE']),
uploadId: z.string().optional(),
partNumber: z.number().int().positive().optional(),
fileId: z.string().min(1),
})
export type S3SignRequest = z.infer<typeof s3SignRequestSchema>
export const s3SignResponseSchema = z.object({
url: z.string(),
})
export type S3SignResponse = z.infer<typeof s3SignResponseSchema>
export const abortUploadRequestSchema = z.object({
fileId: z.string().min(1),
uploadId: z.string().optional(),
key: z.string().optional(),
})
export type AbortUploadRequest = z.infer<typeof abortUploadRequestSchema>
export const abortUploadResponseSchema = z.object({
success: z.boolean(),
})
export type AbortUploadResponse = z.infer<typeof abortUploadResponseSchema>
export const confirmFileUploadRequestSchema = z.object({
fileId: z.string(),
errorMessage: z.string().optional(),
@@ -8,11 +8,11 @@ import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
import { formatSize } from '@/ui/lib/format'
import { useFieldStore } from '@/ui/stores/fields'
import { useUploadStore } from '@/ui/stores/upload'
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
import type {
AssetInfo,
CollectionInfo,
CreateUploadTaskRequest,
PresignedUrl,
SearchCondition,
SearchSort,
ShareLinkInfo,
@@ -461,19 +461,6 @@ export function FileBrowser({
},
})
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
const { mutateAsync: confirmUpload } = useMutation<
InferResponseType<typeof $confirmUpload>,
Error,
InferRequestType<typeof $confirmUpload>
>({
mutationFn: async (request) => {
const res = await $confirmUpload(request)
if (!res.ok) throw new Error('Failed to confirm upload')
return (await res.json()) as InferResponseType<typeof $confirmUpload>
},
})
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
const { mutate: createUploadTaskMutation } = useMutation<
InferResponseType<typeof $createUploadTask>,
@@ -496,11 +483,12 @@ export function FileBrowser({
// Register task and files in the store for real-time progress tracking
const filesProgressInfo = currentFiles
.map((f) => {
const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id)
const urlInfo = (
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
)?.find((p) => p.id === f.id)
return {
fileId: urlInfo?.fileId || f.id,
fileId: assetInfo?.assetId || urlInfo?.fileId || f.id,
name: f.file.name,
size: f.file.size,
}
@@ -522,12 +510,14 @@ export function FileBrowser({
return path.length === 1
})
.map((f) => {
const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id)
const urlInfo = (
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
)?.find((p) => p.id === f.id)
const fileId = assetInfo?.assetId || urlInfo?.fileId || f.id
const hasUrl = !!urlInfo && !!urlInfo.url
return {
id: urlInfo?.fileId || f.id,
id: fileId,
name: f.file.name,
sizeByte: f.file.size,
fileCount: 0,
@@ -564,7 +554,20 @@ export function FileBrowser({
queryKey: ['teams', teamId, 'upload', 'tasks'],
})
await uploadFiles(currentFiles, data.presignedUrls, data.taskId!)
await uploadFilesWithUppy({
files: currentFiles,
taskId: data.taskId!,
teamId: teamId!,
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
createdAssets: data.createdAssets,
presignedUrls: data.presignedUrls,
onFileFinished: async (fileId) => {
await queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
setLocalUploadingFiles((prev) => prev.filter((f) => f.id !== fileId))
},
})
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
@@ -574,12 +577,7 @@ export function FileBrowser({
},
})
const incrementUploading = useUploadStore((state) => state.increment)
const decrementUploading = useUploadStore((state) => state.decrement)
const startTask = useUploadStore((state) => state.startTask)
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
const completeFile = useUploadStore((state) => state.completeFile)
const failFile = useUploadStore((state) => state.failFile)
const { fields } = useFieldStore()
const displayedFields = useMemo(() => {
if (!isShareView) return fields.filter((f) => f.visible)
@@ -737,123 +735,6 @@ export function FileBrowser({
folderInputRef.current?.click()
}
const uploadFiles = async (
files: FileWithId[],
presignedUrls: PresignedUrl[] | undefined,
taskId: string,
) => {
const uploadUrlMap = presignedUrls?.reduce(
(acc: Record<string, { url: string; fileId: string }>, item: PresignedUrl) => {
if (item.id) {
acc[item.id] = {
url: item.url || '',
fileId: item.fileId || '',
}
}
return acc
},
{},
)
if (!uploadUrlMap) return
const concurrencyLimit = 5
const filesToUpload = [...files]
const uploadNext = async () => {
while (filesToUpload.length > 0) {
const file = filesToUpload.shift()
if (file) {
const uploadInfo = uploadUrlMap[file.id]
if (uploadInfo && uploadInfo.url) {
incrementUploading()
try {
try {
const xhr = new XMLHttpRequest()
const uploadPromise = new Promise<{ ok: boolean; status: number }>(
(resolve, reject) => {
xhr.open('PUT', uploadInfo.url)
xhr.setRequestHeader('Content-Type', file.file.type)
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
}
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({ ok: true, status: xhr.status })
} else {
resolve({ ok: false, status: xhr.status })
}
}
xhr.onerror = () => {
reject(new Error('Network error'))
}
xhr.onabort = () => {
reject(new Error('Upload aborted'))
}
xhr.send(file.file)
},
)
const resp = await uploadPromise
if (resp.ok) {
completeFile(taskId, uploadInfo.fileId)
await confirmUpload({
param: { teamId: teamId!, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
},
})
} else {
failFile(taskId, uploadInfo.fileId)
toast.error(`Failed to upload file: ${file.file.name}`)
await confirmUpload({
param: { teamId: teamId!, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
errorMessage: `upload failed with status: ${resp.status}`,
},
})
return
}
} catch (error) {
failFile(taskId, uploadInfo.fileId)
toast.error(`Failed to upload file: ${file.file.name}`)
await confirmUpload({
param: { teamId: teamId!, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
},
})
return
}
} finally {
decrementUploading()
await queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
setLocalUploadingFiles((prev) =>
prev.filter((f) => f.id !== uploadInfo.fileId && f.id !== file.id),
)
}
}
}
}
}
const activeUploaders = Array(concurrencyLimit)
.fill(null)
.map(() => uploadNext())
await Promise.all(activeUploaders)
}
const processAndUploadFiles = useCallback(
(files: FileList | File[], overrideParentId?: string) => {
if (!files || files.length === 0) return
@@ -347,10 +347,10 @@ describe('MobileFileBrowser', () => {
expect(patchMock).toHaveBeenCalledWith(
expect.objectContaining({
param: { teamId: 'team-1', taskId: 'task-2' },
json: {
json: expect.objectContaining({
fileId: 'server-file-2',
errorMessage: 'upload failed with status: 500',
},
errorMessage: expect.any(String),
}),
}),
)
})
@@ -412,10 +412,10 @@ describe('MobileFileBrowser', () => {
expect(patchMock).toHaveBeenCalledWith(
expect.objectContaining({
param: { teamId: 'team-1', taskId: 'task-3' },
json: {
json: expect.objectContaining({
fileId: 'server-file-3',
errorMessage: 'upload failed with error: Network error',
},
errorMessage: expect.any(String),
}),
}),
)
})
@@ -4,7 +4,8 @@ import { client } from '@/ui/api/client'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { m } from '@/ui/paraglide/messages.js'
import { useUploadStore } from '@/ui/stores/upload'
import type { AssetInfo, CreateUploadTaskRequest, PresignedUrl } from '@shumai/dtos'
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
import type { AssetInfo, CreateUploadTaskRequest } from '@shumai/dtos'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { formatSize } from '@/ui/lib/format'
@@ -197,130 +198,7 @@ export function MobileFileBrowser({
])
// Upload actions
const incrementUploading = useUploadStore((state) => state.increment)
const decrementUploading = useUploadStore((state) => state.decrement)
const startTask = useUploadStore((state) => state.startTask)
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
const completeFile = useUploadStore((state) => state.completeFile)
const failFile = useUploadStore((state) => state.failFile)
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
const { mutateAsync: confirmUpload } = useMutation<
InferResponseType<typeof $confirmUpload>,
Error,
InferRequestType<typeof $confirmUpload>
>({
mutationFn: async (request) => {
const res = await $confirmUpload(request)
if (!res.ok) throw new Error('Failed to confirm upload')
return (await res.json()) as InferResponseType<typeof $confirmUpload>
},
})
const uploadFiles = async (
filesList: FileWithId[],
presignedUrls: PresignedUrl[] | undefined,
taskId: string,
) => {
const uploadUrlMap = presignedUrls?.reduce(
(acc: Record<string, { url: string; fileId: string }>, item: PresignedUrl) => {
if (item.id) {
acc[item.id] = {
url: item.url || '',
fileId: item.fileId || '',
}
}
return acc
},
{},
)
if (!uploadUrlMap) return
const concurrencyLimit = 5
const queue = [...filesList]
const uploadNext = async () => {
while (queue.length > 0) {
const item = queue.shift()
if (item) {
const uploadInfo = uploadUrlMap[item.id]
if (uploadInfo && uploadInfo.url) {
incrementUploading()
try {
const xhr = new XMLHttpRequest()
const uploadPromise = new Promise<{ ok: boolean; status: number }>(
(resolve, reject) => {
xhr.open('PUT', uploadInfo.url)
xhr.setRequestHeader('Content-Type', item.file.type)
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
}
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({ ok: true, status: xhr.status })
} else {
resolve({ ok: false, status: xhr.status })
}
}
xhr.onerror = () => reject(new Error('Network error'))
xhr.onabort = () => reject(new Error('Upload aborted'))
xhr.send(item.file)
},
)
const resp = await uploadPromise
if (resp.ok) {
completeFile(taskId, uploadInfo.fileId)
await confirmUpload({
param: { teamId: teamId!, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
},
})
} else {
failFile(taskId, uploadInfo.fileId)
toast.error(`Failed to upload file: ${item.file.name}`)
await confirmUpload({
param: { teamId: teamId!, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
errorMessage: `upload failed with status: ${resp.status}`,
},
})
return
}
} catch (error) {
failFile(taskId, uploadInfo.fileId)
toast.error(`Failed to upload file: ${item.file.name}`)
await confirmUpload({
param: { teamId: teamId!, taskId: taskId },
json: {
fileId: uploadInfo.fileId,
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
},
})
return
} finally {
decrementUploading()
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
}
}
}
}
}
const activeUploaders = Array(concurrencyLimit)
.fill(null)
.map(() => uploadNext())
await Promise.all(activeUploaders)
}
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
const { mutate: createUploadTaskMutation } = useMutation<
@@ -341,9 +219,10 @@ export function MobileFileBrowser({
const currentFiles = context?.files || []
const filesProgressInfo = currentFiles
.map((f) => {
const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id)
const urlInfo = data.presignedUrls?.find((p) => p.id === f.id)
return {
fileId: urlInfo?.fileId || f.id,
fileId: assetInfo?.assetId || urlInfo?.fileId || f.id,
name: f.file.name,
size: f.file.size,
}
@@ -361,7 +240,17 @@ export function MobileFileBrowser({
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
await uploadFiles(currentFiles, data.presignedUrls, data.taskId!)
await uploadFilesWithUppy({
files: currentFiles,
taskId: data.taskId!,
teamId: teamId!,
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
createdAssets: data.createdAssets,
presignedUrls: data.presignedUrls,
onFileFinished: async () => {
await queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
},
})
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
},
+323
View File
@@ -0,0 +1,323 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { activeUploads, uploadFilesWithUppy, isNetworkIssue } from './uploader'
import { acquireWakeLock, releaseWakeLock } from './wake-lock'
import { useUploadStore } from '@/ui/stores/upload'
vi.mock('sonner', () => ({
toast: {
error: vi.fn(),
success: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
dismiss: vi.fn(),
},
}))
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
upload: {
tasks: {
':taskId': {
$patch: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }),
},
},
},
},
},
},
},
}))
import { Uppy, type Meta, type UppyFile } from '@uppy/core'
import { client } from '@/ui/api/client'
import { toast } from 'sonner'
describe('Uploader', () => {
beforeEach(() => {
vi.clearAllMocks()
activeUploads.clear()
useUploadStore.setState({ uploading: 0, tasks: {}, fileProgress: {} })
})
it('manages activeUploads and sends beacon on pagehide', () => {
activeUploads.set('file-1', {
teamId: 'team-1',
taskId: 'task-1',
fileId: 'file-1',
key: 'files/test.mp4',
uploadId: 'up-123',
})
const sendBeaconSpy = vi.fn().mockReturnValue(true)
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconSpy,
configurable: true,
writable: true,
})
window.dispatchEvent(new Event('pagehide'))
expect(sendBeaconSpy).toHaveBeenCalledWith(
'/api/teams/team-1/upload/tasks/task-1/abort',
expect.any(Blob),
)
expect(activeUploads.size).toBe(0)
})
it('acquires and releases wake lock', async () => {
const releaseSpy = vi.fn().mockResolvedValue(undefined)
const requestSpy = vi.fn().mockResolvedValue({
release: releaseSpy,
addEventListener: vi.fn(),
})
Object.defineProperty(navigator, 'wakeLock', {
value: { request: requestSpy },
configurable: true,
writable: true,
})
await acquireWakeLock()
expect(requestSpy).toHaveBeenCalledWith('screen')
await releaseWakeLock()
expect(releaseSpy).toHaveBeenCalled()
})
it('runs uploadFilesWithUppy with empty files without error', async () => {
await expect(
uploadFilesWithUppy({
files: [],
taskId: 'task-1',
teamId: 'team-1',
storageBackend: 's3',
}),
).resolves.toBeUndefined()
})
it('awaits confirmation patch before uploadFilesWithUppy resolves', async () => {
useUploadStore
.getState()
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
let patchResolved = false
vi.mocked(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).mockImplementationOnce(
async () => {
await new Promise((r) => setTimeout(r, 30))
patchResolved = true
return { ok: true, json: async () => ({}) } as unknown as Awaited<
ReturnType<(typeof client.api.teams)[':teamId']['upload']['tasks'][':taskId']['$patch']>
>
},
)
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
const uploadPromise = uploadFilesWithUppy({
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
taskId: 'task-1',
teamId: 'team-1',
storageBackend: 's3',
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
})
await new Promise((r) => setTimeout(r, 10))
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
expect(capturedUppy).toBeDefined()
const mockFile = {
name: 'test.mp4',
meta: { fileId: 'file-1' },
} as unknown as UppyFile<Meta, Record<string, never>>
capturedUppy.emit('upload-success', mockFile, { status: 200 })
capturedUppy.emit('complete', { successful: [mockFile], failed: [] })
// At this point, patch is still in-flight
expect(patchResolved).toBe(false)
await uploadPromise
expect(patchResolved).toBe(true)
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('completed')
addFileSpy.mockRestore()
})
it('marks file as failed and shows toast when confirmation patch fails', async () => {
useUploadStore
.getState()
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
vi.mocked(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).mockResolvedValueOnce({
ok: false,
statusText: 'Server Error',
} as unknown as Awaited<
ReturnType<(typeof client.api.teams)[':teamId']['upload']['tasks'][':taskId']['$patch']>
>)
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
const uploadPromise = uploadFilesWithUppy({
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
taskId: 'task-1',
teamId: 'team-1',
storageBackend: 's3',
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
})
await new Promise((r) => setTimeout(r, 10))
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
expect(capturedUppy).toBeDefined()
const mockFile = {
name: 'test.mp4',
meta: { fileId: 'file-1' },
} as unknown as UppyFile<Meta, Record<string, never>>
capturedUppy.emit('upload-success', mockFile, { status: 200 })
capturedUppy.emit('complete', { successful: [mockFile], failed: [] })
await uploadPromise
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('failed')
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Failed to confirm upload'))
addFileSpy.mockRestore()
})
describe('isNetworkIssue', () => {
it('detects offline state and various network error indicators', () => {
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true })
expect(isNetworkIssue(new Error('Any error'))).toBe(true)
expect(isNetworkIssue()).toBe(true)
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
expect(isNetworkIssue(new Error('Failed to fetch'))).toBe(true)
expect(isNetworkIssue(new Error('NetworkError when attempting to fetch resource.'))).toBe(
true,
)
expect(isNetworkIssue(new Error('net::ERR_INTERNET_DISCONNECTED'))).toBe(true)
expect(isNetworkIssue({ name: 'S3NetworkError', message: 'S3 request failed' })).toBe(true)
expect(isNetworkIssue({ name: 'NetworkError', message: 'Network failed' })).toBe(true)
expect(isNetworkIssue({ isNetworkError: true })).toBe(true)
expect(isNetworkIssue({ request: { readyState: 4, status: 0 } })).toBe(true)
expect(isNetworkIssue(new Error('403 Forbidden'))).toBe(false)
expect(isNetworkIssue(new Error('400 Bad Request'))).toBe(false)
expect(isNetworkIssue(null)).toBe(false)
expect(isNetworkIssue(undefined)).toBe(false)
})
})
it('pauses on network disconnect, does not report terminal failure, and resumes on back-online', async () => {
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
useUploadStore
.getState()
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
const retryAllSpy = vi.spyOn(Uppy.prototype, 'retryAll').mockResolvedValue(undefined as never)
const uploadPromise = uploadFilesWithUppy({
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
taskId: 'task-1',
teamId: 'team-1',
storageBackend: 's3',
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
})
await new Promise((r) => setTimeout(r, 10))
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
expect(capturedUppy).toBeDefined()
const mockFile = {
id: 'f1',
name: 'test.mp4',
meta: { fileId: 'file-1' },
} as unknown as UppyFile<Meta, Record<string, never>>
// 1. Simulate turning off Wi-Fi
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true })
window.dispatchEvent(new Event('offline'))
const networkError = new Error('Failed to fetch')
capturedUppy.emit('upload-error', mockFile, networkError)
capturedUppy.emit('complete', {
successful: [],
failed: [{ ...mockFile, error: 'Failed to fetch' }],
})
// Wait a tick to verify nothing aborted or marked failed
await new Promise((r) => setTimeout(r, 20))
// File must NOT be marked failed in store, activeUploads must retain file, no PATCH with error
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('uploading')
expect(activeUploads.has('file-1')).toBe(true)
expect(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).not.toHaveBeenCalled()
// 2. Simulate turning Wi-Fi back on
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
window.dispatchEvent(new Event('online'))
expect(retryAllSpy).toHaveBeenCalled()
// 3. Simulate successful upload on retry
capturedUppy.emit('upload-success', mockFile, { status: 200 })
capturedUppy.emit('complete', { successful: [mockFile], failed: [] })
await uploadPromise
// Confirm that confirmation patch was called without errorMessage
expect(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).toHaveBeenCalledWith({
param: { teamId: 'team-1', taskId: 'task-1' },
json: { fileId: 'file-1' },
})
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('completed')
expect(activeUploads.size).toBe(0)
addFileSpy.mockRestore()
retryAllSpy.mockRestore()
})
it('fails permanently on non-network error and reports error to server', async () => {
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true })
useUploadStore
.getState()
.startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'test.mp4', size: 100 }])
const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1')
const uploadPromise = uploadFilesWithUppy({
files: [{ id: 'temp-1', file: new File(['content'], 'test.mp4', { type: 'video/mp4' }) }],
taskId: 'task-1',
teamId: 'team-1',
storageBackend: 's3',
createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/test.mp4' }],
})
await new Promise((r) => setTimeout(r, 10))
const capturedUppy = addFileSpy.mock.contexts[0] as Uppy
expect(capturedUppy).toBeDefined()
const mockFile = {
id: 'f1',
name: 'test.mp4',
meta: { fileId: 'file-1' },
} as unknown as UppyFile<Meta, Record<string, never>>
const permanentError = new Error('403 Forbidden')
capturedUppy.emit('upload-error', mockFile, permanentError)
capturedUppy.emit('complete', {
successful: [],
failed: [{ ...mockFile, error: '403 Forbidden' }],
})
await uploadPromise
expect(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).toHaveBeenCalledWith({
param: { teamId: 'team-1', taskId: 'task-1' },
json: { fileId: 'file-1', errorMessage: '403 Forbidden' },
})
expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('failed')
expect(activeUploads.size).toBe(0)
addFileSpy.mockRestore()
})
})
+425
View File
@@ -0,0 +1,425 @@
import { Uppy } from '@uppy/core'
import AwsS3 from '@uppy/aws-s3'
import XHRUpload from '@uppy/xhr-upload'
import type { PresignedUrl } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useUploadStore } from '@/ui/stores/upload'
import { toast } from 'sonner'
import { acquireWakeLock, releaseWakeLock } from './wake-lock'
export type FileWithId = {
id: string
file: File
}
export interface ActiveUploadFile {
teamId: string
taskId: string
fileId: string
key?: string
uploadId?: string
}
export const activeUploads = new Map<string, ActiveUploadFile>()
// Setup beforeunload and pagehide listeners once
if (typeof window !== 'undefined') {
window.addEventListener('beforeunload', (e) => {
if (useUploadStore.getState().uploading > 0 || activeUploads.size > 0) {
e.preventDefault()
e.returnValue = ''
}
})
window.addEventListener('pagehide', () => {
if (activeUploads.size === 0) return
for (const item of activeUploads.values()) {
const url = `/api/teams/${item.teamId}/upload/tasks/${item.taskId}/abort`
const payload = JSON.stringify({
fileId: item.fileId,
uploadId: item.uploadId,
key: item.key,
})
try {
if ('sendBeacon' in navigator) {
const blob = new Blob([payload], { type: 'application/json' })
navigator.sendBeacon(url, blob)
} else {
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: payload,
keepalive: true,
credentials: 'include',
})
}
} catch (err) {
console.warn('Failed to send abort beacon:', err)
}
}
activeUploads.clear()
})
}
export function isNetworkIssue(error?: unknown): boolean {
if (typeof navigator !== 'undefined' && !navigator.onLine) {
return true
}
if (!error) return false
const err = error as Record<string, unknown>
if (err.isNetworkError === true) return true
if (err.name === 'S3NetworkError' || err.name === 'NetworkError') return true
const msg = (typeof err.message === 'string' ? err.message : '').toLowerCase()
if (
msg.includes('network error') ||
msg.includes('failed to fetch') ||
msg.includes('networkerror') ||
msg.includes('load failed') ||
msg.includes('err_internet_disconnected')
) {
return true
}
const req = err.request as Record<string, unknown> | undefined
if (req && req.status === 0) return true
return false
}
export interface StartUploadOptions {
files: FileWithId[]
taskId: string
teamId: string
storageBackend: 's3' | 'local'
createdAssets?: Array<{ tempId: string; assetId: string; key?: string }>
presignedUrls?: PresignedUrl[]
onFileFinished?: (fileId: string) => void | Promise<void>
}
export async function uploadFilesWithUppy({
files,
taskId,
teamId,
storageBackend,
createdAssets = [],
presignedUrls = [],
onFileFinished,
}: StartUploadOptions): Promise<void> {
if (!files.length) return
await acquireWakeLock()
const store = useUploadStore.getState()
const { increment, decrement, updateFileProgress, completeFile, failFile } = store
// Build lookup maps
const assetByTempId = new Map<string, { assetId: string; key?: string }>()
for (const a of createdAssets) {
assetByTempId.set(a.tempId, { assetId: a.assetId, key: a.key })
}
const urlByTempId = new Map<string, { url: string; fileId: string }>()
for (const p of presignedUrls) {
if (p.id) {
urlByTempId.set(p.id, { url: p.url || '', fileId: p.fileId || '' })
}
}
const fileIdByKey = new Map<string, string>()
const uppy = new Uppy({
autoProceed: true,
allowMultipleUploadBatches: false,
})
if (storageBackend === 's3') {
uppy.use(AwsS3, {
shouldUseMultipart: (file) => (file.size || 0) > 100 * 1024 * 1024,
getChunkSize: ({ size }) => {
if (size > 5 * 1024 * 1024 * 1024) return 32 * 1024 * 1024 // 32MB
if (size > 1 * 1024 * 1024 * 1024) return 16 * 1024 * 1024 // 16MB
return 8 * 1024 * 1024 // 8MB
},
generateObjectKey: (file) => (file.meta.key as string) || file.name,
signRequest: async (req) => {
const uploadId = 'uploadId' in req ? req.uploadId : undefined
const partNumber = 'partNumber' in req ? req.partNumber : undefined
const fileId = fileIdByKey.get(req.key)
if (fileId && uploadId) {
const active = activeUploads.get(fileId)
if (active) {
active.uploadId = uploadId
}
}
const res = await fetch(`/api/teams/${teamId}/upload/sign`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
key: req.key,
method: req.method,
uploadId,
partNumber,
fileId,
}),
credentials: 'include',
})
if (!res.ok) {
throw new Error(`Failed to sign request: ${res.statusText}`)
}
const data = (await res.json()) as { url: string }
return { url: data.url }
},
})
} else {
uppy.use(XHRUpload, {
endpoint: (fileOrBundle) => {
const file = Array.isArray(fileOrBundle) ? fileOrBundle[0] : fileOrBundle
return (file?.meta?.url as string) || ''
},
method: 'PUT',
formData: false,
headers: (file) => ({
'Content-Type': file.type || 'application/octet-stream',
}),
getResponseData: (xhr) => {
try {
return xhr.responseText ? JSON.parse(xhr.responseText) : {}
} catch {
return {}
}
},
shouldRetry: () => false,
limit: 5,
})
}
const confirmationPromises = new Map<string, Promise<void>>()
const retryCounts = new Map<string, number>()
const MAX_ONLINE_RETRIES = 3
let retryTimeout: ReturnType<typeof setTimeout> | null = null
const triggerRetry = () => {
if (typeof navigator !== 'undefined' && !navigator.onLine) {
console.log('[Uploader] Delaying retry because browser is currently offline.')
return
}
console.log('[Uploader] Calling uppy.retryAll() to resume paused/failed uploads...')
uppy.retryAll().catch((err: unknown) => {
console.error('[Uploader] Error during retryAll:', err)
})
}
const scheduleRetry = (delayMs = 2000) => {
if (retryTimeout) return
retryTimeout = setTimeout(() => {
retryTimeout = null
triggerRetry()
}, delayMs)
}
// Network recovery: native back-online event and browser online/offline events
const handleBackOnline = () => {
const isOnline = typeof navigator !== 'undefined' ? navigator.onLine : true
console.log(`[Uploader] Network 'online' event received! navigator.onLine = ${isOnline}`)
triggerRetry()
}
const handleOffline = () => {
const isOnline = typeof navigator !== 'undefined' ? navigator.onLine : false
console.warn(`[Uploader] Network 'offline' event received! navigator.onLine = ${isOnline}`)
}
uppy.on('back-online', handleBackOnline)
if (typeof window !== 'undefined') {
window.addEventListener('online', handleBackOnline)
window.addEventListener('offline', handleOffline)
}
uppy.on('upload-progress', (file, progress) => {
if (!file) return
const fileId = file.meta.fileId as string
if (fileId && progress.bytesUploaded != null) {
updateFileProgress(taskId, fileId, progress.bytesUploaded)
}
})
uppy.on('upload-success', (file) => {
if (!file) return
const fileId = file.meta.fileId as string
activeUploads.delete(fileId)
const confirmPromise = (async () => {
try {
const res = await client.api.teams[':teamId'].upload.tasks[':taskId'].$patch({
param: { teamId, taskId },
json: { fileId },
})
if (!res.ok) {
throw new Error(`Failed to confirm upload: ${res.statusText}`)
}
completeFile(taskId, fileId)
decrement()
await onFileFinished?.(fileId)
} catch (err) {
console.error('Failed to confirm upload:', err)
failFile(taskId, fileId)
decrement()
toast.error(`Failed to confirm upload: ${file.name}`)
await onFileFinished?.(fileId)
throw err
}
})()
confirmationPromises.set(fileId, confirmPromise)
})
const handlePermanentError = (
file: { name: string; meta: Record<string, unknown> },
error: unknown,
) => {
const fileId = file.meta.fileId as string
if (!activeUploads.has(fileId)) return
activeUploads.delete(fileId)
failFile(taskId, fileId)
decrement()
toast.error(`Failed to upload file: ${file.name}`)
const errorPromise = (async () => {
try {
await client.api.teams[':teamId'].upload.tasks[':taskId'].$patch({
param: { teamId, taskId },
json: {
fileId,
errorMessage: (error as Error)?.message || 'Upload failed',
},
})
} catch (err) {
console.error('Failed to report upload failure:', err)
}
await onFileFinished?.(fileId)
})()
confirmationPromises.set(fileId, errorPromise)
}
uppy.on('upload-error', (file, error) => {
if (!file) return
console.error(`[Uploader] upload-error for ${file.name}:`, error)
if (isNetworkIssue(error)) {
console.warn(
`[Uploader] Network error detected for ${file.name}. Keeping upload active to resume when connection is restored.`,
)
if (typeof navigator !== 'undefined' && navigator.onLine) {
const fileId = file.meta.fileId as string
const attempts = (retryCounts.get(fileId) || 0) + 1
retryCounts.set(fileId, attempts)
if (attempts > MAX_ONLINE_RETRIES) {
console.error(
`[Uploader] Exceeded max online retries (${MAX_ONLINE_RETRIES}) for ${file.name}. Failing permanently.`,
)
handlePermanentError(file, error)
return
}
console.log(
`[Uploader] Scheduling retry for ${file.name} (attempt ${attempts}/${MAX_ONLINE_RETRIES})...`,
)
scheduleRetry(2000)
}
return
}
handlePermanentError(file, error)
})
// Add files to Uppy
for (const item of files) {
const assetInfo = assetByTempId.get(item.id)
const urlInfo = urlByTempId.get(item.id)
const fileId = assetInfo?.assetId || urlInfo?.fileId || item.id
const key = assetInfo?.key
const url = urlInfo?.url
if (key) {
fileIdByKey.set(key, fileId)
}
activeUploads.set(fileId, {
teamId,
taskId,
fileId,
key,
})
increment()
uppy.addFile({
name: item.file.name,
type: item.file.type,
data: item.file,
meta: {
fileId,
key,
url,
},
})
}
// Wait until Uppy completes all files and all confirmations settle
try {
await new Promise<void>((resolve) => {
const checkCompletion = (result?: { failed?: unknown[] }) => {
if (activeUploads.size === 0) {
resolve()
return
}
const failedFiles = result?.failed || []
const isOffline = typeof navigator !== 'undefined' && !navigator.onLine
const hasNetworkFailures =
isOffline || failedFiles.some((f) => isNetworkIssue((f as { error?: unknown })?.error))
if (hasNetworkFailures) {
console.log(
'[Uploader] Batch completed with network issues; waiting for reconnection to resume...',
)
return
}
for (const f of failedFiles) {
const file = f as { name: string; meta: Record<string, unknown> }
handlePermanentError(file, (f as { error?: unknown })?.error)
}
if (activeUploads.size === 0) {
resolve()
}
}
uppy.on('complete', checkCompletion)
uppy.on('cancel-all', () => {
resolve()
})
})
await Promise.allSettled(Array.from(confirmationPromises.values()))
} finally {
if (retryTimeout) {
clearTimeout(retryTimeout)
}
if (typeof window !== 'undefined') {
window.removeEventListener('online', handleBackOnline)
window.removeEventListener('offline', handleOffline)
}
await releaseWakeLock()
uppy.destroy()
}
}
+50
View File
@@ -0,0 +1,50 @@
let wakeLockSentinel: WakeLockSentinel | null = null
let wakeLockCount = 0
export async function acquireWakeLock(): Promise<void> {
wakeLockCount++
if (wakeLockCount > 1 && wakeLockSentinel) {
return
}
if (typeof navigator !== 'undefined' && 'wakeLock' in navigator) {
try {
wakeLockSentinel = await navigator.wakeLock.request('screen')
wakeLockSentinel.addEventListener('release', () => {
wakeLockSentinel = null
})
} catch (err) {
console.warn('Screen Wake Lock request failed:', err)
}
}
}
export async function releaseWakeLock(): Promise<void> {
wakeLockCount = Math.max(0, wakeLockCount - 1)
if (wakeLockCount === 0 && wakeLockSentinel) {
try {
await wakeLockSentinel.release()
} catch (err) {
console.warn('Screen Wake Lock release failed:', err)
} finally {
wakeLockSentinel = null
}
}
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', async () => {
if (document.visibilityState === 'visible' && wakeLockCount > 0 && !wakeLockSentinel) {
try {
if (typeof navigator !== 'undefined' && 'wakeLock' in navigator) {
wakeLockSentinel = await navigator.wakeLock.request('screen')
wakeLockSentinel.addEventListener('release', () => {
wakeLockSentinel = null
})
}
} catch (err) {
console.warn('Screen Wake Lock re-acquisition failed:', err)
}
}
})
}
+3
View File
@@ -53,6 +53,9 @@
"@tanstack/react-router": "1.170.11",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.14.10",
"@uppy/aws-s3": "6.0.0",
"@uppy/core": "6.0.0",
"@uppy/xhr-upload": "6.0.0",
"better-auth": "1.6.11",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",