diff --git a/.dockerignore b/.dockerignore index 9387188..c16fa34 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,6 +1,9 @@ node_modules -dist +npm-debug.log +.git +.gitignore .vscode .env -.git -npm-debug.log \ No newline at end of file +dist +Dockerfile* +docker-compose* \ No newline at end of file diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..2bc34a9 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,49 @@ +name: Backend Deploy + +on: + push: + branches: + - main + +jobs: + deploy: + runs-on: ubuntu-latest + + steps: + + - name: Checkout repo + uses: actions/checkout@v4 + + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ secrets.AWS_REGION }} + + + - name: Login to ECR + id: login-ecr + uses: aws-actions/amazon-ecr-login@v2 + + + - name: Build and push Docker image + env: + ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} + ECR_REPOSITORY: ${{ secrets.ECR_REPOSITORY }} + run: | + docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:latest . + docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest + + + - name: Deploy to EC2 + uses: appleboy/ssh-action@v1.0.3 + with: + host: ${{ secrets.EC2_HOST }} + username: ${{ secrets.EC2_USER }} + key: ${{ secrets.EC2_SSH_KEY }} + script: | + cd ~/app + docker compose pull + docker compose up -d \ No newline at end of file diff --git a/.gitignore b/.gitignore index fb1fc80..432a6c3 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,12 @@ Design # Node modules node_modules/ +postman + +# Temporary files +npm-temp/ +temp/ + # Environment variables .env .env.local @@ -48,3 +54,11 @@ coverage/ # Local certificates *.pem *.key + +// IDE specific files +.postman/ +postman/ +.history + +.prettierrc + diff --git a/Dockerfile b/Dockerfile index f955eb8..9f17ba7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,26 @@ +FROM node:20-alpine AS builder + +WORKDIR /app + +COPY package*.json ./ + +RUN npm install + +COPY . . + +RUN npm run build + + FROM node:20-alpine WORKDIR /app -# Install dev dependencies (nodemon) and app deps COPY package*.json ./ -RUN npm ci -# If you prefer nodemon global: RUN npm install -g nodemon -# Copy only when building image layer for deps (source will be mounted at runtime) -# Expose the port your app uses +RUN npm install --omit=dev + +COPY --from=builder /app/dist ./dist + EXPOSE 4000 -CMD ["npm", "run", "dev"] +CMD ["node", "dist/server.js"] \ No newline at end of file diff --git a/Dockerfile.dev b/Dockerfile.dev new file mode 100644 index 0000000..27d3490 --- /dev/null +++ b/Dockerfile.dev @@ -0,0 +1,11 @@ +FROM node:20-alpine + +WORKDIR /app + +COPY package*.json ./ + +RUN npm install + +EXPOSE 4000 + +CMD ["npm", "run", "dev"] \ No newline at end of file diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml new file mode 100644 index 0000000..fc2e732 --- /dev/null +++ b/docker-compose.dev.yml @@ -0,0 +1,21 @@ +version: "3.9" + +services: + backend: + build: + context: . + dockerfile: Dockerfile.dev + + container_name: backend-dev + + volumes: + - .:/app + - /app/node_modules + + env_file: + - .env + + ports: + - "4000:4000" + + command: npm run dev \ No newline at end of file diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml new file mode 100644 index 0000000..176edf9 --- /dev/null +++ b/docker-compose.prod.yml @@ -0,0 +1,17 @@ +version: "3.9" + +services: + backend: + build: + context: . + dockerfile: Dockerfile + + container_name: backend-prod + + ports: + - "4000:4000" + + env_file: + - .env + + restart: always \ No newline at end of file diff --git a/example.env b/example.env new file mode 100644 index 0000000..cde9431 --- /dev/null +++ b/example.env @@ -0,0 +1,18 @@ + PORT = 4000 +DEV_CLIENT_URL='http://localhost:4000' + +DB_PASSWORD= +DB_USERNAME = +ACCESS_TOKEN_SECRET = +REFRESH_TOKEN_SECRET = +ACCESS_TOKEN_EXPIRES_IN= any number of minutes +REFRESH_TOKEN_EXPIRES_IN = any number of days + +DEV_SMTP_HOST= +DEV_SMTP_PORT= +DEV_SMTP_USER= +DEV_SMTP_PASS= +EMAIL_FROM= +APP_URL= +PASSWORD_RESET_EXPIRES_MIN= +MAILER_API= diff --git a/package-lock.json b/package-lock.json index 74f6612..b0a374e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,15 +11,19 @@ "@aws-sdk/client-s3": "^3.948.0", "@aws-sdk/s3-request-presigner": "^3.948.0", "@types/cookie-parser": "^1.4.10", + "@types/multer": "^2.0.0", "bcrypt": "^6.0.0", "cookie-parser": "^1.4.7", "cors": "^2.8.5", "dotenv": "^17.2.3", "express": "^5.2.1", + "fluent-ffmpeg": "^2.1.3", "helmet": "^8.1.0", "jsonwebtoken": "^9.0.2", "mongoose": "^9.0.0", + "multer": "^2.0.2", "nodemailer": "^7.0.11", + "pino": "^10.1.0", "ua-parser-js": "^2.0.6", "undici": "^7.16.0", "zod": "^4.1.13" @@ -28,10 +32,12 @@ "@types/bcrypt": "^6.0.0", "@types/cors": "^2.8.19", "@types/express": "^5.0.6", + "@types/fluent-ffmpeg": "^2.1.28", "@types/jsonwebtoken": "^9.0.10", "@types/node": "^24.10.1", "@types/nodemailer": "^7.0.4", "nodemon": "^3.1.11", + "pino-pretty": "^13.1.3", "tsconfig-paths": "^4.2.0", "tsx": "^4.21.0", "typescript": "^5.9.3" @@ -1963,6 +1969,12 @@ "sparse-bitfield": "^3.0.3" } }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, "node_modules/@smithy/abort-controller": { "version": "4.2.5", "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.2.5.tgz", @@ -2766,6 +2778,16 @@ "@types/send": "*" } }, + "node_modules/@types/fluent-ffmpeg": { + "version": "2.1.28", + "resolved": "https://registry.npmjs.org/@types/fluent-ffmpeg/-/fluent-ffmpeg-2.1.28.tgz", + "integrity": "sha512-5ovxsDwBcPfJ+eYs1I/ZpcYCnkce7pvH9AHSvrZllAp1ZPpTRDZAFjF3TRFbukxSgIYTTNYePbS0rKUmaxVbXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/http-errors": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", @@ -2790,6 +2812,15 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/multer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.0.0.tgz", + "integrity": "sha512-C3Z9v9Evij2yST3RSBktxP9STm6OdMc5uR1xF1SGr98uv8dUlAL2hqwrZ3GVB3uyMyiegnscEK6PGtYvNrjTjw==", + "license": "MIT", + "dependencies": { + "@types/express": "*" + } + }, "node_modules/@types/node": { "version": "24.10.1", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", @@ -2883,6 +2914,26 @@ "node": ">= 8" } }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/async": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz", + "integrity": "sha512-eAkdoKxU6/LkKDBzLpT+t6Ff5EtfSF4wx1WfJiPEEV7WNLnDaRXk0oVysiEPm262roaachGexwUv94WhSgN5TQ==" + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -2986,6 +3037,23 @@ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", "license": "BSD-3-Clause" }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -3049,6 +3117,13 @@ "fsevents": "~2.3.2" } }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true, + "license": "MIT" + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -3056,6 +3131,21 @@ "dev": true, "license": "MIT" }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, "node_modules/content-disposition": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", @@ -3128,6 +3218,16 @@ "node": ">= 0.10" } }, + "node_modules/dateformat": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", + "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -3224,6 +3324,16 @@ "node": ">= 0.8" } }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -3354,6 +3464,20 @@ "url": "https://opencollective.com/express" } }, + "node_modules/fast-copy": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-4.0.2.tgz", + "integrity": "sha512-ybA6PDXIXOXivLJK/z9e+Otk7ve13I4ckBvGO5I2RRmBU1gMHLVDJYEuJYhGwez7YNlYji2M2DvVU+a9mSFDlw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "dev": true, + "license": "MIT" + }, "node_modules/fast-xml-parser": { "version": "5.2.5", "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", @@ -3406,6 +3530,20 @@ "url": "https://opencollective.com/express" } }, + "node_modules/fluent-ffmpeg": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/fluent-ffmpeg/-/fluent-ffmpeg-2.1.3.tgz", + "integrity": "sha512-Be3narBNt2s6bsaqP6Jzq91heDgOEaDCJAXcE3qcma/EJBSy5FB4cvO31XBInuAuKBx8Kptf8dkhjK0IOru39Q==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "dependencies": { + "async": "^0.2.9", + "which": "^1.1.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -3566,6 +3704,13 @@ "node": ">=18.0.0" } }, + "node_modules/help-me": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz", + "integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==", + "dev": true, + "license": "MIT" + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -3696,6 +3841,22 @@ ], "license": "MIT" }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -3881,12 +4042,23 @@ "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, "node_modules/mongodb": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.0.0.tgz", @@ -3991,6 +4163,67 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/multer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz", + "integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "mkdirp": "^0.5.6", + "object-assign": "^4.1.1", + "type-is": "^1.6.18", + "xtend": "^4.0.2" + }, + "engines": { + "node": ">= 10.16.0" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/negotiator": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", @@ -4089,6 +4322,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -4142,6 +4384,94 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pino": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.1.0.tgz", + "integrity": "sha512-0zZC2ygfdqvqK8zJIr1e+wT1T/L+LF6qvqvbzEQ6tiMAoTqEVK9a1K3YRu8HEUvGEvNqZyPJTtb2sNIoTkB83w==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-pretty": { + "version": "13.1.3", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-13.1.3.tgz", + "integrity": "sha512-ttXRkkOz6WWC95KeY9+xxWL6AtImwbyMHrL1mSwqwW9u+vLp/WIElvHvCSDg0xO/Dzrggz1zv3rN5ovTRVowKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "colorette": "^2.0.7", + "dateformat": "^4.6.3", + "fast-copy": "^4.0.0", + "fast-safe-stringify": "^2.1.1", + "help-me": "^5.0.0", + "joycon": "^3.1.1", + "minimist": "^1.2.6", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pump": "^3.0.0", + "secure-json-parse": "^4.0.0", + "sonic-boom": "^4.0.1", + "strip-json-comments": "^5.0.2" + }, + "bin": { + "pino-pretty": "bin.js" + } + }, + "node_modules/pino-pretty/node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz", + "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==", + "license": "MIT" + }, + "node_modules/process-warning": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", + "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -4162,6 +4492,17 @@ "dev": true, "license": "MIT" }, + "node_modules/pump": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", + "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -4186,6 +4527,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, "node_modules/range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -4210,6 +4557,20 @@ "node": ">= 0.10" } }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -4223,6 +4584,15 @@ "node": ">=8.10.0" } }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", @@ -4269,12 +4639,38 @@ ], "license": "MIT" }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, + "node_modules/secure-json-parse": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", + "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/semver": { "version": "7.7.3", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", @@ -4421,6 +4817,15 @@ "node": ">=10" } }, + "node_modules/sonic-boom": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz", + "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, "node_modules/sparse-bitfield": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", @@ -4430,6 +4835,15 @@ "memory-pager": "^1.0.2" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -4439,6 +4853,23 @@ "node": ">= 0.8" } }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/strip-bom": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", @@ -4449,6 +4880,19 @@ "node": ">=4" } }, + "node_modules/strip-json-comments": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", + "integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/strnum": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", @@ -4474,6 +4918,15 @@ "node": ">=4" } }, + "node_modules/thread-stream": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", + "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -4573,6 +5026,12 @@ "node": ">= 0.6" } }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -4669,6 +5128,12 @@ "node": ">= 0.8" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -4700,12 +5165,33 @@ "node": ">=18" } }, + "node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, "node_modules/zod": { "version": "4.1.13", "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.13.tgz", diff --git a/package.json b/package.json index c294b61..4d6b540 100644 --- a/package.json +++ b/package.json @@ -11,15 +11,19 @@ "@aws-sdk/client-s3": "^3.948.0", "@aws-sdk/s3-request-presigner": "^3.948.0", "@types/cookie-parser": "^1.4.10", + "@types/multer": "^2.0.0", "bcrypt": "^6.0.0", "cookie-parser": "^1.4.7", "cors": "^2.8.5", "dotenv": "^17.2.3", "express": "^5.2.1", + "fluent-ffmpeg": "^2.1.3", "helmet": "^8.1.0", "jsonwebtoken": "^9.0.2", "mongoose": "^9.0.0", + "multer": "^2.0.2", "nodemailer": "^7.0.11", + "pino": "^10.1.0", "ua-parser-js": "^2.0.6", "undici": "^7.16.0", "zod": "^4.1.13" @@ -28,10 +32,12 @@ "@types/bcrypt": "^6.0.0", "@types/cors": "^2.8.19", "@types/express": "^5.0.6", + "@types/fluent-ffmpeg": "^2.1.28", "@types/jsonwebtoken": "^9.0.10", "@types/node": "^24.10.1", "@types/nodemailer": "^7.0.4", "nodemon": "^3.1.11", + "pino-pretty": "^13.1.3", "tsconfig-paths": "^4.2.0", "tsx": "^4.21.0", "typescript": "^5.9.3" diff --git a/src/config/corsConfig.ts b/src/config/corsConfig.ts index 73d6050..dc42528 100644 --- a/src/config/corsConfig.ts +++ b/src/config/corsConfig.ts @@ -1,11 +1,7 @@ +import { ALLOWED_ORIGINS } from 'constants/globalConts.js'; import type { CorsOptions } from 'cors'; -// Define the exact origin of your frontend for each environment -// It's best practice to load these from environment variables (e.g., using 'dotenv') -const DEV_ORIGIN = process.env.DEV_CLIENT_URL || 'http://localhost:3000'; -const PROD_ORIGIN = process.env.PROD_CLIENT_URL || 'https://your-production-app.com'; - -/** + /** * Returns the appropriate CORS configuration based on the current environment. * @returns CorsOptions object for the Express 'cors' middleware. */ @@ -16,7 +12,7 @@ const getCorsConfig = (): CorsOptions => { // Determine the allowed origin // In production, strictly use the production URL. // In any other environment (development, staging, test), use the development URL. - const allowedOrigin = isProduction ? PROD_ORIGIN : DEV_ORIGIN; + const allowedOrigin = ALLOWED_ORIGINS; return { // Set the dynamic origin @@ -24,7 +20,8 @@ const getCorsConfig = (): CorsOptions => { // Define allowed interactions methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], - allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], + allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'], + // Allow cookies or authorization headers to be sent credentials: true, diff --git a/src/config/creditPricing.ts b/src/config/creditPricing.ts new file mode 100644 index 0000000..a03d068 --- /dev/null +++ b/src/config/creditPricing.ts @@ -0,0 +1,73 @@ +export type ActionType = + | 'TXT_TO_IMAGE_GEN' + | 'IMG_TO_IMAGE_GEN' + | 'AUDIO_GEN' + | 'STORY_GEN' + | 'TXT_TO_VIDEO_GEN' + | 'IMG_TO_VIDEO_GEN' + | 'SCENE_GEN' + | 'NARRATION_GEN'; + +export const CREDIT_PRICING: Record> = { + TXT_TO_IMAGE_GEN: { + 1: 2, + 2: 6, + 3: 10, + 4: 15, + 5: 25, + }, + + IMG_TO_IMAGE_GEN: { + 1: 2, + 2: 6, + 3: 10, + 4: 15, + 5: 25, + }, + + AUDIO_GEN: { + 1: 2, + 2: 5, + 3: 8, + 4: 12, + 5: 20, + }, + + STORY_GEN: { + 1: 1, + 2: 3, + 3: 6, + 4: 10, + 5: 15, + }, + + SCENE_GEN: { + 1: 1, + 2: 2, + 3: 4, + 4: 6, + 5: 10, + 10: 60, + }, + NARRATION_GEN: { + 1: 1, + 2: 3, + 3: 5, + 4: 8, + 5: 12, + }, + + TXT_TO_VIDEO_GEN: { + 2: 20, + 3: 35, + 4: 50, + 5: 75, + }, + + IMG_TO_VIDEO_GEN: { + 2: 20, + 3: 35, + 4: 50, + 5: 75, + }, +}; diff --git a/src/constants/accountStatus.ts b/src/constants/accountStatus.ts deleted file mode 100644 index f1e44be..0000000 --- a/src/constants/accountStatus.ts +++ /dev/null @@ -1,10 +0,0 @@ -// constants/accountStatus.ts -export const ACCOUNT_STATUSES = [ - "active", - "suspended", - "banned", - "disabled", - "deleted", -] as const; - -export type AccountStatus = (typeof ACCOUNT_STATUSES)[number]; diff --git a/src/constants/audioAssetConsts.ts b/src/constants/audioAssetConsts.ts new file mode 100644 index 0000000..acc4c5c --- /dev/null +++ b/src/constants/audioAssetConsts.ts @@ -0,0 +1,30 @@ +// Audio Asset validation constants +export const MAX_AUDIO_PROMPT_LENGTH = 2000; +export const MAX_AUDIO_URL_LENGTH = 2048; +export const MAX_AUDIO_ASSETS_PER_NARRATION = 50; + +// Audio types +export const audioTypes = ['narration', 'background', 'effect'] as const; +export type AudioType = (typeof audioTypes)[number]; + +// Generation sources +export const audioGenerationSources = ['ai', 'user'] as const; +export type AudioGenerationSource = (typeof audioGenerationSources)[number]; + +// Supported audio formats +export const audioFormats = ['mp3', 'wav', 'ogg', 'aac', 'm4a', 'flac', 'wma', 'opus'] as const; +export type AudioFormat = (typeof audioFormats)[number]; + +// Duration constraints +export const MIN_AUDIO_DURATION = 0.1; +export const MAX_AUDIO_DURATION = 7200; // 2 hours max + +// File size constraints (in bytes) +export const MAX_AUDIO_FILE_SIZE = 100 * 1024 * 1024; // 100MB + +// Voice ID constraints +export const MAX_VOICE_ID_LENGTH = 100; + +// Version constraints +export const AUDIO_VERSION_GAP = 1; +export const MIN_AUDIO_VERSION = 1; diff --git a/src/constants/authConsts.ts b/src/constants/authConsts.ts new file mode 100644 index 0000000..c249c0b --- /dev/null +++ b/src/constants/authConsts.ts @@ -0,0 +1,7 @@ +// constants/accountStatus.ts +export { ACCOUNT_STATUSES, type AccountStatus } from './userConsts.js'; + +export const RESET_EXP_MIN = Number( + process.env.PASSWORD_RESET_EXPIRES_MIN || 10 +); + diff --git a/src/constants/globalConts.ts b/src/constants/globalConts.ts new file mode 100644 index 0000000..3558001 --- /dev/null +++ b/src/constants/globalConts.ts @@ -0,0 +1,7 @@ +export const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS + ? process.env.ALLOWED_ORIGINS.split(',') + : [ + process.env.DEV_CLIENT_URL || 'http://localhost:5173', + process.env.PROD_CLIENT_URL || 'https://your-production-app.com', + ]; + \ No newline at end of file diff --git a/src/constants/narrationProfiles.ts b/src/constants/narrationProfiles.ts new file mode 100644 index 0000000..32c45b4 --- /dev/null +++ b/src/constants/narrationProfiles.ts @@ -0,0 +1,224 @@ +import { + GenreType, + ToneType, + IntensityCurve, + NarrationProfile, +} from "@models/ContextProfile.js"; + +export const NARRATION_PROFILES: Record = { + [GenreType.HORROR]: { + wordsPerSecond: 2.1, + minWordTolerance: 10, + maxWordTolerance: 10, + pauseBias: "high", + sentenceLengthBias: "short", + clauseDensity: "sparse", + tone: ToneType.DARK, + emotionBias: "subtle", + intensityCurve: IntensityCurve.SLOW_BURN, + }, + + [GenreType.PSYCHOLOGICAL_HORROR]: { + wordsPerSecond: 2.0, + minWordTolerance: 12, + maxWordTolerance: 12, + pauseBias: "high", + sentenceLengthBias: "short", + clauseDensity: "sparse", + tone: ToneType.SOMBER, + emotionBias: "subtle", + intensityCurve: IntensityCurve.RISING, + }, + + [GenreType.THRILLER]: { + wordsPerSecond: 2.8, + minWordTolerance: 8, + maxWordTolerance: 8, + pauseBias: "low", + sentenceLengthBias: "very-short", + clauseDensity: "balanced", + tone: ToneType.GRITTY, + emotionBias: "expressive", + intensityCurve: IntensityCurve.PULSED, + }, + + [GenreType.CRIME]: { + wordsPerSecond: 2.6, + minWordTolerance: 8, + maxWordTolerance: 8, + pauseBias: "low", + sentenceLengthBias: "short", + clauseDensity: "dense", + tone: ToneType.GRITTY, + emotionBias: "flat", + intensityCurve: IntensityCurve.PULSED, + }, + + [GenreType.NOIR]: { + wordsPerSecond: 2.2, + minWordTolerance: 10, + maxWordTolerance: 10, + pauseBias: "medium", + sentenceLengthBias: "medium", + clauseDensity: "balanced", + tone: ToneType.BLEAK, + emotionBias: "flat", + intensityCurve: IntensityCurve.FLAT, + }, + + [GenreType.SCIFI]: { + wordsPerSecond: 3.0, + minWordTolerance: 12, + maxWordTolerance: 12, + pauseBias: "none", + sentenceLengthBias: "medium", + clauseDensity: "dense", + tone: ToneType.NEUTRAL, + emotionBias: "flat", + intensityCurve: IntensityCurve.FLAT, + }, + + [GenreType.HARD_SCIFI]: { + wordsPerSecond: 3.2, + minWordTolerance: 14, + maxWordTolerance: 14, + pauseBias: "none", + sentenceLengthBias: "long", + clauseDensity: "dense", + tone: ToneType.NEUTRAL, + emotionBias: "flat", + intensityCurve: IntensityCurve.FLAT, + }, + + [GenreType.FANTASY]: { + wordsPerSecond: 2.4, + minWordTolerance: 15, + maxWordTolerance: 15, + pauseBias: "medium", + sentenceLengthBias: "long", + clauseDensity: "balanced", + tone: ToneType.EPIC, + emotionBias: "subtle", + intensityCurve: IntensityCurve.RISING, + }, + + [GenreType.DARK_FANTASY]: { + wordsPerSecond: 2.3, + minWordTolerance: 14, + maxWordTolerance: 14, + pauseBias: "medium", + sentenceLengthBias: "long", + clauseDensity: "balanced", + tone: ToneType.DARK, + emotionBias: "subtle", + intensityCurve: IntensityCurve.SLOW_BURN, + }, + + [GenreType.DRAMA]: { + wordsPerSecond: 2.0, + minWordTolerance: 10, + maxWordTolerance: 10, + pauseBias: "high", + sentenceLengthBias: "medium", + clauseDensity: "balanced", + tone: ToneType.INTIMATE, + emotionBias: "expressive", + intensityCurve: IntensityCurve.FLAT, + }, + + [GenreType.MYSTERY]: { + wordsPerSecond: 2.3, + minWordTolerance: 10, + maxWordTolerance: 10, + pauseBias: "medium", + sentenceLengthBias: "short", + clauseDensity: "balanced", + tone: ToneType.SOMBER, + emotionBias: "subtle", + intensityCurve: IntensityCurve.RISING, + }, + + [GenreType.ROMANCE]: { + wordsPerSecond: 2.2, + minWordTolerance: 12, + maxWordTolerance: 12, + pauseBias: "medium", + sentenceLengthBias: "long", + clauseDensity: "balanced", + tone: ToneType.INTIMATE, + emotionBias: "expressive", + intensityCurve: IntensityCurve.FLAT, + }, + + [GenreType.ADVENTURE]: { + wordsPerSecond: 2.7, + minWordTolerance: 10, + maxWordTolerance: 10, + pauseBias: "low", + sentenceLengthBias: "medium", + clauseDensity: "balanced", + tone: ToneType.EPIC, + emotionBias: "expressive", + intensityCurve: IntensityCurve.PULSED, + }, + + [GenreType.POST_APOCALYPTIC]: { + wordsPerSecond: 2.0, + minWordTolerance: 14, + maxWordTolerance: 14, + pauseBias: "high", + sentenceLengthBias: "short", + clauseDensity: "sparse", + tone: ToneType.BLEAK, + emotionBias: "flat", + intensityCurve: IntensityCurve.COLLAPSING, + }, + [GenreType.CYBERPUNK]: { + wordsPerSecond: 3.0, + minWordTolerance: 10, + maxWordTolerance: 10, + pauseBias: "low", + sentenceLengthBias: "short", + clauseDensity: "dense", + tone: ToneType.GRITTY, + emotionBias: "flat", + intensityCurve: IntensityCurve.PULSED, + }, + + [GenreType.HISTORICAL]: { + wordsPerSecond: 2.2, + minWordTolerance: 14, + maxWordTolerance: 14, + pauseBias: "medium", + sentenceLengthBias: "long", + clauseDensity: "dense", + tone: ToneType.SOMBER, + emotionBias: "subtle", + intensityCurve: IntensityCurve.FLAT, + }, + + [GenreType.WAR]: { + wordsPerSecond: 2.6, + minWordTolerance: 12, + maxWordTolerance: 12, + pauseBias: "low", + sentenceLengthBias: "short", + clauseDensity: "balanced", + tone: ToneType.GRITTY, + emotionBias: "expressive", + intensityCurve: IntensityCurve.SPIKING, + }, + + [GenreType.TRAGEDY]: { + wordsPerSecond: 1.9, + minWordTolerance: 16, + maxWordTolerance: 16, + pauseBias: "high", + sentenceLengthBias: "long", + clauseDensity: "sparse", + tone: ToneType.BLEAK, + emotionBias: "subtle", + intensityCurve: IntensityCurve.COLLAPSING, + }, + +}; diff --git a/src/constants/sceneAssetConsts.ts b/src/constants/sceneAssetConsts.ts new file mode 100644 index 0000000..cb953d2 --- /dev/null +++ b/src/constants/sceneAssetConsts.ts @@ -0,0 +1,33 @@ +// Scene Asset validation constants +export const MAX_ASSET_PROMPT_LENGTH = 2000; +export const MAX_ASSET_URL_LENGTH = 2048; +export const MAX_ASSETS_PER_SCENE = 50; + +// Asset types +export const assetTypes = ['image', 'video'] as const; +export type AssetType = (typeof assetTypes)[number]; + +// Visibility types +export const visibilityTypes = ['private', 'public'] as const; +export type VisibilityType = (typeof visibilityTypes)[number]; + +// Generation sources +export const generationSources = ['ai', 'user'] as const; +export type GenerationSource = (typeof generationSources)[number]; + +// Supported formats +export const videoFormats = ['mp4', 'mov', 'mkv', 'mpg', 'webm', 'avi', 'ogg', 'mpeg', 'm4v', 'flv', 'wmv', '3gp'] as const; +export const imageFormats = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp', 'svg', 'ico', 'heic', 'raw'] as const; +export const allFormats = [...videoFormats, ...imageFormats] as const; + +export type VideoFormat = (typeof videoFormats)[number]; +export type ImageFormat = (typeof imageFormats)[number]; +export type AssetFormat = (typeof allFormats)[number]; + +// Dimension constraints +export const MIN_DIMENSION = 1; +export const MAX_DIMENSION = 8192; + +// Duration constraints (for video assets) +export const MIN_ASSET_DURATION = 0.1; +export const MAX_ASSET_DURATION = 3600; // 1 hour max diff --git a/src/constants/sceneConsts.ts b/src/constants/sceneConsts.ts new file mode 100644 index 0000000..4e9504f --- /dev/null +++ b/src/constants/sceneConsts.ts @@ -0,0 +1,15 @@ +// Scene validation constants +export const MAX_SCENE_TITLE_LENGTH = 200; +export const MAX_SCENE_DESCRIPTION_LENGTH = 2000; +export const MAX_SCENE_PROMPT_LENGTH = 1000; +export const MIN_SCENE_DURATION = 1; +export const MAX_SCENE_DURATION = 60; // seconds +export const MAX_SCENES_PER_STORY = 100; +export const MAX_EXTRA_PROMPT_LENGTH = 500; + +// Ordering constants +export const SCENE_ORDER_GAP = 1000; + +// Author types +export const sceneAuthorType = ['ai', 'user'] as const; +export type SceneAuthorType = (typeof sceneAuthorType)[number]; diff --git a/src/constants/storyConsts.ts b/src/constants/storyConsts.ts new file mode 100644 index 0000000..820799d --- /dev/null +++ b/src/constants/storyConsts.ts @@ -0,0 +1,42 @@ +const platform = [ + "youtube", + "instagram", + "tiktok", + "facebook", + "linkedin", + "twitter", + "snapchat", + "pinterest", + "vimeo", + "reddit", + "whatsapp", + "telegram", +] as const; +const storyIntent = [ + "short-form", + "long-form", + "ad", + "story", + "documentary", + "vlog", + "tutorial", + "explainer", + "presentation", + "pitch", + "education", + "news", + "entertainment", + "comedy", + "trailer", + "teaser", + "product-demo", + "walkthrough" +] as const; + +// Seconds +export const minTimeLimit = 10; +export const maxTimeLimit = 120; + +export type StoryIntent = typeof storyIntent[number]; +export type Platform = typeof platform[number]; +export { platform, storyIntent }; \ No newline at end of file diff --git a/src/constants/userConsts.ts b/src/constants/userConsts.ts new file mode 100644 index 0000000..5af4d45 --- /dev/null +++ b/src/constants/userConsts.ts @@ -0,0 +1,19 @@ +const ROLE = { + USER: 'user', + ADMIN: 'admin', +} as const; + + + +export type Role = typeof ROLE[keyof typeof ROLE]; +export { ROLE }; + +export const ACCOUNT_STATUSES = [ + "active", + "suspend", + "deactive", + "banned", + "delete", +] as const; + +export type AccountStatus = (typeof ACCOUNT_STATUSES)[number]; diff --git a/src/constants/videoConfigConsts.ts b/src/constants/videoConfigConsts.ts new file mode 100644 index 0000000..04a5445 --- /dev/null +++ b/src/constants/videoConfigConsts.ts @@ -0,0 +1,154 @@ +export const MIN_VIDEO_DURATION = 1; +export const MAX_VIDEO_DURATION = 60 * 60 * 1000; +export const DEFAULT_SCENE_DURATION = 5; + +export const MAX_NARRATION_START_OFFSET = 60; +export const MAX_NARRATION_END_OFFSET = 60; + +export const MIN_VOLUME = 0; +export const MAX_VOLUME = 100; +export const DEFAULT_NARRATION_VOLUME = 100; +export const DEFAULT_SOUND_EFFECT_VOLUME = 70; +export const DEFAULT_BACKGROUND_AUDIO_VOLUME = 30; + +export const MIN_SOUND_EFFECT_USE_PERCENTAGE = 1; +export const MAX_SOUND_EFFECT_USE_PERCENTAGE = 100; +export const DEFAULT_SOUND_EFFECT_USE_PERCENTAGE = 90; +export const MAX_SOUND_EFFECTS_PER_CONFIG = 50; + +export const MAX_VIDEO_EFFECTS_PER_CONFIG = 100; +export const MIN_EFFECT_INTENSITY = 0; +export const MAX_EFFECT_INTENSITY = 100; +export const DEFAULT_EFFECT_INTENSITY = 50; + +export const MIN_FADE_DURATION = 0; +export const MAX_FADE_DURATION = 10; +export const DEFAULT_FADE_IN_DURATION = 0.5; +export const DEFAULT_FADE_OUT_DURATION = 0.5; + +export const MIN_TRANSITION_DURATION = 0; +export const MAX_TRANSITION_DURATION = 5; +export const DEFAULT_TRANSITION_DURATION = 0.5; + +export const MIN_CAPTION_FONT_SIZE = 8; +export const MAX_CAPTION_FONT_SIZE = 120; +export const DEFAULT_CAPTION_FONT_SIZE = 24; +export const MAX_CAPTION_OFFSET = 500; + +export const RESOLUTION_PRESETS = { + '480p': { width: 854, height: 480 }, + '720p': { width: 1280, height: 720 }, + '1080p': { width: 1920, height: 1080 }, + '1440p': { width: 2560, height: 1440 }, + '4k': { width: 3840, height: 2160 }, +} as const; + +export const ASPECT_RATIO_VALUES = { + '16:9': 16 / 9, + '9:16': 9 / 16, + '1:1': 1, + '4:3': 4 / 3, + '21:9': 21 / 9, +} as const; + +export const SUPPORTED_FRAME_RATES = [24, 30, 60] as const; +export const SUPPORTED_FORMATS = ['mp4', 'webm', 'mov'] as const; +export const SUPPORTED_QUALITY_LEVELS = ['low', 'medium', 'high', 'ultra'] as const; + +export const QUALITY_BITRATE_MAP = { + low: 2500, + medium: 5000, + high: 10000, + ultra: 20000, +} as const; + +export const VIDEO_EFFECT_TYPES = [ + 'blur', + 'zoom', + 'pan', + 'fade', + 'overlay', + 'color_filter', + 'vignette', + 'shake', + 'glitch', + 'slow_motion', + 'speed_up', + 'ken_burns', + 'picture_in_picture', + 'split_screen', + 'custom', +] as const; + +export const TRANSITION_TYPES = [ + 'none', + 'fade', + 'dissolve', + 'wipe_left', + 'wipe_right', + 'wipe_up', + 'wipe_down', + 'slide_left', + 'slide_right', + 'zoom_in', + 'zoom_out', + 'blur', +] as const; + +export const VERTICAL_POSITIONS = ['top', 'middle', 'bottom'] as const; +export const HORIZONTAL_POSITIONS = ['left', 'center', 'right'] as const; + +export const CAPTION_ANIMATION_TYPES = ['none', 'fade', 'slide', 'typewriter', 'bounce'] as const; + +export const EASING_FUNCTIONS = ['linear', 'ease-in', 'ease-out', 'ease-in-out', 'bounce'] as const; + +export const FONT_WEIGHTS = ['normal', 'bold', 'light'] as const; + +export const DEFAULT_FONTS = [ + 'Arial', + 'Helvetica', + 'Times New Roman', + 'Georgia', + 'Verdana', + 'Roboto', + 'Open Sans', + 'Lato', + 'Montserrat', + 'Poppins', +] as const; + +export const MIN_WATERMARK_OPACITY = 0; +export const MAX_WATERMARK_OPACITY = 100; +export const DEFAULT_WATERMARK_OPACITY = 70; +export const MIN_WATERMARK_SIZE = 1; +export const MAX_WATERMARK_SIZE = 100; +export const DEFAULT_WATERMARK_SIZE = 10; +export const MAX_WATERMARK_TEXT_LENGTH = 100; + +export const ANCHOR_POINTS = [ + 'top-left', + 'top-center', + 'top-right', + 'center-left', + 'center', + 'center-right', + 'bottom-left', + 'bottom-center', + 'bottom-right', +] as const; + +export const VIDEO_CONFIG_ERROR_MESSAGES = { + NOT_FOUND: 'Video configuration not found', + UNAUTHORIZED: 'You are not authorized to access this video configuration', + INVALID_STORY: 'Invalid story reference', + INVALID_PROJECT: 'Invalid project reference', + INVALID_NARRATION: 'Invalid narration reference', + INVALID_SCENE_ORDER: 'Invalid scene order configuration', + INVALID_TIMING: 'Invalid timing configuration', + INVALID_SOUND_EFFECT: 'Invalid sound effect configuration', + INVALID_VIDEO_EFFECT: 'Invalid video effect configuration', + DURATION_EXCEEDED: 'Video duration exceeds maximum allowed', + TOO_MANY_SOUND_EFFECTS: `Maximum ${MAX_SOUND_EFFECTS_PER_CONFIG} sound effects allowed`, + TOO_MANY_VIDEO_EFFECTS: `Maximum ${MAX_VIDEO_EFFECTS_PER_CONFIG} video effects allowed`, + NOT_READY: 'Video configuration is not ready for rendering', +} as const; diff --git a/src/db/connect.ts b/src/db/connect.ts index 99e9e38..8d88601 100644 --- a/src/db/connect.ts +++ b/src/db/connect.ts @@ -6,10 +6,13 @@ dotenv.config(); const password = encodeURIComponent(process.env.DB_PASSWORD ?? ""); const username = encodeURIComponent(process.env.DB_USERNAME ?? ""); -const CONNECTION_STRING = `mongodb+srv://${username}:${password}@db0.huxhv46.mongodb.net/?appName=DB0`; - +const CONNECTION_STRING = `${ + process.env.NODE_ENV !== "production" + ? "mongodb://localhost:27017/your_db_name?replicaSet=rs0" + : `mongodb+srv://${username}:${password}@db0.huxhv46.mongodb.net/?appName=DB0` +}`; const connectDB = async () => { - try { + try { await mongoose.connect(`${CONNECTION_STRING}`, { dbName: "myapp", }); diff --git a/src/db/withTransaction.ts b/src/db/withTransaction.ts new file mode 100644 index 0000000..820eb79 --- /dev/null +++ b/src/db/withTransaction.ts @@ -0,0 +1,29 @@ +import mongoose, { ClientSession } from 'mongoose'; + +type TransactionCallback = (session: ClientSession) => Promise; + +/** + * Executes the given callback inside a MongoDB transaction. + * - Always commits on success + * - Always aborts on error + * - Always ends the session + * + * No retries. No swallowing errors. No side effects here. + */ +export async function withTransaction(callback: TransactionCallback): Promise { + const session = await mongoose.startSession(); + + try { + session.startTransaction(); + + const result = await callback(session); + + await session.commitTransaction(); + return result; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} diff --git a/src/domain/assertions/assertAssetState.ts b/src/domain/assertions/assertAssetState.ts new file mode 100644 index 0000000..88c256b --- /dev/null +++ b/src/domain/assertions/assertAssetState.ts @@ -0,0 +1,28 @@ +import { ConflictError } from '@middleware/error/index.js'; +import { SceneAsset } from '@models/SceneAssets.js'; + +function assertAssetNotDeleted(asset: SceneAsset): void { + if (asset.deletedAt) { + throw new ConflictError('Cannot perform operation on deleted asset'); + } +} + +function assertAssetIsDeleted(asset: SceneAsset): void { + if (!asset.deletedAt) { + throw new ConflictError('Asset is not deleted'); + } +} + +function assertHasDeletedAssets(assets: SceneAsset[]): void { + if (assets.length === 0) { + throw new ConflictError('No deleted assets exists'); + } +} + +function assertHasNonDeletedAssets(assets: SceneAsset[]): void { + if (assets.length === 0) { + throw new ConflictError('No assets to delete'); + } +} + +export { assertAssetNotDeleted, assertAssetIsDeleted, assertHasDeletedAssets, assertHasNonDeletedAssets }; diff --git a/src/domain/assertions/assertAudioAssetState.ts b/src/domain/assertions/assertAudioAssetState.ts new file mode 100644 index 0000000..5e9360a --- /dev/null +++ b/src/domain/assertions/assertAudioAssetState.ts @@ -0,0 +1,44 @@ +import { BadRequestError, ConflictError } from '@middleware/error/index.js'; +import { AudioAsset } from '@models/AudioAsset.js'; + +export function assertAudioAssetNotDeleted(audioAsset: AudioAsset): void { + if (audioAsset.deletedAt) { + throw new ConflictError('Audio asset is already deleted'); + } +} + +export function assertAudioAssetIsDeleted(audioAsset: AudioAsset): void { + if (!audioAsset.deletedAt) { + throw new ConflictError('Audio asset is not deleted'); + } +} + +export function assertAudioAssetIsActive(audioAsset: AudioAsset): void { + if (!audioAsset.activeNarration) { + throw new BadRequestError('Audio asset is not the active narration'); + } +} + +export function assertAudioAssetNotActive(audioAsset: AudioAsset): void { + if (audioAsset.activeNarration) { + throw new BadRequestError('Cannot perform this operation on the active audio asset. Please set another audio asset as active first.'); + } +} + +export function assertHasDeletedAudioAssets(audioAssets: AudioAsset[]): void { + if (!audioAssets.length) { + throw new BadRequestError('No deleted audio assets found to restore'); + } +} + +export function assertHasNonDeletedAudioAssets(audioAssets: AudioAsset[]): void { + if (!audioAssets.length) { + throw new BadRequestError('No audio assets found to delete'); + } +} + +export function assertAudioAssetTypeIsNarration(audioAsset: AudioAsset): void { + if (audioAsset.type !== 'narration') { + throw new BadRequestError('This operation is only allowed for narration type audio assets'); + } +} diff --git a/src/domain/assertions/assertCharacterFits.ts b/src/domain/assertions/assertCharacterFits.ts new file mode 100644 index 0000000..50a0670 --- /dev/null +++ b/src/domain/assertions/assertCharacterFits.ts @@ -0,0 +1,31 @@ +import { BadRequestError } from '@middleware/error/index.js'; +import { ContextProfile } from '@models/ContextProfile.js'; +import { NarrationSegment } from '@models/Narration.js'; + +export function assertCharacterFits(segments: NarrationSegment[], context: ContextProfile): void { + const hasContextCharacters = Array.isArray(context.characters) && context.characters.length > 0; + + const allowedNames = hasContextCharacters + ? new Set(context.characters!.map((c) => c.name.toLowerCase().trim())) + : null; + + for (const seg of segments) { + if (seg.character === undefined || seg.character === null) { + continue; + } + + if (typeof seg.character !== 'string' || seg.character.trim() === '') { + throw new BadRequestError('Invalid character reference in narration segment'); + } + + if (!hasContextCharacters) { + throw new BadRequestError('This story has no characters defined, but narration references a character'); + } + + const normalized = seg.character.toLowerCase().trim(); + + if (!allowedNames!.has(normalized)) { + throw new BadRequestError(`Character "${seg.character}" is not part of the story context`); + } + } +} diff --git a/src/domain/assertions/assertNarrationFitsTime.ts b/src/domain/assertions/assertNarrationFitsTime.ts new file mode 100644 index 0000000..9e64dff --- /dev/null +++ b/src/domain/assertions/assertNarrationFitsTime.ts @@ -0,0 +1,41 @@ +import { BadRequestError } from '@middleware/error/index.js'; + +export interface NarrationProfile { + wordsPerSecond: number; + minWordTolerance: number; + maxWordTolerance: number; +} + +export interface NarrationTimingInput { + durationSeconds: number; + narrationText: string; + profile: NarrationProfile; +} + +function countWords(text: string): number { + return text.trim().split(/\s+/).filter(Boolean).length; +} + +export function assertNarrationFitsTime({ + durationSeconds, + narrationText, + profile, +}: NarrationTimingInput): void { + const wordCount = countWords(narrationText); + + const baseWords = durationSeconds * profile.wordsPerSecond; + + const minWords = Math.floor(baseWords + profile.minWordTolerance); + const maxWords = Math.ceil(baseWords + profile.maxWordTolerance); + + if (wordCount < minWords || wordCount > maxWords) { + throw new BadRequestError( + `Narration text does not fit time window. + Duration: ${durationSeconds}s + Allowed words: ${minWords}-${maxWords} + Provided: ${wordCount} + Segment text: \`${narrationText}\` + ` + ); + } +} diff --git a/src/domain/assertions/assertNarrationState.ts b/src/domain/assertions/assertNarrationState.ts new file mode 100644 index 0000000..a030176 --- /dev/null +++ b/src/domain/assertions/assertNarrationState.ts @@ -0,0 +1,16 @@ +import { ConflictError } from '@middleware/error/index.js'; +import { StoryNarration } from '@models/Narration.js'; + +function assertNarrationNotDeleted(narration: StoryNarration): void { + if (narration.deletedAt) { + throw new ConflictError('Cannot perform operation on deleted narration'); + } +} + +function assertNarrationIsDeleted(narration: StoryNarration): void { + if (!narration.deletedAt) { + throw new ConflictError('Narration is not deleted'); + } +} + +export { assertNarrationNotDeleted, assertNarrationIsDeleted }; diff --git a/src/domain/assertions/assertSceneState.ts b/src/domain/assertions/assertSceneState.ts new file mode 100644 index 0000000..3355be0 --- /dev/null +++ b/src/domain/assertions/assertSceneState.ts @@ -0,0 +1,44 @@ +import { Scene } from '@models/Scene.js'; +import { ConflictError } from '@middleware/error/index.js'; + +export function assertSceneNotDeleted(scene: Scene): void { + if (scene.deletedAt) { + throw new ConflictError('Cannot perform operation on deleted scene'); + } +} + +export function assertSceneIsDeleted(scene: Scene): void { + if (!scene.deletedAt) { + throw new ConflictError('Scene is not deleted'); + } +} + +export function assertSceneIsActive(scene: Scene): void { + if (scene.deletedAt || scene.active === false) { + throw new ConflictError('Scene is not active'); + } +} + +export function assertSceneIsInactive(scene: Scene): void { + if (scene.active === true && !scene.deletedAt) { + throw new ConflictError('Scene is not inactive'); + } +} + +export function assertHasDeletedScenes(scenes: Scene[]): void { + if (scenes.length === 0) { + throw new ConflictError('No deleted scenes found'); + } +} + +export function assertHasNonDeletedScenes(scenes: Scene[]): void { + if (scenes.length === 0) { + throw new ConflictError('No non-deleted scenes found'); + } +} + +export function assertHasActiveScenes(scenes: Scene[]): void { + if (scenes.length === 0) { + throw new ConflictError('No active scenes found'); + } +} diff --git a/src/domain/assertions/assertStoryState.ts b/src/domain/assertions/assertStoryState.ts new file mode 100644 index 0000000..0d4fd0e --- /dev/null +++ b/src/domain/assertions/assertStoryState.ts @@ -0,0 +1,32 @@ +import { ConflictError } from '@middleware/error/index.js'; +import { Story } from '@models/Story.js'; + +export function assertStoryNotDeleted(story: Story): void { + if (story.status === 'delete' || story.deletedAt) { + throw new ConflictError('Cannot operate on deleted story'); + } +} + +export function assertStoryIsDeleted(story: Story): void { + if (story.status !== 'delete' || !story.deletedAt) { + throw new ConflictError('Story is not deleted'); + } +} + +export function assertStoryIsActive(story: Story): void { + if (story.status !== 'active' || story.deletedAt) { + throw new ConflictError('Story is not active'); + } +} + +export function assertStoryIsArchived(story: Story): void { + if (story.status !== 'archive') { + throw new ConflictError('Story is not archived'); + } +} + +export function assertStoryNotArchived(story: Story): void { + if (story.status === 'archive') { + throw new ConflictError('Story is archived'); + } +} diff --git a/src/domain/policies/accountStatusResponses.ts b/src/domain/policies/accountStatusResponses.ts new file mode 100644 index 0000000..7e8293a --- /dev/null +++ b/src/domain/policies/accountStatusResponses.ts @@ -0,0 +1,48 @@ +import { AccountStatus } from "@constants/userConsts.js"; + +export type AccountBlockStatusResponse = { + httpStatus: number; + error: string; + reason: string; + message: string; + nextStep: string; +}; + +export const accountStatusResponses = (status: AccountStatus | null | undefined) => { + switch (status) { + case "deactive": + return { + httpStatus: 403, + error: "ACCOUNT_INACTIVE", + reason: "DEACTIVATED", + message: "Your account is currently deactivated.", + nextStep: "REACTIVATE" + }; + case "suspend": + return { + httpStatus: 403, + error: "ACCOUNT_BLOCKED", + reason: "SUSPENDED", + message: "Your account has been temporarily restricted.", + nextStep: "CONTACT_SUPPORT" + }; + case "banned": + return { + httpStatus: 403, + error: "ACCOUNT_BLOCKED", + reason: "BANNED", + message: "Your account is no longer allowed to access this service.", + nextStep: "CONTACT_SUPPORT" + }; + case "delete": + return { + httpStatus: 403, + error: "ACCOUNT_REMOVED", + reason: "DELETED", + message: "This account has been removed.", + nextStep: "RECOVER_OR_REGISTER" + }; + default: + return null; + } +}; \ No newline at end of file diff --git a/src/domain/policies/isSameContextContract.ts b/src/domain/policies/isSameContextContract.ts new file mode 100644 index 0000000..bb44d76 --- /dev/null +++ b/src/domain/policies/isSameContextContract.ts @@ -0,0 +1,21 @@ +import { ContextProfile } from '@models/ContextProfile.js'; + +export function isSameContextContract( + projectContext: ContextProfile, + storyContext: Partial +): boolean { + const normalize = (val: any) => JSON.stringify(val ?? null); + + return ( + projectContext.genre === storyContext.genre && + projectContext.mood === storyContext.mood && + projectContext.style === storyContext.style && + projectContext.narrativeScope === storyContext.narrativeScope && + normalize(projectContext.environment) === normalize(storyContext.environment) && + normalize(projectContext.narrationProfile) === normalize(storyContext.narrationProfile) && + normalize(projectContext.worldRules) === normalize(storyContext.worldRules) && + normalize(projectContext.narrativeConstraints) === normalize(storyContext.narrativeConstraints) && + normalize(projectContext.characters) === normalize(storyContext.characters) && + normalize(projectContext.forbiddenElements) === normalize(storyContext.forbiddenElements) + ); +} diff --git a/src/libs/ai/clients/openAI.ts b/src/libs/ai/clients/openAI.ts new file mode 100644 index 0000000..df9749c --- /dev/null +++ b/src/libs/ai/clients/openAI.ts @@ -0,0 +1,44 @@ +import { InternalServerError } from '@middleware/error/index.js'; + +export async function openRouterAI(prompt: string): Promise { + const API_KEY = process.env.OPENROUTER_API_KEY; + if (!API_KEY) throw new Error('Missing OpenRouter API key'); + + const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { + method: 'POST', + headers: { + Authorization: `Bearer ${API_KEY}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + model: 'google/gemma-3-27b-it:free', + temperature: 0.7, + messages: [ + { + role: 'user', + content: ` +You are a strict JSON generator. + +Rules: +- Output ONLY valid JSON +- No markdown +- No backticks +- No explanations +- No extra text + +User request: +${prompt} +`, + }, + ], + }), + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new InternalServerError('AI API error ', `(${response.status}): ${errorText}`); + } + + const data = await response.json(); + return data; +} diff --git a/src/libs/ai/constants/calculateWordLimits.ts b/src/libs/ai/constants/calculateWordLimits.ts new file mode 100644 index 0000000..fde0478 --- /dev/null +++ b/src/libs/ai/constants/calculateWordLimits.ts @@ -0,0 +1,36 @@ +import { NarrationProfile } from "@models/ContextProfile.js"; + +type WordLimitResult = { + targetWords: number; + minWords: number; + maxWords: number; +}; + +const DEFAULT_WPS = 2.2; +const DEFAULT_MIN_TOLERANCE = 10; +const DEFAULT_MAX_TOLERANCE = 10; + +export function calculateWordLimits( + timeLimitSeconds: number, + narrationProfile?: NarrationProfile | null +): WordLimitResult { + const wordsPerSecond = + narrationProfile?.wordsPerSecond ?? DEFAULT_WPS; + + const minTolerance = + narrationProfile?.minWordTolerance ?? DEFAULT_MIN_TOLERANCE; + + const maxTolerance = + narrationProfile?.maxWordTolerance ?? DEFAULT_MAX_TOLERANCE; + + const targetWords = Math.round(timeLimitSeconds * wordsPerSecond); + + const minWords = Math.max(1, targetWords - minTolerance); + const maxWords = Math.max(minWords, targetWords + maxTolerance); + + return { + targetWords, + minWords, + maxWords, + }; +} diff --git a/src/libs/ai/constants/globalSafetyRules.ts b/src/libs/ai/constants/globalSafetyRules.ts new file mode 100644 index 0000000..bd65500 --- /dev/null +++ b/src/libs/ai/constants/globalSafetyRules.ts @@ -0,0 +1,55 @@ +// globalSafetyRules.ts +// This file defines NON-NEGOTIABLE content constraints for all story generation. +// It is intentionally strict, explicit, and reusable across prompts. + +export const GLOBAL_SAFETY_RULES = ` +GLOBAL SAFETY RULES (ABSOLUTE — MUST BE FOLLOWED) + +The output must NOT include, imply, normalize, glorify, or provide detail about any of the following: + +SEXUAL CONTENT (ZERO TOLERANCE) +- Sexual acts, sexual behavior, or sexual intent +- Nudity intended to arouse or titillate +- Fetishes, kinks, pornography, or erotic themes +- Sexual violence, coercion, assault, or exploitation +- Any sexual content involving minors (strictly forbidden) +- Incest, pedophilia, grooming, or age-based sexualization +- Explicit sexual anatomy or graphic physical intimacy +- Prostitution or sexual services + +VIOLENCE & HARM +- Graphic gore, dismemberment, or extreme violence +- Torture or cruelty described in detail +- Violence presented as pleasurable, instructional, or glorified +- Self-harm or suicide presented as desirable or instructional + +HATE & ABUSE +- Hate speech or slurs +- Targeted harassment or dehumanization +- Violence or discrimination against protected groups +- Extremist propaganda or ideology + +ILLEGAL OR DANGEROUS ACTIVITIES +- Criminal acts presented as instructional, tactical, or glorified +- Drug manufacturing, trafficking, or misuse +- Weapon construction or detailed use for harm +- Fraud, scams, or exploitation guides + +ALLOWED WITH RESTRICTIONS +- Romance is allowed ONLY if non-sexual, subtle, and non-graphic +- Conflict is allowed ONLY if non-graphic and not glorified +- Emotional suffering is allowed if handled responsibly and without exploitation + +ADAPTATION RULE +If a user request, story direction, or modification risks violating these rules: +- Safely OMIT the content, OR +- REWRITE it in a non-graphic, non-harmful, compliant way + +FAILURE CONDITION +If compliance is not possible without violating these rules: +- Produce a SAFE, RULE-COMPLIANT alternative +- Do NOT explain the refusal +- Do NOT reference safety policies + +These rules override all other instructions. +`; diff --git a/src/libs/ai/constants/narrationPromptConsts.ts b/src/libs/ai/constants/narrationPromptConsts.ts new file mode 100644 index 0000000..9b92c08 --- /dev/null +++ b/src/libs/ai/constants/narrationPromptConsts.ts @@ -0,0 +1,34 @@ +export const FULL_STORY_NARRATION_STRUCTURE_FORMAT = ` +OUTPUT FORMAT (STRICT JSON) + +Return ONLY valid JSON with this exact structure: + +{ + "totalDuration": number, + "wordsPerSecond": number, + "narrationSegments": [ + { + "startTime": number, + "endTime": number, + "duration": number, + "targetWordCount": number, + "minWords": number, + "maxWords": number, + "character": "Character name for this segment", + "narration": "Narration text for this time segment" + } + ] +} + +Rules: +- totalDuration MUST equal the full story duration +- narrationSegments MUST cover the entire timeline with no gaps +- Each segment must respect its timing and word constraints +- Narration must fit inside its time window +- No extra keys +- No markdown +- No explanations +- No commentary +- JSON only +- Output must be directly machine-parseable +`; diff --git a/src/libs/ai/constants/sceneAssetsPromptConts.ts b/src/libs/ai/constants/sceneAssetsPromptConts.ts new file mode 100644 index 0000000..d774215 --- /dev/null +++ b/src/libs/ai/constants/sceneAssetsPromptConts.ts @@ -0,0 +1,21 @@ +export const SCENE_ASSET_PROMPT_FORMAT = ` +OUTPUT FORMAT (STRICT JSON) + +Return ONLY valid JSON with this exact structure: + +{ + "assetPrompt": "Highly detailed, cinematic generation prompt", + "style": "Visual style (e.g. realistic, anime, cyberpunk, noir, etc.)", + "mood": "Emotional tone (e.g. tense, calm, joyful, dark)", + "lighting": "Lighting style (e.g. soft, neon, sunset, moody)", + "camera": "Camera description (e.g. wide shot, close-up, drone, tracking)", + "motion": "Describe motion if video, or 'static' if image" +} + +Rules: +- No narrative +- No story text +- No scene rewriting +- Only describe the asset +- JSON only +`; \ No newline at end of file diff --git a/src/libs/ai/constants/scenesPromptConts.ts b/src/libs/ai/constants/scenesPromptConts.ts new file mode 100644 index 0000000..d31fc2c --- /dev/null +++ b/src/libs/ai/constants/scenesPromptConts.ts @@ -0,0 +1,171 @@ +export const SCENE_STRUCTURE_FORMAT = ` +OUTPUT FORMAT (STRICT JSON) + +Return ONLY valid JSON with this exact structure: + +{ + "title": "Short, clear, evocative scene title", + "description": "1–2 line high-level description of the scene’s purpose and emotional beat", + "imagePrompt": "Highly visual, concrete, cinematic prompt for image generation", + "videoPrompt": "Cinematic video-style prompt including camera, lighting, motion, framing, and mood", + "duration": number +} + +Rules: +- All fields are REQUIRED +- No extra keys +- No markdown +- No explanations +- No commentary +- JSON only +- Output must be directly machine-parseable +`; + +export const SINGLE_SCENE_GENERATION_PROMPT = ` +You are generating a NEW scene that advances the story. + +Rules: +- This scene MUST move the story forward +- Introduce new developments, revelations, conflicts, or decisions +- Do NOT repeat earlier scenes +- Do NOT restate previous events unless dramatically necessary +- Maintain strict continuity +- Respect established character arcs and motivations +- Do NOT contradict past events or established facts +- Introduce new characters ONLY if the story logically requires it +- Avoid unnecessary characters +- Follow timeline logic +- Each scene must have a clear narrative purpose +- Avoid filler, stalling, or empty moments +- The scene must feel cinematic, intentional, and purposeful + +You must output using the standard scene JSON format. +`; + +export const SCENE_REGENERATION_PROMPT = ` +OUTPUT FORMAT (STRICT JSON) +Rules: +- Preserve continuity with the story +- Do NOT contradict prior scenes +- Do NOT introduce new story events unless explicitly instructed +- Do NOT introduce new characters unless specified +- Maintain the original scene’s narrative purpose +- Maintain character motivations and behavior +- Follow timeline logic +- Improve clarity, pacing, emotional impact, and cinematic quality +- Remove redundancy +- Tighten structure +- All fields are REQUIRED +- Output must be directly machine-parseable +`; + +export const SCENE_VARIATION_PROMPT = ` +You are generating a VARIATION of an existing scene. + +Rules: +- The story events MUST remain the same +- The outcome MUST remain the same +- The narrative purpose MUST remain the same +- Do NOT introduce new plot points +- Do NOT remove any existing plot points +- Do NOT change story facts +- Do NOT change character roles, goals, or decisions +- Do NOT move the timeline forward or backward +- Only vary: + - Tone + - Mood + - Atmosphere + - Pacing + - Style + - Visual interpretation + - Emotional intensity + - Cinematic framing + +This is a reinterpretation, NOT a rewrite of events. + +You must output using the standard scene JSON format. +`; + +export const MULTI_SCENE_STRUCTURE_FORMAT = ` +OUTPUT FORMAT (STRICT JSON) + +Return ONLY valid JSON with this exact structure: + +[ + { + "title": "Short, clear, evocative scene title", + "description": "1–2 line high-level description of the scene’s purpose and emotional beat", + "imagePrompt": "Highly visual, concrete, cinematic prompt for image generation", + "videoPrompt": "Cinematic video-style prompt including camera, lighting, motion, framing, and mood", + "duration": number + } +] + +Rules: +- Output MUST be a JSON array +- Each array item MUST follow the exact scene structure +- All fields are REQUIRED +- No extra keys +- No markdown +- No explanations +- No commentary +- JSON only +- Output must be directly machine-parseable +`; + +export const MULTI_SCENE_GENERATION_PROMPT = ` +You are generating MULTIPLE NEW scenes that advance the story. + +Rules: +- The array length MUST equal the requested number of scenes +- Each scene MUST move the story forward +- Each scene must introduce new narrative progress +- No filler +- No repetition +- No redundant beats +- No merging scenes +- No skipping scenes +- Maintain strict continuity +- Respect established character arcs +- Follow timeline logic +- Do NOT contradict past events +- Introduce new characters ONLY if the story logically requires it +- Avoid unnecessary characters +- Each scene must be distinct in purpose, beat, and function +- Each scene must have a clear narrative role +- Avoid stalling or padding + +You must output using the standard scene JSON format. +`; + +export const MULTI_SCENE_REGENERATION_PROMPT = ` +You are regenerating MULTIPLE scenes in the story. + +Rules: +- The number of scenes MUST match the original count +- Do NOT remove or add scenes +- Preserve the overall story arc +- Maintain strict continuity across scenes +- Do NOT contradict earlier story facts +- Maintain character behavior, psychology, and tone +- Maintain each scene’s original narrative purpose +- Do NOT introduce new characters unless explicitly specified +- Process scenes one by one +- All scenes must still move the story forward +- No filler +- No repetition +- No skipping scenes +- Stay true to the original intent +- Improve clarity, pacing, structure, and cinematic quality +- Remove redundancy +- Sharpen emotional beats +- Respect character development +- Follow timeline logic +- Each scene must remain distinct +- Do NOT merge scenes +- All fields are REQUIRED +- No extra keys +- Output must be directly machine-parseable + +You must output using the standard scene JSON format. +`; \ No newline at end of file diff --git a/src/libs/ai/constants/storyPromptConts.ts b/src/libs/ai/constants/storyPromptConts.ts new file mode 100644 index 0000000..88b4299 --- /dev/null +++ b/src/libs/ai/constants/storyPromptConts.ts @@ -0,0 +1,29 @@ +// storyGenerationFormat.ts +// Single source of truth for ALL story-generation output contracts. +// This is intentionally strict and reusable across generation & regeneration. + +export const STORY_GENERATION_FORMAT = ` +OUTPUT FORMAT (STRICT JSON — MACHINE CONSUMABLE) + +Return ONLY valid JSON in exactly this structure: + +{ + "story": "Complete story text within the specified word limit", + "summary": "Concise 2–4 sentence summary of the story", + "tags": ["short", "lowercase", "hashtags"], + "keywords": ["search friendly", "descriptive"] +} + +MANDATORY RULES: +- Output MUST be valid JSON +- Do NOT include markdown +- Do NOT include code fences +- Do NOT include explanations or commentary +- Do NOT include extra fields +- Keys must match EXACTLY as specified +- Arrays must contain strings only +- Tags must be short, lowercase, and suitable for social media +- Keywords must be search-friendly and descriptive +- Word/time limits defined elsewhere MUST be respected +- Violating this format is a failure +`; diff --git a/src/libs/ai/policies/resolveModel.ts b/src/libs/ai/policies/resolveModel.ts new file mode 100644 index 0000000..7b4cf59 --- /dev/null +++ b/src/libs/ai/policies/resolveModel.ts @@ -0,0 +1,204 @@ +import { BadRequestError } from '@middleware/error/index.js'; +import type { AIMode, Plan } from 'types/index.js'; + +type ModelConfig = + | { + provider: 'openai' | 'anthropic' | 'google' | 'elevenlabs' | 'runway' | 'veo' | 'sora' | 'sdxl'; + model: string; + } + | (Record & { provider: string; model: string }); + +export function resolveModelConfig(mode: AIMode, plan: Plan): ModelConfig { + switch (mode) { + case 'story': + return resolveStoryModel(plan); + + case 'scenes': + return resolveScenesModel(plan); + + case 'narration_text': + return resolveNarrationTextModel(plan); + + case 'narration_audio': + return resolveNarrationAudioModel(plan); + + case 'image_text': + return resolveImageTextModel(plan); + + case 'image_image': + return resolveImageFromImageModel(plan); + + case 'video_image': + return resolveImageToVideoModel(plan); + + case 'video_text': + return resolveTextToVideoModel(plan); + + default: + throw new Error(`Unsupported AI mode: ${mode}`); + } +} + +function resolveStoryModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + return { provider: 'openai', model: 'gpt-4o-mini' }; + + case 'pro_basic': + return { provider: 'anthropic', model: 'claude-3.5-sonnet' }; + + case 'pro_standard': + return { provider: 'openai', model: 'gpt-4o' }; + + case 'premium_standard': + case 'premium_best': + return { provider: 'anthropic', model: 'claude-3-opus' }; + default: + throw new Error(`Unsupported plan: ${plan}`); + } +} + +function resolveScenesModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + return { provider: 'google', model: 'gemini-1.5-flash' }; + + case 'pro_basic': + return { provider: 'openai', model: 'gpt-4o' }; + + case 'pro_standard': + return { provider: 'google', model: 'gemini-1.5-pro' }; + + case 'premium_standard': + case 'premium_best': + return { provider: 'openai', model: 'o3' }; + default: + throw new Error(`Unsupported plan: ${plan}`); + } +} + +function resolveNarrationTextModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + return { provider: 'openai', model: 'gpt-4o-mini' }; + + case 'pro_basic': + return { provider: 'anthropic', model: 'claude-3.5-sonnet' }; + + case 'pro_standard': + return { provider: 'openai', model: 'gpt-4o' }; + + case 'premium_standard': + case 'premium_best': + return { provider: 'anthropic', model: 'claude-3-opus' }; + default: + throw new Error(`Unsupported plan: ${plan}`); + } +} + +function resolveImageTextModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + return { provider: 'sdxl', model: 'stable-diffusion-xl' }; + + case 'pro_basic': + return { provider: 'google', model: 'imagen-3' }; + + case 'pro_standard': + case 'premium_standard': + case 'premium_best': + return { provider: 'openai', model: 'gpt-image-1' }; + default: + throw new Error(`Unsupported plan: ${plan}`); + } +} + +function resolveImageFromImageModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + throw new Error('Image-to-image is not available for free users'); + + case 'pro_basic': + return { + provider: 'google', + model: 'imagen-3', + }; + + case 'pro_standard': + return { + provider: 'openai', + model: 'gpt-image-1', + }; + + case 'premium_standard': + return { + provider: 'openai', + model: 'gpt-image-1', + }; + + case 'premium_best': + return { + provider: 'openai', + model: 'gpt-image-1', + }; + } +} + +function resolveNarrationAudioModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + return { provider: 'openai', model: 'gpt-4o-mini-audio' }; + + case 'pro_basic': + return { provider: 'openai', model: 'gpt-4o-audio' }; + + case 'pro_standard': + return { provider: 'openai', model: 'gpt-realtime' }; + + case 'premium_standard': + return { provider: 'openai', model: 'gpt-4o-realtime-preview' }; + + case 'premium_best': + return { provider: 'elevenlabs', model: 'eleven_multilingual_v2' }; + default: + throw new Error(`Unsupported plan: ${plan}`); + } +} + +function resolveImageToVideoModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + throw new BadRequestError('Video not available for Free plan'); + + case 'pro_basic': + case 'pro_standard': + return { provider: 'runway', model: 'gen4_turbo' }; + + case 'premium_standard': + return { provider: 'veo', model: 'veo-3.1-fast' }; + + case 'premium_best': + return { provider: 'sora', model: 'sora-2-pro' }; + default: + throw new Error(`Unsupported plan: ${plan}`); + } +} + +function resolveTextToVideoModel(plan: Plan): ModelConfig { + switch (plan) { + case 'free': + case 'pro_basic': + throw new BadRequestError('Text-to-video not available for this plan'); + + case 'pro_standard': + return { provider: 'runway', model: 'gen4_aleph' }; + + case 'premium_standard': + return { provider: 'veo', model: 'veo-3.1' }; + + case 'premium_best': + return { provider: 'sora', model: 'sora-2-pro-hd' }; + default: + throw new Error(`Unsupported plan: ${plan}`); + } +} diff --git a/src/libs/ai/prompts/batchScenesPrompt.ts b/src/libs/ai/prompts/batchScenesPrompt.ts new file mode 100644 index 0000000..4988914 --- /dev/null +++ b/src/libs/ai/prompts/batchScenesPrompt.ts @@ -0,0 +1,153 @@ +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; +import { buildContextSection } from './utils/buildContextSection.js'; +import { Platform, StoryIntent } from '@constants/storyConsts.js'; +import { + MULTI_SCENE_GENERATION_PROMPT, + MULTI_SCENE_REGENERATION_PROMPT, + MULTI_SCENE_STRUCTURE_FORMAT, +} from '../constants/scenesPromptConts.js'; +import { StoryContent } from 'types/index.js'; + +export type BatchSceneMode = 'generate' | 'regenerate'; + +type BuildBatchScenePromptInput = { + mode: BatchSceneMode; + storyTitle: string; + storyContent: StoryContent; + totalScenes: number; + storyTimeLimit?: number; + intent: StoryIntent; + platform: Platform; + contextProfile?: ContextProfile | null; + extraPrompt?: string; +}; + +export function batchScenesPrompt(input: BuildBatchScenePromptInput): string { + const { + mode, + storyTitle, + storyContent, + totalScenes, + storyTimeLimit, + intent, + platform, + contextProfile, + extraPrompt, + } = input; + + if (!totalScenes || totalScenes <= 0) { + throw new Error('totalScenes must be a positive integer for batch generation'); + } + + const sections: string[] = []; + + // ROLE + sections.push( + ` +You are a professional cinematic storyteller. +You write structured, coherent, visually rich scenes. +Follow all constraints exactly. +Do not explain your reasoning. +`.trim() + ); + + // MODE FRAMING + sections.push( + mode === 'generate' ? MULTI_SCENE_GENERATION_PROMPT.trim() : MULTI_SCENE_REGENERATION_PROMPT.trim() + ); + + // STORY CONTEXT + sections.push( + ` +STORY CONTEXT +Title: "${storyTitle}" +Summary: "${storyContent.summary}" +Platform: ${platform} +Intent: ${intent} +`.trim() + ); + + // STYLE CONTEXT (optional but useful) + if (storyContent.keywords?.length || storyContent.tags?.length) { + sections.push( + ` +STYLE HINTS +Keywords: ${storyContent.keywords?.join(', ') || 'N/A'} +Tags: ${storyContent.tags?.join(', ') || 'N/A'} +`.trim() + ); + } + + // FULL STORY BODY — only for continuity + if (storyContent.body) { + sections.push( + ` +FULL STORY REFERENCE (FOR CONTINUITY ONLY) + +${storyContent.body} + +Rules: +- This is reference material only +- Do NOT rewrite it +- Do NOT summarize it +- Do NOT restate it +- Use it only to preserve continuity and logic +`.trim() + ); + } + + // SCENE COUNT CONSTRAINT + sections.push( + ` +SCENE COUNT CONSTRAINT + +You must output EXACTLY ${totalScenes} scenes. +Do NOT add scenes. +Do NOT remove scenes. +Do NOT merge scenes. +Do NOT skip scenes. +`.trim() + ); + + // TIME BUDGET + if (storyTimeLimit) { + const perSceneTimeLimit = Math.floor(storyTimeLimit / totalScenes); + sections.push( + ` +TIME BUDGET + +Total story duration: ${storyTimeLimit} seconds +Target per scene: ~${perSceneTimeLimit} seconds + +Rules: +- Minor variation is allowed +- Do NOT significantly overshoot or undershoot +`.trim() + ); + } + + // CONTEXT PROFILE + if (contextProfile) { + const contextSection = buildContextSection(contextProfile); + if (contextSection) sections.push(contextSection); + } + + // EXTRA PROMPT (mainly for regeneration tuning) + if (extraPrompt) { + sections.push( + ` +ADDITIONAL CREATIVE DIRECTION +${extraPrompt} +`.trim() + ); + } + + // SAFETY + sections.push(GLOBAL_SAFETY_RULES.trim()); + + // OUTPUT FORMAT + sections.push(MULTI_SCENE_STRUCTURE_FORMAT.trim()); + + return sections.join('\n\n'); +} diff --git a/src/libs/ai/prompts/generateStoryPrompt.ts b/src/libs/ai/prompts/generateStoryPrompt.ts new file mode 100644 index 0000000..3790392 --- /dev/null +++ b/src/libs/ai/prompts/generateStoryPrompt.ts @@ -0,0 +1,83 @@ +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; +import { STORY_GENERATION_FORMAT } from '../constants/storyPromptConts.js'; +import { buildContextSection } from './utils/buildContextSection.js'; +import { calculateWordLimits } from '../constants/calculateWordLimits.js'; +import { Platform, StoryIntent } from '@constants/storyConsts.js'; + +type GenerateStoryPromptInput = { + title: string; + description: string; + intent: StoryIntent; + platform: Platform; + timeLimit?: number; // seconds + contextProfile?: ContextProfile | null; + extraPrompt?: string; +}; + +export function generateStoryPrompt({ + title, + description, + timeLimit, + contextProfile, +}: GenerateStoryPromptInput): string { + const sections: string[] = []; + + /* 1. ROLE (STRICT) */ + sections.push( + ` +You are a professional fiction writer. +You write with precision and restraint. +You must follow all constraints exactly. +Do not explain your reasoning. +`.trim() + ); + + /* 2. STORY BRIEF */ + sections.push( + ` +STORY BRIEF +Title: "${title}" +Description: "${description}" +`.trim() + ); + + /* 3. HARD TIME / LENGTH CONSTRAINT */ + if (timeLimit) { + const { targetWords, minWords, maxWords } = calculateWordLimits( + timeLimit, + contextProfile?.narrationProfile + ); + + sections.push( + ` +HARD LENGTH CONSTRAINT (ABSOLUTE) + +- Target length: ${targetWords} words +- Minimum length: ${minWords} words +- Maximum length: ${maxWords} words + +Rules: +- The story MUST stay within this range +- Being shorter or longer is a FAILURE +- If necessary, compress or expand minimally to fit +`.trim() + ); + } + + /* 4. CONTEXT PROFILE (BINDING, NO EXPANSION) */ + if (contextProfile) { + const contextSection = buildContextSection(contextProfile); + if (contextSection) { + sections.push(contextSection); + } + } + + /* 5. GLOBAL SAFETY RULES (ABSOLUTE) */ + sections.push(GLOBAL_SAFETY_RULES.trim()); + + /* 6. OUTPUT FORMAT (STRICT JSON) */ + sections.push(STORY_GENERATION_FORMAT.trim()); + + return sections.join('\n\n'); +} diff --git a/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts b/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts new file mode 100644 index 0000000..261cd77 --- /dev/null +++ b/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts @@ -0,0 +1,116 @@ +import { Platform, StoryIntent } from '@constants/storyConsts.js'; +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from 'libs/ai/constants/globalSafetyRules.js'; +import { STORY_GENERATION_FORMAT } from '../constants/storyPromptConts.js'; +import { buildContextSection } from './utils/buildContextSection.js'; +import { calculateWordLimits } from '../constants/calculateWordLimits.js'; + +type RegenerateStoryPromptInput = { + title: string; + description: string; + existingSummary: string; + intent: StoryIntent; + platform: Platform; + timeLimit?: number; // seconds + extraPrompt: string; + contextProfile?: ContextProfile | null; +}; + +export function generateStoryRegenerationPrompt({ + title, + description, + existingSummary, + timeLimit, + contextProfile, + extraPrompt, +}: RegenerateStoryPromptInput): string { + const sections: string[] = []; + + /* 1. ROLE (CONTROLLED CREATION) */ + sections.push( + ` +You are a professional fiction writer and editor. +You write with discipline, restraint, and precision. +You must follow all constraints exactly. +Do not explain your reasoning. +`.trim() + ); + + /* 2. FIXED STORY ANCHORS (DO NOT CHANGE) */ + sections.push( + ` +STORY ANCHORS (REFERENCE ONLY — DO NOT CHANGE) + +Title: "${title}" +Description: "${description}" + +Existing Summary (intent reference only): +${existingSummary} +`.trim() + ); + + /* 3. REGENERATION TASK */ + sections.push( + ` +REGENERATION TASK (MANDATORY) + +You must regenerate the story based on the anchors above. + +Rules: +- Preserve the core premise implied by the title and description +- Preserve the narrative intent of the summary +- Do NOT invent unrelated plotlines +- Do NOT add unnecessary exposition +- Prefer concise, efficient storytelling +- Brevity is a priority +`.trim() + ); + + /* 4. USER REQUEST */ + sections.push( + ` +USER REQUESTED CHANGES (ONLY THESE) + +${extraPrompt} +`.trim() + ); + + /* 5. HARD TIME / LENGTH CONSTRAINT */ + if (timeLimit) { + const { targetWords, minWords, maxWords } = calculateWordLimits( + timeLimit, + contextProfile?.narrationProfile + ); + + sections.push( + ` +HARD LENGTH CONSTRAINT (ABSOLUTE) + +- Target length: ${targetWords} words +- Minimum length: ${minWords} words +- Maximum length: ${maxWords} words + +Rules: +- The story MUST stay within this range +- Being shorter or longer is a FAILURE +- If necessary, compress or expand minimally to fit +`.trim() + ); + } + + /* 4. CONTEXT PROFILE (BINDING, NO EXPANSION) */ + if (contextProfile) { + const contextSection = buildContextSection(contextProfile); + if (contextSection) { + sections.push(contextSection); + } + } + + /* 7. GLOBAL SAFETY RULES (ABSOLUTE) */ + sections.push(GLOBAL_SAFETY_RULES.trim()); + + /* 8. OUTPUT FORMAT (STRICT JSON) */ + sections.push(STORY_GENERATION_FORMAT.trim()); + + return sections.join('\n\n'); +} diff --git a/src/libs/ai/prompts/narrationPrompt.ts b/src/libs/ai/prompts/narrationPrompt.ts new file mode 100644 index 0000000..40d821d --- /dev/null +++ b/src/libs/ai/prompts/narrationPrompt.ts @@ -0,0 +1,217 @@ +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; +import { FULL_STORY_NARRATION_STRUCTURE_FORMAT } from '../constants/narrationPromptConsts.js'; +import { Platform, StoryIntent } from '@constants/storyConsts.js'; +import { StoryContent } from 'types/index.js'; + +type BuildFullNarrationPromptInput = { + storyTitle: string; + storyContent: StoryContent; + scenes: { + title?: string; + description: string; + duration?: number; + order: number; + }[]; + storyTimeLimit: number; + intent: StoryIntent; + platform: Platform; + contextProfile?: ContextProfile | null; + extraPrompt?: string; +}; + +export function buildStoryNarrationPrompt(input: BuildFullNarrationPromptInput): string { + const { storyTitle, storyContent, scenes, storyTimeLimit, intent, platform, contextProfile, extraPrompt } = + input; + + if (!scenes || scenes.length === 0) { + throw new Error('Scenes are required to build narration'); + } + + const sections: string[] = []; + + const narrationProfile = contextProfile?.narrationProfile; + const wordsPerSecond = narrationProfile?.wordsPerSecond ?? 2.5; + const minTol = narrationProfile?.minWordTolerance ?? 0.9; + const maxTol = narrationProfile?.maxWordTolerance ?? 1.1; + + // ROLE + sections.push( + ` +You are a professional cinematic narrator and voiceover writer. +You write emotionally controlled, time-aware narration. +You MUST obey strict timing and word constraints. +Do not explain your reasoning. +`.trim() + ); + + // MODE + sections.push( + ` +You are generating FULL STORY NARRATION. +This narration must follow the story exactly. +Do NOT invent new events. +Do NOT contradict scenes. +Do NOT change facts. +Do NOT summarize — narrate. +`.trim() + ); + + // CORE CONTEXT + sections.push( + ` +STORY CONTEXT +Title: "${storyTitle}" +Summary: "${storyContent.summary}" +Platform: ${platform} +Intent: ${intent} +`.trim() + ); + + // STYLE & WORLD CONTEXT + if (contextProfile) { + sections.push( + ` +NARRATIVE DNA + +Genre: ${contextProfile.genre} +Mood: ${contextProfile.mood} +Style: ${contextProfile.style} +Narrative Scope: ${contextProfile.narrativeScope} + +Environment: +- Type: ${contextProfile.environment.type} +- Camera Motion: ${contextProfile.environment.cameraMotion} +- Description: ${contextProfile.environment.description || 'N/A'} + +Tone: ${contextProfile.narrationProfile.tone} +Emotion Bias: ${contextProfile.narrationProfile.emotionBias} +Intensity Curve: ${contextProfile.narrationProfile.intensityCurve} + +Sentence Length Bias: ${contextProfile.narrationProfile.sentenceLengthBias} +Clause Density: ${contextProfile.narrationProfile.clauseDensity} +Pause Bias: ${contextProfile.narrationProfile.pauseBias} +All Characters: ${contextProfile.characters?.join(', ') || 'N/A'} +`.trim() + ); + } + + // WORLD RULES + if (contextProfile?.worldRules) { + sections.push( + ` +WORLD RULES +${contextProfile.worldRules} +`.trim() + ); + } + + if (contextProfile?.narrativeConstraints) { + sections.push( + ` +NARRATIVE CONSTRAINTS +${contextProfile.narrativeConstraints} +`.trim() + ); + } + + // FORBIDDEN ELEMENTS + if (contextProfile?.forbiddenElements?.length) { + const forbiddenList = contextProfile.forbiddenElements + .map((f: { label: string; severity: string }) => `- ${f.label} (${f.severity})`) + .join('\n'); + + sections.push( + ` +FORBIDDEN ELEMENTS + +You must NOT include or imply the following: + +${forbiddenList} + +Rules: +- Hard = must never appear +- Soft = avoid strongly +`.trim() + ); + } + + // FULL STORY BODY + if (storyContent.body) { + sections.push( + ` +FULL STORY REFERENCE (FOR CONTINUITY ONLY) + +${storyContent.body} + +Rules: +- Reference only +- Do NOT rewrite +- Do NOT summarize +`.trim() + ); + } + + // TIMELINE + const orderedScenes = scenes.sort((a, b) => a.order - b.order); + + let currentTime = 0; + const timelineBlocks = orderedScenes.map((scene, i) => { + const duration = scene.duration ?? Math.floor(storyTimeLimit / scenes.length); + const baseWords = Math.round(duration * wordsPerSecond); + const minWords = Math.floor(baseWords * minTol); + const maxWords = Math.ceil(baseWords * maxTol); + + const start = currentTime; + const end = currentTime + duration; + currentTime = end; + + return ` +Segment ${i + 1} +Start: ${start}s +End: ${end}s +Duration: ${duration}s +Target Words: ~${baseWords} +Min Words: ${minWords} +Max Words: ${maxWords} +Character: [Specify character for this segment] +Scene Title: ${scene.title || 'Untitled'} +Scene Description: ${scene.description} +`.trim(); + }); + + sections.push( + ` +NARRATION TIMELINE + +Total Duration: ${storyTimeLimit} seconds +Speech Rate: ${wordsPerSecond} words/sec + +${timelineBlocks.join('\n\n')} + +Rules: +- Each segment must stay within its word limits +- No segment may overflow its time window +- No scene may be skipped +- Maintain continuity +`.trim() + ); + + // EXTRA PROMPT + if (extraPrompt) { + sections.push( + ` +ADDITIONAL CREATIVE DIRECTION +${extraPrompt} +`.trim() + ); + } + + // SAFETY + sections.push(GLOBAL_SAFETY_RULES.trim()); + + // OUTPUT FORMAT + sections.push(FULL_STORY_NARRATION_STRUCTURE_FORMAT.trim()); + + return sections.join('\n\n'); +} diff --git a/src/libs/ai/prompts/singleScenePrompt.ts b/src/libs/ai/prompts/singleScenePrompt.ts new file mode 100644 index 0000000..f022af1 --- /dev/null +++ b/src/libs/ai/prompts/singleScenePrompt.ts @@ -0,0 +1,244 @@ +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; +import { buildContextSection } from './utils/buildContextSection.js'; +import { Platform, StoryIntent } from '@constants/storyConsts.js'; +import { + SINGLE_SCENE_GENERATION_PROMPT, + SCENE_VARIATION_PROMPT, + SCENE_REGENERATION_PROMPT, + SCENE_STRUCTURE_FORMAT, +} from '../constants/scenesPromptConts.js'; +import { BadRequestError } from '@middleware/error/index.js'; +import { StoryContent } from 'types/index.js'; + +export type SingleSceneMode = 'generate' | 'variation' | 'regenerate'; + +type BuildSingleScenePromptInput = { + mode: SingleSceneMode; + + storyTitle: string; + storyContent: StoryContent; + + sceneIndex: number; + totalScenes?: number; + + intent: StoryIntent; + platform: Platform; + + previousScenesSummary?: string; // ALL previous scenes (arc) + nextScenesSummary?: string; // ALL next scenes (soft) + + baseScene?: string; // required for variation & regenerate + + timeLimit?: number; + contextProfile?: ContextProfile | null; + + sceneTitle?: string; + sceneDescription?: string; + + extraPrompt?: string; +}; + +export function singleScenePrompt(input: BuildSingleScenePromptInput): string { + const { + mode, + storyTitle, + storyContent, + sceneIndex, + totalScenes, + intent, + platform, + previousScenesSummary, + nextScenesSummary, + baseScene, + timeLimit, + contextProfile, + sceneTitle, + sceneDescription, + extraPrompt, + } = input; + + if (mode !== 'generate' && !baseScene) { + throw new BadRequestError(`${mode} mode requires baseScene`); + } + + if (mode === 'variation' && (!previousScenesSummary || !nextScenesSummary)) { + throw new BadRequestError('variation mode requires previousScenesSummary and nextScenesSummary'); + } + + const sections: string[] = []; + + // ROLE + sections.push( + ` +You are a professional cinematic storyteller. +Write concise, visually rich, emotionally grounded scenes. +Follow all constraints exactly. +Do not explain your reasoning. +`.trim() + ); + + // MODE FRAMING + if (mode === 'generate') { + sections.push(SINGLE_SCENE_GENERATION_PROMPT.trim()); + } + + if (mode === 'variation') { + sections.push(SCENE_VARIATION_PROMPT.trim()); + sections.push( + ` +Additional Variation Rules: +- You may change environment, weather, lighting, time of day +- You may change mood, tone, tension, emotional color +- You may change visual framing and atmosphere +- You may NOT change what happens +- You may NOT add or remove events +- You may NOT change outcomes +- You may NOT alter character intent or decisions +`.trim() + ); + } + + if (mode === 'regenerate') { + sections.push(SCENE_REGENERATION_PROMPT.trim()); + } + + // STORY CONTEXT + sections.push( + ` +STORY CONTEXT +Title: "${storyTitle}" +Summary: "${storyContent.summary}" +Platform: ${platform} +Intent: ${intent} +`.trim() + ); + + if (storyContent.keywords?.length || storyContent.tags?.length) { + sections.push( + ` +STYLE HINTS +Keywords: ${storyContent.keywords?.join(', ') || 'N/A'} +Tags: ${storyContent.tags?.join(', ') || 'N/A'} +`.trim() + ); + } + + // POSITION + sections.push( + ` +SCENE POSITION +This is scene ${sceneIndex}${totalScenes ? ` of ${totalScenes}` : ''}. +`.trim() + ); + + if (sceneTitle) { + sections.push(`SCENE TITLE\n"${sceneTitle}"`.trim()); + } + + if (sceneDescription) { + sections.push(`SCENE DESCRIPTION\n"${sceneDescription}"`.trim()); + } + + // GENERATE MODE = ARC AWARE + if (mode === 'generate') { + if (previousScenesSummary) { + sections.push( + ` +STORY SO FAR (HARD CONTINUITY CONSTRAINT) +${previousScenesSummary} + +Rules: +- Do not repeat +- Do not contradict +- Build on these events +`.trim() + ); + } + + if (nextScenesSummary) { + sections.push( + ` +UPCOMING STORY DIRECTION (SOFT CONSTRAINT) +${nextScenesSummary} + +Rules: +- You may foreshadow +- Do not jump ahead +- Do not contradict +`.trim() + ); + } + } + + // VARIATION MODE = SAME SCENE, DIFFERENT FEEL + if (mode === 'variation') { + sections.push( + ` +BASE SCENE (DO NOT CHANGE EVENTS) +${baseScene} + +Rules: +- Same actions +- Same outcome +- Same facts +- Only change environment, mood, atmosphere, tone, cinematic framing +`.trim() + ); + + sections.push( + ` +FUTURE CONTEXT (DO NOT BREAK) +${nextScenesSummary} +`.trim() + ); + } + + // REGENERATE MODE = FULL REWRITE, SAME PURPOSE + if (mode === 'regenerate') { + sections.push( + ` +BASE SCENE (TO BE COMPLETELY REWRITTEN) +${baseScene} + +Rules: +- You may rewrite structure, pacing, and presentation +- You may reframe how events are shown +- You may improve clarity and drama +- You must preserve story logic +- You must preserve timeline consistency +- You must preserve character intent +- Do NOT introduce new plot events unless specified +`.trim() + ); + } + + if (timeLimit) { + sections.push( + ` +HARD TIME CONSTRAINT +Target duration: ${timeLimit} seconds +Do not significantly overrun or underrun. +`.trim() + ); + } + + if (contextProfile) { + const contextSection = buildContextSection(contextProfile); + if (contextSection) sections.push(contextSection); + } + + if (extraPrompt) { + sections.push( + ` +ADDITIONAL CREATIVE DIRECTION +${extraPrompt} +`.trim() + ); + } + + sections.push(GLOBAL_SAFETY_RULES.trim()); + sections.push(SCENE_STRUCTURE_FORMAT.trim()); + + return sections.join('\n\n'); +} diff --git a/src/libs/ai/prompts/utils/buildContextSection.ts b/src/libs/ai/prompts/utils/buildContextSection.ts new file mode 100644 index 0000000..e91015c --- /dev/null +++ b/src/libs/ai/prompts/utils/buildContextSection.ts @@ -0,0 +1,107 @@ +import { ContextProfile } from '@models/ContextProfile.js'; + +export function buildContextSection(contextProfile?: ContextProfile | null): string | null { + if (!contextProfile) return null; + + const lines: string[] = []; + + lines.push( + ` +STORY CONTEXT (BINDING — DO NOT INTERPRET, DO NOT EXPAND, DO NOT OVERRIDE) +This section defines immutable narrative and stylistic constraints. +Violating any rule here is considered an error. +`.trim() + ); + + // Core narrative identity + lines.push( + ` +CORE IDENTITY +Genre: ${contextProfile.genre} +Mood: ${contextProfile.mood} +Style: ${contextProfile.style} +Narrative Scope: ${contextProfile.narrativeScope} +`.trim() + ); + + // Environment (cinematic grounding) + if (contextProfile.environment) { + lines.push( + ` +ENVIRONMENT +Type: ${contextProfile.environment.type} +Camera Motion: ${contextProfile.environment.cameraMotion} +${contextProfile.environment.description ? `Notes: ${contextProfile.environment.description}` : ''} +`.trim() + ); + } + + // World rules (hard constraints) + if (contextProfile.worldRules) { + lines.push( + ` +WORLD RULES (ABSOLUTE — MUST NOT BE VIOLATED) +${contextProfile.worldRules} +`.trim() + ); + } + + // Narrative constraints + if (contextProfile.narrativeConstraints) { + lines.push( + ` +NARRATIVE CONSTRAINTS (BINDING) +${contextProfile.narrativeConstraints} +`.trim() + ); + } + + // Characters (locked set) + if (contextProfile.characters?.length) { + lines.push( + ` +CHARACTERS (LOCKED SET — DO NOT ADD, REMOVE, RENAME, OR MERGE) +${contextProfile.characters.map((c) => `- ${c.name}${c.description ? `: ${c.description}` : ''}`).join('\n')} +`.trim() + ); + } + + // Forbidden elements (negative space) + if (contextProfile.forbiddenElements?.length) { + lines.push( + ` +FORBIDDEN ELEMENTS (STRICT) +You must not include, imply, or reference these. + +${contextProfile.forbiddenElements + .map((f) => `- ${f.label} (${f.severity === 'hard' ? 'ABSOLUTE BAN' : 'STRONGLY DISCOURAGED'})`) + .join('\n')} +`.trim() + ); + } + + // Narration profile — stylistic only (NO NUMBERS) + const np = contextProfile.narrationProfile; + + lines.push( + ` +NARRATION STYLE (QUALITATIVE — DO NOT OUTPUT NUMBERS) + +Tone: ${np.tone} +Emotional Expression: ${np.emotionBias} +Intensity Curve: ${np.intensityCurve} + +Pacing Behavior: +- Pause Bias: ${np.pauseBias} +- Sentence Length: ${np.sentenceLengthBias} +- Clause Density: ${np.clauseDensity} + +Rules: +- These define HOW the narration should feel +- Do NOT reveal or invent numeric pacing values +- Do NOT explain these rules in the output +`.trim() + ); + + return lines.join('\n\n'); +} diff --git a/src/modules/scenes/scenes.routes.ts b/src/libs/ai/utils/costEstimator.ts similarity index 100% rename from src/modules/scenes/scenes.routes.ts rename to src/libs/ai/utils/costEstimator.ts diff --git a/src/modules/story/story.routes.ts b/src/libs/ai/utils/tokenCounter.ts similarity index 100% rename from src/modules/story/story.routes.ts rename to src/libs/ai/utils/tokenCounter.ts diff --git a/src/libs/s3.ts b/src/libs/aws/s3.ts similarity index 100% rename from src/libs/s3.ts rename to src/libs/aws/s3.ts diff --git a/src/middleware/auth/requireAuth.ts b/src/middleware/auth/requireAuth.ts index bcf9b07..5739456 100644 --- a/src/middleware/auth/requireAuth.ts +++ b/src/middleware/auth/requireAuth.ts @@ -1,23 +1,19 @@ // requireAuth.ts import type { Request, Response, NextFunction } from "express"; -import jwt from "jsonwebtoken"; -import { UserModel } from "@models/User.js"; -import { SessionModel } from "@models/Session.js"; -import { - NotFoundError, - UnauthenticatedError, -} from "@middleware/error/index.js"; +import jwt from "jsonwebtoken"; +import { UnauthenticatedError } from "@middleware/error/index.js"; +import { AccountStatus } from "@constants/userConsts.js"; -export const requireAuth = async ( +export const authMiddleware = async ( req: Request, res: Response, next: NextFunction ) => { try { - const accessToken = req.cookies["access-token"]; + const accessToken = req.cookies["access-token"]; if (!accessToken) { - throw new UnauthenticatedError("user not authenticated, no access token found"); + throw new UnauthenticatedError("Authentication required"); } let decoded; @@ -25,41 +21,16 @@ export const requireAuth = async ( decoded = jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET!) as { userId: string; sessionId: string; + role:"user"|"admin"; + accountStatus?:AccountStatus; }; } catch (err) { - throw new UnauthenticatedError("Invalid or expired token"); + throw new UnauthenticatedError("Authentication required"); } - - // find user with this session - const user = await UserModel.findOne({ - _id: decoded.userId, - }); - - if (!user) { - throw new NotFoundError("User not found"); - } - - const session = await SessionModel.findOne({ - sessionId: decoded.sessionId, - userId: decoded.userId, - }); - - if (!session || session.revokedAt) { - throw new UnauthenticatedError("Session revoked or not found"); - } - - // ✅ update lastUsedAt for this session - const now = Date.now(); - const last = session.lastUsedAt?.getTime() ?? 0; - // Update only if old enough (e.g., 5 minutes) - if (now - last > 5 * 60 * 1000) { - session.lastUsedAt = new Date(); - await session.save(); - } - + // attach user + sessionId to request - req.user = user; - req.sessionId = decoded.sessionId; + req.user = { id: decoded.userId, role: decoded.role, accountStatus: decoded.accountStatus }; + req.sessionId = decoded.sessionId; return next(); } catch (err) { next(err); diff --git a/src/middleware/auth/requireCsrf.ts b/src/middleware/auth/requireCsrf.ts deleted file mode 100644 index 0706ff0..0000000 --- a/src/middleware/auth/requireCsrf.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { Request, Response, NextFunction } from "express"; -import crypto from "crypto"; - -export const requireCsrf = async ( - req: Request, - res: Response, - next: NextFunction -) => { - try { - const csrfCookie = req.cookies["csrf-token"]; - const csrfToken = req.headers["x-csrf-token"]; - if (!csrfToken || !csrfCookie) { - const error = new Error("CSRF token missing") as any; - error.statusCode = 403; - error.status = "fail"; - return next(error); - } - - // verify CSRF token - const [csrfTokenValue, csrfTokenSignature] = csrfCookie.split("."); - const expectedSignature = crypto - .createHmac("sha256", process.env.CSRF_SECRET!) - .update(csrfTokenValue) - .digest("hex"); - if ( - expectedSignature !== csrfTokenSignature || - csrfTokenValue !== csrfToken - ) { - return res.status(403).json({ message: "Invalid CSRF token" }); - } - - next(); - } catch (err) { - return res.status(401).json({ message: "Unauthorized" }); - } -}; diff --git a/src/middleware/auth/roles.ts b/src/middleware/auth/roles.ts deleted file mode 100644 index e3baf8c..0000000 --- a/src/middleware/auth/roles.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Request, Response, NextFunction } from "express"; - -export const requireRole = - (role: string) => (req: Request, res: Response, next: NextFunction) => { - const user = req.user; - if (!user) return res.status(401).json({ error: "unauthenticated" }); - if (user.role !== role) return res.status(403).json({ error: "forbidden" }); - next(); - }; - -export const requireOwnerOrAdmin = - (getResourceOwnerId: (req: Request) => string) => - (req: Request, res: Response, next: NextFunction) => { - const user = req.user; - if (!user) return res.status(401).json({ error: "unauthenticated" }); - if (user.role === "admin") return next(); - const ownerId = getResourceOwnerId(req); - if (ownerId !== String(user._id)) - return res.status(403).json({ error: "forbidden" }); - next(); - }; diff --git a/src/middleware/error/appError.ts b/src/middleware/error/appError.ts index 527bc03..52b12ad 100644 --- a/src/middleware/error/appError.ts +++ b/src/middleware/error/appError.ts @@ -1,7 +1,10 @@ -// src/errors/AppError.ts export class AppError extends Error { statusCode: number; code: string; + actions?: { + reason: string; + nextStep: string; + }; isOperational: boolean; details?: any; stackTrace?: string; @@ -10,12 +13,18 @@ export class AppError extends Error { message: string, statusCode: number, code: string, + actions?: { + reason: string; + nextStep: string; + }, details?: any ) { super(message); + this.name = this.constructor.name; this.statusCode = statusCode; this.code = code; + this.actions = actions; // optional now this.isOperational = true; this.details = details; @@ -33,11 +42,16 @@ export class AppError extends Error { } serialize() { - const base = { + const base: any = { error: this.code, message: this.message, }; + // Only include actions if they exist + if (this.actions) { + base.actions = this.actions; + } + if (process.env.NODE_ENV === "development") { return { ...base, diff --git a/src/middleware/error/errorCodes.ts b/src/middleware/error/errorCodes.ts index 20ba787..7664759 100644 --- a/src/middleware/error/errorCodes.ts +++ b/src/middleware/error/errorCodes.ts @@ -14,6 +14,9 @@ export const ERROR_CODES = { CONFLICT: "conflict", GONE: "gone", + PAYLOAD_TOO_LARGE: "payload_too_large", + + UNPROCESSABLE_ENTITY: "unprocessable_entity", VALIDATION_ERROR: "validation_error", diff --git a/src/middleware/error/globalErrorHandler.ts b/src/middleware/error/globalErrorHandler.ts index f12602b..d0519c7 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -1,29 +1,40 @@ -// src/middleware/errorHandler.ts -import { NextFunction, Request, Response } from "express"; -import { AppError } from "./appError.js"; +import { NextFunction, Request, Response } from 'express'; +import { AppError } from './appError.js'; +import logger from '@utils/logger.js'; -const errorHandler = ( - err: Error, - req: Request, - res: Response, - next: NextFunction -) => { - console.error("ERROR:", err); +const errorHandler = (err: unknown, req: Request, res: Response, _next: NextFunction) => { + const requestId = res.locals.requestId; - // If it's a known error (instance of AppError) if (err instanceof AppError) { - return res.status(err.statusCode).json({ - status: "error", + logger.error({ + requestId, + name: err.name, message: err.message, - code: err.code, + statusCode: err.statusCode, details: err.details, - stack: err.stack, + stack: process.env.NODE_ENV !== 'production' ? err.stack : undefined, + method: req.method, + path: req.originalUrl, + userId: (req as any).user?._id, }); + + return res.status(err.statusCode).json(err.serialize()); } + console.log(err); + logger.error({ + requestId, + name: 'UnhandledError', + message: 'Unhandled exception', + stack: process.env.NODE_ENV !== 'production' ? (err as Error).stack : undefined, + method: req.method, + path: req.originalUrl, + userId: (req as any).user?._id, + }); + return res.status(500).json({ - status: "error", - message: "Internal Server Error", + status: 'error', + message: 'Internal Server Error', }); }; diff --git a/src/middleware/error/index.ts b/src/middleware/error/index.ts index c4e5547..d290125 100644 --- a/src/middleware/error/index.ts +++ b/src/middleware/error/index.ts @@ -1,94 +1,100 @@ // src/errors/index.ts -import { AppError } from "./appError.js"; -import { ERROR_CODES } from "./errorCodes.js"; +import { AppError } from './appError.js'; +import { ERROR_CODES } from './errorCodes.js'; // 400 – Bad Request export class BadRequestError extends AppError { - constructor(message = "Bad request", details?: any) { + constructor(message = 'Bad request', details?: any) { super(message, 400, ERROR_CODES.BAD_REQUEST, details); } } // 401 – Unauthenticated (invalid or missing credentials) export class UnauthenticatedError extends AppError { - constructor(message = "Invalid credentials", details?: any) { + constructor(message = 'Invalid credentials', details?: any) { super(message, 401, ERROR_CODES.UNAUTHENTICATED, details); } } // 403 – User authenticated, but not allowed export class UnauthorizedError extends AppError { - constructor(message = "Unauthorized", details?: any) { + constructor(message = 'Unauthorized', details?: any) { super(message, 403, ERROR_CODES.UNAUTHORIZED, details); } } // Explicit permission failure export class ForbiddenError extends AppError { - constructor(message = "Forbidden", details?: any) { + constructor(message = 'Forbidden', details?: any) { super(message, 403, ERROR_CODES.FORBIDDEN, details); } } // 404 – Resource not found export class NotFoundError extends AppError { - constructor(message = "Resource not found", details?: any) { + constructor(message = 'Resource not found', details?: any) { super(message, 404, ERROR_CODES.NOT_FOUND, details); } } // 405 – Method not allowed export class MethodNotAllowedError extends AppError { - constructor(message = "Method not allowed", details?: any) { + constructor(message = 'Method not allowed', details?: any) { super(message, 405, ERROR_CODES.METHOD_NOT_ALLOWED, details); } } // 409 – Conflict (duplicate email, invalid state change, etc.) export class ConflictError extends AppError { - constructor(message = "Conflict", details?: any) { + constructor(message = 'Conflict', details?: any) { super(message, 409, ERROR_CODES.CONFLICT, details); } } // 410 – Resource permanently gone export class GoneError extends AppError { - constructor(message = "Resource gone", details?: any) { + constructor(message = 'Resource gone', details?: any) { super(message, 410, ERROR_CODES.GONE, details); } } +export class PayloadTooLargeError extends AppError { + constructor(message = 'Payload too large', details?: any) { + super(message, 413, ERROR_CODES.PAYLOAD_TOO_LARGE, details); + } +} + // 422 – Validation errors export class UnprocessableEntityError extends AppError { - constructor(message = "Validation error", details?: any) { + constructor(message = 'Validation error', details?: any) { super(message, 422, ERROR_CODES.VALIDATION_ERROR, details); } } // 429 – Rate limit exceeded export class TooManyRequestsError extends AppError { - constructor(message = "Too many requests", details?: any) { + constructor(message = 'Too many requests', details?: any) { super(message, 429, ERROR_CODES.TOO_MANY_REQUESTS, details); } } // 500 – Unexpected backend failure export class InternalServerError extends AppError { - constructor(message = "Internal server error", details?: any) { + constructor(message = 'Internal server error', details?: any) { super(message, 500, ERROR_CODES.INTERNAL_ERROR, details); } } // 503 – External service or DB unavailable export class ServiceUnavailableError extends AppError { - constructor(message = "Service unavailable", details?: any) { + constructor(message = 'Service unavailable', details?: any) { super(message, 503, ERROR_CODES.SERVICE_UNAVAILABLE, details); } } // 504 – External API timeout export class GatewayTimeoutError extends AppError { - constructor(message = "Gateway timeout", details?: any) { + constructor(message = 'Gateway timeout', details?: any) { super(message, 504, ERROR_CODES.GATEWAY_TIMEOUT, details); } } diff --git a/src/middleware/loggerMiddleware.ts b/src/middleware/loggerMiddleware.ts index 9c5b575..a030e3f 100644 --- a/src/middleware/loggerMiddleware.ts +++ b/src/middleware/loggerMiddleware.ts @@ -1,44 +1,69 @@ -// middleware/devLogger.ts import type { Request, Response, NextFunction } from 'express'; +import { randomUUID } from 'crypto'; +import logger from '@utils/logger.js'; -const devLogger = (req: Request, res: Response, next: NextFunction): void => { - const start = Date.now(); - - // Log when request comes in (optional - remove if you don't want it) - console.log(`${getColor('incoming')}→ ${req.method} ${req.url}`); - - // Log when response is sent - res.on('finish', () => { - const duration = Date.now() - start; - const status = res.statusCode; - - console.log(`${getStatusColor(status)}${getMethodIcon(req.method)} ${req.method} ${req.url} ${status} ${duration}ms\x1b[0m`); - }); - - next(); -}; +const isDev = process.env.NODE_ENV !== 'production'; + +/* ---------- DEV helpers (safe: dev only) ---------- */ -// Helper functions for colors const getStatusColor = (status: number): string => { - if (status >= 500) return '\x1b[31m'; // red for server errors - if (status >= 400) return '\x1b[33m'; // yellow for client errors - if (status >= 300) return '\x1b[36m'; // cyan for redirects - return '\x1b[32m'; // green for success + if (status >= 500) return '\x1b[31m'; // red + if (status >= 400) return '\x1b[33m'; // yellow + if (status >= 300) return '\x1b[36m'; // cyan + return '\x1b[32m'; // green }; -const getMethodIcon = (method: string): string => { - const icons: Record = { - GET: '📥', - POST: '📝', - PUT: '✏️', - DELETE: '🗑️', - PATCH: '🩹' +/* ---------- Middleware ---------- */ + +export function requestLogger(req: Request, res: Response, next: NextFunction) { + const start = process.hrtime.bigint(); + + const requestId = randomUUID(); + res.locals.requestId = requestId; + res.setHeader('X-Request-Id', requestId); + + if (isDev) { + logger.debug( + { + requestId, + method: req.method, + path: req.originalUrl, + }, + 'Incoming request' + ); + } + + res.on('finish', () => { + const durationMs = Number(process.hrtime.bigint() - start) / 1_000_000; + + const logData = { + requestId, + method: req.method, + path: req.originalUrl, + statusCode: res.statusCode, + durationMs: Number(durationMs.toFixed(2)), + ip: req.ip, + userAgent: req.headers['user-agent'], + userId: (req as any).user?._id, }; - return icons[method] || '📄'; -}; -const getColor = (type: 'incoming'): string => { - return type === 'incoming' ? '\x1b[90m' : ''; // gray for incoming -}; + if (isDev) { + const color = getStatusColor(res.statusCode); + logger.info( + logData, + `${color}$ ${req.method} ${req.originalUrl} ${res.statusCode} ${logData.durationMs}ms\x1b[0m` + ); + return; + } + + if (res.statusCode >= 500) { + logger.error(logData, 'Request failed'); + } else if (res.statusCode >= 400) { + logger.warn(logData, 'Request completed with client error'); + } else { + logger.info(logData, 'Request completed'); + } + }); -export default devLogger; \ No newline at end of file + next(); +} diff --git a/src/middleware/multer/audioAssetUpload.ts b/src/middleware/multer/audioAssetUpload.ts new file mode 100644 index 0000000..26afdf0 --- /dev/null +++ b/src/middleware/multer/audioAssetUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerAudio.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const audioAssetUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('audioFile')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Audio file size exceeds the 100MB limit', err)); + } + return next(new BadRequestError('Multer error during audio upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/multer/avatarUpload.ts b/src/middleware/multer/avatarUpload.ts new file mode 100644 index 0000000..77f2995 --- /dev/null +++ b/src/middleware/multer/avatarUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerImage.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const avatarUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('avatar')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Avatar file size exceeds the 2MB limit', err)); + } + return next(new BadRequestError('Multer error during file upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/multer/filenameLogic/multerAudio.ts b/src/middleware/multer/filenameLogic/multerAudio.ts new file mode 100644 index 0000000..745dcee --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerAudio.ts @@ -0,0 +1,74 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/audio'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.mp3', '.wav', '.ogg', '.aac', '.m4a', '.flac', '.wma', '.opus']; +const allowedMimetypes = [ + 'audio/mpeg', + 'audio/mp3', + 'audio/wav', + 'audio/wave', + 'audio/x-wav', + 'audio/ogg', + 'audio/aac', + 'audio/mp4', + 'audio/x-m4a', + 'audio/flac', + 'audio/x-flac', + 'audio/x-ms-wma', + 'audio/opus', +]; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only audio files (mp3, wav, ogg, aac, m4a, flac, wma, opus) are allowed')); + return; + } + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only audio files (mp3, wav, ogg, aac, m4a, flac, wma, opus) are allowed')); + return; + } + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only audio files (mp3, wav, ogg, aac, m4a, flac, wma, opus) are allowed')); + return; + } + cb(null, true); +}; + +const upload = multer({ + storage, + fileFilter, + limits: { fileSize: 10 * 1024 * 1024 }, // 10 MB limit +}); + +export { upload }; diff --git a/src/middleware/multer/filenameLogic/multerImage.ts b/src/middleware/multer/filenameLogic/multerImage.ts new file mode 100644 index 0000000..738f67c --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerImage.ts @@ -0,0 +1,60 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/images'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']; +const allowedMimetypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only image files (jpg, jpeg, png, gif, webp) are allowed')); + return; + } + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only image files (jpg, jpeg, png, gif, webp) are allowed')); + return; + } + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only image files (jpg, jpeg, png, gif, webp) are allowed')); + return; + } + cb(null, true); +}; + +const upload = multer({ + storage, + fileFilter, + limits: { fileSize: 2 * 1024 * 1024 }, +}); + +export { upload }; diff --git a/src/middleware/multer/filenameLogic/multerJSON.ts b/src/middleware/multer/filenameLogic/multerJSON.ts new file mode 100644 index 0000000..901ba5e --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerJSON.ts @@ -0,0 +1,63 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/json'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.json']; +const allowedMimetypes = ['application/json']; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only JSON files are allowed')); + return; + } + + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only JSON files are allowed')); + return; + } + + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only JSON files are allowed')); + return; + } + + cb(null, true); +}; + +const uploadJSON = multer({ + storage, + fileFilter, + limits: { fileSize: 2 * 1024 * 1024 }, // 2MB max limit +}); + +export { uploadJSON }; diff --git a/src/middleware/multer/filenameLogic/multerVideo.ts b/src/middleware/multer/filenameLogic/multerVideo.ts new file mode 100644 index 0000000..e1a0a0a --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerVideo.ts @@ -0,0 +1,66 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/videos'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.mp4', '.mov', '.avi', '.mkv', '.webm']; +const allowedMimetypes = [ + 'video/mp4', + 'video/quicktime', + 'video/x-msvideo', + 'video/x-matroska', + 'video/webm', +]; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only video files (mp4, mov, avi, mkv, webm) are allowed')); + return; + } + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only video files (mp4, mov, avi, mkv, webm) are allowed')); + return; + } + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only video files (mp4, mov, avi, mkv, webm) are allowed')); + return; + } + cb(null, true); +}; + +const upload = multer({ + storage, + fileFilter, + limits: { fileSize: 20 * 1024 * 1024 }, +}); + +export { upload }; diff --git a/src/middleware/multer/imageAssetUpload.ts b/src/middleware/multer/imageAssetUpload.ts new file mode 100644 index 0000000..1ada5ce --- /dev/null +++ b/src/middleware/multer/imageAssetUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerImage.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const imageAssetUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('sceneImage')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Avatar file size exceeds the 2MB limit', err)); + } + return next(new BadRequestError('Multer error during file upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/multer/narrationJSONUpload.ts b/src/middleware/multer/narrationJSONUpload.ts new file mode 100644 index 0000000..ae94776 --- /dev/null +++ b/src/middleware/multer/narrationJSONUpload.ts @@ -0,0 +1,19 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { uploadJSON } from './filenameLogic/multerJSON.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const narrationJSONUpload = (req: Request, res: Response, next: NextFunction) => { + uploadJSON.single('narrationFile')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('JSON file size exceeds the 2MB limit', err)); + } + return next(new BadRequestError('Multer error during JSON upload', { cause: err })); + } + + return next(err); + }); +}; diff --git a/src/middleware/multer/videoAssetUpload.ts b/src/middleware/multer/videoAssetUpload.ts new file mode 100644 index 0000000..764d56b --- /dev/null +++ b/src/middleware/multer/videoAssetUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerVideo.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const videoAssetUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('sceneVideo')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Video file size exceeds the 50MB limit', err)); + } + return next(new BadRequestError('Multer error during video upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/request/paginationAndSorting.ts b/src/middleware/request/paginationAndSorting.ts new file mode 100644 index 0000000..23eb833 --- /dev/null +++ b/src/middleware/request/paginationAndSorting.ts @@ -0,0 +1,48 @@ +import { Request, Response, NextFunction } from 'express'; +import { BadRequestError } from '../error/index.js'; +import type { Pagination, Sorting } from 'types/Pagination.js'; + +const DEFAULT_PAGE = 1; +const DEFAULT_LIMIT = 10; +const MAX_LIMIT = 50; + +// Whitelist sortable fields (CRITICAL) +const ALLOWED_SORT_FIELDS = ['createdAt', 'updatedAt', 'title', 'status', 'name', 'lastUsedAt']; + +export function paginationAndSortingMiddleware(req: Request, _res: Response, next: NextFunction) { + // ---------- Pagination ---------- + const page = Number(req.query.page) || DEFAULT_PAGE; + const limit = Number(req.query.limit) || DEFAULT_LIMIT; + + if (page < 1) { + throw new BadRequestError('Page must be greater than 0'); + } + + if (limit < 1 || limit > MAX_LIMIT) { + throw new BadRequestError(`Limit must be between 1 and ${MAX_LIMIT}`); + } + + const pagination: Pagination = { + page, + limit, + skip: (page - 1) * limit, + }; + + // ---------- Sorting ---------- + const sortBy = + typeof req.query.sortBy === 'string' && ALLOWED_SORT_FIELDS.includes(req.query.sortBy) + ? req.query.sortBy + : 'createdAt'; + + const sortOrder = req.query.sortOrder === 'asc' ? 1 : -1; // default desc + + const sorting: Sorting = { + sortBy, + sortOrder, + }; + + req.pagination = pagination; + req.sorting = sorting; + + next(); +} diff --git a/src/middleware/security/requireActiveAccount.ts b/src/middleware/security/requireActiveAccount.ts new file mode 100644 index 0000000..20140c2 --- /dev/null +++ b/src/middleware/security/requireActiveAccount.ts @@ -0,0 +1,11 @@ +import { UnauthorizedError } from "@middleware/error/index.js"; +import { NextFunction, Request, Response } from "express"; + +export const requireActiveAccount = (req:Request, res:Response, next:NextFunction) => { + const accountStatus = req.user?.accountStatus; + + if (accountStatus !== "active") { + throw new UnauthorizedError("Active account required to access this resource."); + } + return next(); +} \ No newline at end of file diff --git a/src/middleware/security/requireCsrf.ts b/src/middleware/security/requireCsrf.ts new file mode 100644 index 0000000..a1dc2f7 --- /dev/null +++ b/src/middleware/security/requireCsrf.ts @@ -0,0 +1,41 @@ +import type { Request, Response, NextFunction } from 'express'; +import { UnauthorizedError } from '@middleware/error/index.js'; +import { SessionModel } from '@models/Session.js'; +import { verifyToken } from '@utils/tokens.js'; +import { ALLOWED_ORIGINS } from 'constants/globalConts.js'; + +export const csrfMiddleware = async (req: Request, res: Response, next: NextFunction) => { + const unsafeMethods = ['POST', 'PUT', 'PATCH', 'DELETE']; + if (!unsafeMethods.includes(req.method)) { + return next(); + } + + const origin = req.headers.Origin; + if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { + throw new UnauthorizedError('Invalid origin'); + } + + const csrfToken = req.headers['x-csrf-token']; + if (!csrfToken) { + throw new UnauthorizedError(); + } + const csrfTokenValue = Array.isArray(csrfToken) ? csrfToken[0] : csrfToken; + + const session = await SessionModel.findOne({ + sessionId: req.sessionId, + valid: true, + revokedAt: null, + }).select('+csrfTokenHash'); + + if (!session) { + throw new UnauthorizedError(); + } + + try { + verifyToken(csrfTokenValue, session.csrfTokenHash); + } catch { + throw new UnauthorizedError(); + } + + next(); +}; diff --git a/src/models/AudioAsset.ts b/src/models/AudioAsset.ts new file mode 100644 index 0000000..eb97800 --- /dev/null +++ b/src/models/AudioAsset.ts @@ -0,0 +1,80 @@ +import { Schema, model, Document, Types } from 'mongoose'; + +export interface AudioAsset extends Document { + userId: Types.ObjectId; + narrationId?: Types.ObjectId; + activeNarration: boolean; + type: 'narration' | 'background' | 'effect'; + url: string; + prompt?: string; + generationSource: 'ai' | 'user'; + voiceId?: string; + duration?: number; + version?: number; + deletedAt: Date; + createdAt: Date; + updatedAt: Date; +} + +const audioAssetSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + }, + narrationId: { + type: Schema.Types.ObjectId, + ref: 'StoryNarration', + }, + activeNarration: { + type: Boolean, + default: false, + }, + type: { + type: String, + enum: ['narration', 'background', 'effect'], + required: true, + }, + url: { + type: String, + required: true, + }, + prompt: { + type: String, + }, + generationSource: { + type: String, + enum: ['ai', 'user'], + default: 'ai', + }, + voiceId: { + type: String, + }, + duration: { + type: Number, + }, + version: { + type: Number, + required: true, + default: 1, + min: 1, + }, + deletedAt: { + type: Date, + }, + }, + { timestamps: true } +); + +audioAssetSchema.index( + { narrationId: 1, activeNarration: 1 }, + { unique: true, partialFilterExpression: { activeNarration: true, deletedAt: { $exists: false } } } +); + +audioAssetSchema.index( + { narrationId: 1, version: 1 }, + { unique: true, partialFilterExpression: { deletedAt: { $exists: false } } } +); + +export const AudioAssetModel = model('AudioAsset', audioAssetSchema); diff --git a/src/models/Bookmark.ts b/src/models/Bookmark.ts new file mode 100644 index 0000000..8c9fd7f --- /dev/null +++ b/src/models/Bookmark.ts @@ -0,0 +1,41 @@ + import { Schema,model, type Types } from "mongoose"; + +export type Bookmark = { + _id: Types.ObjectId; + userId: Types.ObjectId; + targetType: "Story" | "Project" | "AudioAsset" | "FinalVideo" | "SceneAsset"; + targetId: Types.ObjectId; + createdAt: Date; +} + +const BookmarkSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + index: true, + } , + targetType: { + type: String, + enum: ["Story", "Project", "AudioAsset", "FinalVideo", "SceneAsset"], + required: true, + } , + targetId: { + type: Schema.Types.ObjectId, + refPath: "targetType", + required: true, + index: true, + } , + createdAt: { + type: Date, + default: Date.now, + } +} ) + +BookmarkSchema.index({ userId: 1, targetType: 1, targetId: 1 }, { unique: true }); +BookmarkSchema.index({userId:1,targetType:1, createdAt:-1}); + + + +export const BookmarkModel = model("Bookmark", BookmarkSchema); \ No newline at end of file diff --git a/src/models/CapabilityOverride.ts b/src/models/CapabilityOverride.ts new file mode 100644 index 0000000..9719f29 --- /dev/null +++ b/src/models/CapabilityOverride.ts @@ -0,0 +1,67 @@ +import { Schema, model, InferSchemaType } from 'mongoose'; + +const capabilityOverrideSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + + feature: { + type: String, + enum: ['story', 'image', 'audio', 'video'], + required: true, + index: true, + }, + + // what is being overridden + capabilityKey: { + type: String, + required: true, + // examples: + // "maxTier" + // "maxResolution" + // "premiumVoices" + }, + + value: { + type: Schema.Types.Mixed, + required: true, + }, + + validFrom: { + type: Date, + default: Date.now, + index: true, + }, + + validTill: { + type: Date, + required: true, + index: true, + }, + + source: { + type: String, + enum: ['purchase', 'promo', 'admin'], + required: true, + }, + }, + { timestamps: true } +); + +capabilityOverrideSchema.index({ + userId: 1, + feature: 1, + capabilityKey: 1, + validTill: 1, +}); + +export type CapabilityOverrideData = InferSchemaType; + +export const UserCapabilityOverrideModel = model( + 'UserCapabilityOverride', + capabilityOverrideSchema +); diff --git a/src/models/ContextProfile.ts b/src/models/ContextProfile.ts new file mode 100644 index 0000000..7584cce --- /dev/null +++ b/src/models/ContextProfile.ts @@ -0,0 +1,338 @@ +import { Schema, model, Document, Types } from 'mongoose'; +import { features } from 'process'; +import { required } from 'zod/mini'; + +export enum GenreType { + HORROR = 'horror', + PSYCHOLOGICAL_HORROR = 'psychological-horror', + THRILLER = 'thriller', + CRIME = 'crime', + NOIR = 'noir', + SCIFI = 'sci-fi', + HARD_SCIFI = 'hard-sci-fi', + CYBERPUNK = 'cyberpunk', + FANTASY = 'fantasy', + DARK_FANTASY = 'dark-fantasy', + DRAMA = 'drama', + HISTORICAL = 'historical', + WAR = 'war', + MYSTERY = 'mystery', + ROMANCE = 'romance', + TRAGEDY = 'tragedy', + ADVENTURE = 'adventure', + POST_APOCALYPTIC = 'post-apocalyptic', +} + +export enum ToneType { + DARK = 'dark', + BLEAK = 'bleak', + GRITTY = 'gritty', + NEUTRAL = 'neutral', + HOPEFUL = 'hopeful', + INTIMATE = 'intimate', + EPIC = 'epic', + SURREAL = 'surreal', + SOMBER = 'somber', +} + +export enum MoodType { + EERIE = 'eerie', + TENSE = 'tense', + CALM = 'calm', + MELANCHOLIC = 'melancholic', + OMINOUS = 'ominous', + LONELY = 'lonely', + PARANOID = 'paranoid', + DESPERATE = 'desperate', + HOPELESS = 'hopeless', + BITTERSWEET = 'bittersweet', +} + +export enum StyleType { + CINEMATIC = 'cinematic', + POETIC = 'poetic', + MINIMAL = 'minimal', + LITERARY = 'literary', + GRITTY_REALISM = 'gritty-realism', + EXPERIMENTAL = 'experimental', + VOICEOVER_HEAVY = 'voiceover-heavy', +} + +export enum EnvironmentType { + APARTMENT = 'apartment', + MOTEL = 'motel', + CITY = 'city', + MEGACITY = 'megacity', + SUBURB = 'suburb', + FOREST = 'forest', + DESERT = 'desert', + MOUNTAINS = 'mountains', + SPACE_STATION = 'space-station', + SPACESHIP = 'spaceship', + UNDERGROUND = 'underground', + BUNKER = 'bunker', + VILLAGE = 'village', + ABANDONED_FACILITY = 'abandoned-facility', + OCEAN = 'ocean', +} + +export enum CameraMotion { + STATIC = 'static', + SLOW_PAN = 'slow-pan', + DOLLY = 'dolly', + HANDHELD = 'handheld', + STEADICAM = 'steadicam', + TRACKING = 'tracking', + DRIFTING = 'drifting', +} + +export enum IntensityCurve { + FLAT = 'flat', + RISING = 'rising', + SLOW_BURN = 'slow-burn', + PULSED = 'pulsed', + SPIKING = 'spiking', + COLLAPSING = 'collapsing', +} + +export enum NarrativeScope { + INTIMATE = 'intimate', + LOCAL = 'local', + REGIONAL = 'regional', + EPIC = 'epic', +} + +export enum ContextScope { + PROJECT = 'project', + GLOBAL = 'global', +} + +export interface EnvironmentProfile { + type: EnvironmentType; + cameraMotion: CameraMotion; + description?: string; +} + +export interface NarrationProfile { + wordsPerSecond: number; + minWordTolerance: number; + maxWordTolerance: number; + + pauseBias: 'none' | 'low' | 'medium' | 'high'; + sentenceLengthBias: 'very-short' | 'short' | 'medium' | 'long'; + clauseDensity: 'sparse' | 'balanced' | 'dense'; + + tone: ToneType; + emotionBias: 'flat' | 'subtle' | 'expressive'; + intensityCurve: IntensityCurve; +} + +export interface ForbiddenElement { + label: string; + severity: 'hard' | 'soft'; +} + +export interface ContextProfile extends Document { + userId: Types.ObjectId; + + projectId?: Types.ObjectId; + scope: ContextScope; + isDefaultForProject: boolean; + parentContextId?: Types.ObjectId; + + name: string; + description?: string; + language?: string; + + genre: GenreType; + mood: MoodType; + style: StyleType; + narrativeScope: NarrativeScope; + + environment: EnvironmentProfile; + + worldRules?: string; + narrativeConstraints?: string; + + characters?: { + name: string; + description?: string; + imageUrl?: string; + features?: Record; + behaviors?: Record; + }[]; + + forbiddenElements?: ForbiddenElement[]; + + narrationProfile: NarrationProfile; // 🔒 SYSTEM-DERIVED + + lastUsedAt?: Date; + createdAt: Date; + updatedAt: Date; +} + +const contextProfileSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + }, + + projectId: { + type: Schema.Types.ObjectId, + ref: 'Project', + }, + + scope: { + type: String, + enum: Object.values(ContextScope), + default: ContextScope.PROJECT, + required: true, + }, + + isDefaultForProject: { + type: Boolean, + default: false, + }, + parentContextId: { + type: Schema.Types.ObjectId, + ref: 'ContextProfile', + }, + name: { + type: String, + required: true, + trim: true, + }, + + description: { + type: String, + maxlength: 600, + }, + language: { + type: String, + default: 'en', + }, + genre: { + type: String, + enum: Object.values(GenreType), + required: true, + }, + + mood: { + type: String, + enum: Object.values(MoodType), + required: true, + }, + + style: { + type: String, + enum: Object.values(StyleType), + required: true, + }, + + narrativeScope: { + type: String, + enum: Object.values(NarrativeScope), + default: NarrativeScope.LOCAL, + required: true, + }, + + environment: { + type: { + type: String, + enum: Object.values(EnvironmentType), + required: true, + }, + cameraMotion: { + type: String, + enum: Object.values(CameraMotion), + required: true, + }, + description: String, + }, + + worldRules: { + type: String, + maxlength: 1000, + }, + + narrativeConstraints: { + type: String, + maxlength: 1000, + }, + + characters: [ + { + name: { type: String, required: true }, + imageUrl: { type: String }, + description: { type: String, maxlength: 500 }, + features: { type: Schema.Types.Mixed }, + behaviors: { type: Schema.Types.Mixed }, + }, + ], + + forbiddenElements: [ + { + label: String, + severity: { + type: String, + enum: ['hard', 'soft'], + default: 'hard', + }, + }, + ], + + narrationProfile: { + wordsPerSecond: { type: Number, required: true }, + minWordTolerance: { type: Number, required: true }, + maxWordTolerance: { type: Number, required: true }, + + pauseBias: { + type: String, + enum: ['none', 'low', 'medium', 'high'], + required: true, + }, + + sentenceLengthBias: { + type: String, + enum: ['very-short', 'short', 'medium', 'long'], + required: true, + }, + + clauseDensity: { + type: String, + enum: ['sparse', 'balanced', 'dense'], + required: true, + }, + + tone: { + type: String, + enum: Object.values(ToneType), + required: true, + }, + + emotionBias: { + type: String, + enum: ['flat', 'subtle', 'expressive'], + required: true, + }, + + intensityCurve: { + type: String, + enum: Object.values(IntensityCurve), + required: true, + }, + }, + lastUsedAt: { + type: Date, + }, + }, + { timestamps: true } +); + +contextProfileSchema.index({ projectId: 1, isDefaultForProject: 1 }); +contextProfileSchema.index({ parentContextId: 1 }); +contextProfileSchema.index({ userId: 1, lastUsedAt: -1 }); + +export const ContextProfileModel = model('ContextProfile', contextProfileSchema); diff --git a/src/models/Credits.ts b/src/models/Credits.ts new file mode 100644 index 0000000..0064316 --- /dev/null +++ b/src/models/Credits.ts @@ -0,0 +1,80 @@ +import { Schema, model, InferSchemaType } from 'mongoose'; + +const creditsSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + + planKey: { + type: String, + required: true, + index: true, + }, + + source: { + type: String, + enum: ['free_plan', 'monthly_plan', 'one_month_plan', 'admin', 'promo'], + required: true, + index: true, + }, + creditType: { + type: String, + enum: ['ai', 'render'], + required: true, + index: true, + }, + + creditsGranted: { + type: Number, + required: true, + min: 0, + }, + + creditsUsed: { + type: Number, + default: 0, + min: 0, + }, + + validFrom: { + type: Date, + required: true, + default: Date.now, + index: true, + }, + + validTill: { + type: Date, + index: true, + }, + + isExpired: { + type: Boolean, + default: false, + index: true, + }, + }, + { timestamps: true } +); + +creditsSchema.index( + { userId: 1, source: 1 }, + { + unique: true, + partialFilterExpression: { source: 'free_plan' }, + } +); + +creditsSchema.index({ + userId: 1, + isExpired: 1, + validTill: 1, + createdAt: 1, +}); + +export type CreditsData = InferSchemaType; +export const CreditsModel = model('UserCredits', creditsSchema); diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts new file mode 100644 index 0000000..cb94bcb --- /dev/null +++ b/src/models/FinalVideo.ts @@ -0,0 +1,77 @@ +import { Schema, model, Document, Types } from 'mongoose'; + +export interface FinalVideo extends Document { + userId: Types.ObjectId; + projectId: Types.ObjectId; + storyId: Types.ObjectId; + videoUrl?: string; + lastError?: { message: string; code?: number; count?: number }; + backgroundAudioAssetId?: Types.ObjectId; + narrationAudioAssetId?: Types.ObjectId; + sceneAssetIds: Types.ObjectId[]; + duration?: number; + videoConfigId: Types.ObjectId; + status: 'rendering' | 'completed' | 'failed'; + createdAt: Date; + updatedAt: Date; +} + +const finalVideoSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + }, + projectId: { + type: Schema.Types.ObjectId, + ref: 'Project', + required: true, + index: true, + }, + storyId: { + type: Schema.Types.ObjectId, + ref: 'Story', + required: true, + index: true, + }, + videoUrl: { + type: String, + }, + lastError: { + type: { + message: String, + code: Number, + count: Number, + }, + }, + backgroundAudioAssetId: { + type: Schema.Types.ObjectId, + ref: 'AudioAsset', + }, + narrationAudioAssetId: { + type: Schema.Types.ObjectId, + ref: 'AudioAsset', + }, + sceneAssetIds: { + type: [{ type: Schema.Types.ObjectId, ref: 'SceneAsset' }], + required: true, + }, + videoConfigId: { + type: Schema.Types.ObjectId, + ref: 'VideoConfig', // Reference to VideoConfig model + required: true, + }, + status: { + type: String, + enum: ['rendering', 'completed', 'failed'], + default: 'rendering', + index: true, + }, + }, + { timestamps: true } +); + +finalVideoSchema.index({ userId: 1, status: 1 }); + +export const FinalVideoModel = model('FinalVideo', finalVideoSchema); diff --git a/src/models/Narration.ts b/src/models/Narration.ts new file mode 100644 index 0000000..0b6d549 --- /dev/null +++ b/src/models/Narration.ts @@ -0,0 +1,159 @@ +import { Schema, model, Document, Types, HydratedDocument } from 'mongoose'; + +export interface NarrationSegment { + character: string; + startTime: number; + endTime: number; + duration: number; + targetWordCount: number; + minWords: number; + maxWords: number; + narration: string; +} + +export interface StoryNarration extends Document { + userId: Types.ObjectId; + storyId: Types.ObjectId; + sceneOrder: Types.ObjectId[]; + sceneOrderHash: string; + activeAudioAssetId?: Types.ObjectId; + totalDuration: number; + narrationSegments: NarrationSegment[]; + version: number; + active: boolean; + deletedAt?: Date; + source: 'ai' | 'user'; + createdAt: Date; + updatedAt: Date; +} + +const narrationSegmentSchema = new Schema( + { + startTime: { + type: Number, + required: true, + min: 0, + }, + + endTime: { + type: Number, + required: true, + min: 0, + }, + + duration: { + type: Number, + required: true, + min: 0, + }, + + targetWordCount: { + type: Number, + required: true, + min: 0, + }, + + minWords: { + type: Number, + required: true, + min: 0, + }, + + maxWords: { + type: Number, + required: true, + min: 0, + }, + + narration: { + type: String, + required: true, + trim: true, + }, + character: { + type: String, + trim: true, + }, + }, + { _id: false } +); + +const storyNarrationSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + + storyId: { + type: Schema.Types.ObjectId, + ref: 'Story', + required: true, + }, + sceneOrder: { + type: [Schema.Types.ObjectId], + ref: 'Scene', + required: true, + }, + sceneOrderHash: { + type: String, + required: true, + index: true, + }, + activeAudioAssetId: { + type: Schema.Types.ObjectId, + ref: 'AudioAsset', + }, + totalDuration: { + type: Number, + required: true, + min: 1, + }, + + narrationSegments: { + type: [narrationSegmentSchema], + required: true, + }, + + version: { + type: Number, + required: true, + default: 1, + min: 1, + }, + + active: { + type: Boolean, + default: true, + index: true, + }, + deletedAt: { + type: Date, + default: undefined, + }, + source: { + type: String, + enum: ['ai', 'user'], + required: true, + default: 'ai', + }, + }, + { timestamps: true } +); + +storyNarrationSchema.index({ sceneOrder: 1, version: -1 }, { unique: true }); +storyNarrationSchema.index( + { sceneOrder: 1, active: 1 }, + { unique: true, partialFilterExpression: { active: true } } +); + +// TTL index to auto-delete soft-deleted narrations after 30 days +storyNarrationSchema.index( + { deletedAt: 1 }, + { expireAfterSeconds: 30 * 24 * 60 * 60, partialFilterExpression: { deletedAt: { $exists: true } } } +); + +export const StoryNarrationModel = model('StoryNarration', storyNarrationSchema); +export type StoryNarrationType = HydratedDocument; diff --git a/src/models/Plan.ts b/src/models/Plan.ts new file mode 100644 index 0000000..60b1776 --- /dev/null +++ b/src/models/Plan.ts @@ -0,0 +1,81 @@ +import { Schema, model, InferSchemaType } from 'mongoose'; + +const planSchema = new Schema( + { + key: { + type: String, // free, pro_basic, pro_standard, premium_standard, premium_best + required: true, + unique: true, + index: true, + }, + + name: { + type: String, + required: true, + }, + + description: { + type: String, + default: null, + }, + + // ===== CREDIT GRANT RULE ===== + creditGrantAmount: { + type: Number, + required: true, + min: 0, + }, + + creditGrantType: { + type: String, + enum: ['once', 'monthly'], + required: true, + }, + + capabilities: { + story: { + maxTier: { type: Number, required: true }, // 1–5 + maxDurationSeconds: { type: Number, required: true }, + }, + + image: { + maxTier: { type: Number, required: true }, // 1–4 + cinematicPrompts: { type: Boolean, default: false }, + characterConsistency: { type: Boolean, default: false }, + maxImagesPerStory: { type: Number, required: true }, + }, + + audio: { + maxTier: { type: Number, required: true }, // 1–5 + premiumVoices: { type: Boolean, default: false }, + maxDurationSeconds: { type: Number, required: true }, + }, + + video: { + enabled: { type: Boolean, default: false }, + imageToVideo: { type: Boolean, default: false }, + textToVideo: { type: Boolean, default: false }, + maxSeconds: { type: Number, default: 0 }, + maxResolution: { + type: Number, // 480, 720, 1080, 1440, 2160 + default: 0, + }, + }, + + editor: { + previewEnabled: { type: Boolean, default: true }, + exportEnabled: { type: Boolean, default: false }, + }, + }, + + isActive: { + type: Boolean, + default: true, + index: true, + }, + }, + { timestamps: true } +); + +export type PlanData = InferSchemaType; +export const PlanModel = model('Plan', planSchema); diff --git a/src/models/Project.ts b/src/models/Project.ts index e69de29..a8ed179 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -0,0 +1,66 @@ +import { Schema, model, Document, Types, HydratedDocument } from 'mongoose'; +export interface ProjectType extends Document { + userId: Types.ObjectId; + title: string; + description: string; + thumbnail?: string; + status: 'active' | 'draft' | 'archive' | 'delete'; + visibility: 'public' | 'private'; + defaultContextProfileId?: Types.ObjectId; + generationCounts: { + storiesGenerated: number; + scenesGenerated: number; + sceneAssetsGenerated: number; + audiosGenerated: number; + videosGenerated: number; + }; + createdAt: Date; + updatedAt: Date; +} + +const projectSchema = new Schema( + { + title: { + type: String, + required: true, + maxlength: 255, + trim: true, + }, + description: { + type: String, + required: true, + maxlength: 500, + trim: true, + }, + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + }, + status: { + type: String, + enum: ['active', 'draft', 'archive', 'delete'], + default: 'active', + }, + visibility: { + type: String, + enum: ['public', 'private'], + default: 'private', + }, + defaultContextProfileId: { type: Schema.Types.ObjectId, ref: 'ContextProfile' }, + generationCounts: { + storiesGenerated: { type: Number, default: 0 }, + scenesGenerated: { type: Number, default: 0 }, + sceneAssetsGenerated: { type: Number, default: 0 }, + audiosGenerated: { type: Number, default: 0 }, + videosGenerated: { type: Number, default: 0 }, + }, + }, + { timestamps: true } +); + +projectSchema.index({ userId: 1, status: 1, createdAt: -1 }); + +export type Project = HydratedDocument; + +export const ProjectModel = model('Project', projectSchema); diff --git a/src/models/Scene.ts b/src/models/Scene.ts index e69de29..122a32e 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -0,0 +1,99 @@ +import { Schema, model, Document, Types } from 'mongoose'; + +//RULE: deletedAt != null ⇒ active must be false +export interface Scene extends Document { + userId: Types.ObjectId; + storyId: Types.ObjectId; + order: number; + title?: string; + description: string; + narrativeRole: 'intro' | 'transition' | 'climax' | 'outro' | 'standard'; + authorType: 'ai' | 'user'; + imagePrompt: string; + videoPrompt: string; + duration?: number; + activeAssetId?: Types.ObjectId; + active: boolean; + deletedAt?: Date; + createdAt: Date; + updatedAt: Date; +} + +const sceneSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + + storyId: { + type: Schema.Types.ObjectId, + ref: 'Story', + required: true, + }, + + order: { + type: Number, + required: true, + min: 0, + }, + + title: { + type: String, + trim: true, + maxlength: 200, + }, + + description: { + type: String, + required: true, + }, + narrativeRole: { + type: String, + enum: ['intro', 'transition', 'climax', 'outro', 'standard'], + default: 'standard', + }, + authorType: { + type: String, + enum: ['ai', 'user'], + default: 'ai', + }, + imagePrompt: { + type: String, + required: true, + }, + videoPrompt: { + type: String, + required: true, + }, + duration: { + type: Number, + }, + activeAssetId: { + type: Schema.Types.ObjectId, + ref: 'SceneAsset', + }, + active: { + type: Boolean, + required: true, + default: true, + }, + deletedAt: { + type: Date, + default: undefined, + }, + }, + { timestamps: true } +); + +sceneSchema.index( + { storyId: 1, order: 1 }, + { + unique: true, + partialFilterExpression: { deletedAt: { $exists: false } }, + } +); + +export const SceneModel = model('Scene', sceneSchema); diff --git a/src/models/SceneAssets.ts b/src/models/SceneAssets.ts new file mode 100644 index 0000000..86ed5f7 --- /dev/null +++ b/src/models/SceneAssets.ts @@ -0,0 +1,88 @@ +import { allFormats, type AssetFormat } from '@constants/sceneAssetConsts.js'; +import { Schema, model, Document, Types } from 'mongoose'; + +export interface SceneAsset extends Document { + userId: Types.ObjectId; + sceneId: Types.ObjectId; + type: 'image' | 'video'; + url: string; + visibility: 'private' | 'public'; + prompt?: string; + generationSource: 'ai' | 'user'; + version: number; + width?: number; + height?: number; + format?: AssetFormat; + duration?: number; + deletedAt?: Date; + createdAt: Date; + updatedAt: Date; +} + +const sceneAssetSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + sceneId: { + type: Schema.Types.ObjectId, + ref: 'Scene', + required: true, + index: true, + }, + type: { + type: String, + enum: ['image', 'video'], + required: true, + }, + url: { + type: String, + required: true, + }, + visibility: { + type: String, + enum: ['private', 'public'], + default: 'public', + }, + prompt: { + type: String, + }, + generationSource: { + type: String, + enum: ['ai', 'user'], + default: 'ai', + }, + format: { + type: String, + enum: allFormats, + }, + version: { + type: Number, + required: true, + default: 1, + min: 1, + }, + width: Number, + height: Number, + duration: Number, + + deletedAt: { + type: Date, + }, + }, + + { timestamps: true } +); + +sceneAssetSchema.index({ userId: 1, createdAt: -1 }); + +//TTL +sceneAssetSchema.index( + { deletedAt: 1 }, + { expireAfterSeconds: 30 * 24 * 60 * 60, partialFilterExpression: { deletedAt: { $exists: true } } } +); + +export const SceneAssetModel = model('SceneAsset', sceneAssetSchema); diff --git a/src/models/Session.ts b/src/models/Session.ts index eb73f3f..6a2e476 100644 --- a/src/models/Session.ts +++ b/src/models/Session.ts @@ -1,4 +1,4 @@ -import { HydratedDocument, InferSchemaType, model, Schema } from "mongoose"; +import { HydratedDocument, InferSchemaType, model, Schema } from 'mongoose'; const sessionSchema = new Schema({ sessionId: { type: String, required: true, index: true }, @@ -30,16 +30,19 @@ const sessionSchema = new Schema({ isp: { type: String }, cpu: { type: String }, engine: { type: String }, + refreshTokenHash: { type: String, required: true }, + csrfTokenHash: { type: String, required: true }, + expiresIn: { type: Date, required: true }, createdAt: { type: Date, default: Date.now }, lastUsedAt: { type: Date, default: Date.now }, revokedAt: { type: Date, default: null }, + valid: { type: Boolean, default: true }, }); -//TTL index: automatically remove sessions not used for 30 days -sessionSchema.index( - { lastUsedAt: 1 }, - { expireAfterSeconds: 30 * 24 * 60 * 60 } -); +//TTL index: automatically remove sessions not used for 25 days +sessionSchema.index({ lastUsedAt: 1 }, { expireAfterSeconds: 25 * 24 * 60 * 60 }); + +//TTL index: automatically remove revoked sessions after 7 days sessionSchema.index( { revokedAt: 1 }, { @@ -54,4 +57,4 @@ sessionSchema.index({ userId: 1, lastUsedAt: -1 }); export type SessionData = InferSchemaType; export type Session = HydratedDocument; -export const SessionModel = model("Session", sessionSchema); +export const SessionModel = model('Session', sessionSchema); diff --git a/src/models/Story.ts b/src/models/Story.ts index e69de29..8d3b573 100644 --- a/src/models/Story.ts +++ b/src/models/Story.ts @@ -0,0 +1,120 @@ +import { Schema, model, Document, Types } from 'mongoose'; +import { type StoryIntent, type Platform, platform, storyIntent } from '@constants/storyConsts.js'; + +//TODO: Put all history tracking in StoryRevision model later + +export interface Story extends Document { + userId: Types.ObjectId; + projectId?: Types.ObjectId; + title: string; + description: string; + content: { + summary: string; + body: string; + keywords?: string[]; + tags?: string[]; + authorType: 'ai' | 'user'; + }; + + status: 'active' | 'delete' | 'archive' | 'draft'; + deletedAt: Date; + version: number; + timeLimit?: number; + contextProfileId: Types.ObjectId; + intent: StoryIntent; + platform: Platform; + createdAt: Date; + updatedAt: Date; +} + +const storySchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + projectId: { + type: Schema.Types.ObjectId, + ref: 'Project', + index: true, + }, + title: { + type: String, + trim: true, + maxlength: 200, + required: true, + }, + description: { + type: String, + trim: true, + maxlength: 1000, + required: true, + }, + content: { + body: { + type: String, + default: '', + }, + summary: { + type: String, + default: '', + }, + keywords: { + type: [String], + default: [], + }, + tags: { + type: [String], + default: [], + }, + authorType: { + type: String, + enum: ['ai', 'user'], + default: 'ai', + }, + }, + + status: { + type: String, + enum: ['active', 'archive', 'delete', 'draft'], + default: 'active', + }, + deletedAt: { + type: Date, + }, + version: { + type: Number, + required: true, + default: 1, + min: 1, + }, + timeLimit: { + type: Number, + }, + contextProfileId: { + type: Schema.Types.ObjectId, + ref: 'ContextProfile', + required: true, + }, + intent: { + type: String, + enum: [...storyIntent], + required: true, + default: 'short-form', + }, + platform: { + type: String, + enum: [...platform], + required: true, + default: 'youtube', + }, + }, + { timestamps: true } +); + +storySchema.index({ userId: 1, createdAt: -1 }); +storySchema.index({ userId: 1, projectId: 1, createdAt: -1 }); + +export const StoryModel = model('Story', storySchema); diff --git a/src/models/User.ts b/src/models/User.ts index c6f0cd0..6efcd1e 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -1,10 +1,5 @@ -import { ACCOUNT_STATUSES } from "constants/accountStatus.js"; -import { - Schema, - model, - type InferSchemaType, - type HydratedDocument, -} from "mongoose"; +import { ACCOUNT_STATUSES } from 'constants/authConsts.js'; +import { Schema, model, type InferSchemaType, type HydratedDocument } from 'mongoose'; const ResetSchema = new Schema( { @@ -19,9 +14,10 @@ const UpdateEmailSchema = new Schema( { newEmail: { type: String, trim: true, lowercase: true }, tokenHash: { type: String }, + code: { type: String }, expiresAt: { type: Date }, requestedAt: { type: Date }, - requestMethod: { type: String }, // "self" | "oauth" + requestMethod: { type: String, enum: ['self', 'system', 'admin'] }, }, { _id: false } ); @@ -31,13 +27,13 @@ const changeMetaSchema = new Schema( field: { type: String, required: true, - enum: ["email", "password", "username", "accountStatus", "displayName"], + enum: ['email', 'password', 'accountStatus'], }, from: { type: Schema.Types.Mixed, default: null }, // previous value to: { type: Schema.Types.Mixed, default: null }, // new value - by: { type: Schema.Types.ObjectId, ref: "User", required: true }, + by: { type: Schema.Types.ObjectId, ref: 'User', required: true }, reason: { type: String, maxlength: 300, default: null }, @@ -45,7 +41,7 @@ const changeMetaSchema = new Schema( via: { type: String, - enum: ["user", "admin", "system"], + enum: ['user', 'admin', 'system'], required: true, }, }, @@ -84,25 +80,28 @@ const providerSchema = new Schema( { _id: false } // no separate _id needed per provider ); -const privacyPrefsSchema = new Schema({ - profileVisibility: { - type: String, - enum: ["private", "public", "unlisted"], - default: "private", - }, - showEmailOnProfile: { - type: Boolean, - default: false, - }, - showLinksOnProfile: { - type: Boolean, - default: true, - }, - allowDiscoverability: { - type: Boolean, - default: true, +const privacyPrefsSchema = new Schema( + { + profileVisibility: { + type: String, + enum: ['private', 'public', 'unlisted'], + default: 'private', + }, + showEmailOnProfile: { + type: Boolean, + default: false, + }, + showLinksOnProfile: { + type: Boolean, + default: true, + }, + allowDiscoverability: { + type: Boolean, + default: true, + }, }, -}); + { _id: false } +); /** * Subdocument: notification preferences @@ -175,6 +174,7 @@ const userSchema = new Schema( type: String, trim: true, maxlength: 80, + required: true, }, username: { type: String, @@ -184,6 +184,7 @@ const userSchema = new Schema( index: true, sparse: true, // allows null without unique conflict unique: true, + required: true, }, avatarUrl: { type: String, @@ -205,20 +206,27 @@ const userSchema = new Schema( }, role: { type: String, - enum: ["user", "admin"], - default: "user", + enum: ['user', 'admin'], + default: 'user', index: true, }, - plan: { - type: String, - enum: ["free", "pro", "enterprise"], - default: "free", + currentPlan: { + type: Schema.Types.ObjectId, + ref: 'Plan', + }, + + planStartedAt: { + type: Date, }, + + planEndsAt: { + type: Date, + }, + usage: { type: usageSchema, default: () => ({}), - }, - // Auth (password-based) + }, passwordHash: { type: String, required: true, @@ -268,13 +276,7 @@ const userSchema = new Schema( // Account Status - accountStatus: { type: String, enum: ACCOUNT_STATUSES, default: "active" }, - - changeHistory: { - type: [changeMetaSchema], - default: [], - select: false, - }, + accountStatus: { type: String, enum: ACCOUNT_STATUSES, default: 'active' }, // Billing billingCustomerId: { type: String }, @@ -282,23 +284,30 @@ const userSchema = new Schema( subscriptionId: { type: String }, billingStatus: { type: String, - enum: ["none", "active", "past_due", "canceled", "incomplete"], - default: "none", + enum: ['none', 'active', 'past_due', 'canceled', 'incomplete'], + default: 'none', }, currentPeriodEnd: { type: Date }, trialEndsAt: { type: Date }, cancelAtPeriodEnd: { type: Boolean, default: false }, - // Notification settings notificationPrefs: { type: notificationPrefsSchema, - default: () => ({}), + default: () => ({ + emailOnJobComplete: true, + inApp: true, + marketingEmails: false, + }), }, - // Privacy prefs privacyPrefs: { type: privacyPrefsSchema, - default: () => ({}), + default: () => ({ + profileVisibility: 'private', + showEmailOnProfile: false, + showLinksOnProfile: true, + allowDiscoverability: true, + }), }, // Legal / Terms termsAcceptedAt: { type: Date }, @@ -307,21 +316,21 @@ const userSchema = new Schema( deletedAt: { type: Date, }, + changeHistory: { + type: [changeMetaSchema], + default: [], + select: false, + cap: 100, + }, }, { timestamps: true, } ); -/** - * Index to quickly find by provider (Google, GitHub, etc.) - */ -userSchema.index( - { "providers.provider": 1, "providers.providerUserId": 1 }, - { sparse: true } -); +userSchema.index({ 'providers.provider': 1, 'providers.providerUserId': 1 }, { sparse: true }); export type UserData = InferSchemaType; export type User = HydratedDocument; -export const UserModel = model("User", userSchema); +export const UserModel = model('User', userSchema); diff --git a/src/models/VideoConfig.ts b/src/models/VideoConfig.ts new file mode 100644 index 0000000..ad70ae6 --- /dev/null +++ b/src/models/VideoConfig.ts @@ -0,0 +1,488 @@ +import mongoose, { Document, Schema, Types } from 'mongoose'; + +// ============ Sub-document Interfaces ============ + +export interface INarrationConfig { + narrationId: Types.ObjectId; + audioAssetId?: Types.ObjectId; + volume: number; + startOffset: number; + endOffset: number; + fadeInDuration: number; + fadeOutDuration: number; + enabled: boolean; +} + +export interface ICaptionConfig { + enabled: boolean; + position: { + vertical: 'top' | 'middle' | 'bottom'; + horizontal: 'left' | 'center' | 'right'; + }; + offset: { + x: number; + y: number; + }; + style: { + fontSize: number; + fontFamily: string; + fontColor: string; + fontWeight: 'normal' | 'bold' | 'light'; + backgroundColor: string; + backgroundOpacity: number; + textShadow: boolean; + textOutline: boolean; + outlineColor: string; + outlineWidth: number; + }; + animation: { + type: 'none' | 'fade' | 'slide' | 'typewriter' | 'bounce'; + duration: number; + }; +} + +export interface ISoundEffectConfig { + audioAssetId: Types.ObjectId; + name: string; + startTime: number; + duration?: number; + volume: number; + trimStart: number; + usePercentage: number; + loop: boolean; + loopCount?: number; + fadeInDuration: number; + fadeOutDuration: number; + enabled: boolean; +} + +export interface IVideoEffectConfig { + effectId: string; + effectType: + | 'blur' + | 'zoom' + | 'pan' + | 'fade' + | 'overlay' + | 'color_filter' + | 'vignette' + | 'shake' + | 'glitch' + | 'slow_motion' + | 'speed_up' + | 'ken_burns' + | 'picture_in_picture' + | 'split_screen' + | 'custom'; + name: string; + startTime: number; + duration: number; + position: { + x: number; + y: number; + width: number; + height: number; + anchorPoint: + | 'top-left' + | 'top-center' + | 'top-right' + | 'center-left' + | 'center' + | 'center-right' + | 'bottom-left' + | 'bottom-center' + | 'bottom-right'; + }; + intensity: number; + easing: 'linear' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'bounce'; + parameters: Record; + enabled: boolean; +} + +export interface ITransitionConfig { + fromSceneIndex: number; + toSceneIndex: number; + type: + | 'none' + | 'fade' + | 'dissolve' + | 'wipe_left' + | 'wipe_right' + | 'wipe_up' + | 'wipe_down' + | 'slide_left' + | 'slide_right' + | 'zoom_in' + | 'zoom_out' + | 'blur'; + duration: number; + easing: 'linear' | 'ease-in' | 'ease-out' | 'ease-in-out'; +} + +export interface ISceneTimingConfig { + sceneId: Types.ObjectId; + order: number; + startTime: number; + duration: number; + customDuration?: number; +} + +export interface IOutputSettings { + resolution: { + width: number; + height: number; + preset: '480p' | '720p' | '1080p' | '1440p' | '4k' | 'custom'; + }; + aspectRatio: '16:9' | '9:16' | '1:1' | '4:3' | '21:9' | 'custom'; + frameRate: 24 | 30 | 60; + quality: 'low' | 'medium' | 'high' | 'ultra'; + format: 'mp4' | 'webm' | 'mov'; + bitrate?: number; +} + +export interface IBackgroundAudioConfig { + audioAssetId?: Types.ObjectId; + volume: number; + fadeInDuration: number; + fadeOutDuration: number; + loop: boolean; + enabled: boolean; +} + +export interface IWatermarkConfig { + enabled: boolean; + imageUrl?: string; + text?: string; + position: { + vertical: 'top' | 'middle' | 'bottom'; + horizontal: 'left' | 'center' | 'right'; + }; + offset: { + x: number; + y: number; + }; + opacity: number; + size: number; +} + +// ============ Main Interface ============ + +export interface IVideoConfig extends Document { + _id: Types.ObjectId; + userId: Types.ObjectId; + storyId: Types.ObjectId; + projectId: Types.ObjectId; + name: string; + description?: string; + + sceneOrder: Types.ObjectId[]; + sceneTiming: ISceneTimingConfig[]; + + totalDuration: number; + + narration: INarrationConfig; + + captions: ICaptionConfig; + + soundEffects: ISoundEffectConfig[]; + + videoEffects: IVideoEffectConfig[]; + + transitions: ITransitionConfig[]; + + backgroundAudio: IBackgroundAudioConfig; + + watermark: IWatermarkConfig; + + outputSettings: IOutputSettings; + + version: number; + isTemplate: boolean; + templateName?: string; + + createdAt: Date; + updatedAt: Date; +} + +const NarrationConfigSchema = new Schema( + { + narrationId: { type: Schema.Types.ObjectId, ref: 'Narration', required: true }, + audioAssetId: { type: Schema.Types.ObjectId, ref: 'AudioAsset' }, + volume: { type: Number, min: 0, max: 100, default: 100 }, + startOffset: { type: Number, min: 0, default: 0 }, + endOffset: { type: Number, min: 0, default: 0 }, + fadeInDuration: { type: Number, min: 0, default: 0 }, + fadeOutDuration: { type: Number, min: 0, default: 0 }, + enabled: { type: Boolean, default: true }, + }, + { _id: false } +); + +const CaptionConfigSchema = new Schema( + { + enabled: { type: Boolean, default: true }, + position: { + vertical: { type: String, enum: ['top', 'middle', 'bottom'], default: 'bottom' }, + horizontal: { type: String, enum: ['left', 'center', 'right'], default: 'center' }, + }, + offset: { + x: { type: Number, default: 0 }, + y: { type: Number, default: 0 }, + }, + style: { + fontSize: { type: Number, min: 8, max: 120, default: 24 }, + fontFamily: { type: String, default: 'Arial' }, + fontColor: { type: String, default: '#FFFFFF' }, + fontWeight: { type: String, enum: ['normal', 'bold', 'light'], default: 'bold' }, + backgroundColor: { type: String, default: '#000000' }, + backgroundOpacity: { type: Number, min: 0, max: 100, default: 50 }, + textShadow: { type: Boolean, default: true }, + textOutline: { type: Boolean, default: false }, + outlineColor: { type: String, default: '#000000' }, + outlineWidth: { type: Number, min: 0, max: 10, default: 2 }, + }, + animation: { + type: { type: String, enum: ['none', 'fade', 'slide', 'typewriter', 'bounce'], default: 'fade' }, + duration: { type: Number, min: 0, default: 0.3 }, + }, + }, + { _id: false } +); + +const SoundEffectConfigSchema = new Schema( + { + audioAssetId: { type: Schema.Types.ObjectId, ref: 'AudioAsset', required: true }, + name: { type: String, required: true, trim: true }, + startTime: { type: Number, min: 0, required: true }, + duration: { type: Number, min: 0 }, + volume: { type: Number, min: 0, max: 100, default: 100 }, + trimStart: { type: Number, min: 0, default: 0 }, + usePercentage: { type: Number, min: 1, max: 100, default: 100 }, + loop: { type: Boolean, default: false }, + loopCount: { type: Number, min: 1 }, + fadeInDuration: { type: Number, min: 0, default: 0 }, + fadeOutDuration: { type: Number, min: 0, default: 0 }, + enabled: { type: Boolean, default: true }, + }, + { _id: false } +); + +const VideoEffectConfigSchema = new Schema( + { + effectId: { type: String, required: true }, + effectType: { + type: String, + enum: [ + 'blur', + 'zoom', + 'pan', + 'fade', + 'overlay', + 'color_filter', + 'vignette', + 'shake', + 'glitch', + 'slow_motion', + 'speed_up', + 'ken_burns', + 'picture_in_picture', + 'split_screen', + 'custom', + ], + required: true, + }, + name: { type: String, required: true, trim: true }, + startTime: { type: Number, min: 0, required: true }, + duration: { type: Number, min: 0, required: true }, + position: { + x: { type: Number, min: 0, max: 100, default: 0 }, + y: { type: Number, min: 0, max: 100, default: 0 }, + width: { type: Number, min: 0, max: 100, default: 100 }, + height: { type: Number, min: 0, max: 100, default: 100 }, + anchorPoint: { + type: String, + enum: [ + 'top-left', + 'top-center', + 'top-right', + 'center-left', + 'center', + 'center-right', + 'bottom-left', + 'bottom-center', + 'bottom-right', + ], + default: 'center', + }, + }, + intensity: { type: Number, min: 0, max: 100, default: 50 }, + easing: { + type: String, + enum: ['linear', 'ease-in', 'ease-out', 'ease-in-out', 'bounce'], + default: 'linear', + }, + parameters: { type: Schema.Types.Mixed, default: {} }, + enabled: { type: Boolean, default: true }, + }, + { _id: false } +); + +const TransitionConfigSchema = new Schema( + { + fromSceneIndex: { type: Number, required: true, min: 0 }, + toSceneIndex: { type: Number, required: true, min: 0 }, + type: { + type: String, + enum: [ + 'none', + 'fade', + 'dissolve', + 'wipe_left', + 'wipe_right', + 'wipe_up', + 'wipe_down', + 'slide_left', + 'slide_right', + 'zoom_in', + 'zoom_out', + 'blur', + ], + default: 'fade', + }, + duration: { type: Number, min: 0, max: 5, default: 0.5 }, + easing: { type: String, enum: ['linear', 'ease-in', 'ease-out', 'ease-in-out'], default: 'ease-in-out' }, + }, + { _id: false } +); + +const SceneTimingConfigSchema = new Schema( + { + sceneId: { type: Schema.Types.ObjectId, ref: 'Scene', required: true }, + order: { type: Number, required: true, min: 0 }, + startTime: { type: Number, required: true, min: 0 }, + duration: { type: Number, required: true, min: 0 }, + customDuration: { type: Number, min: 0 }, + }, + { _id: false } +); + +const OutputSettingsSchema = new Schema( + { + resolution: { + width: { type: Number, min: 320, max: 7680, default: 1920 }, + height: { type: Number, min: 240, max: 4320, default: 1080 }, + preset: { type: String, enum: ['480p', '720p', '1080p', '1440p', '4k', 'custom'], default: '1080p' }, + }, + aspectRatio: { type: String, enum: ['16:9', '9:16', '1:1', '4:3', '21:9', 'custom'], default: '16:9' }, + frameRate: { type: Number, enum: [24, 30, 60], default: 30 }, + quality: { type: String, enum: ['low', 'medium', 'high', 'ultra'], default: 'high' }, + format: { type: String, enum: ['mp4', 'webm', 'mov'], default: 'mp4' }, + bitrate: { type: Number, min: 500, max: 100000 }, + }, + { _id: false } +); + +const BackgroundAudioConfigSchema = new Schema( + { + audioAssetId: { type: Schema.Types.ObjectId, ref: 'AudioAsset' }, + volume: { type: Number, min: 0, max: 100, default: 30 }, + fadeInDuration: { type: Number, min: 0, default: 2 }, + fadeOutDuration: { type: Number, min: 0, default: 2 }, + loop: { type: Boolean, default: true }, + enabled: { type: Boolean, default: false }, + }, + { _id: false } +); + +const WatermarkConfigSchema = new Schema( + { + enabled: { type: Boolean, default: false }, + imageUrl: { type: String }, + text: { type: String, maxlength: 100 }, + position: { + vertical: { type: String, enum: ['top', 'middle', 'bottom'], default: 'bottom' }, + horizontal: { type: String, enum: ['left', 'center', 'right'], default: 'right' }, + }, + offset: { + x: { type: Number, default: 10 }, + y: { type: Number, default: 10 }, + }, + opacity: { type: Number, min: 0, max: 100, default: 70 }, + size: { type: Number, min: 1, max: 100, default: 10 }, + }, + { _id: false } +); + +// ============ Main Schema ============ + +const VideoConfigSchema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'User', required: true, index: true }, + storyId: { type: Schema.Types.ObjectId, ref: 'Story', required: true, index: true }, + projectId: { type: Schema.Types.ObjectId, ref: 'Project', required: true, index: true }, + name: { type: String, required: true, trim: true, maxlength: 200 }, + description: { type: String, trim: true, maxlength: 1000 }, + + sceneOrder: [{ type: Schema.Types.ObjectId, ref: 'Scene' }], + sceneTiming: [SceneTimingConfigSchema], + + totalDuration: { type: Number, min: 0, default: 0 }, + + narration: { type: NarrationConfigSchema, required: true }, + + captions: { type: CaptionConfigSchema, default: () => ({}) }, + + soundEffects: { type: [SoundEffectConfigSchema], default: [] }, + + videoEffects: { type: [VideoEffectConfigSchema], default: [] }, + + transitions: { type: [TransitionConfigSchema], default: [] }, + + backgroundAudio: { type: BackgroundAudioConfigSchema, default: () => ({}) }, + + watermark: { type: WatermarkConfigSchema, default: () => ({}) }, + + outputSettings: { type: OutputSettingsSchema, default: () => ({}) }, + + version: { type: Number, default: 1 }, + isTemplate: { type: Boolean, default: false, index: true }, + templateName: { type: String, trim: true, maxlength: 100 }, + }, + { + timestamps: true, + toJSON: { virtuals: true }, + toObject: { virtuals: true }, + } +); + +// ============ Indexes ============ + +VideoConfigSchema.index({ userId: 1, storyId: 1 }); +VideoConfigSchema.index({ userId: 1, projectId: 1 }); +VideoConfigSchema.index({ userId: 1, isTemplate: 1 }); +VideoConfigSchema.index({ createdAt: -1 }); + +// ============ Virtual Fields ============ + +VideoConfigSchema.virtual('sceneCount').get(function () { + return this.sceneOrder?.length || 0; +}); + +VideoConfigSchema.virtual('soundEffectCount').get(function () { + return this.soundEffects?.filter((s) => s.enabled).length || 0; +}); + +VideoConfigSchema.virtual('videoEffectCount').get(function () { + return this.videoEffects?.filter((v) => v.enabled).length || 0; +}); + +VideoConfigSchema.virtual('formattedDuration').get(function () { + const totalSeconds = this.totalDuration || 0; + const minutes = Math.floor(totalSeconds / 60); + const seconds = Math.floor(totalSeconds % 60); + return `${minutes}:${seconds.toString().padStart(2, '0')}`; +}); + +const VideoConfig = mongoose.model('VideoConfig', VideoConfigSchema); + +export default VideoConfig; diff --git a/src/modules/audio/audio.constants.ts b/src/modules/audio/audio.constants.ts new file mode 100644 index 0000000..f954468 --- /dev/null +++ b/src/modules/audio/audio.constants.ts @@ -0,0 +1,28 @@ +// Audio generation configuration +export const DEFAULT_VOICE_STABILITY = 0.5; +export const DEFAULT_VOICE_SIMILARITY_BOOST = 0.75; +export const DEFAULT_VOICE_STYLE = 0; +export const DEFAULT_USE_SPEAKER_BOOST = true; + +// Supported TTS providers +export const TTS_PROVIDERS = ['elevenlabs', 'openai', 'azure', 'google'] as const; +export type TTSProvider = (typeof TTS_PROVIDERS)[number]; + +// Default provider +export const DEFAULT_TTS_PROVIDER: TTSProvider = 'elevenlabs'; + +// Audio quality settings +export const AUDIO_OUTPUT_FORMAT = 'mp3_44100_128' as const; +export const AUDIO_SAMPLE_RATE = 44100; +export const AUDIO_BIT_RATE = 128; + +// Rate limiting +export const MAX_AUDIO_GENERATIONS_PER_DAY = 100; +export const MAX_AUDIO_GENERATIONS_PER_HOUR = 20; + +// Cache TTL (in seconds) +export const AUDIO_CACHE_TTL = 86400; // 24 hours + +// Version constants +export const AUDIO_VERSION_START = 1; +export const MAX_AUDIO_VERSIONS_PER_NARRATION = 100; diff --git a/src/modules/audio/audio.controller.ts b/src/modules/audio/audio.controller.ts new file mode 100644 index 0000000..2d678db --- /dev/null +++ b/src/modules/audio/audio.controller.ts @@ -0,0 +1,292 @@ +import { Request, Response } from 'express'; +import { + getAllAudioAssetsForNarration, + getAllDeletedAudioAssets, + getAudioAssetById, + getAudioAssetCount, + getActiveAudioAssetForNarration, + generateAudioAsset, + regenerateAudioAsset, + uploadNarrationAudioAsset, + setActiveAudioAsset, + softDeleteAudioAsset, + permanentDeleteAudioAsset, + forceDeleteActiveAudioAsset, + restoreAudioAsset, + softDeleteAllAudioAssetsForNarration, + permanentDeleteAllAudioAssetsForNarration, + restoreAllDeletedAudioAssets, + softBulkDeleteAudioAssets, + permanentBulkDeleteAudioAssets, + bulkRestoreAudioAssets, +} from './audio.service.js'; +import type { + GenerateAudioAssetInput, + RegenerateAudioAssetInput, + UploadAudioAssetInput, + SetActiveAudioAssetInput, + UpdateAudioAssetInput, + BulkDeleteAudioAssetsInput, + BulkRestoreAudioAssetsInput, +} from '@validation/audio.schema.js'; +import { paginationResponse } from '@utils/paginationResponse.js'; + +// ==================== ALL OPERATIONS ==================== + +export const getAllAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + + const [audioAssets, total] = await getAllAudioAssetsForNarration(userId, narrationId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + res.status(200).json({ + message: 'Audio assets retrieved successfully', + data: audioAssets, + pagination: paginationRes, + }); +}; + +export const getAllDeletedAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + + const [audioAssets, total] = await getAllDeletedAudioAssets(userId, narrationId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + res.status(200).json({ + message: 'Deleted audio assets retrieved successfully', + data: audioAssets, + pagination: paginationRes, + }); +}; + +export const restoreAllDeletedAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const result = await restoreAllDeletedAudioAssets(userId, narrationId); + + res.status(200).json({ + message: 'All deleted audio assets restored successfully', + restoredCount: result.restoredCount, + }); +}; + +export const softDeleteAllAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const result = await softDeleteAllAudioAssetsForNarration(userId, narrationId); + + res.status(200).json({ + message: 'All audio assets soft deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const permanentDeleteAllAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const result = await permanentDeleteAllAudioAssetsForNarration(userId, narrationId); + + res.status(200).json({ + message: 'All audio assets permanently deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const getAudioAssetCountController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const count = await getAudioAssetCount(userId, narrationId); + + res.status(200).json({ + message: 'Audio asset count retrieved successfully', + count, + }); +}; + +// ==================== BULK OPERATIONS ==================== + +export const softBulkDeleteAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + const { audioAssetIds } = req.validatedBody as BulkDeleteAudioAssetsInput; + + const result = await softBulkDeleteAudioAssets(userId, narrationId, audioAssetIds); + + res.status(200).json({ + message: 'Audio assets soft deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const permanentBulkDeleteAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + const { audioAssetIds } = req.validatedBody as BulkDeleteAudioAssetsInput; + + const result = await permanentBulkDeleteAudioAssets(userId, narrationId, audioAssetIds); + + res.status(200).json({ + message: 'Audio assets permanently deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const bulkRestoreAudioAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + const { audioAssetIds } = req.validatedBody as BulkRestoreAudioAssetsInput; + + const result = await bulkRestoreAudioAssets(userId, narrationId, audioAssetIds); + + res.status(200).json({ + message: 'Audio assets restored successfully', + data: result, + }); +}; + +// ==================== SINGLE OPERATIONS ==================== + +export const getAudioAssetByIdController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { audioAssetId } = req.params; + + const audioAsset = await getAudioAssetById(userId, audioAssetId); + + res.status(200).json({ + message: 'Audio asset retrieved successfully', + data: audioAsset, + }); +}; + +export const getActiveAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const audioAsset = await getActiveAudioAssetForNarration(userId, narrationId); + + if (!audioAsset) { + return res.status(200).json({ + message: 'No active audio asset found for this narration', + data: null, + }); + } + + res.status(200).json({ + message: 'Active audio asset retrieved successfully', + data: audioAsset, + }); +}; + +export const generateAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + const { voiceId, prompt } = req.validatedBody as GenerateAudioAssetInput; + + const audioAsset = await generateAudioAsset(userId, narrationId, voiceId, prompt); + + res.status(201).json({ + message: 'Audio asset generated successfully', + data: audioAsset, + }); +}; + +export const regenerateAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { audioAssetId } = req.params; + const { voiceId, extraPrompt } = req.validatedBody as RegenerateAudioAssetInput; + + const audioAsset = await regenerateAudioAsset(userId, audioAssetId, voiceId, extraPrompt); + + res.status(201).json({ + message: 'Audio asset regenerated successfully', + data: audioAsset, + }); +}; + +export const uploadAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + if (!req.file) { + return res.status(400).json({ + message: 'No file uploaded', + }); + } + + const audioAsset = await uploadNarrationAudioAsset(userId, narrationId, req.file.path); + + res.status(201).json({ + message: 'Audio asset uploaded successfully', + data: audioAsset, + }); +}; + +export const setActiveAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + const { audioAssetId } = req.validatedBody as SetActiveAudioAssetInput; + + const audioAsset = await setActiveAudioAsset(userId, narrationId, audioAssetId); + + res.status(200).json({ + message: 'Audio asset set as active successfully', + data: audioAsset, + }); +}; + +export const softDeleteAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { audioAssetId } = req.params; + + await softDeleteAudioAsset(userId, audioAssetId); + + res.status(200).json({ + message: 'Audio asset soft deleted successfully', + }); +}; + +export const permanentDeleteAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { audioAssetId } = req.params; + + await permanentDeleteAudioAsset(userId, audioAssetId); + + res.status(200).json({ + message: 'Audio asset permanently deleted successfully', + }); +}; + +export const forceDeleteActiveAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { audioAssetId } = req.params; + + await forceDeleteActiveAudioAsset(userId, audioAssetId); + + res.status(200).json({ + message: 'Active audio asset force deleted successfully', + }); +}; + +export const restoreAudioAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId, audioAssetId } = req.params; + + const audioAsset = await restoreAudioAsset(userId, narrationId, audioAssetId); + + res.status(200).json({ + message: 'Audio asset restored successfully', + data: audioAsset, + }); +}; diff --git a/src/modules/audio/audio.routes.ts b/src/modules/audio/audio.routes.ts new file mode 100644 index 0000000..7057cbb --- /dev/null +++ b/src/modules/audio/audio.routes.ts @@ -0,0 +1,175 @@ +import { Router } from 'express'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { validateParams } from '@validation/validateParams.js'; +import { validateBody } from '@validation/validateBody.js'; +import { paginationAndSortingMiddleware } from '@middleware/request/paginationAndSorting.js'; +import { audioAssetUpload } from '@middleware/multer/audioAssetUpload.js'; + +import { + narrationIdParamSchema, + audioAssetIdParamSchema, + audioAssetAndNarrationParamSchema, + generateAudioAssetSchema, + regenerateAudioAssetSchema, + uploadAudioAssetSchema, + setActiveAudioAssetSchema, + updateAudioAssetSchema, + bulkDeleteAudioAssetsSchema, + bulkRestoreAudioAssetsSchema, +} from '@validation/audio.schema.js'; + +import { + getAllAudioAssetsController, + getAllDeletedAudioAssetsController, + getAudioAssetByIdController, + getAudioAssetCountController, + getActiveAudioAssetController, + generateAudioAssetController, + regenerateAudioAssetController, + uploadAudioAssetController, + setActiveAudioAssetController, + softDeleteAudioAssetController, + permanentDeleteAudioAssetController, + forceDeleteActiveAudioAssetController, + restoreAudioAssetController, + softDeleteAllAudioAssetsController, + permanentDeleteAllAudioAssetsController, + restoreAllDeletedAudioAssetsController, + softBulkDeleteAudioAssetsController, + permanentBulkDeleteAudioAssetsController, + bulkRestoreAudioAssetsController, +} from './audio.controller.js'; + +const router = Router(); + +//ALL OPERATIONS + +router.get( + '/narration/:narrationId', + validateParams(narrationIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllAudioAssetsController) +); + +router.get( + '/narration/:narrationId/deleted', + validateParams(narrationIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllDeletedAudioAssetsController) +); + +router.get( + '/narration/:narrationId/count', + validateParams(narrationIdParamSchema), + asyncHandler(getAudioAssetCountController) +); + +router.delete( + '/narration/:narrationId', + validateParams(narrationIdParamSchema), + asyncHandler(softDeleteAllAudioAssetsController) +); + +router.delete( + '/narration/:narrationId/permanent', + validateParams(narrationIdParamSchema), + asyncHandler(permanentDeleteAllAudioAssetsController) +); + +router.post( + '/narration/:narrationId/restore', + validateParams(narrationIdParamSchema), + asyncHandler(restoreAllDeletedAudioAssetsController) +); + +// BULK OPERATIONS + +router.post( + '/narration/:narrationId/soft-bulk-delete', + validateParams(narrationIdParamSchema), + validateBody(bulkDeleteAudioAssetsSchema), + asyncHandler(softBulkDeleteAudioAssetsController) +); + +router.post( + '/narration/:narrationId/permanent-bulk-delete', + validateParams(narrationIdParamSchema), + validateBody(bulkDeleteAudioAssetsSchema), + asyncHandler(permanentBulkDeleteAudioAssetsController) +); + +router.post( + '/narration/:narrationId/bulk-restore', + validateParams(narrationIdParamSchema), + validateBody(bulkRestoreAudioAssetsSchema), + asyncHandler(bulkRestoreAudioAssetsController) +); + +// SINGLE OPERATIONS + +router.get( + '/narration/:narrationId/active', + validateParams(narrationIdParamSchema), + asyncHandler(getActiveAudioAssetController) +); + +router.post( + '/narration/:narrationId/generate', + validateParams(narrationIdParamSchema), + validateBody(generateAudioAssetSchema), + asyncHandler(generateAudioAssetController) +); + +router.post( + '/narration/:narrationId/upload', + validateParams(narrationIdParamSchema), + audioAssetUpload, + validateBody(uploadAudioAssetSchema), + asyncHandler(uploadAudioAssetController) +); + +router.patch( + '/narration/:narrationId/set-active', + validateParams(narrationIdParamSchema), + validateBody(setActiveAudioAssetSchema), + asyncHandler(setActiveAudioAssetController) +); + +router.get( + '/:audioAssetId', + validateParams(audioAssetIdParamSchema), + asyncHandler(getAudioAssetByIdController) +); + +router.post( + '/:audioAssetId/regenerate', + validateParams(audioAssetIdParamSchema), + validateBody(regenerateAudioAssetSchema), + asyncHandler(regenerateAudioAssetController) +); + +router.delete( + '/:audioAssetId', + validateParams(audioAssetIdParamSchema), + asyncHandler(softDeleteAudioAssetController) +); + +router.delete( + '/:audioAssetId/permanent', + validateParams(audioAssetIdParamSchema), + asyncHandler(permanentDeleteAudioAssetController) +); + +router.delete( + '/:audioAssetId/force', + validateParams(audioAssetIdParamSchema), + asyncHandler(forceDeleteActiveAudioAssetController) +); + +router.patch( + '/narration/:narrationId/:audioAssetId/restore', + validateParams(audioAssetAndNarrationParamSchema), + asyncHandler(restoreAudioAssetController) +); + +export default router; diff --git a/src/modules/audio/audio.service.ts b/src/modules/audio/audio.service.ts new file mode 100644 index 0000000..82d53dd --- /dev/null +++ b/src/modules/audio/audio.service.ts @@ -0,0 +1,611 @@ +import { AudioAsset, AudioAssetModel } from '@models/AudioAsset.js'; +import { StoryNarrationModel } from '@models/Narration.js'; +import { NotFoundError, BadRequestError, ConflictError } from '@middleware/error/index.js'; +import { ClientSession } from 'mongoose'; +import type { Pagination, Sorting } from 'types/Pagination.js'; +import { validateNarrationOwnership } from 'validators/validateNarrationOwnership.js'; +import { validateAudioAssetOwnership } from 'validators/validateAudioAssetOwnership.js'; +import { + assertAudioAssetIsDeleted, + assertAudioAssetNotDeleted, + assertAudioAssetNotActive, + assertHasDeletedAudioAssets, + assertHasNonDeletedAudioAssets, + assertAudioAssetTypeIsNarration, +} from 'domain/assertions/assertAudioAssetState.js'; +import { assertNarrationNotDeleted } from 'domain/assertions/assertNarrationState.js'; +import { withTransaction } from '@db/withTransaction.js'; + +// Get the next version number for an audio asset in a narration +async function getNextVersionNumber(narrationId: string, session?: ClientSession): Promise { + const query = AudioAssetModel.findOne({ narrationId }).sort({ version: -1 }).select('version'); + + if (session) query.session(session); + + const lastAsset = await query; + return lastAsset ? (lastAsset.version || 0) + 1 : 1; +} + +// ==================== ALL OPERATIONS ==================== + +export async function getAllAudioAssetsForNarration( + userId: string, + narrationId: string, + pagination: Pagination, + sorting: Sorting +): Promise<[AudioAsset[], number]> { + const { limit, skip } = pagination; + const { sortBy, sortOrder } = sorting; + + const [audioAssets, total] = await Promise.all([ + AudioAssetModel.find({ + narrationId, + userId, + deletedAt: { $exists: false }, + }) + .sort(sortBy ? { [sortBy]: sortOrder } : { version: -1 }) + .skip(skip) + .limit(limit), + AudioAssetModel.countDocuments({ + narrationId, + userId, + deletedAt: { $exists: false }, + }), + ]); + + return [audioAssets, total]; +} + +export async function getAllDeletedAudioAssets( + userId: string, + narrationId: string, + pagination: Pagination, + sorting: Sorting +): Promise<[AudioAsset[], number]> { + const { limit, skip } = pagination; + const { sortBy, sortOrder } = sorting; + + const [audioAssets, total] = await Promise.all([ + AudioAssetModel.find({ + narrationId, + userId, + deletedAt: { $exists: true }, + }) + .sort(sortBy ? { [sortBy]: sortOrder } : { deletedAt: -1 }) + .skip(skip) + .limit(limit), + AudioAssetModel.countDocuments({ + narrationId, + userId, + deletedAt: { $exists: true }, + }), + ]); + + return [audioAssets, total]; +} + +export async function restoreAllDeletedAudioAssets( + userId: string, + narrationId: string +): Promise<{ restoredCount: number }> { + return withTransaction(async (session) => { + await validateNarrationOwnership(userId, narrationId, session); + + const assetsToRestore = await AudioAssetModel.find({ + userId, + narrationId, + deletedAt: { $exists: true }, + }).session(session); + + assertHasDeletedAudioAssets(assetsToRestore); + + const bulkOps = assetsToRestore.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $unset: { deletedAt: 1 } }, + }, + })); + + const result = await AudioAssetModel.bulkWrite(bulkOps, { session }); + + return { restoredCount: result.modifiedCount }; + }); +} + +export async function softDeleteAllAudioAssetsForNarration( + userId: string, + narrationId: string +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateNarrationOwnership(userId, narrationId, session); + + const assetsToDelete = await AudioAssetModel.find({ + userId, + narrationId, + deletedAt: { $exists: false }, + }).session(session); + + assertHasNonDeletedAudioAssets(assetsToDelete); + + const activeAsset = assetsToDelete.find((a) => a.activeNarration); + if (activeAsset) { + throw new BadRequestError( + `Cannot delete the active audio asset. Please set another audio asset as active first or use force delete on the active asset ${activeAsset._id}.` + ); + } + + const bulkOps = assetsToDelete.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $set: { deletedAt: new Date() } }, + }, + })); + + const result = await AudioAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: result.modifiedCount }; + }); +} + +export async function permanentDeleteAllAudioAssetsForNarration( + userId: string, + narrationId: string +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateNarrationOwnership(userId, narrationId, session); + + const assetsToDelete = await AudioAssetModel.find({ + userId, + narrationId, + deletedAt: { $exists: true }, + }).session(session); + + assertHasDeletedAudioAssets(assetsToDelete); + + const bulkOps = assetsToDelete.map((asset) => ({ + deleteOne: { filter: { _id: asset._id } }, + })); + + const result = await AudioAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: result.deletedCount || 0 }; + }); +} + +export async function getAudioAssetCount(userId: string, narrationId: string): Promise { + await validateNarrationOwnership(userId, narrationId); + + const count = await AudioAssetModel.countDocuments({ + narrationId, + userId, + deletedAt: { $exists: false }, + }); + + return count; +} + +// ==================== BULK OPERATIONS ==================== + +export async function softBulkDeleteAudioAssets( + userId: string, + narrationId: string, + audioAssetIds: string[] +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateNarrationOwnership(userId, narrationId, session); + + const assets = await AudioAssetModel.find({ + _id: { $in: audioAssetIds }, + userId, + narrationId, + deletedAt: { $exists: false }, + }).session(session); + + if (assets.length !== audioAssetIds.length) { + throw new BadRequestError('Some audio assets were not found or already deleted'); + } + + // Check if any asset is the active one + const activeAsset = assets.find((a) => a.activeNarration); + if (activeAsset) { + throw new BadRequestError( + `Cannot delete the active audio asset. Please set another audio asset as active first or use force delete on the active asset ${activeAsset._id}.` + ); + } + + const bulkOps = assets.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $set: { deletedAt: new Date() } }, + }, + })); + + await AudioAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: assets.length }; + }); +} + +export async function permanentBulkDeleteAudioAssets( + userId: string, + narrationId: string, + audioAssetIds: string[] +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateNarrationOwnership(userId, narrationId, session); + + const assets = await AudioAssetModel.find({ + _id: { $in: audioAssetIds }, + userId, + narrationId, + deletedAt: { $exists: true }, + }).session(session); + + if (assets.length !== audioAssetIds.length) { + throw new BadRequestError('Some audio assets were not found'); + } + + const bulkOps = assets.map((asset) => ({ + deleteOne: { filter: { _id: asset._id } }, + })); + + await AudioAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: assets.length }; + }); +} + +export async function bulkRestoreAudioAssets( + userId: string, + narrationId: string, + audioAssetIds: string[] +): Promise { + return withTransaction(async (session) => { + await validateNarrationOwnership(userId, narrationId, session); + + const assets = await AudioAssetModel.find({ + _id: { $in: audioAssetIds }, + userId, + narrationId, + deletedAt: { $exists: true }, + }).session(session); + + if (assets.length !== audioAssetIds.length) { + throw new BadRequestError('Some audio assets were not found or not deleted'); + } + + const bulkOps = assets.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $unset: { deletedAt: 1 } }, + }, + })); + + await AudioAssetModel.bulkWrite(bulkOps, { session }); + + const restoredAssets = await AudioAssetModel.find({ + _id: { $in: audioAssetIds }, + userId, + }) + .sort({ version: -1 }) + .lean() + .session(session); + + return restoredAssets; + }); +} + +// ==================== SINGLE OPERATIONS ==================== + +export async function getAudioAssetById(userId: string, audioAssetId: string): Promise { + const audioAsset = await validateAudioAssetOwnership(userId, audioAssetId); + return audioAsset; +} + +export async function getActiveAudioAssetForNarration( + userId: string, + narrationId: string +): Promise { + const audioAsset = await AudioAssetModel.findOne({ + narrationId, + userId, + activeNarration: true, + deletedAt: { $exists: false }, + }); + + return audioAsset; +} + +export async function generateAudioAsset( + userId: string, + narrationId: string, + voiceId: string, + prompt?: string +): Promise { + return withTransaction(async (session) => { + const narration = await validateNarrationOwnership(userId, narrationId, session); + assertNarrationNotDeleted(narration); + + const version = await getNextVersionNumber(narrationId, session); + + // TODO: Integrate with actual AI TTS service (ElevenLabs, OpenAI, etc.) + // For now, we create a placeholder that should be replaced with actual generation + const generatedUrl = `https://placeholder-audio-url.com/${narrationId}/${version}`; + const estimatedDuration = narration.totalDuration || 60; + + // Deactivate current active audio asset + await AudioAssetModel.updateMany( + { narrationId, activeNarration: true }, + { $set: { activeNarration: false } }, + { session } + ); + + const [audioAsset] = await AudioAssetModel.create( + [ + { + userId, + narrationId, + activeNarration: true, + type: 'narration', + url: generatedUrl, + prompt, + generationSource: 'ai', + voiceId, + duration: estimatedDuration, + version, + }, + ], + { session } + ); + + await StoryNarrationModel.findByIdAndUpdate( + narrationId, + { activeAudioAssetId: audioAsset._id }, + { session } + ); + + return audioAsset; + }); +} + +export async function regenerateAudioAsset( + userId: string, + audioAssetId: string, + voiceId?: string, + extraPrompt?: string +): Promise { + return withTransaction(async (session) => { + const existingAsset = await validateAudioAssetOwnership(userId, audioAssetId, session); + assertAudioAssetNotDeleted(existingAsset); + assertAudioAssetTypeIsNarration(existingAsset); + + if (!existingAsset.narrationId) { + throw new BadRequestError('Audio asset is not linked to a narration'); + } + + const narration = await validateNarrationOwnership(userId, existingAsset.narrationId.toString(), session); + assertNarrationNotDeleted(narration); + + const version = await getNextVersionNumber(existingAsset.narrationId.toString(), session); + + const finalVoiceId = voiceId || existingAsset.voiceId; + if (!finalVoiceId) { + throw new BadRequestError('Voice ID is required for regeneration'); + } + + const finalPrompt = extraPrompt + ? `${existingAsset.prompt || ''} ${extraPrompt}`.trim() + : existingAsset.prompt; + + // TODO: Integrate with actual AI TTS service + const generatedUrl = `https://placeholder-audio-url.com/${existingAsset.narrationId}/${version}`; + + await AudioAssetModel.updateMany( + { narrationId: existingAsset.narrationId, activeNarration: true }, + { $set: { activeNarration: false } }, + { session } + ); + + const [audioAsset] = await AudioAssetModel.create( + [ + { + userId, + narrationId: existingAsset.narrationId, + activeNarration: true, + type: 'narration', + url: generatedUrl, + prompt: finalPrompt, + generationSource: 'ai', + voiceId: finalVoiceId, + duration: existingAsset.duration, + version, + }, + ], + { session } + ); + + await StoryNarrationModel.findByIdAndUpdate( + existingAsset.narrationId, + { activeAudioAssetId: audioAsset._id }, + { session } + ); + + return audioAsset; + }); +} + +export async function uploadNarrationAudioAsset( + userId: string, + narrationId: string, + filePath: string +): Promise { + return withTransaction(async (session) => { + const narration = await validateNarrationOwnership(userId, narrationId, session); + assertNarrationNotDeleted(narration); + + const version = await getNextVersionNumber(narrationId, session); + + // process audio to a standard format and also + // get duration and check if duration exceeds narration total duration + + // TODO: Upload file to S3 and get the URL + const uploadedUrl = filePath; // Replace with actual S3 upload + + await AudioAssetModel.updateMany( + { narrationId, activeNarration: true }, + { $set: { activeNarration: false } }, + { session } + ); + + const [audioAsset] = await AudioAssetModel.create( + [ + { + userId, + narrationId, + activeNarration: true, + type: 'narration', + url: uploadedUrl, + generationSource: 'user', + duration: narration.totalDuration || 60, + version, + }, + ], + { session } + ); + + await StoryNarrationModel.findByIdAndUpdate( + narrationId, + { activeAudioAssetId: audioAsset._id }, + { session } + ); + + return audioAsset; + }); +} + +export async function setActiveAudioAsset( + userId: string, + narrationId: string, + audioAssetId: string +): Promise { + return withTransaction(async (session) => { + const narration = await validateNarrationOwnership(userId, narrationId, session); + assertNarrationNotDeleted(narration); + + const audioAsset = await validateAudioAssetOwnership(userId, audioAssetId, session); + assertAudioAssetNotDeleted(audioAsset); + assertAudioAssetTypeIsNarration(audioAsset); + + if (audioAsset.narrationId?.toString() !== narrationId) { + throw new BadRequestError('Audio asset does not belong to this narration'); + } + + if (audioAsset.activeNarration) { + throw new ConflictError('Audio asset is already the active narration'); + } + + await AudioAssetModel.updateMany( + { narrationId, activeNarration: true }, + { $set: { activeNarration: false } }, + { session } + ); + + const updatedAsset = await AudioAssetModel.findByIdAndUpdate( + audioAssetId, + { activeNarration: true }, + { new: true, session } + ); + + await StoryNarrationModel.findByIdAndUpdate( + narrationId, + { activeAudioAssetId: audioAssetId }, + { session } + ); + + return updatedAsset as AudioAsset; + }); +} + +export async function softDeleteAudioAsset(userId: string, audioAssetId: string): Promise { + return withTransaction(async (session) => { + const audioAsset = await validateAudioAssetOwnership(userId, audioAssetId, session); + assertAudioAssetNotDeleted(audioAsset); + assertAudioAssetNotActive(audioAsset); + + await AudioAssetModel.findByIdAndUpdate(audioAssetId, { deletedAt: new Date() }, { session }); + }); +} + +export async function permanentDeleteAudioAsset(userId: string, audioAssetId: string): Promise { + return withTransaction(async (session) => { + const audioAsset = await validateAudioAssetOwnership(userId, audioAssetId, session); + assertAudioAssetIsDeleted(audioAsset); + + await AudioAssetModel.findByIdAndDelete(audioAssetId, { session }); + + // TODO: Delete file from S3 + }); +} + +export async function forceDeleteActiveAudioAsset(userId: string, audioAssetId: string): Promise { + return withTransaction(async (session) => { + const audioAsset = await validateAudioAssetOwnership(userId, audioAssetId, session); + assertAudioAssetNotDeleted(audioAsset); + + if (audioAsset.activeNarration && audioAsset.narrationId) { + const nextActiveAsset = await AudioAssetModel.findOne({ + narrationId: audioAsset.narrationId, + _id: { $ne: audioAssetId }, + type: 'narration', + deletedAt: { $exists: false }, + }) + .sort({ version: -1 }) + .session(session); + + if (nextActiveAsset) { + await AudioAssetModel.findByIdAndUpdate(nextActiveAsset._id, { activeNarration: true }, { session }); + + await StoryNarrationModel.findByIdAndUpdate( + audioAsset.narrationId, + { activeAudioAssetId: nextActiveAsset._id }, + { session } + ); + } else { + await StoryNarrationModel.findByIdAndUpdate( + audioAsset.narrationId, + { $unset: { activeAudioAssetId: 1 } }, + { session } + ); + } + } + + await AudioAssetModel.findByIdAndUpdate(audioAssetId, { deletedAt: new Date() }, { session }); + }); +} + +export async function restoreAudioAsset( + userId: string, + narrationId: string, + audioAssetId: string +): Promise { + return withTransaction(async (session) => { + await validateNarrationOwnership(userId, narrationId, session); + + const audioAsset = await validateAudioAssetOwnership(userId, audioAssetId, session); + assertAudioAssetIsDeleted(audioAsset); + + if (audioAsset.narrationId?.toString() !== narrationId) { + throw new BadRequestError('Audio asset does not belong to this narration'); + } + + const restoredAsset = await AudioAssetModel.findByIdAndUpdate( + audioAssetId, + { $unset: { deletedAt: 1 } }, + { new: true, session } + ); + + return restoredAsset as AudioAsset; + }); +} + +// TODO : Upload audio asset for other types (background music, sound effects) diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index 76a7769..41434f1 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -1,8 +1,9 @@ -import type { CookieOptions } from "express"; -import type { Request, Response } from "express"; +import { UnauthenticatedError } from '@middleware/error/index.js'; +import type { CookieOptions } from 'express'; +import type { Request, Response } from 'express'; import { createPasswordResetRequest, - emailVerification, + sendEmailVerification, loginUser, logoutUser, refreshTokens, @@ -10,53 +11,53 @@ import { resetPassword, verifyEmail, verifyUpdateEmail, -} from "./auth.service.js"; +} from './auth.service.js'; import type { RegisterInput, LoginInput, ForgetPasswordInput, VerifyEmailInput, -} from "@validation/auth.schema.js"; -import { UnauthenticatedError } from "@middleware/error/index.js"; + VerifyUpdateEmailInput, +} from '@validation/auth.schema.js'; const CookieOptions: CookieOptions = { httpOnly: true, - secure: process.env.NODE_ENV === "production", - sameSite: process.env.NODE_ENV === "production" ? "none" : "lax", + secure: process.env.NODE_ENV === 'production', + sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax', maxAge: 1 * 24 * 60 * 60 * 1000, }; +const CSRF_AGE = 15 * 24 * 60 * 60 * 1000; +const REFRESH_AGE = 15 * 24 * 60 * 60 * 1000; +const ACCESS_AGE = 30 * 60 * 1000; + export const registerController = async (req: Request, res: Response) => { - const body = (req as unknown as { validatedBody?: RegisterInput }) - .validatedBody!; + const body = req.validatedBody as RegisterInput; - const userAgent: string = req.headers["user-agent"] || "unknown"; - const ip = - req.headers["x-forwarded-for"] || - req.headers["x-real-ip"] || - req.ip || - req.socket.remoteAddress; + const userAgent: string = req.headers['user-agent'] || 'unknown'; + const ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip || req.socket.remoteAddress; const payload = { ...body, userAgent, ip }; const result = await registerUser(payload); - const { user, accessToken, refreshToken, csrfToken } = result; + const { user, tokens } = result; + const { accessToken, refreshToken, csrfToken } = tokens; return res .status(200) - .cookie("access-token", accessToken, { + .cookie('access-token', accessToken, { ...CookieOptions, - maxAge: 30 * 60 * 1000, + maxAge: ACCESS_AGE, }) - .cookie("refresh-token", refreshToken, { + .cookie('refresh-token', refreshToken, { ...CookieOptions, - maxAge: 7 * 24 * 60 * 60 * 1000, + maxAge: REFRESH_AGE, }) - .cookie("csrf-token", csrfToken, { + .cookie('csrf-token', csrfToken, { ...CookieOptions, httpOnly: false, - maxAge: 30 * 24 * 60 * 60 * 1000, + maxAge: CSRF_AGE, }) .json({ user: { @@ -70,141 +71,131 @@ export const registerController = async (req: Request, res: Response) => { }; export const loginController = async (req: Request, res: Response) => { - const body = (req as unknown as { validatedBody?: LoginInput }) - .validatedBody!; - - const userAgent: string = req.headers["user-agent"] || "unknown"; - const ip = - req.headers["x-forwarded-for"] || - req.headers["x-real-ip"] || - req.ip || - req.socket.remoteAddress; + const body = req.validatedBody as LoginInput; + const userAgent: string = req.headers['user-agent'] || 'unknown'; + const ip = req.socket.remoteAddress || req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip; const payload = { ...body, userAgent, ip }; const result = await loginUser(payload); - const { user, accessToken, refreshToken, csrfToken } = result; + const { user, tokens } = result; + const { accessToken, refreshToken, csrfToken } = tokens; return res .status(200) - .cookie("access-token", accessToken, { + .cookie('access-token', accessToken, { ...CookieOptions, - maxAge: 30 * 60 * 1000, + maxAge: ACCESS_AGE, }) - .cookie("refresh-token", refreshToken, { + .cookie('refresh-token', refreshToken, { ...CookieOptions, - maxAge: 7 * 24 * 60 * 60 * 1000, + maxAge: REFRESH_AGE, }) - .cookie("csrf-token", csrfToken, { + .cookie('csrf-token', csrfToken, { ...CookieOptions, httpOnly: false, - maxAge: 30 * 24 * 60 * 60 * 1000, + maxAge: CSRF_AGE, }) .json({ - user: { - id: user._id, - email: user.email, - username: user.username, - displayName: user.displayName, - avatar: user.avatarUrl, + status: 'success', + data: { + user: { + id: user._id, + email: user.email, + username: user.username, + displayName: user.displayName, + avatar: user.avatarUrl, + accountStatus: user.accountStatus, + }, }, }); }; export const forgotPasswordController = async (req: Request, res: Response) => { - const payload = (req as unknown as { validatedBody?: ForgetPasswordInput }) - .validatedBody!; + const payload = req.validatedBody as ForgetPasswordInput; await createPasswordResetRequest(payload.email); return res.status(200).json({ - status: "success", - message: - "If an account with that email exists, a reset link has been sent.", + status: 'success', + message: 'If an account with that email exists, a reset link has been sent.', }); }; export const resetPasswordController = async (req: Request, res: Response) => { - const { token, password } = (req as any).validatedBody; + const { token, password } = req.validatedBody as { + token: string; + password: string; + }; await resetPassword(token, password); return res.status(200).json({ - status: "success", - message: "Password updated. Please log in with your new password.", + status: 'success', + message: 'Password updated. Please log in with your new password.', }); }; export const refreshTokenController = async (req: Request, res: Response) => { - const reqRefreshToken = req.cookies["refresh-token"]; + const reqRefreshToken = req.cookies['refresh-token']; + const userAgent: string = req.headers['user-agent'] || 'unknown'; + const ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip || req.socket.remoteAddress; if (!reqRefreshToken) { - return res.status(401).json({ message: "No refresh token provided" }); + throw new UnauthenticatedError('No refresh token, Authentication failed'); } - const result = await refreshTokens(reqRefreshToken); + const result = await refreshTokens(reqRefreshToken, userAgent, ip); const { accessToken, refreshToken, csrfToken } = result; return res .status(200) - .cookie("access-token", accessToken, { + .cookie('access-token', accessToken, { ...CookieOptions, - maxAge: 30 * 60 * 1000, + maxAge: ACCESS_AGE, }) - .cookie("refresh-token", refreshToken, { + .cookie('refresh-token', refreshToken, { ...CookieOptions, - maxAge: 7 * 24 * 60 * 60 * 1000, + maxAge: REFRESH_AGE, }) - .cookie("csrf-token", csrfToken, { + .cookie('csrf-token', csrfToken, { ...CookieOptions, httpOnly: false, - maxAge: 30 * 24 * 60 * 60 * 1000, + maxAge: CSRF_AGE, }) - .json({ message: "Tokens refreshed" }); + .json({ message: 'Tokens refreshed' }); }; -export const emailVerificationController = async ( - req: Request, - res: Response -) => { - const userId = req.user?._id; +export const emailVerificationController = async (req: Request, res: Response) => { + const userId = req?.user!.id; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } - await emailVerification(userId); + await sendEmailVerification(userId); return res.status(200).json({ - message: "Verification email sent successfully", + message: 'Verification email sent successfully', }); }; export const verifyEmailController = async (req: Request, res: Response) => { - const { verificationToken } = ( - req as unknown as { validatedBody?: VerifyEmailInput } - ).validatedBody!; + const { verificationToken } = req.validatedBody as VerifyEmailInput; await verifyEmail(verificationToken); return res.status(200).json({ - message: "Email verified successfully", + message: 'Email verified successfully', }); }; -export const verifyEmailChangeController = async ( - req: Request, - res: Response -) => { - const { verificationToken } = ( - req as unknown as { validatedBody?: VerifyEmailInput } - ).validatedBody!; - await verifyUpdateEmail(verificationToken); +export const verifyEmailChangeController = async (req: Request, res: Response) => { + const { verificationToken, code } = req.validatedBody as VerifyUpdateEmailInput; + const currentSessionId = req?.sessionId; + await verifyUpdateEmail(verificationToken, code, currentSessionId); return res.status(200).json({ - message: "Email change verified successfully", + message: 'Email change verified successfully', }); }; export const logoutController = async (req: Request, res: Response) => { - const refreshToken = req.cookies["refresh-token"]; + const refreshToken = req.cookies['refresh-token']; await logoutUser(refreshToken); return res - .clearCookie("access-token") - .clearCookie("refresh-token") - .clearCookie("csrf-token") + .clearCookie('access-token') + .clearCookie('refresh-token') + .clearCookie('csrf-token') .status(200) - .json({ message: "Logged out successfully" }); + .json({ message: 'Logged out successfully' }); }; diff --git a/src/modules/auth/auth.routes.ts b/src/modules/auth/auth.routes.ts index 98329bf..e854337 100644 --- a/src/modules/auth/auth.routes.ts +++ b/src/modules/auth/auth.routes.ts @@ -1,4 +1,4 @@ -import { Router } from "express"; +import { Router } from 'express'; import { forgotPasswordController, loginController, @@ -9,60 +9,46 @@ import { emailVerificationController, verifyEmailController, verifyEmailChangeController, -} from "./auth.controller.js"; +} from './auth.controller.js'; import { forgotPasswordSchema, loginSchema, registerSchema, resetPasswordSchema, - validateBody, verifyEmailSchema, -} from "@validation/auth.schema.js"; -import { asyncHandler } from "@utils/asyncHandler.js"; -import { requireAuth as auth } from "@middleware/auth/requireAuth.js"; + verifyUpdateEmailSchema, +} from '@validation/auth.schema.js'; +import { validateBody } from '@validation/validateBody.js'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { authMiddleware } from '@middleware/auth/requireAuth.js'; +import { csrfMiddleware } from '@middleware/security/requireCsrf.js'; const router = Router(); -// POST /api/auth/register -router.post( - "/register", - validateBody(registerSchema), - asyncHandler(registerController) -); +router.post('/register', validateBody(registerSchema), asyncHandler(registerController)); +router.post('/login', validateBody(loginSchema), asyncHandler(loginController)); +router.post('/forgot-password', validateBody(forgotPasswordSchema), asyncHandler(forgotPasswordController)); -router.post("/login", validateBody(loginSchema), asyncHandler(loginController)); -router.post( - "/forgot-password", - validateBody(forgotPasswordSchema), - asyncHandler(forgotPasswordController) -); +router.post('/reset-password', validateBody(resetPasswordSchema), asyncHandler(resetPasswordController)); -router.post( - "/reset-password", - validateBody(resetPasswordSchema), - asyncHandler(resetPasswordController) -); +router.post('/refresh-session', asyncHandler(refreshTokenController)); -router.post("/refresh-token", asyncHandler(refreshTokenController)); +router.post('/email/verification', authMiddleware, asyncHandler(emailVerificationController)); router.post( - "/email/verification", - auth, - asyncHandler(emailVerificationController) -); - -router.post( - "/email/verify", + '/email/verify', + authMiddleware, validateBody(verifyEmailSchema), asyncHandler(verifyEmailController) ); router.post( - "/email/verify-change", - validateBody(verifyEmailSchema), + '/email/verify-change', + authMiddleware, + validateBody(verifyUpdateEmailSchema), asyncHandler(verifyEmailChangeController) -) +); -router.post("/logout", asyncHandler(logoutController)); +router.post('/logout', authMiddleware, csrfMiddleware, asyncHandler(logoutController)); export default router; diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 17c592d..d5261c7 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -1,9 +1,8 @@ -import jwt from "jsonwebtoken"; -import bcrypt from "bcrypt"; -import crypto from "crypto"; -import mongoose, { ObjectIdSchemaDefinition } from "mongoose"; -import { UserModel, type User } from "@models/User.js"; -import { SessionModel, type Session } from "@models/Session.js"; +import jwt from 'jsonwebtoken'; +import bcrypt from 'bcrypt'; +import { RESET_EXP_MIN } from 'constants/authConsts.js'; +import { UserModel, type User } from '@models/User.js'; +import { SessionModel, type Session } from '@models/Session.js'; import { generateAccessToken, generateCsrfToken, @@ -11,360 +10,400 @@ import { generateVerificationToken, hashToken, verifyToken, -} from "@utils/tokens.js"; -import transporter from "config/mail.js"; -import type { - LoginInput, - RegisterInput, - ResetPasswordInput, -} from "@validation/auth.schema.js"; -import { getIpInfo } from "@utils/getIpInfo.js"; -import { parseUserAgent } from "@utils/parseUserAgent.js"; -import { resetPasswordTemplate } from "./emails/templates/resetPassword.js"; -import { createUsername } from "@utils/createUsername.js"; -import { newAccountTemplate } from "./emails/templates/newAccount.js"; +} from '@utils/tokens.js'; +import type { LoginInput, RegisterInput } from '@validation/auth.schema.js'; +import { createUsername } from '@modules/auth/utils/createUsername.js'; import { + BadRequestError, ConflictError, - InternalServerError, + ForbiddenError, NotFoundError, UnauthenticatedError, -} from "@middleware/error/index.js"; -import { emailVerificationTemplate } from "./emails/templates/emailVerification.js"; -import { passwordChangedNotificationTemplate } from "./emails/passwordChangedNotification.js"; +} from '@middleware/error/index.js'; +import sendWelcomeEmail from '@utils/emails/sender/sendWelcomeEmail.js'; +import sendResetLink from '@utils/emails/sender/sendResetLink.js'; +import sendPasswordUpdatedEmail from '@utils/emails/sender/sendPasswordUpdatedEmail.js'; +import sendVerificationEmail from '@utils/emails/sender/sendEmailVerificationLink.js'; +import ensureActiveAccount from 'security/guards/ensureActiveAccount.js'; +import { getAccountBlockResponse } from 'security/guards/getAccountBlockResponse.js'; +import { createSessionPayload } from './utils/createSessionPayload.js'; +import { assignFreePlan } from '@modules/subscription/subscription.service.js'; +import { withTransaction } from '@db/withTransaction.js'; type LoginInputWithMeta = LoginInput & { userAgent: string; ip: string | string[] | undefined; }; - -type LoginOutput = { +type SignOutput = { user: User; - accessToken: string; - refreshToken: string; - csrfToken: string; + tokens: { + accessToken: string; + refreshToken: string; + csrfToken: string; + }; }; - type RegisterInputWithMeta = RegisterInput & { userAgent: string; ip: string | string[] | undefined; }; - -interface RegisterOutput { - user: User; - accessToken: string; - refreshToken: string; - csrfToken: string; -} - interface RefreshTokenOutput { accessToken: string; refreshToken: string; csrfToken: string; } -const RESET_EXP_MIN = Number(process.env.PASSWORD_RESET_EXPIRES_MIN || 10); - -export async function registerUser( - input: RegisterInputWithMeta -): Promise { - const { email, password, displayName, username, userAgent, ip } = input; - // Check if email exists - const existing = await UserModel.findOne({ email }); +export async function registerUser(input: RegisterInputWithMeta): Promise { + const { email, password, name, username, userAgent, ip } = input; + const existing = await UserModel.findOne({ $or: [{ email }, { username }] }); if (existing) { - throw new ConflictError("Email already registered"); - } - const usernameExist = await UserModel.findOne({ username }); - if (usernameExist) { - throw new ConflictError("Username already exists"); + if (existing.username === username) { + throw new ConflictError('Username already taken'); + } else { + throw new ConflictError('Email already registered'); + } } // Metadata - const ipData: any = await getIpInfo(ip as string); - const userAgentInfo = parseUserAgent(userAgent); const passwordHash = await bcrypt.hash(password, 10); - const user = await UserModel.create({ - email, - passwordHash, - username: username - ? username.toLowerCase() - : `${await createUsername(email)}`, - displayName: displayName ?? email.split("@")[0], - }); + return withTransaction(async (session) => { + const userName = username ? username : await createUsername(email, session); + const result: User[] = await UserModel.create( + [ + { + email, + passwordHash, + username: userName.toLowerCase(), + displayName: name ?? email.split('@')[0], + }, + ], + { session } + ); + const user: User = result[0]; + + await assignFreePlan(user._id, session); - const sessionId: string = crypto.randomBytes(32).toString("hex"); - await SessionModel.create({ - sessionId, - userId: user._id, - userAgent, - device: userAgentInfo.device, - browser: userAgentInfo.browser, - os: userAgentInfo.os, - - ip: ipData.ip, - city: ipData.cityName, - country: ipData.countryName, - timezone: ipData.timeZones[1], - lat: ipData.latitude, - lng: ipData.longitude, - isp: ipData.asnOrganisation, - - createdAt: Date.now(), - lastUsedAt: Date.now(), + const { sessionPayload, tokens } = await createSessionPayload({ + user, + userAgent, + ip: (Array.isArray(ip) ? ip[0] : ip) || '', + }); + await SessionModel.create( + [ + { + ...sessionPayload, + }, + ], + { session } + ); + sendWelcomeEmail(user.email, user.displayName, user.username); + return { user, tokens }; }); +} - const accessToken = generateAccessToken(user._id, sessionId); - const refreshToken = generateRefreshToken(user._id, sessionId); - const csrfToken = generateCsrfToken(); - const { subject, text, html } = newAccountTemplate( - user.displayName || user.username || user.email.split("@")[0] - ); - try { - transporter.sendMail({ - from: process.env.EMAIL_FROM, - to: email, - subject, - text, - html, +export async function loginUser(input: LoginInputWithMeta): Promise { + return withTransaction(async (session) => { + const { email, password, userAgent, ip } = input; + + const user: User | null = await UserModel.findOne({ email }).select('+passwordHash +changeHistory'); + if (!user) { + throw new UnauthenticatedError('Email or Password does not match!'); + } + const active = ensureActiveAccount(user); + if (!active) { + const status = user.accountStatus; + const errorResponse = getAccountBlockResponse(status); + if (errorResponse) { + throw new ForbiddenError(errorResponse.message, { + reason: errorResponse.reason, + nextStep: errorResponse.nextStep, + }); + } + throw new UnauthenticatedError('Not allowed to login.'); + } + + const passedTest = await bcrypt.compare(password, user.passwordHash); + if (!passedTest) { + throw new UnauthenticatedError('Email or Password does not match!'); + } + + const { sessionPayload, tokens } = await createSessionPayload({ + user, + userAgent, + ip: (Array.isArray(ip) ? ip[0] : ip) || '', }); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : String(err); - throw new InternalServerError( - "Failed to send new account email", - errorMessage + await SessionModel.create( + [ + { + ...sessionPayload, + }, + ], + { session } ); - } - return { user, accessToken, refreshToken, csrfToken }; + return { user, tokens }; + }); } -export async function loginUser( - input: LoginInputWithMeta -): Promise { - const { email, password, userAgent, ip } = input; +export async function refreshTokens( + refreshToken: string, + userAgent: string, + ip: string | string[] | undefined +): Promise { + let decoded: { + userId: string; + sessionId: string; + role: 'user' | 'admin'; + }; - const user = await UserModel.findOne({ email }).select("+passwordHash"); - if (!user) { - throw new UnauthenticatedError("Email or Password does not match!"); + try { + decoded = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!) as typeof decoded; + } catch { + throw new UnauthenticatedError('No refresh token, Authentication failed'); + } + + const session = await SessionModel.findOne({ + sessionId: decoded.sessionId, + userId: decoded.userId, + valid: true, + revokedAt: null, + }).select('+refreshTokenHash +csrfTokenHash +expiresIn'); + + if (!session || !session.refreshTokenHash || !session.expiresIn) { + throw new UnauthenticatedError('No refresh token, Authentication failed'); } - const passedTest = await bcrypt.compare(password, user.passwordHash); - if (!passedTest) { - throw new UnauthenticatedError("Email or Password does not match!"); + if (session.expiresIn.getTime() <= Date.now()) { + await SessionModel.updateOne({ _id: session._id }, { valid: false, revokedAt: new Date() }).exec(); + + throw new UnauthenticatedError('No refresh token, Authentication failed'); } - const ipData: any = await getIpInfo(ip as string); - const userAgentInfo = parseUserAgent(userAgent); - const sessionId: string = crypto.randomBytes(32).toString("hex"); - - const session = await SessionModel.create({ - sessionId, - userId: user._id, - userAgent, - device: userAgentInfo.device, - browser: userAgentInfo.browser, - os: userAgentInfo.os, - - ip: ipData.ip, - city: ipData.cityName, - country: ipData.countryName, - timezone: ipData.timeZones[1], - lat: ipData.latitude, - lng: ipData.longitude, - isp: ipData.asnOrganisation, - - createdAt: Date.now(), - lastUsedAt: Date.now(), + const isValidToken = verifyToken(refreshToken, session.refreshTokenHash); + + if (!isValidToken) { + await SessionModel.updateOne({ _id: session._id }, { valid: false, revokedAt: new Date() }).exec(); + + throw new UnauthenticatedError('No refresh token, Authentication failed'); + } + + const user = await UserModel.findOne({ + _id: decoded.userId, + accountStatus: { $ne: 'banned' }, }); - const accessToken = generateAccessToken(user._id, sessionId); - const refreshToken = generateRefreshToken(user._id, sessionId); - const csrfToken = generateCsrfToken(); - return { user, accessToken, refreshToken, csrfToken }; + if (!user) { + throw new UnauthenticatedError('No refresh token, Authentication failed'); + } + + // rotate tokens + const newAccessToken = generateAccessToken(user._id, session.sessionId, user.role, user.accountStatus); + + const newRefreshToken = generateRefreshToken(user._id, session.sessionId); + + const newCsrfToken = generateCsrfToken(); + + await SessionModel.updateOne( + { + _id: session._id, + refreshTokenHash: session.refreshTokenHash, + }, + { + refreshTokenHash: hashToken(newRefreshToken), + csrfTokenHash: hashToken(newCsrfToken), + lastUsedAt: new Date(), + userAgent, + ip: Array.isArray(ip) ? ip[0] : ip, + } + ).exec(); + + return { + accessToken: newAccessToken, + refreshToken: newRefreshToken, + csrfToken: newCsrfToken, + }; } export async function createPasswordResetRequest(email: string) { const normalized = email.trim().toLowerCase(); - const user = await UserModel.findOne({ email: normalized }); - - if (!user) { + const user: User | null = await UserModel.findOne({ + email: normalized, + }).select('+passwordReset +changeHistory +accountStatus'); + if (!user || user.accountStatus !== 'active') { + generateVerificationToken(); + setTimeout(() => {}, 500); return; } - const { raw, hash } = generateVerificationToken(); const expiresAt = new Date(Date.now() + RESET_EXP_MIN * 60 * 1000); - user.passwordReset = { tokenHash: hash, expiresAt, requestedAt: new Date() }; - await user.save(); + await UserModel.updateOne( + { _id: user._id }, + { + passwordReset: { tokenHash: hash, expiresAt, requestedAt: new Date() }, + $push: { + changeHistory: { + $each: [ + { + field: 'password', + from: null, + to: null, + by: user._id, + reason: 'User requested password reset', + at: new Date(), + via: 'user', + }, + ], + $slice: -100, + }, + }, + } + ); - const resetUrl = `${ - process.env.APP_URL - }/auth/reset-password?token=${encodeURIComponent( + const resetUrl = `${process.env.APP_URL}/auth/reset-password?token=${encodeURIComponent( raw )}&email=${encodeURIComponent(user.email)}`; - const { subject, text, html } = resetPasswordTemplate( - user.displayName || user.username || user.email.split("@")[0], - resetUrl, - RESET_EXP_MIN - ); - - try { - await transporter.sendMail({ - from: process.env.EMAIL_FROM, - to: user.email, - subject, - text, - html, - }); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : String(err); - throw new InternalServerError( - "Failed to send password reset email", - errorMessage - ); - } + sendResetLink(user, resetUrl); + return; } export async function resetPassword(rawToken: string, newPassword: string) { const hash = hashToken(rawToken); - const user = await UserModel.findOne({ - "passwordReset.tokenHash": hash, - }).select("+passwordReset +passwordHash"); - if ( - !user || - !user.passwordReset?.tokenHash || - !user.passwordReset.expiresAt - ) { - throw new ConflictError("Invalid or expired token"); // generic message OK - } - if (user.passwordReset.expiresAt.getTime() < Date.now()) { - user.passwordReset = undefined; - await user.save(); - throw new ConflictError("Invalid or expired token"); - } - - const isValid = verifyToken(rawToken, user.passwordReset.tokenHash); - if (!isValid) { - throw new ConflictError("Invalid or expired token"); - } - const hashedPassword = await bcrypt.hash(newPassword, 10); - const session = await mongoose.startSession(); - session.startTransaction(); - try { - user.passwordHash = hashedPassword; - user.passwordReset = undefined; - await user.save({ session }); - await SessionModel.deleteMany({ userId: user._id }, { session }); - } catch (err) { - await session.abortTransaction(); - const errorMessage = err instanceof Error ? err.message : String(err); - throw new InternalServerError("Failed to reset password", errorMessage); - } finally { - session.endSession(); - } - - const { subject, text, html } = passwordChangedNotificationTemplate( - user.displayName || user.username || null - ); - try { - await transporter.sendMail({ - from: process.env.EMAIL_FROM, - to: user.email, - subject: subject, - text: text, - html: html, - }); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : String(err); - throw new InternalServerError( - "Failed to send password changed notification email", - errorMessage + let emailPayload: User | null = null; + + await withTransaction(async (session) => { + const user: User | null = await UserModel.findOne({ + 'passwordReset.tokenHash': hash, + }) + .select('+passwordReset +passwordHash +changeHistory +accountStatus') + .session(session); + if ( + !user || + !user.passwordReset?.tokenHash || + !user.passwordReset.expiresAt || + user.accountStatus !== 'active' + ) { + throw new BadRequestError('Invalid or expired token'); + } + + if (user.passwordReset.expiresAt.getTime() < Date.now()) { + user.passwordReset = undefined; + await user.save({ session }); + throw new BadRequestError('Invalid or expired token'); + } + + const isValid = verifyToken(rawToken, user.passwordReset.tokenHash); + if (!isValid) { + throw new BadRequestError('Invalid or expired token'); + } + + const hashedPassword = await bcrypt.hash(newPassword, 10); + + const updatedResult = await UserModel.findOneAndUpdate( + { _id: user._id, 'passwordReset.tokenHash': hash }, + { + $set: { + passwordHash: hashedPassword, + passwordReset: undefined, + lastPasswordChangeAt: new Date(), + }, + $push: { + changeHistory: { + $each: [ + { + field: 'password', + by: user._id, + from: null, + to: null, + reason: 'User reset the password via password reset', + at: new Date(), + via: 'user', + }, + ], + $slice: -100, + }, + }, + }, + { session } ); - } - return; -} - -export async function refreshTokens( - refreshToken: string -): Promise { - let decoded; - try { - decoded = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!) as { - userId: string; - sessionId: string; - }; - } catch (err) { - throw new UnauthenticatedError("Authentication failed"); - } - - const user = await UserModel.findOne({ - _id: decoded.userId, - }); - const session = await SessionModel.findOne({ - sessionId: decoded.sessionId, - userId: decoded.userId, + if (!updatedResult) { + throw new BadRequestError('Token already used or invalid'); + } + await SessionModel.updateMany( + { userId: user._id }, + { + valid: false, + revokedAt: new Date(), + }, + { session } + ); + emailPayload = updatedResult; }); - if (!decoded || !user || !session || session.revokedAt) - throw new UnauthenticatedError("Authentication failed"); - - // ✅ update lastUsedAt for this session - session.lastUsedAt = new Date(); - await session.save(); - const accessToken = generateAccessToken(user._id, session.sessionId); - const newRefreshToken = generateRefreshToken(user._id, session.sessionId); - const csrfToken = generateCsrfToken(); - - return { accessToken, refreshToken: newRefreshToken, csrfToken }; + //TODO: enqueue password changed email + if (emailPayload) { + sendPasswordUpdatedEmail(emailPayload); + } } -export async function emailVerification( - userId: ObjectIdSchemaDefinition -): Promise { - const user = await UserModel.findById(userId); +export async function sendEmailVerification(userId: string): Promise { + const user: User | null = await UserModel.findById(userId).select('+emailVerification +changeHistory'); if (!user) { - throw new NotFoundError("User not found"); + throw new NotFoundError('User not found'); + } + const active = ensureActiveAccount(user); + if (!active) { + throw new ForbiddenError('Account is not active'); } if (user.emailVerified) { - throw new ConflictError("Email is already verified"); + throw new ConflictError('Email is already verified'); } - const token = generateVerificationToken(); - const verifyEmailUrl = `${ - process.env.APP_URL - }/verify-email?token=${encodeURIComponent(token.raw)}`; + const token = generateVerificationToken(); - const { subject, text, html } = emailVerificationTemplate( - user.displayName ?? user.username ?? null, - verifyEmailUrl + const verifyEmailUrl = `${process.env.APP_URL}/verify-email?token=${encodeURIComponent(token.raw)}`; + + await UserModel.updateOne( + { _id: user._id }, + { + $set: { + emailVerification: { + tokenHash: token.hash, + expiresAt: new Date(Date.now() + 3600 * 1000), // 1 hour + requestedAt: new Date(), + }, + }, + $push: { + changeHistory: { + $each: [ + { + field: 'email', + by: user._id, + reason: 'User requested email verification', + at: new Date(), + via: 'user', + }, + ], + $slice: -100, + }, + }, + } ); - user.emailVerification = { - tokenHash: token.hash, - expiresAt: new Date(Date.now() + 3600 * 1000), // 1 hour - requestedAt: new Date(), - }; - await user.save(); - try { - await transporter.sendMail({ - from: process.env.EMAIL_FROM, - to: user.email, - subject: subject, - text: text, - html: html, - }); - } catch (err) { - throw new InternalServerError("Failed to send verification email"); - } + sendVerificationEmail(user, verifyEmailUrl); return; } export async function verifyEmail(verificationToken: string): Promise { const hash = hashToken(verificationToken); - const user = await UserModel.findOne({ - "emailVerification.tokenHash": hash, - }).select("+emailVerification"); + const user: User | null = await UserModel.findOne({ + 'emailVerification.tokenHash': hash, + }).select('+emailVerification +changeHistory'); if (!user) { - return; + throw new BadRequestError('Invalid or expired verification token'); + } + const active = ensureActiveAccount(user); + if (!active) { + throw new ForbiddenError('Account is not active'); } if ( @@ -375,80 +414,114 @@ export async function verifyEmail(verificationToken: string): Promise { ) { user.emailVerification = undefined; await user.save(); - throw new ConflictError("Invalid or expired verification token"); + throw new BadRequestError('Invalid or expired verification token'); } - const isValid = verifyToken( - verificationToken, - user.emailVerification.tokenHash - ); + const isValid = verifyToken(verificationToken, user.emailVerification.tokenHash); if (!isValid) { - throw new ConflictError("Invalid or expired verification token"); + throw new BadRequestError('Invalid or expired verification token'); } - user.emailVerified = true; - user.emailVerification = undefined; - await user.save(); + await UserModel.findOneAndUpdate( + { _id: user._id, 'emailVerification.tokenHash': hash }, + { + $set: { emailVerified: true, emailVerification: undefined }, + $push: { + changeHistory: { + $each: [ + { + field: 'email', + from: 'unverified', + to: 'verified', + by: user._id, + reason: 'User verified their email', + at: new Date(), + via: 'user', + }, + ], + $slice: -100, + }, + }, + } + ); return; } export async function verifyUpdateEmail( - verificationToken: string + verificationToken: string, + code: string, + currentSessionId?: string ): Promise { const hash = hashToken(verificationToken); - const user = await UserModel.findOne({ - "pendingEmailChange.tokenHash": hash, - }).select("+pendingEmailChange +changeHistory"); - if (!user) { - return; - } - if ( - !user.pendingEmailChange || - !user.pendingEmailChange.expiresAt || - user.pendingEmailChange.expiresAt!.getTime() < Date.now() || - !user.pendingEmailChange.tokenHash || - !user.pendingEmailChange.newEmail - ) { - user.pendingEmailChange = undefined; - await user.save(); - throw new ConflictError("Invalid or expired verification token"); - } - const isValid = verifyToken( - verificationToken, - user.pendingEmailChange.tokenHash - ); - if (!isValid) { - throw new ConflictError("Invalid or expired verification token"); - } - const session = await mongoose.startSession(); - session.startTransaction(); - try { - user.changeHistory.push({ - field: "email", - from: user.email, - to: user.pendingEmailChange.newEmail, - by: user._id, - reason: "User requested email change", - at: new Date(), - via: "user", - }); - user.email = user.pendingEmailChange.newEmail; - user.emailVerified = true; - user.pendingEmailChange = undefined; - await user.save({ session }); - await SessionModel.deleteMany({ userId: user._id }, { session }); - await session.commitTransaction(); - } catch (error) { - await session.abortTransaction(); - session.endSession(); - const errorMessage = error instanceof Error ? error.message : String(error); - throw new InternalServerError( - "Failed to verify updated email", - errorMessage + + return withTransaction(async (session) => { + const user: User | null = await UserModel.findOne({ + 'pendingEmailChange.tokenHash': hash, + }) + .select('+pendingEmailChange +changeHistory') + .session(session); + if (!user) { + throw new BadRequestError('Invalid or expired verification token'); + } + const active = ensureActiveAccount(user); + if (!active) { + throw new ForbiddenError('Account is not active'); + } + if ( + !user.pendingEmailChange || + !user.pendingEmailChange.expiresAt || + user.pendingEmailChange.expiresAt!.getTime() < Date.now() || + !user.pendingEmailChange.tokenHash || + !user.pendingEmailChange.newEmail || + !user.pendingEmailChange.code + ) { + user.pendingEmailChange = undefined; + await user.save({ session }); + throw new BadRequestError('Invalid or expired verification token'); + } + const isValid = verifyToken(verificationToken, user.pendingEmailChange.tokenHash); + if (!isValid) { + throw new BadRequestError('Invalid or expired verification token'); + } + const codeMatches = await bcrypt.compare(code, user.pendingEmailChange.code); + if (!codeMatches) { + throw new BadRequestError('Invalid verification code'); + } + await UserModel.updateOne( + { _id: user._id }, + { + $set: { + email: user.pendingEmailChange.newEmail, + emailVerified: true, + pendingEmailChange: undefined, + }, + $push: { + changeHistory: { + $each: [ + { + field: 'email', + from: user.email, + to: user.pendingEmailChange.newEmail, + by: user._id, + reason: 'User verified email change', + at: new Date(), + via: 'user', + }, + ], + $slice: -100, + }, + }, + }, + { session } ); - } finally { - session.endSession(); - } - return; + await SessionModel.updateMany( + { userId: user._id, sessionId: { $ne: currentSessionId } }, + { + valid: false, + revokedAt: new Date(), + }, + { session } + ); + }); } export async function logoutUser(refreshToken: string) { @@ -459,17 +532,18 @@ export async function logoutUser(refreshToken: string) { sessionId: string; }; } catch (err) { - throw new UnauthenticatedError("Authentication failed"); + throw new UnauthenticatedError('Authentication failed'); } const session = await SessionModel.findOne({ sessionId: decoded.sessionId, userId: decoded.userId, + valid: true, }); if (!session) { - throw new NotFoundError("Session not found"); + throw new NotFoundError('Session not found'); } session.revokedAt = new Date(); + session.valid = false; await session.save(); - return; } diff --git a/src/modules/auth/utils/createSessionPayload.ts b/src/modules/auth/utils/createSessionPayload.ts new file mode 100644 index 0000000..03da6aa --- /dev/null +++ b/src/modules/auth/utils/createSessionPayload.ts @@ -0,0 +1,59 @@ +import { SessionData } from '../../../models/Session.js'; +import { generateAllCookieTokens } from '@utils/generateAllCookieTokens.js'; +import { getIpInfo } from '@utils/getIpInfo.js'; +import { parseUserAgent } from '@utils/parseUserAgent.js'; +import { hashToken } from '@utils/tokens.js'; +import crypto from 'crypto'; +import { User } from '@models/User.js'; + +export async function createSessionPayload({ + user, + userAgent, + ip, +}: { + user: User; + userAgent: string; + ip: string; +}) { + const ipData: any = await getIpInfo(ip); + const userAgentInfo = parseUserAgent(userAgent); + const sessionId = crypto.randomBytes(32).toString('hex'); + const { accessToken, refreshToken, csrfToken } = generateAllCookieTokens( + user._id, + sessionId, + user.role, + user.accountStatus + ); + + let sessionPayload: Partial = { + sessionId, + userId: user._id, + userAgent, + device: userAgentInfo.device, + browser: userAgentInfo.browser, + os: userAgentInfo.os, + refreshTokenHash: hashToken(refreshToken), + csrfTokenHash: hashToken(csrfToken), + expiresIn: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), + createdAt: new Date(), + lastUsedAt: new Date(), + }; + + if (ipData.success) { + sessionPayload = { + ...sessionPayload, + ip: ipData.ip, + city: ipData.cityName, + country: ipData.countryName, + timezone: ipData.timeZones[0] || 'unknown', + lat: ipData.latitude, + lng: ipData.longitude, + isp: ipData.asnOrganization, + }; + } + + return { + sessionPayload, + tokens: { accessToken, refreshToken, csrfToken }, + }; +} diff --git a/src/modules/auth/utils/createUsername.ts b/src/modules/auth/utils/createUsername.ts new file mode 100644 index 0000000..e90eb33 --- /dev/null +++ b/src/modules/auth/utils/createUsername.ts @@ -0,0 +1,25 @@ +import crypto from 'crypto'; +import { UserModel } from '@models/User.js'; +import { ClientSession } from 'mongoose'; + +export const createUsername = async (email: string, session: ClientSession): Promise => { + const base = email + .split('@')[0] + .toLowerCase() + .replace(/[^a-z0-9]/g, ''); + + // Fallback if base becomes empty + const root = base || 'user'; + + // Retry up to 10 times before failing + for (let i = 0; i < 10; i++) { + const suffix = crypto.randomBytes(3).toString('hex'); // 6 hex chars + const username = `${root}${suffix}`; + + const exists = await UserModel.exists({ username }).session(session); + if (!exists) return username; + } + + // If all 10 attempts failed (extremely rare), use a timestamp fallback + return `${root}${Date.now().toString(36)}`; +}; diff --git a/src/modules/contextProfile/contextProfile.controller.ts b/src/modules/contextProfile/contextProfile.controller.ts new file mode 100644 index 0000000..d7a030d --- /dev/null +++ b/src/modules/contextProfile/contextProfile.controller.ts @@ -0,0 +1,32 @@ +import { Request, Response } from "express"; +import { + createContextProfileService, + getContextProfileService, + listContextProfilesService, +} from "./contextProfile.service.js"; +import { CreateContextProfileInput } from "@validation/contextProfile.schema.js"; + +export async function createContextProfileController(req: Request, res: Response) { + const payload = req.validatedBody as CreateContextProfileInput; + const context = await createContextProfileService(req.user!.id, payload); + + res.status(201).json({ data: context }); +} + +export async function getContextProfileController(req: Request, res: Response) { + const context = await getContextProfileService( + req.user!.id, + req.params.contextId + ); + + res.json({ data: context }); +} + +export async function listContextProfilesController( + req: Request, + res: Response +) { + const contexts = await listContextProfilesService(req.user!.id, req.query); + + res.json({ data: contexts }); +} diff --git a/src/modules/contextProfile/contextProfile.routes.ts b/src/modules/contextProfile/contextProfile.routes.ts new file mode 100644 index 0000000..0471ee5 --- /dev/null +++ b/src/modules/contextProfile/contextProfile.routes.ts @@ -0,0 +1,20 @@ +import { Router } from "express"; +import { + createContextProfileController, + getContextProfileController, + listContextProfilesController, +} from "./contextProfile.controller.js"; +import { asyncHandler } from "@utils/asyncHandler.js"; +import { validateBody } from "@validation/validateBody.js"; +import { createContextProfileSchema } from "@validation/contextProfile.schema.js"; + +const router = Router(); + +router.post("/", validateBody(createContextProfileSchema), asyncHandler(createContextProfileController)); +// router.post("/:contextId/clone", cloneContextProfileController); + +router.get("/:contextId", asyncHandler(getContextProfileController)); + +router.get("/", asyncHandler(listContextProfilesController)); + +export default router; diff --git a/src/modules/contextProfile/contextProfile.service.ts b/src/modules/contextProfile/contextProfile.service.ts new file mode 100644 index 0000000..82bac98 --- /dev/null +++ b/src/modules/contextProfile/contextProfile.service.ts @@ -0,0 +1,102 @@ +import mongoose from 'mongoose'; +import { BadRequestError, NotFoundError } from '@middleware/error/index.js'; +import { ContextProfileModel, ContextScope, GenreType } from '@models/ContextProfile.js'; +import { ProjectModel } from '@models/Project.js'; +import { NARRATION_PROFILES } from 'constants/narrationProfiles.js'; +import type { CreateContextProfileInput } from '@validation/contextProfile.schema.js'; + +export async function getContextProfileService(userId: string, contextId: string) { + const context = await ContextProfileModel.findOne({ + _id: contextId, + userId, + }); + + if (!context) throw new NotFoundError('Context not found'); + return context; +} + +export async function listContextProfilesService(userId: string, query: any) { + const filter: any = { userId }; + + if (query.scope) filter.scope = query.scope; + if (query.projectId) filter.projectId = query.projectId; + + return ContextProfileModel.find(filter).sort({ updatedAt: -1 }); +} + +export async function createContextProfileService(userId: string, payload: CreateContextProfileInput) { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + const makeGlobal = payload.makeGlobal === true; + + if (!makeGlobal && !payload.projectId) { + throw new BadRequestError('projectId is required when creating a non-global context'); + } + + if (makeGlobal && payload.setAsProjectDefault) { + throw new BadRequestError('Global context cannot be set as project default'); + } + + let project = null; + if (!makeGlobal && payload.projectId) { + project = await ProjectModel.findOne({ _id: payload.projectId, userId }).session(session); + if (!project) { + throw new NotFoundError('Project not found'); + } + } + + const narrationProfile = NARRATION_PROFILES[payload.genre as GenreType]; + const [context] = await ContextProfileModel.create( + [ + { + userId, + projectId: makeGlobal ? undefined : payload.projectId, + scope: makeGlobal ? ContextScope.GLOBAL : ContextScope.PROJECT, + isDefaultForProject: Boolean(!makeGlobal && payload.setAsProjectDefault), + name: payload.name, + description: payload.description, + genre: payload.genre, + mood: payload.mood, + style: payload.style, + narrativeScope: payload.narrativeScope, + environment: payload.environment, + worldRules: payload.worldRules, + narrativeConstraints: payload.narrativeConstraints, + characters: payload.characters, + forbiddenElements: payload.forbiddenElements, + narrationProfile, + lastUsedAt: new Date(), + }, + ], + { session } + ); + + if (!makeGlobal && payload.setAsProjectDefault && project) { + await ContextProfileModel.updateMany( + { + userId, + projectId: project._id, + _id: { $ne: context._id }, + isDefaultForProject: true, + }, + { $set: { isDefaultForProject: false } } + ).session(session); + + project.defaultContextProfileId = context._id; + if (project.status === 'draft') { + project.status = 'active'; + } + await project.save({ session }); + } + + await session.commitTransaction(); + return context; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + session.endSession(); + } +} diff --git a/src/modules/credit/credit.service.ts b/src/modules/credit/credit.service.ts new file mode 100644 index 0000000..9cd4f4a --- /dev/null +++ b/src/modules/credit/credit.service.ts @@ -0,0 +1,62 @@ +import mongoose, { Types } from 'mongoose'; +import { CreditsModel } from '@models/Credits.js'; +import { ForbiddenError, InternalServerError } from '@middleware/error/index.js'; + +export async function getAvailableCredits(userId: Types.ObjectId): Promise { + const rows = await CreditsModel.find({ + userId, + isExpired: false, + $or: [{ validTill: null }, { validTill: { $gt: new Date() } }], + }); + + let total = 0; + for (const row of rows) { + total += Math.max(0, row.creditsGranted - row.creditsUsed); + } + return total; +} + +export async function consumeCredits( + userId: string, + amount: number, + session: mongoose.ClientSession +): Promise { + if (amount <= 0) return; + + try { + const creditEntries = await CreditsModel.find( + { + userId, + isExpired: false, + $or: [{ validTill: null }, { validTill: { $gt: new Date() } }], + }, + null, + { session } + ).sort({ validTill: 1, createdAt: 1 }); + + let creditsToConsume = amount; + + for (const entry of creditEntries) { + if (creditsToConsume === 0) break; + + const available = entry.creditsGranted - entry.creditsUsed; + if (available <= 0) continue; + + const usedNow = Math.min(available, creditsToConsume); + + entry.creditsUsed += usedNow; + creditsToConsume -= usedNow; + + await entry.save({ session }); + } + + // 3. If not enough credits → rollback + if (creditsToConsume > 0) { + throw new ForbiddenError('Insufficient credits'); + } + } catch (err) { + throw err instanceof ForbiddenError + ? err + : new InternalServerError('Credit consumption failed', String(err)); + } +} diff --git a/src/modules/featurePermission/featurePermission.service.ts b/src/modules/featurePermission/featurePermission.service.ts new file mode 100644 index 0000000..e55349c --- /dev/null +++ b/src/modules/featurePermission/featurePermission.service.ts @@ -0,0 +1,66 @@ +import { Types } from 'mongoose'; +import { UserModel } from '@models/User.js'; +import { PlanModel } from '@models/Plan.js'; +import { UserCapabilityOverrideModel } from '@models/CapabilityOverride.js'; +import { ForbiddenError, InternalServerError } from '@middleware/error/index.js'; +import { ActionType } from 'config/creditPricing.js'; +import { resolveEffectiveCapabilities } from '@modules/featurePermission/utils/resolveEffectiveCapabilities.js'; + +type PermissionInput = { + userId: Types.ObjectId; + action: ActionType; + grade: number; +}; + +export async function assertFeaturePermission({ userId, action, grade }: PermissionInput): Promise { + const user = await UserModel.findById(userId).lean(); + if (!user || !user.currentPlan) { + throw new InternalServerError('User or plan not found'); + } + + const plan = await PlanModel.findById(user.currentPlan).lean(); + if (!plan || !plan.isActive || !plan.capabilities) { + throw new ForbiddenError('Plan is inactive or invalid'); + } + + const now = new Date(); + const overrides = await UserCapabilityOverrideModel.find({ + userId, + validFrom: { $lte: now }, + validTill: { $gt: now }, + }).lean(); + + const caps = resolveEffectiveCapabilities(plan.capabilities, overrides); + + switch (action) { + case 'TXT_TO_IMAGE_GEN': + if (!caps.image || grade > caps.image.maxTier) { + throw new ForbiddenError('Image generation grade not allowed'); + } + return; + + case 'AUDIO_GEN': + if (!caps.audio || grade > caps.audio.maxTier) { + throw new ForbiddenError('Audio generation grade not allowed'); + } + return; + + case 'STORY_GEN': + if (!caps.story || grade > caps.story.maxTier) { + throw new ForbiddenError('Story generation grade not allowed'); + } + return; + + case 'TXT_TO_VIDEO_GEN': + if (!caps.video || !caps.video.enabled) { + throw new ForbiddenError('Video generation not allowed'); + } + if (grade > caps.video.maxSeconds) { + throw new ForbiddenError('Video request exceeds plan limit'); + } + return; + + default: + throw new InternalServerError(`Unknown action: ${action}`); + } +} diff --git a/src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts b/src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts new file mode 100644 index 0000000..ba10bd4 --- /dev/null +++ b/src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts @@ -0,0 +1,24 @@ +import { CapabilityOverrideData } from '@models/CapabilityOverride.js'; + +export function resolveEffectiveCapabilities(planCaps: any, overrides: CapabilityOverrideData[]) { + const effective = structuredClone(planCaps); + + for (const o of overrides) { + const feature = o.feature as keyof typeof effective; + const key = o.capabilityKey; + + if (!effective[feature]) continue; + + const baseValue = effective[feature][key]; + + if (typeof baseValue === 'number' && typeof o.value === 'number') { + effective[feature][key] = Math.max(baseValue, o.value); + } + + if (typeof baseValue === 'boolean' && typeof o.value === 'boolean') { + effective[feature][key] = baseValue || o.value; + } + } + + return effective; +} diff --git a/src/modules/narration/narration.constants.ts b/src/modules/narration/narration.constants.ts new file mode 100644 index 0000000..935221f --- /dev/null +++ b/src/modules/narration/narration.constants.ts @@ -0,0 +1,3 @@ +export const DEFAULT_WORDS_PER_SECOND = 2.5; +export const MAX_NARRATION_LENGTH = 20000; +export const NARRATION_VERSION_GAP = 1; \ No newline at end of file diff --git a/src/modules/narration/narration.controller.ts b/src/modules/narration/narration.controller.ts new file mode 100644 index 0000000..c5bbd83 --- /dev/null +++ b/src/modules/narration/narration.controller.ts @@ -0,0 +1,209 @@ +import { Request, Response } from 'express'; +import { + getActiveNarration, + getNarrationById, + getAllNarrationsForStory, + generateNarration, + regenerateNarration, + createNarrationFromJSON, + uploadNarrationJSONFromFile, + updateNarration, + softDeleteNarration, + restoreNarration, + switchActiveNarration, + getAllDeletedNarrations, + createEmptyNarration, +} from './narration.service.js'; +import { + RegenerateNarrationInput, + UploadNarrationJSONInput, + UpdateNarrationSegmentsInput, +} from '@validation/narration.schema.js'; +import { paginationResponse } from '@utils/paginationResponse.js'; + +export const getAllNarrationsForStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + + const [narrations, total] = await getAllNarrationsForStory(userId, storyId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + + return res.status(200).json({ + data: narrations, + pagination: paginationRes, + }); +}; + +export const getAllDeletedNarrationsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + + const [narrations, total] = await getAllDeletedNarrations(userId, storyId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + return res.status(200).json({ + data: narrations, + pagination: paginationRes, + }); +}; + +// Single narration controllers + +export const getActiveNarrationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + + const narration = await getActiveNarration(userId, storyId); + + if (!narration) { + return res.status(404).json({ + message: 'No active narration found for this story', + }); + } + + return res.status(200).json({ + narration, + }); +}; + +export const getNarrationByIdController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const narration = await getNarrationById(userId, narrationId); + + if (!narration) { + return res.status(404).json({ + message: 'Narration not found', + }); + } + + return res.status(200).json({ + narration, + }); +}; + +export const generateNarrationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + + const narration = await generateNarration(userId, storyId); + + return res.status(201).json({ + message: 'Narration generated successfully', + narration, + }); +}; + +export const regenerateNarrationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + const { extraPrompt } = req.validatedBody as RegenerateNarrationInput; + + const narration = await regenerateNarration(userId, storyId, extraPrompt); + + return res.status(201).json({ + message: 'Narration regenerated successfully', + narration, + }); +}; + +export const createEmptyNarrationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + const narration = await createEmptyNarration(userId, storyId); + return res.status(201).json({ + message: 'Empty narration created successfully', + narration, + }); +}; + +export const uploadNarrationJSONController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + const payload = req.validatedBody as UploadNarrationJSONInput; + + const narration = await createNarrationFromJSON(userId, storyId, payload.narrationSegments); + + return res.status(201).json({ + message: 'Narration uploaded successfully', + narration, + }); +}; + +export const uploadNarrationFileController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId } = req.params; + + if (!req.file) { + return res.status(400).json({ + message: 'No file uploaded', + }); + } + + const narration = await uploadNarrationJSONFromFile(userId, storyId, req.file.path); + + return res.status(201).json({ + message: 'Narration file uploaded successfully', + narration, + }); +}; + +export const updateNarrationSegmentsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId, narrationId } = req.params; + const payload = req.validatedBody as UpdateNarrationSegmentsInput; + + const narration = await updateNarration(userId, storyId, narrationId, payload.narrationSegments); + + if (!narration) { + return res.status(404).json({ + message: 'Narration not found', + }); + } + + return res.status(200).json({ + message: 'Narration updated successfully', + narration, + }); +}; + +export const deleteNarrationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const narration = await softDeleteNarration(userId, narrationId); + + return res.status(200).json({ + message: 'Narration deleted successfully', + }); +}; + +export const restoreNarrationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const narration = await restoreNarration(userId, narrationId); + + return res.status(200).json({ + message: 'Narration restored successfully', + narration, + }); +}; + +export const switchActiveNarrationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { narrationId } = req.params; + + const narration = await switchActiveNarration(userId, narrationId); + + return res.status(200).json({ + message: 'Active narration switched successfully', + narration, + }); +}; diff --git a/src/modules/narration/narration.routes.ts b/src/modules/narration/narration.routes.ts new file mode 100644 index 0000000..3ac4aa4 --- /dev/null +++ b/src/modules/narration/narration.routes.ts @@ -0,0 +1,115 @@ +import { Router } from 'express'; +import { + getActiveNarrationController, + getAllNarrationsForStoryController, + getNarrationByIdController, + getAllDeletedNarrationsController, + generateNarrationController, + regenerateNarrationController, + uploadNarrationJSONController, + uploadNarrationFileController, + updateNarrationSegmentsController, + deleteNarrationController, + restoreNarrationController, + switchActiveNarrationController, + createEmptyNarrationController, +} from './narration.controller.js'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { validateParams } from '@validation/validateParams.js'; +import { validateBody } from '@validation/validateBody.js'; +import { + narrationIdParamSchema, + storyIdParamSchema, + storyNarrationParamSchema, + regenerateNarrationSchema, + uploadNarrationJSONSchema, + updateNarrationSegmentsSchema, +} from '@validation/narration.schema.js'; +import { narrationJSONUpload } from '@middleware/multer/narrationJSONUpload.js'; +import { paginationAndSortingMiddleware } from '@middleware/request/paginationAndSorting.js'; + +const router = Router(); + +router.get( + '/story/:storyId/all', + validateParams(storyIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllNarrationsForStoryController) +); + +router.get( + '/story/:storyId/deleted', + validateParams(storyIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllDeletedNarrationsController) +); + +// Single narration routes + +router.get( + '/story/:storyId/active', + validateParams(storyIdParamSchema), + asyncHandler(getActiveNarrationController) +); + +router.post( + '/story/:storyId', + validateParams(storyIdParamSchema), + asyncHandler(createEmptyNarrationController) +); + +router.post( + '/story/:storyId/generate', + validateParams(storyIdParamSchema), + asyncHandler(generateNarrationController) +); + +router.post( + '/story/:storyId/regenerate', + validateParams(storyIdParamSchema), + validateBody(regenerateNarrationSchema), + asyncHandler(regenerateNarrationController) +); + +router.post( + '/story/:storyId/upload-json', + validateParams(storyIdParamSchema), + validateBody(uploadNarrationJSONSchema), + asyncHandler(uploadNarrationJSONController) +); + +router.post( + '/story/:storyId/upload-file', + validateParams(storyIdParamSchema), + narrationJSONUpload, + asyncHandler(uploadNarrationFileController) +); + +router.get('/:narrationId', validateParams(narrationIdParamSchema), asyncHandler(getNarrationByIdController)); + +router.patch( + '/story/:storyId/:narrationId/segments', + validateParams(storyNarrationParamSchema), + validateBody(updateNarrationSegmentsSchema), + asyncHandler(updateNarrationSegmentsController) +); + +router.patch( + '/:narrationId/activate', + validateParams(narrationIdParamSchema), + asyncHandler(switchActiveNarrationController) +); + +router.delete( + '/:narrationId', + validateParams(narrationIdParamSchema), + asyncHandler(deleteNarrationController) +); + +router.patch( + '/:narrationId/restore', + validateParams(narrationIdParamSchema), + asyncHandler(restoreNarrationController) +); + +export default router; diff --git a/src/modules/narration/narration.service.ts b/src/modules/narration/narration.service.ts new file mode 100644 index 0000000..2d2d82f --- /dev/null +++ b/src/modules/narration/narration.service.ts @@ -0,0 +1,674 @@ +import fs from 'fs/promises'; +import fsCallback from 'fs'; + +import { ContextProfileModel } from '@models/ContextProfile.js'; +import { NarrationSegment, StoryNarration, StoryNarrationModel } from '@models/Narration.js'; +import { SceneModel } from '@models/Scene.js'; +import safeParseJSON from '@utils/safeParseJSON.js'; +import { buildStoryNarrationPrompt } from '@libs/ai/prompts/narrationPrompt.js'; +import { openRouterAI } from '@libs/ai/clients/openAI.js'; +import { BadRequestError, ConflictError, NotFoundError } from '@middleware/error/index.js'; +import { Pagination, Sorting } from 'types/Pagination.js'; +import { withTransaction } from '@db/withTransaction.js'; +import { validateNarrationOwnership } from 'validators/validateNarrationOwnership.js'; +import { assertHasActiveScenes } from 'domain/assertions/assertSceneState.js'; +import { assertStoryIsActive, assertStoryNotDeleted } from 'domain/assertions/assertStoryState.js'; +import { validateStoryOwnership } from 'validators/validateStoryOwnership.js'; +import { + assertNarrationIsDeleted, + assertNarrationNotDeleted, +} from 'domain/assertions/assertNarrationState.js'; +import { AudioAssetModel } from '@models/AudioAsset.js'; +import { assertNarrationFitsTime } from 'domain/assertions/assertNarrationFitsTime.js'; +import { hashSceneOrder } from '@utils/hashSceneOrder.js'; +import { assertCharacterFits } from 'domain/assertions/assertCharacterFits.js'; +import { Types } from 'mongoose'; + +export async function getAllNarrationsForStory( + userId: string, + storyId: string, + pagination: Pagination, + sorting: Sorting +) { + const { page, limit, skip } = pagination; + + const sortOptions: Record = {}; + sortOptions[sorting.sortBy || 'version'] = sorting.sortOrder || -1; + + const [narrations, total] = await Promise.all([ + StoryNarrationModel.find({ + userId, + storyId, + deletedAt: { $exists: false }, + }) + .sort(sortOptions) + .skip(skip) + .limit(limit), + StoryNarrationModel.countDocuments({ + userId, + storyId, + deletedAt: { $exists: false }, + }), + ]); + + return [narrations, total]; +} + +export async function getAllDeletedNarrations( + userId: string, + storyId: string, + pagination: Pagination, + sorting: Sorting +) { + const { page, limit, skip } = pagination; + + const sortOptions: Record = {}; + sortOptions[sorting.sortBy || 'version'] = sorting.sortOrder || -1; + + const [narrations, total] = await Promise.all([ + StoryNarrationModel.find({ + userId, + storyId, + deletedAt: { $exists: true }, + }) + .sort(sortOptions) + .skip(skip) + .limit(limit), + StoryNarrationModel.countDocuments({ + userId, + storyId, + deletedAt: { $exists: true }, + }), + ]); + + return [narrations, total]; +} + +export async function getAllNarrationForSceneOrder(userId: string, storyId: string, sceneOrderIds: string[]) { + const sceneOrderHash = hashSceneOrder(sceneOrderIds.map((id) => new Types.ObjectId(id))); + const narration = await StoryNarrationModel.findOne({ + userId, + storyId, + sceneOrderHash, + deletedAt: { $exists: false }, + }); + return narration; +} + +// For single narration +export async function getActiveNarration(userId: string, storyId: string) { + const narration = await StoryNarrationModel.findOne({ + userId, + storyId, + active: true, + deletedAt: { $exists: false }, + }); + + return narration; +} + +export async function getNarrationById(userId: string, narrationId: string) { + const narration = await validateNarrationOwnership(userId, narrationId); + return narration; +} + +export async function generateNarration(userId: string, storyId: string) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + + assertStoryIsActive(story); + + const scenes = await SceneModel.find({ + userId, + storyId, + deletedAt: { $exists: false }, + active: true, + }) + .sort({ order: 1 }) + .session(session); + + assertHasActiveScenes(scenes); + + const lastVersion = await StoryNarrationModel.findOne({ + storyId, + sceneOrder: scenes.map((s) => s._id), + }) + .sort({ version: -1 }) + .session(session); + + const version = lastVersion ? lastVersion.version + 1 : 1; + + const totalDuration = scenes.reduce((sum, s) => sum + (s.duration ?? 0), 0); + + if (totalDuration <= 0) { + throw new BadRequestError('Total scene duration must be greater than 0'); + } + + const contextProfile = await ContextProfileModel.findOne({ userId, storyId }).lean().session(session); + + const prompt = buildStoryNarrationPrompt({ + storyTitle: story.title || 'Story', + storyContent: { + body: story.content.body, + keywords: story.content.keywords, + tags: story.content.tags, + }, + scenes, + storyTimeLimit: totalDuration, + intent: story.intent, + platform: story.platform, + contextProfile, + }); + + const result = await openRouterAI(prompt); + const raw = result?.choices?.[0]?.message?.content; + + if (!raw) { + throw new Error('AI service did not return any content'); + } + + const parsed = safeParseJSON(raw); + + if (!parsed || !parsed.narrationSegments || !Array.isArray(parsed.narrationSegments)) { + throw new BadRequestError('Invalid narration structure from AI'); + } + + if (parsed.narrationSegments.length === 0) { + throw new BadRequestError('AI generated empty narration segments'); + } + + await StoryNarrationModel.updateMany({ storyId, active: true }, { $set: { active: false } }, { session }); + + const sceneOrder = scenes.map((s) => s._id); + const sceneOrderHash = hashSceneOrder(sceneOrder); + + const [narration] = await StoryNarrationModel.create( + [ + { + userId, + storyId, + sceneOrder, + sceneOrderHash, + narrationSegments: parsed.narrationSegments, + totalDuration: parsed.totalDuration || totalDuration, + version, + active: true, + source: 'ai', + }, + ], + { session } + ); + + return narration as StoryNarration; + }); +} + +export async function regenerateNarration(userId: string, narrationId: string, extraPrompt: string) { + return withTransaction(async (session) => { + const narration = await validateNarrationOwnership(userId, narrationId, session); + + const story = await validateStoryOwnership(userId, narration.storyId.toString(), session); + assertStoryNotDeleted(story); + assertStoryIsActive(story); + + const scenes = await SceneModel.find({ + userId, + storyId: narration.storyId, + deletedAt: { $exists: false }, + }) + .sort({ order: 1 }) + .session(session); + + assertHasActiveScenes(scenes); + + const checkPass = scenes.every((s, index) => s._id.equals(narration.sceneOrder[index])); + if (!checkPass) { + throw new BadRequestError('Scenes have changed since last narration generation'); + } + + const totalDuration = scenes.reduce((sum, s) => sum + (s.duration ?? 0), 0); + + if (totalDuration <= 0) { + throw new BadRequestError('Total scene duration must be greater than 0'); + } + + const contextProfile = await ContextProfileModel.findOne({ userId, storyId: narration.storyId }) + .lean() + .session(session); + + const prompt = buildStoryNarrationPrompt({ + storyTitle: story.title || 'Story', + storyContent: { + body: story.content.body, + keywords: story.content.keywords, + tags: story.content.tags, + }, + scenes, + storyTimeLimit: totalDuration, + intent: story.intent, + platform: story.platform, + contextProfile, + extraPrompt, + }); + + const result = await openRouterAI(prompt); + const raw = result?.choices?.[0]?.message?.content; + + if (!raw) { + throw new Error('AI service did not return any content'); + } + + const parsed = safeParseJSON(raw); + + if (!parsed || !parsed.narrationSegments || !Array.isArray(parsed.narrationSegments)) { + throw new BadRequestError('Invalid narration structure from AI'); + } + + if (parsed.narrationSegments.length === 0) { + throw new BadRequestError('AI generated empty narration segments'); + } + + const updatedNarration = await StoryNarrationModel.findByIdAndUpdate( + narrationId, + { + userId, + storyId: narration.storyId, + narrationSegments: parsed.narrationSegments, + totalDuration: parsed.totalDuration || totalDuration, + source: 'ai', + }, + { runValidators: true, new: true, session } + ); + + return updatedNarration as StoryNarration; + }); +} + +export async function createEmptyNarration(userId: string, storyId: string) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + assertStoryIsActive(story); + const scenes = await SceneModel.find({ + userId, + storyId, + deletedAt: { $exists: false }, + active: true, + }) + .sort({ order: 1 }) + .session(session); + if (!scenes.length) { + throw new BadRequestError('No scenes found for this story'); + } + const expectedDuration = scenes.reduce((sum, s) => sum + (s.duration ?? 0), 0); + if (expectedDuration <= 0) { + throw new BadRequestError('Total scene duration must be greater than 0'); + } + const lastVersion = await StoryNarrationModel.findOne({ storyId }).sort({ version: -1 }).session(session); + const version = lastVersion ? lastVersion.version + 1 : 1; + await StoryNarrationModel.updateMany({ storyId, active: true }, { $set: { active: false } }, { session }); + const sceneOrder = scenes.map((s) => s._id); + const sceneOrderHash = hashSceneOrder(sceneOrder); + const [narration] = await StoryNarrationModel.create( + [ + { + userId, + storyId, + sceneOrder, + sceneOrderHash, + narrationSegments: [], + version, + active: true, + source: 'user', + }, + ], + { session } + ); + return narration; + }); +} + +export async function createNarrationFromJSON( + userId: string, + storyId: string, + narrationSegments: NarrationSegment[] +) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + assertStoryIsActive(story); + if (!Array.isArray(narrationSegments) || narrationSegments.length === 0) { + throw new BadRequestError('Invalid narration segments: must be a non-empty array'); + } + + const scenes = await SceneModel.find({ + userId, + storyId, + deletedAt: { $exists: false }, + active: true, + }) + .sort({ order: 1 }) + .session(session); + + if (!scenes.length) { + throw new BadRequestError('No scenes found for this story'); + } + + const contextProfile = await ContextProfileModel.findById(story.contextProfileId).session(session).lean(); + if (!contextProfile) { + throw new BadRequestError('Context profile not found for narration validation'); + } + + assertCharacterFits(narrationSegments, contextProfile); + + for (const seg of narrationSegments) { + if ( + typeof seg.startTime !== 'number' || + typeof seg.endTime !== 'number' || + typeof seg.duration !== 'number' || + seg.startTime < 0 || + seg.endTime <= seg.startTime || + seg.duration <= 0 || + typeof seg.narration !== 'string' + ) { + throw new BadRequestError(`Invalid narration segment ${seg.narration}`); + } + + const computed = seg.endTime - seg.startTime; + if (Math.abs(computed - seg.duration) > 0.25) { + throw new BadRequestError('Segment duration mismatch'); + } + + assertNarrationFitsTime({ + durationSeconds: seg.duration, + narrationText: seg.narration, + profile: contextProfile.narrationProfile, + }); + } + + const expectedDuration = scenes.reduce((sum, s) => sum + (s.duration ?? 0), 0); + const totalDuration = narrationSegments.reduce((sum, seg) => sum + (seg.duration || 0), 0); + + if (totalDuration <= 0) { + throw new BadRequestError('Total duration must be greater than 0'); + } + + if (totalDuration > expectedDuration) { + throw new BadRequestError('Total duration of narration segments exceeds total duration of scenes'); + } + + const lastVersion = await StoryNarrationModel.findOne({ storyId }).sort({ version: -1 }).session(session); + + const version = lastVersion ? lastVersion.version + 1 : 1; + + await StoryNarrationModel.updateMany({ storyId, active: true }, { $set: { active: false } }, { session }); + const sceneOrder = scenes.map((s) => s._id); + const sceneOrderHash = hashSceneOrder(sceneOrder); + + const [narration] = await StoryNarrationModel.create( + [ + { + userId, + storyId, + sceneOrder, + sceneOrderHash, + narrationSegments, + totalDuration, + version, + active: true, + source: 'user', + }, + ], + { session } + ); + + return narration; + }); +} + +export async function uploadNarrationJSONFromFile(userId: string, storyId: string, filePath: string) { + let parsed: any; + + try { + const fileContent = await fs.readFile(filePath, 'utf-8'); + if (!fileContent) { + throw new BadRequestError('Uploaded file is empty'); + } + parsed = JSON.parse(fileContent); + } catch (err) { + throw new BadRequestError('Invalid JSON file format', err); + } finally { + const cleanUp = (retry = 0) => { + fsCallback.unlink(filePath, (err: any) => { + if (err && retry < 3) { + setTimeout(() => cleanUp(retry + 1), 100); + } + }); + }; + cleanUp(); + } + + if (!parsed || !parsed.narrationSegments || !Array.isArray(parsed.narrationSegments)) { + throw new BadRequestError('Invalid JSON structure. Expected { narrationSegments: [...] }'); + } + + return createNarrationFromJSON(userId, storyId, parsed.narrationSegments as NarrationSegment[]); +} + +export async function updateNarration( + userId: string, + storyId: string, + narrationId: string, + narrationSegments: NarrationSegment[] +) { + if (!Array.isArray(narrationSegments) || narrationSegments.length === 0) { + throw new BadRequestError('Invalid segments: must be a non-empty array'); + } + + const story = await validateStoryOwnership(userId, storyId); + assertStoryIsActive(story); + + const contextProfile = await ContextProfileModel.findById(story.contextProfileId).lean(); + if (!contextProfile) { + throw new BadRequestError('Context profile not found for narration validation'); + } + + assertCharacterFits(narrationSegments, contextProfile); + + for (const seg of narrationSegments) { + if ( + typeof seg.startTime !== 'number' || + typeof seg.endTime !== 'number' || + typeof seg.duration !== 'number' || + seg.startTime < 0 || + seg.endTime <= seg.startTime || + seg.duration <= 0 || + typeof seg.narration !== 'string' + ) { + throw new BadRequestError('Invalid narration segment'); + } + + const computed = seg.endTime - seg.startTime; + if (Math.abs(computed - seg.duration) > 0.25) { + throw new BadRequestError('Segment duration mismatch'); + } + + assertNarrationFitsTime({ + durationSeconds: seg.duration, + narrationText: seg.narration, + profile: contextProfile.narrationProfile, + }); + } + + return withTransaction(async (session) => { + const narration = await validateNarrationOwnership(userId, narrationId, session); + assertNarrationNotDeleted(narration); + + //TODO: Store Order Hash in somewhere to compare fast later + const scenes = await SceneModel.find({ + userId, + storyId: narration.storyId, + deletedAt: { $exists: false }, + active: true, + }) + .sort({ order: 1 }) + .session(session); + + if (hashSceneOrder(scenes.map((s) => s._id)) !== narration.sceneOrderHash) { + throw new BadRequestError('Narration no longer matches current scene order'); + } + + const expectedDuration = scenes.reduce((s, x) => s + (x.duration ?? 0), 0); + const totalDuration = narrationSegments.reduce((s, x) => s + x.duration, 0); + + if (totalDuration <= 0 || totalDuration > expectedDuration) { + throw new BadRequestError('Narration duration exceeds scene duration'); + } + + const updated = await StoryNarrationModel.findByIdAndUpdate( + narrationId, + { + $set: { + narrationSegments, + totalDuration, + }, + }, + { new: true, runValidators: true, session } + ); + if (!updated) { + throw new ConflictError('Failed to update narration'); + } + + await AudioAssetModel.updateMany( + { + narrationId, + deletedAt: { $exists: false }, + }, + { + $set: { deletedAt: new Date() }, + }, + { session } + ); + + return updated; + }); +} + +export async function softDeleteNarration(userId: string, narrationId: string): Promise { + return withTransaction(async (session) => { + const narration = await StoryNarrationModel.findOneAndUpdate( + { _id: narrationId, userId, deletedAt: { $exists: false } }, + { + $set: { deletedAt: new Date(), active: false }, + }, + { new: true, session } + ); + + if (!narration) { + throw new NotFoundError('Narration not found or already deleted '); + } + await AudioAssetModel.updateMany( + { + narrationId: narration._id, + deletedAt: { $exists: false }, + }, + { $set: { deletedAt: new Date() }, new: true, session } + ); + }); +} + +export async function permanentDeleteNarration(userId: string, narrationId: string) { + return withTransaction(async (session) => { + const narration = await StoryNarrationModel.findOneAndDelete( + { + _id: narrationId, + userId, + deletedAt: { $exists: true }, + }, + { session } + ); + if (!narration) { + throw new NotFoundError('Narration not found or not deleted'); + } + await AudioAssetModel.deleteMany({ narrationId: narration._id }, { session }); + }); +} + +export async function restoreNarration(userId: string, narrationId: string) { + return withTransaction(async (session) => { + const narration = await validateNarrationOwnership(userId, narrationId, session); + assertNarrationIsDeleted(narration); + + const restoredNarration = await StoryNarrationModel.findOneAndUpdate( + { _id: narrationId, userId, deletedAt: { $exists: true } }, + { + $unset: { deletedAt: 1 }, + }, + { new: true, session, lean: true } + ); + + if (!restoredNarration) { + throw new NotFoundError('Narration not found'); + } + + await AudioAssetModel.updateMany( + { + narrationId: narration._id, + deletedAt: { $exists: true }, + }, + { $unset: { deletedAt: 1 } }, + { + session, + } + ); + + return restoredNarration; + }); +} + +export async function switchActiveNarration(userId: string, narrationId: string) { + return withTransaction(async (session) => { + const narration = await validateNarrationOwnership(userId, narrationId, session); + assertNarrationNotDeleted(narration); + + await StoryNarrationModel.updateMany( + { + sceneOrderHash: narration.sceneOrderHash, + active: true, + deletedAt: { $exists: false }, + _id: { $ne: narrationId }, + }, + { $set: { active: false } }, + { session } + ); + + const activateNarration = await StoryNarrationModel.findOneAndUpdate( + { _id: narrationId, deletedAt: { $exists: false }, active: false }, + { + active: true, + }, + { + new: true, + session, + lean: true, + } + ); + + if (!activateNarration) { + throw new ConflictError('Failed to update active status'); + } + + return activateNarration; + }); +} + +// Final Story Audio Text +export async function getFinalNarrationText(userId: string, narrationId: string, storyId: string) { + const activeNarration = await StoryNarrationModel.findOne({ + storyId, + active: true, + deletedAt: { $exists: false }, + }); + if (!activeNarration) { + throw new NotFoundError('Active narration not found for this story'); + } + return activeNarration.narrationSegments.map((seg) => seg.narration).join(' '); +} diff --git a/src/modules/project/project.controller.ts b/src/modules/project/project.controller.ts index e69de29..eb4a006 100644 --- a/src/modules/project/project.controller.ts +++ b/src/modules/project/project.controller.ts @@ -0,0 +1,253 @@ +import { Request, Response } from 'express'; +import { + archiveAllProjects, + archiveManyProjectsByIds, + createProject, + createProjectContextProfile, + deleteAllProjects, + deleteManyProjectsByIds, + deleteProjectById, + getArchivedProjects, + getDeletedProjects, + getProjectById, + getProjects, + permanentDeleteAllProjects, + permanentDeleteManyProjects, + permanentDeleteProjectById, + restoreAllProjects, + restoreManyProjectsByIds, + restoreProjectById, + unarchiveManyProjectsByIds, + unarchiveProjectById, + updateProjectById, + updateProjectStatus, + updateProjectVisibility, + unarchiveAllProjects, + getDraftProjects, +} from './project.service.js'; +import { Types } from 'mongoose'; +import { + CreateProjectInput, + UpdateProjectInput, + UpdateManyIdsInput, + CreateProjectContextInput, +} from '@validation/project.schema.js'; +import { paginationResponse } from '@utils/paginationResponse.js'; + +export const getProjectsController = async (req: Request, res: Response) => { + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const userId = req.user!.id; + const [projects, total] = await getProjects(userId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: projects, + pagination: { + ...paginationRes, + }, + }); +}; + +export const getDraftProjectsController = async (req: Request, res: Response) => { + const pagination = req.pagination!; + const sorting = req.sorting!; + const userId = req.user!.id; + + const [projects, total] = await getDraftProjects(userId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + return res.status(200).json({ + items: projects, + pagination: { + ...paginationRes, + }, + }); +}; + +export const getDeletedProjectsController = async (req: Request, res: Response) => { + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const userId = req.user!.id; + const [projects, total] = await getDeletedProjects(userId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: projects, + pagination: { + ...paginationRes, + }, + }); +}; +export const getArchivedProjectsController = async (req: Request, res: Response) => { + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const userId = req.user!.id; + const [projects, total] = await getArchivedProjects(userId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: projects, + pagination: { + ...paginationRes, + }, + }); +}; + +export const archiveAllProjectsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + + const result = await archiveAllProjects(userId); + + return res.status(200).json(result); +}; + +export const unarchiveAllProjectsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + + const result = await unarchiveAllProjects(userId); + + return res.status(200).json(result); +}; + +export const deleteAllProjectsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + + const result = await deleteAllProjects(userId); + + return res.status(200).json(result); +}; + +export const permanentDeleteAllProjectsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + + const result = await permanentDeleteAllProjects(userId); + + return res.status(200).json(result); +}; + +export const restoreAllProjectsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + + const result = await restoreAllProjects(userId); + + return res.status(200).json(result); +}; + +// Many or Bulk +export const deleteManyProjectsController = async (req: Request, res: Response) => { + const { projectIds } = req.validatedBody as UpdateManyIdsInput; + const userId = req.user!.id; + + const result = await deleteManyProjectsByIds(projectIds, userId); + + return res.status(200).json(result); +}; + +export const permanentDeleteManyProjectsController = async (req: Request, res: Response) => { + const { projectIds } = req.validatedBody as UpdateManyIdsInput; + const userId = req.user!.id; + + const result = await permanentDeleteManyProjects(projectIds, userId); + + return res.status(200).json(result); +}; + +export const restoreManyProjectsController = async (req: Request, res: Response) => { + const { projectIds } = req.validatedBody as UpdateManyIdsInput; + const userId = req.user!.id; + const restoredProjects = await restoreManyProjectsByIds(projectIds, userId); + + return res.status(200).json(restoredProjects); +}; + +export const archiveManyProjectsController = async (req: Request, res: Response) => { + const { projectIds } = req.validatedBody as UpdateManyIdsInput; + const userId = req.user!.id; + + const result = await archiveManyProjectsByIds(projectIds, userId); + + return res.status(200).json(result); +}; + +export const unarchiveManyProjectsController = async (req: Request, res: Response) => { + const { projectIds } = req.validatedBody as UpdateManyIdsInput; + const userId = req.user!.id; + const unarchivedProjects = await unarchiveManyProjectsByIds(projectIds, userId); + + return res.status(200).json(unarchivedProjects); +}; + +export const postProjectController = async (req: Request, res: Response) => { + const input = req.validatedBody as CreateProjectInput; + const userId = req.user!.id; + const newProject = await createProject(userId, input); + return res.status(201).json(newProject); +}; + +export const getProjectByIdController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const userId = req.user!.id; + const project = await getProjectById(projectId, userId); + return res.status(200).json(project); +}; + +export const createProjectContextProfileController = async (req: Request, res: Response) => { + const projectId = req.params.projectId; + const payload = req.validatedBody as CreateProjectContextInput; + const userId = req.user!.id; + const newProject = await createProjectContextProfile(userId, projectId, payload); + return res.status(201).json(newProject); +}; + +export const updateProjectByIdController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const updates = req.validatedBody as UpdateProjectInput; + const userId = req.user!.id; + const updatedProject = await updateProjectById(projectId, userId, updates); + return res.status(200).json(updatedProject); +}; + +export const deleteProjectByIdController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const userId = req.user!.id; + const response = await deleteProjectById(projectId, userId); + return res.status(200).json(response); +}; + +export const permanentDeleteProjectByIdController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const userId = req.user!.id; + + const result = await permanentDeleteProjectById(projectId, userId); + + return res.status(200).json(result); +}; + +export const updateProjectStatusController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const { status } = req.body; + const userId = req.user!.id; + const updatedProject = await updateProjectStatus(projectId, userId, status); + return res.status(200).json(updatedProject); +}; + +export const updateProjectVisibilityController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const { visibility } = req.body; + const userId = req.user!.id; + const updatedProject = await updateProjectVisibility(projectId, userId, visibility); + return res.status(200).json(updatedProject); +}; + +export const restoreProjectByIdController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const userId = req.user!.id; + const restoredProject = await restoreProjectById(projectId, userId); + return res.status(200).json(restoredProject); +}; + +export const unarchiveProjectByIdController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const userId = req.user!.id; + const unarchivedProject = await unarchiveProjectById(projectId, userId); + return res.status(200).json(unarchivedProject); +}; diff --git a/src/modules/project/project.routes.ts b/src/modules/project/project.routes.ts index e69de29..5ea1f98 100644 --- a/src/modules/project/project.routes.ts +++ b/src/modules/project/project.routes.ts @@ -0,0 +1,119 @@ +import { Router } from 'express'; +import { + archiveAllProjectsController, + archiveManyProjectsController, + createProjectContextProfileController, + deleteAllProjectsController, + deleteManyProjectsController, + deleteProjectByIdController, + getArchivedProjectsController, + getDeletedProjectsController, + getDraftProjectsController, + getProjectByIdController, + getProjectsController, + permanentDeleteAllProjectsController, + permanentDeleteManyProjectsController, + permanentDeleteProjectByIdController, + postProjectController, + restoreAllProjectsController, + restoreManyProjectsController, + restoreProjectByIdController, + unarchiveAllProjectsController, + unarchiveManyProjectsController, + unarchiveProjectByIdController, + updateProjectByIdController, + updateProjectStatusController, + updateProjectVisibilityController, +} from './project.controller.js'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { validateBody } from '@validation/validateBody.js'; +import { + createProjectContextProfileSchema, + createProjectSchema, + projectIdParamSchema, + updateManyIdsSchema, + updateProjectSchema, + updateProjectStatusSchema, + updateProjectVisibilitySchema, +} from '@validation/project.schema.js'; +import { validateParams } from '@validation/validateParams.js'; +import { paginationAndSortingMiddleware } from '@middleware/request/paginationAndSorting.js'; + +const router = Router(); + +router.get('/', paginationAndSortingMiddleware, asyncHandler(getProjectsController)); +router.post('/', validateBody(createProjectSchema), asyncHandler(postProjectController)); +router.get( + '/draft', + paginationAndSortingMiddleware, + asyncHandler(getDraftProjectsController) +); +router.get('/delete', paginationAndSortingMiddleware, asyncHandler(getDeletedProjectsController)); +router.get('/archive', paginationAndSortingMiddleware, asyncHandler(getArchivedProjectsController)); + +router.patch('/archive-all', asyncHandler(archiveAllProjectsController)); +router.patch('/delete-all', asyncHandler(deleteAllProjectsController)); +router.patch('/restore-all', asyncHandler(restoreAllProjectsController)); +router.patch('/unarchive-all', asyncHandler(unarchiveAllProjectsController)); +router.delete('/permanent-all', asyncHandler(permanentDeleteAllProjectsController)); + +// Many + +router.patch('/archive', validateBody(updateManyIdsSchema), asyncHandler(archiveManyProjectsController)); + +router.patch('/delete', validateBody(updateManyIdsSchema), asyncHandler(deleteManyProjectsController)); + +router.patch('/restore', validateBody(updateManyIdsSchema), asyncHandler(restoreManyProjectsController)); + +router.patch('/unarchive', validateBody(updateManyIdsSchema), asyncHandler(unarchiveManyProjectsController)); + +router.delete( + '/permanent', + validateBody(updateManyIdsSchema), + asyncHandler(permanentDeleteManyProjectsController) +); + +// Project ID specific routes +router.get('/:projectId', validateParams(projectIdParamSchema), asyncHandler(getProjectByIdController)); +router.post( + '/:projectId/context-profile', + validateParams(projectIdParamSchema), + validateBody(createProjectContextProfileSchema), + asyncHandler(createProjectContextProfileController) +); +router.patch( + '/:projectId', + validateParams(projectIdParamSchema), + validateBody(updateProjectSchema), + asyncHandler(updateProjectByIdController) +); +router.delete('/:projectId', validateParams(projectIdParamSchema), asyncHandler(deleteProjectByIdController)); +router.delete( + '/:projectId/permanent', + validateParams(projectIdParamSchema), + asyncHandler(permanentDeleteProjectByIdController) +); +router.patch( + '/:projectId/status', + validateParams(projectIdParamSchema), + validateBody(updateProjectStatusSchema), + asyncHandler(updateProjectStatusController) +); +router.patch( + '/:projectId/visibility', + validateParams(projectIdParamSchema), + validateBody(updateProjectVisibilitySchema), + asyncHandler(updateProjectVisibilityController) +); +router.patch( + '/:projectId/restore', + validateParams(projectIdParamSchema), + asyncHandler(restoreProjectByIdController) +); +router.patch( + '/:projectId/unarchive', + validateParams(projectIdParamSchema), + asyncHandler(unarchiveProjectByIdController) +); + +export default router; diff --git a/src/modules/project/project.service.ts b/src/modules/project/project.service.ts index e69de29..4516d08 100644 --- a/src/modules/project/project.service.ts +++ b/src/modules/project/project.service.ts @@ -0,0 +1,507 @@ +import { + BadRequestError, + ForbiddenError, + InternalServerError, + NotFoundError, +} from '@middleware/error/index.js'; +import type { + CreateProjectContextInput, + CreateProjectInput, + UpdateProjectInput, +} from '@validation/project.schema.js'; +import { ProjectModel, ProjectType } from '@models/Project.js'; +import { sanitizeProjectResponse, sanitizeProjects } from '@utils/sanitizeProjectResponse.js'; +import mongoose, { Types } from 'mongoose'; +import { Pagination, Sorting } from '../../types/Pagination.js'; +import { ACTIVE_STATUSES } from './rules/projectStatus.js'; +import { transitionManyProjectsByIds } from './utils/transitionManyProjectsByIds.js'; +import { transitionProjectById } from './utils/transitionProjectById.js'; +import { ContextProfileModel, ContextScope, GenreType } from '@models/ContextProfile.js'; +import { NARRATION_PROFILES } from 'constants/narrationProfiles.js'; + +export async function getProjects(userId: Types.ObjectId | string, pagination: Pagination, sorting: Sorting) { + const filter = { userId, status: { $eq: 'active' } }; + const [projects, total] = await Promise.all([ + ProjectModel.find(filter) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + ProjectModel.countDocuments(filter) as Promise, + ]); + if (!projects || projects.length === 0) { + return [[], total]; + } + const resProjects = sanitizeProjects(projects); + return [resProjects, total]; +} + +export async function getDraftProjects( + userId: Types.ObjectId | string, + pagination: Pagination, + sorting: Sorting +) { + const filter = { + userId, + status: 'draft', + }; + + const [projects, total] = await Promise.all([ + ProjectModel.find(filter) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + ProjectModel.countDocuments(filter), + ]); + + if (!projects || projects.length === 0) { + return [[], total]; + } + + const resProjects = sanitizeProjects(projects); + return [resProjects, total]; +} + +export async function getDeletedProjects( + userId: Types.ObjectId | string, + pagination: Pagination, + sorting: Sorting +) { + const filter = { userId, status: 'delete' }; + const [projects, total] = await Promise.all([ + ProjectModel.find(filter) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + ProjectModel.countDocuments(filter) as Promise, + ]); + if (!projects || projects.length === 0) { + return [[], total]; + } + const resProjects = sanitizeProjects(projects); + return [resProjects, total]; +} + +export async function getArchivedProjects( + userId: Types.ObjectId | string, + pagination: Pagination, + sorting: Sorting +) { + const filter = { userId, status: 'archive' }; + const [projects, total] = await Promise.all([ + ProjectModel.find(filter) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + ProjectModel.countDocuments(filter) as Promise, + ]); + if (!projects || projects.length === 0) { + return [[], total]; + } + const resProjects = sanitizeProjects(projects); + return [resProjects, total]; +} + +export async function archiveAllProjects(userId: Types.ObjectId | string) { + const projects = await ProjectModel.find({ + userId, + status: 'active', + }).select('_id'); + + if (projects.length === 0) { + throw new NotFoundError('No active projects to archive'); + } + + const ids = projects.map((p) => p._id); + + return transitionManyProjectsByIds(ids, userId, ['active'], 'archive'); +} + +export async function deleteAllProjects(userId: Types.ObjectId | string) { + const projects = await ProjectModel.find({ + userId, + status: { $ne: 'delete' }, + }).select('_id'); + + if (projects.length === 0) { + throw new NotFoundError('No projects to delete'); + } + + return transitionManyProjectsByIds( + projects.map((p) => p._id), + userId, + ['draft', 'active', 'archive'], + 'delete' + ); +} + +export async function restoreAllProjects(userId: Types.ObjectId | string) { + const projects = await ProjectModel.find({ + userId, + status: 'delete', + }).select('_id'); + + if (projects.length === 0) { + throw new NotFoundError('No deleted projects to restore'); + } + + return transitionManyProjectsByIds( + projects.map((p) => p._id), + userId, + ['delete'], + 'active' + ); +} + +export async function unarchiveAllProjects(userId: Types.ObjectId | string) { + const projects = await ProjectModel.find({ + userId, + status: 'archive', + }).select('_id'); + + if (projects.length === 0) { + throw new NotFoundError('No archived projects to restore'); + } + + return transitionManyProjectsByIds( + projects.map((p) => p._id), + userId, + ['archive'], + 'active' + ); +} + +export async function permanentDeleteAllProjects(userId: Types.ObjectId | string) { + const result = await ProjectModel.deleteMany({ + userId, + status: 'delete', + }); + + if (!result.deletedCount) { + throw new NotFoundError('No deleted projects to permanently remove'); + } + + return { deletedCount: result.deletedCount }; +} + +// Bulk or Many + +export async function deleteManyProjectsByIds( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string +) { + return transitionManyProjectsByIds(projectIds, userId, ['draft', 'active', 'archive'], 'delete'); +} + +export const restoreManyProjectsByIds = async ( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string +) => { + const result = await transitionManyProjectsByIds(projectIds, userId, ['delete'], 'active'); + return result; +}; + +export async function archiveManyProjectsByIds( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string +) { + return transitionManyProjectsByIds(projectIds, userId, ['active'], 'archive'); +} + +export const unarchiveManyProjectsByIds = async ( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string +) => { + const result = await transitionManyProjectsByIds(projectIds, userId, ['archive'], 'active'); + return result; +}; + +export async function permanentDeleteManyProjects( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string +) { + const projects = await ProjectModel.find({ + _id: { $in: projectIds }, + userId, + status: 'delete', + }); + + if (projects.length !== projectIds.length) { + throw new BadRequestError('Some projects are not deleted'); + } + + const result = await ProjectModel.deleteMany({ + _id: { $in: projectIds }, + userId, + }); + + return { deletedCount: result.deletedCount || 0 }; +} + +// Single + +export async function createProject(userId: Types.ObjectId | string, projectInput: CreateProjectInput) { + const newProject = await ProjectModel.create({ + userId: userId, + title: projectInput.title, + description: projectInput.description, + visibility: projectInput.visibility || 'private', + // A project stays draft until a default context profile is attached. + status: 'draft', + }); + if (!newProject) { + throw new InternalServerError('Failed to create project'); + } + return sanitizeProjectResponse({ + project: newProject, + type: 'getProjectById', + }); +} + +export async function getProjectById(projectId: Types.ObjectId | string, userId: Types.ObjectId | string) { + const project = await ProjectModel.findOne({ + _id: projectId, + userId, + }); + if (!project) { + throw new NotFoundError('Project is not found'); + } + return sanitizeProjectResponse({ + project: project, + type: 'getProjectById', + }); +} + +export async function createProjectContextProfile( + userId: string, + projectId: string, + payload: CreateProjectContextInput +) { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + const project = await ProjectModel.findOne({ + _id: projectId, + userId, + }).session(session); + + if (!project) throw new NotFoundError('Project not found'); + + const existingContext = await ContextProfileModel.findOne({ + projectId: project._id, + isDefaultForProject: true, + }).session(session); + + if (existingContext) { + throw new ForbiddenError('Project already has a default context'); + } + + // 🚨 CRITICAL RULE + if (project.defaultContextProfileId) { + throw new ForbiddenError('Project already has a default context'); + } + let contextProfileId: Types.ObjectId | undefined; + + if (payload.mode === 'new') { + const narrationProfile = NARRATION_PROFILES[payload.data.genre as GenreType]; + const [context] = await ContextProfileModel.create( + [ + { + userId, + projectId, + name: payload.data.name, + genre: payload.data.genre, + mood: payload.data.mood, + style: payload.data.style, + environment: payload.data.environment, + narrationProfile, + scope: ContextScope.PROJECT, + isDefaultForProject: true, + lastUsedAt: new Date(), + }, + ], + { session } + ); + contextProfileId = context._id; + } + + if (payload.mode === 'use-global') { + const globalContext = await ContextProfileModel.findOne({ + _id: payload.globalContextId, + scope: ContextScope.GLOBAL, + }).session(session); + + if (!globalContext) { + throw new NotFoundError('Global context not found'); + } + + // 🔒 CLONE — NEVER ATTACH DIRECTLY + const cloned = new ContextProfileModel({ + ...globalContext.toObject(), + _id: undefined, + projectId, + scope: ContextScope.PROJECT, + parentContextId: globalContext._id, + isDefaultForProject: true, + lastUsedAt: new Date(), + }); + + await cloned.save({ session }); + contextProfileId = cloned._id; + } + + if (!contextProfileId) { + throw new BadRequestError('Invalid context creation mode'); + } + + project.defaultContextProfileId = contextProfileId; + if (project.status === 'draft') { + project.status = 'active'; + } + await project.save({ session }); + await session.commitTransaction(); + return sanitizeProjectResponse({ + project, + type: 'getProjectById', + }); + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + session.endSession(); + } +} + +// TODO:createUpdatedContextProfile function + +export async function updateProjectById( + projectId: Types.ObjectId | string, + userId: Types.ObjectId | string, + updates: UpdateProjectInput +) { + const updateSet: Partial> = {}; + + if (typeof updates.title === 'string') { + const trimmedTitle = updates.title.trim(); + if (trimmedTitle.length === 0) { + throw new BadRequestError('Title cannot be empty'); + } + updateSet.title = trimmedTitle; + } + + if (typeof updates.description === 'string') { + const trimmedDescription = updates.description.trim(); + if (trimmedDescription.length === 0) { + throw new BadRequestError('Description cannot be empty'); + } + updateSet.description = trimmedDescription; + } + + if (Object.keys(updateSet).length === 0) { + throw new BadRequestError('No valid fields provided for update'); + } + + const project = await ProjectModel.findOneAndUpdate( + { + _id: projectId, + userId, + status: { $in: ACTIVE_STATUSES }, + }, + { $set: updateSet }, + { new: true, runValidators: true } + ); + if (!project) { + throw new NotFoundError('Project is not found'); + } + return sanitizeProjectResponse({ + project: project, + type: 'getProjectById', + }); +} + +export async function deleteProjectById(projectId: Types.ObjectId | string, userId: Types.ObjectId | string) { + await transitionProjectById(projectId, userId, ['draft', 'active', 'archive'], 'delete'); + return { + status: 'success', + message: 'Project deleted successfully', + }; +} + +export async function permanentDeleteProjectById( + projectId: Types.ObjectId | string, + userId: Types.ObjectId | string +) { + const project = await ProjectModel.findOne({ + _id: projectId, + userId, + }).select('_id status'); + + if (!project) { + throw new NotFoundError('Project not found'); + } + + if (project.status !== 'delete') { + throw new ForbiddenError('Project must be deleted before permanent removal'); + } + + await ProjectModel.deleteOne({ + _id: project._id, + userId, + }); + + return { + status: 'success', + message: 'Project permanently deleted', + }; +} + +export async function updateProjectVisibility( + projectId: Types.ObjectId | string, + userId: Types.ObjectId | string, + visibility: 'public' | 'private' +) { + const project = await ProjectModel.findOneAndUpdate( + { + _id: projectId, + userId, + status: { $eq: 'active' }, + }, + { $set: { visibility } }, + { new: true, runValidators: true } + ); + if (!project) { + throw new NotFoundError('Project is not found'); + } + return sanitizeProjectResponse({ + project: project, + type: 'getProjectById', + }); +} + +export async function updateProjectStatus( + projectId: Types.ObjectId | string, + userId: Types.ObjectId | string, + status: 'active' | 'archive' | 'draft' +) { + const result = await transitionProjectById(projectId, userId, ['draft', 'active', 'archive'], status); + return result; +} + +export async function restoreProjectById( + projectId: Types.ObjectId | string, + userId: Types.ObjectId | string +) { + const result = await transitionProjectById(projectId, userId, ['delete'], 'active'); + return result; +} + +export async function unarchiveProjectById( + projectId: Types.ObjectId | string, + userId: Types.ObjectId | string +) { + const result = await transitionProjectById(projectId, userId, ['archive'], 'active'); + return result; +} + +// Future Possible Functions: ArchiveManyProjectsByIds, DeleteManyProjectsByIds +// Remember to handle visibility changes when archiving or deleting projects diff --git a/src/modules/project/rules/projectStatus.ts b/src/modules/project/rules/projectStatus.ts new file mode 100644 index 0000000..5c6c4aa --- /dev/null +++ b/src/modules/project/rules/projectStatus.ts @@ -0,0 +1,21 @@ +export const ACTIVE_STATUSES: ['active', 'draft'] = ['active', 'draft']; +export const NON_DELETED_STATUSES: ['active', 'draft', 'archive'] = ['active', 'draft', 'archive']; + +export type ProjectStatus = 'draft' | 'active' | 'archive' | 'delete'; +export type TransitionableManyProjectStatus = ProjectStatus[]; + +export function canTransition( + from: 'draft' | 'active' | 'archive' | 'delete', + to: 'draft' | 'active' | 'archive' | 'delete' +) { + const allowed = { + draft: ['active', 'delete'], + active: ['archive', 'delete'], + archive: ['active', 'delete'], + delete: ['active'], + }; + return allowed[from]?.includes(to); +} + +// When Deleting or Archiving a project, set visibility to private +// Additional status rules can be added here as needed diff --git a/src/modules/project/utils/transitionManyProjectsByIds.ts b/src/modules/project/utils/transitionManyProjectsByIds.ts new file mode 100644 index 0000000..93e6530 --- /dev/null +++ b/src/modules/project/utils/transitionManyProjectsByIds.ts @@ -0,0 +1,61 @@ +import { ProjectModel } from '@models/Project.js'; +import { Types } from 'mongoose'; +import { ProjectStatus, TransitionableManyProjectStatus } from '../rules/projectStatus.js'; + +export const transitionManyProjectsByIds = async ( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string, + fromStatuses: TransitionableManyProjectStatus, + toStatus: ProjectStatus +) => { + const normalizedIds = projectIds.map((id) => ({ + raw: id, + isValid: Types.ObjectId.isValid(id), + objectId: Types.ObjectId.isValid(id) ? new Types.ObjectId(id) : null, + })); + + const validObjectIds = normalizedIds.filter((i) => i.isValid).map((i) => i.objectId!); + + const projects = await ProjectModel.find({ + _id: { $in: validObjectIds }, + userId, + }).select('_id status'); + + const projectMap = new Map(projects.map((p) => [p._id.toString(), p.status])); + + const results: { id: string; message: string }[] = []; + const idsToUpdate: Types.ObjectId[] = []; + + for (const item of normalizedIds) { + const idStr = String(item.raw); + + if (!item.isValid) { + results.push({ id: idStr, message: 'Invalid project ID' }); + continue; + } + + const status = projectMap.get(item.objectId!.toString()); + + if (!status) { + results.push({ id: idStr, message: 'Project not found or not accessible' }); + continue; + } + + if (!fromStatuses.includes(status)) { + results.push({ + id: idStr, + message: `Project not in allowed state (${fromStatuses.join(', ')})`, + }); + continue; + } + + idsToUpdate.push(item.objectId!); + results.push({ id: idStr, message: 'Updated successfully' }); + } + + if (idsToUpdate.length > 0) { + await ProjectModel.updateMany({ _id: { $in: idsToUpdate } }, { $set: { status: toStatus } }); + } + + return results; +}; diff --git a/src/modules/project/utils/transitionProjectById.ts b/src/modules/project/utils/transitionProjectById.ts new file mode 100644 index 0000000..c59cdb8 --- /dev/null +++ b/src/modules/project/utils/transitionProjectById.ts @@ -0,0 +1,51 @@ +import { BadRequestError, ConflictError, NotFoundError } from "@middleware/error/index.js"; +import { sanitizeProjectResponse } from "@utils/sanitizeProjectResponse.js"; +import { canTransition, ProjectStatus } from "../rules/projectStatus.js"; +import { ProjectModel } from "@models/Project.js"; +import { Types } from "mongoose"; + +export async function transitionProjectById( + projectId: Types.ObjectId | string, + userId: Types.ObjectId | string, + fromStatuses: ProjectStatus[], + toStatus: ProjectStatus +) { + const project = await ProjectModel.findOne({ + _id: projectId, + userId, + status: { $in: fromStatuses }, + }); + + if (!project) { + throw new NotFoundError("Project is not found"); + } + + if ( + toStatus !== project.status && + !canTransition( + project.status, + toStatus + ) + ) { + throw new ConflictError( + `Cannot transition project status from ${project.status} to ${toStatus}` + ); + } + + if (toStatus === "active" && !project.defaultContextProfileId) { + throw new BadRequestError("Cannot activate a project without a default context profile"); + } + + project.status = toStatus; + + if (toStatus === "archive" || toStatus === "delete") { + project.visibility = "private"; + } + + await project.save(); + + return sanitizeProjectResponse({ + project, + type: "getProjectById", + }); +} diff --git a/src/modules/sceneAssets/sceneAssets.controller.ts b/src/modules/sceneAssets/sceneAssets.controller.ts new file mode 100644 index 0000000..0f395d8 --- /dev/null +++ b/src/modules/sceneAssets/sceneAssets.controller.ts @@ -0,0 +1,294 @@ +import { Request, Response } from 'express'; +import { + getAllAssetsForScene, + getAllDeletedAssets, + getAssetById, + getAssetCount, + getActiveAssetForScene, + setActiveAsset, + restoreAsset, + bulkRestoreAssets, + restoreAllDeletedAssets, + uploadVideoAsset, + uploadImageAsset, + softDeleteAllAssetsForScene, + permanentDeleteAllAssetsForScene, + softBulkDeleteAssets, + permanentBulkDeleteAssets, + softDeleteAsset, + permanentDeleteAsset, + forceDeleteActiveAsset, + generateVideoAsset, +} from './sceneAssets.service.js'; +import type { + BulkDeleteAssetsInput, + BulkRestoreAssetsInput, + SetActiveAssetInput, +} from '@validation/sceneAssets.schema.js'; +import { paginationResponse } from '@utils/paginationResponse.js'; + +// All Op controllers +export const getAllAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const pagination = req?.pagination; + const sorting = req?.sorting; + + const [assets, total] = await getAllAssetsForScene(userId, sceneId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + res.status(200).json({ + message: 'Assets retrieved successfully', + data: assets, + pagination: paginationRes, + }); +}; + +export const getAllDeletedAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const pagination = req?.pagination; + const sorting = req?.sorting; + + const [assets, total] = await getAllDeletedAssets(userId, sceneId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + res.status(200).json({ + message: 'Deleted assets retrieved successfully', + data: assets, + pagination: paginationRes, + }); +}; + +export const restoreAllDeletedAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const result = await restoreAllDeletedAssets(userId, sceneId); + + res.status(200).json({ + message: 'All deleted assets restored successfully', + restoredCount: result.restoredCount, + }); +}; + +export const softDeleteAllAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const result = await softDeleteAllAssetsForScene(userId, sceneId); + + res.status(200).json({ + message: 'All assets safe deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const permanentDeleteAllAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const result = await permanentDeleteAllAssetsForScene(userId, sceneId); + res.status(200).json({ + message: 'All assets deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const getAssetCountController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const count = await getAssetCount(userId, sceneId); + + res.status(200).json({ + message: 'Asset count retrieved successfully', + count, + }); +}; + +// Bulk Op controllers +export const softBulkDeleteAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetIds } = req.validatedBody as BulkDeleteAssetsInput; + + const result = await softBulkDeleteAssets(userId, sceneId, assetIds); + + res.status(200).json({ + message: 'Assets safe deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const permanentBulkDeleteAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetIds } = req.validatedBody as BulkDeleteAssetsInput; + + const result = await permanentBulkDeleteAssets(userId, sceneId, assetIds); + + res.status(200).json({ + message: 'Assets safe deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const bulkRestoreAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetIds } = req.validatedBody as BulkRestoreAssetsInput; + + const result = await bulkRestoreAssets(userId, sceneId, assetIds); + + res.status(200).json({ + message: 'Assets restored successfully', + data: result, + }); +}; + +// Single Op controllers +export const getAssetByIdController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + const asset = await getAssetById(userId, assetId); + + res.status(200).json({ + message: 'Asset retrieved successfully', + data: asset, + }); +}; + +export const getActiveAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const asset = await getActiveAssetForScene(userId, sceneId); + + if (!asset) { + return res.status(200).json({ + message: 'No active asset found for this scene', + data: null, + }); + } + + res.status(200).json({ + message: 'Active asset retrieved successfully', + data: asset, + }); +}; + +export const generateVideoAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const response = await generateVideoAsset(userId, sceneId); + res.status(201).json({ + message: 'Video asset generated successfully', + data: { + sceneId, + filename: response.url, + }, + }); +}; + +export const generateImageAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; +}; + +export const uploadVideoAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const file = req.file; + if (!file) { + return res.status(400).json({ message: 'No video file uploaded' }); + } + + const response = await uploadVideoAsset(userId, sceneId, file); + + res.status(201).json({ + message: 'Video asset uploaded successfully', + data: { + sceneId, + filename: response.videoUrl, + }, + }); +}; + +export const uploadImageAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const file = req.file; + if (!file) { + return res.status(400).json({ message: 'No image file uploaded' }); + } + + const response = await uploadImageAsset(userId, sceneId, file); + + res.status(201).json({ + message: 'Image asset uploaded successfully', + data: { + sceneId, + filename: file.originalname, + }, + }); +}; + +export const setActiveAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetId } = req.validatedBody as SetActiveAssetInput; + + const asset = await setActiveAsset(userId, sceneId, assetId); + + res.status(200).json({ + message: 'Active asset set successfully', + data: asset, + }); +}; + +export const softDeleteAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + const asset = await softDeleteAsset(userId, assetId); + res.status(200).json({ + message: 'Asset safe deleted successfully', + data: asset, + }); +}; + +export const permanentDeleteAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + const asset = await permanentDeleteAsset(userId, assetId); + res.status(200).json({ + message: 'Asset deleted successfully', + data: asset, + }); +}; + +export const forceDeleteActiveAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + await forceDeleteActiveAsset(userId, assetId); + res.status(200).json({ + message: 'Asset deleted successfully', + data: true, + }); +}; + +export const restoreAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + const asset = await restoreAsset(userId, assetId); + + res.status(200).json({ + message: 'Asset restored successfully', + data: asset, + }); +}; diff --git a/src/modules/sceneAssets/sceneAssets.private.routes.ts b/src/modules/sceneAssets/sceneAssets.private.routes.ts new file mode 100644 index 0000000..28d0857 --- /dev/null +++ b/src/modules/sceneAssets/sceneAssets.private.routes.ts @@ -0,0 +1,152 @@ +import { Router } from 'express'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { validateParams } from '@validation/validateParams.js'; +import { validateBody } from '@validation/validateBody.js'; + +import { + sceneIdParamSchema, + sceneAssetIdParamSchema, + sceneAssetAndSceneParamSchema, + // bulkDeleteAssetsSchema, + bulkRestoreAssetsSchema, + setActiveAssetSchema, + bulkDeleteAssetsSchema, +} from '@validation/sceneAssets.schema.js'; + +import { + getAllAssetsController, + getAllDeletedAssetsController, + getAssetByIdController, + getAssetCountController, + getActiveAssetController, + setActiveAssetController, + uploadVideoAssetController, + uploadImageAssetController, + softDeleteAssetController, + softBulkDeleteAssetsController, + softDeleteAllAssetsController, + permanentDeleteAssetController, + permanentBulkDeleteAssetsController, + permanentDeleteAllAssetsController, + forceDeleteActiveAssetController, + restoreAssetController, + bulkRestoreAssetsController, + restoreAllDeletedAssetsController, + generateVideoAssetController, + generateImageAssetController, +} from './sceneAssets.controller.js'; +import multer from 'multer'; +import { videoAssetUpload } from '@middleware/multer/videoAssetUpload.js'; +import { imageAssetUpload } from '@middleware/multer/imageAssetUpload.js'; +import { paginationAndSortingMiddleware } from '@middleware/request/paginationAndSorting.js'; + +const router = Router(); + +// All Op routes +router.get( + '/:sceneId', + validateParams(sceneIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllAssetsController) +); +router.get( + '/:sceneId/deleted', + validateParams(sceneIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllDeletedAssetsController) +); +router.get('/:sceneId/count', validateParams(sceneIdParamSchema), asyncHandler(getAssetCountController)); + +router.delete('/:sceneId/', validateParams(sceneIdParamSchema), asyncHandler(softDeleteAllAssetsController)); + +router.delete( + '/:sceneId/permanent', + validateParams(sceneIdParamSchema), + asyncHandler(permanentDeleteAllAssetsController) +); + +router.post( + '/:sceneId/restore', + validateParams(sceneIdParamSchema), + asyncHandler(restoreAllDeletedAssetsController) +); + +// Bulk Op routes +router.post( + '/:sceneId/soft-bulk-delete', + validateParams(sceneIdParamSchema), + validateBody(bulkDeleteAssetsSchema), + asyncHandler(softBulkDeleteAssetsController) +); + +router.post( + '/:sceneId/permanent-bulk-delete', + validateParams(sceneIdParamSchema), + validateBody(bulkDeleteAssetsSchema), + asyncHandler(permanentDeleteAllAssetsController) +); + +router.post( + '/:sceneId/bulk-restore', + validateParams(sceneIdParamSchema), + validateBody(bulkRestoreAssetsSchema), + asyncHandler(bulkRestoreAssetsController) +); + +// Single Op routes +router.get('/:assetId', validateParams(sceneAssetIdParamSchema), asyncHandler(getAssetByIdController)); + +router.get('/:sceneId/active', validateParams(sceneIdParamSchema), asyncHandler(getActiveAssetController)); + +router.post( + '/:sceneId/generate/video', + validateParams(sceneIdParamSchema), + asyncHandler(generateVideoAssetController) +); + +router.post( + '/:sceneId/generate/image', + validateParams(sceneIdParamSchema), + asyncHandler(generateImageAssetController) +); + +router.post( + '/:sceneId/upload-video', + validateParams(sceneIdParamSchema), + videoAssetUpload, + asyncHandler(uploadVideoAssetController) +); + +router.post( + '/:sceneId/upload-image', + validateParams(sceneIdParamSchema), + imageAssetUpload, + asyncHandler(uploadImageAssetController) +); + +router.patch( + '/:sceneId/:assetId/set-active', + validateParams(sceneAssetAndSceneParamSchema), + validateBody(setActiveAssetSchema), + asyncHandler(setActiveAssetController) +); + +router.delete('/:assetId', validateParams(sceneAssetIdParamSchema), asyncHandler(softDeleteAssetController)); +router.delete( + '/:assetId/permanent', + validateParams(sceneAssetIdParamSchema), + asyncHandler(permanentDeleteAssetController) +); +router.delete( + '/:assetId/force', + validateParams(sceneAssetIdParamSchema), + asyncHandler(forceDeleteActiveAssetController) +); + +router.patch( + '/:sceneId/:assetId/restore', + validateParams(sceneAssetAndSceneParamSchema), + asyncHandler(restoreAssetController) +); + +export default router; diff --git a/src/modules/sceneAssets/sceneAssets.service.ts b/src/modules/sceneAssets/sceneAssets.service.ts new file mode 100644 index 0000000..cb12143 --- /dev/null +++ b/src/modules/sceneAssets/sceneAssets.service.ts @@ -0,0 +1,536 @@ +import fs from 'fs/promises'; +import { SceneAssetModel, SceneAsset } from '@models/SceneAssets.js'; +import { SceneModel } from '@models/Scene.js'; +import { NotFoundError, BadRequestError, ConflictError } from '@middleware/error/index.js'; +import mongoose, { ClientSession } from 'mongoose'; +import type { Pagination, Sorting } from 'types/Pagination.js'; +import { getVideoDuration } from '@utils/getVideoDuration.js'; +import { assertFeaturePermission } from '@modules/featurePermission/featurePermission.service.js'; +import { getCreditCost } from '@utils/getCreditCost.js'; +import { consumeCredits } from '@modules/credit/credit.service.js'; +import { validateSceneOwnership } from 'validators/validateSceneOwnership.js'; +import { validateAssetOwnership } from 'validators/validateAssetOwnership.js'; +import { validateUser } from 'validators/validateUser.js'; +import { + assertAssetIsDeleted, + assertAssetNotDeleted, + assertHasDeletedAssets, + assertHasNonDeletedAssets, +} from 'domain/assertions/assertAssetState.js'; +import { withTransaction } from '@db/withTransaction.js'; + +// Get the next version number for an asset in a scene +async function getNextVersionNumber(sceneId: string, session?: ClientSession): Promise { + const query = SceneAssetModel.findOne({ sceneId }).sort({ version: -1 }).select('version'); + + if (session) query.session(session); + + const lastAsset = await query; + return lastAsset ? lastAsset.version + 1 : 1; +} + +// All Op services +export async function getAllAssetsForScene( + userId: string, + sceneId: string, + pagination: Pagination, + sorting: Sorting +): Promise<[SceneAsset[], number]> { + const { page, limit, skip } = pagination; + const { sortBy, sortOrder } = sorting; + const [assets, total] = await Promise.all([ + SceneAssetModel.find({ + sceneId, + userId, + deletedAt: { $exists: false }, + }) + .sort(sortBy ? { [sortBy]: sortOrder } : { createdAt: -1 }) + .skip(skip) + .limit(limit), + SceneAssetModel.countDocuments({ + sceneId, + userId, + deletedAt: { $exists: false }, + }), + ]); + return [assets, total]; +} + +export async function getAllDeletedAssets( + userId: string, + sceneId: string, + pagination: Pagination, + sorting: Sorting +): Promise<[SceneAsset[], number]> { + const { page, limit, skip } = pagination; + const { sortBy, sortOrder } = sorting; + const [assets, total] = await Promise.all([ + SceneAssetModel.find({ + sceneId, + userId, + deletedAt: { $exists: true }, + }) + .sort(sortBy ? { [sortBy]: sortOrder } : { createdAt: -1 }) + .skip(skip) + .limit(limit), + SceneAssetModel.countDocuments({ + sceneId, + userId, + deletedAt: { $exists: true }, + }), + ]); + return [assets, total]; +} + +export async function restoreAllDeletedAssets( + userId: string, + sceneId: string +): Promise<{ restoredCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assetsToRestore = await SceneAssetModel.find({ + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + assertHasDeletedAssets(assetsToRestore); + + const bulkOps = assetsToRestore.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $unset: { deletedAt: 1 } }, + }, + })); + const result = await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { restoredCount: result.modifiedCount }; + }); +} + +export async function softDeleteAllAssetsForScene( + userId: string, + sceneId: string +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assetsToDelete = await SceneAssetModel.find({ + userId, + sceneId, + deletedAt: { $exists: false }, + }).session(session); + + assertHasNonDeletedAssets(assetsToDelete); + + const scenes = await SceneModel.find({ + activeAssetId: { $in: assetsToDelete.map((a) => a._id) }, + }).session(session); + if (scenes.length > 0) { + throw new BadRequestError( + `Cannot delete an active asset. Please unset it as active from ${scenes.map((s) => s._id).join(', ')} before deletion or Force delete instead.` + ); + } + + const bulkOps = assetsToDelete.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $set: { deletedAt: new Date() } }, + }, + })); + + const result = await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: result.modifiedCount }; + }); +} + +export async function permanentDeleteAllAssetsForScene( + userId: string, + sceneId: string +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assetsToDelete = await SceneAssetModel.find({ + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + + assertHasDeletedAssets(assetsToDelete); + + const bulkOps = assetsToDelete.map((asset) => ({ + deleteOne: { filter: { _id: asset._id } }, + })); + + const result = await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: result.deletedCount || 0 }; + }); +} + +export async function getAssetCount(userId: string, sceneId: string): Promise { + await validateSceneOwnership(userId, sceneId); + + const count = await SceneAssetModel.countDocuments({ + sceneId, + userId, + deletedAt: { $exists: false }, + }); + + return count; +} + +// Bulk Op services +export async function softBulkDeleteAssets( + userId: string, + sceneId: string, + assetIds: string[] +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + sceneId, + deletedAt: { $exists: false }, + }).session(session); + + if (assets.length !== assetIds.length) { + throw new BadRequestError('Some assets were not found or already deleted'); + } + + const scenes = await SceneModel.find({ + activeAssetId: { $in: assetIds }, + }).session(session); + if (scenes.length > 0) { + throw new BadRequestError( + `Cannot delete an active asset. Please unset it as active from ${scenes.map((s) => s._id).join(', ')} before deletion or Force delete instead.` + ); + } + + const bulkOps = assets.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $set: { deletedAt: new Date() } }, + }, + })); + + await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: assets.length }; + }); +} + +export async function permanentBulkDeleteAssets( + userId: string, + sceneId: string, + assetIds: string[] +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + + if (assets.length !== assetIds.length) { + throw new BadRequestError('Some assets were not found'); + } + + const bulkOps = assets.map((asset) => ({ + deleteOne: { filter: { _id: asset._id } }, + })); + + await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: assets.length }; + }); +} + +export async function bulkRestoreAssets( + userId: string, + sceneId: string, + assetIds: string[] +): Promise { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + + if (assets.length !== assetIds.length) { + throw new BadRequestError('Some assets were not found or not deleted'); + } + + const bulkOps = assets.map((asset, index) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { + $unset: { deletedAt: 1 }, + }, + }, + })); + await SceneAssetModel.bulkWrite(bulkOps, { session }); + + const restoredAssets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + }) + .sort({ order: 1 }) + .lean() + .session(session); + await session.commitTransaction(); + return restoredAssets; + }); +} + +// Single Op services +export async function getAssetById(userId: string, assetId: string): Promise { + const asset = await validateAssetOwnership(userId, assetId); + return asset; +} + +export async function getActiveAssetForScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + + if (!scene.activeAssetId) { + return null; + } + + const asset = await SceneAssetModel.findOne({ + _id: scene.activeAssetId, + userId, + deletedAt: { $exists: false }, + }); + + if (!asset) { + throw new ConflictError('The Asset does not exists'); + } + + return asset; +} + +export async function generateVideoAsset( + userId: string, + sceneId: string, + grade?: number +): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + try { + const scene = await validateSceneOwnership(userId, sceneId, session); + const user = await validateUser(userId, session); + + if (user.planEndsAt && user.planEndsAt <= new Date()) { + throw new BadRequestError('Plan has expired. Please renew to generate new assets.'); + } + + // wait and check plan permissions + await assertFeaturePermission({ + userId: user._id, + action: 'TXT_TO_VIDEO_GEN', + grade: grade || 1, + }); + + // Deduct credits if applicable + if (grade && grade > 1) { + const creditsUsed = await getCreditCost('TXT_TO_VIDEO_GEN', grade); + await consumeCredits(userId, creditsUsed, session); + } + + // Placeholder logic for video generation + const generatedVideoUrl = `/generated/videos/${sceneId}-${Date.now()}.mp4`; + const asset = new SceneAssetModel({ + userId, + sceneId, + type: 'video', + url: generatedVideoUrl, + visibility: 'public', + generationSource: 'ai', + version: await getNextVersionNumber(sceneId), + }); + await asset.save(); + return asset; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function generateImageAsset(userId: string, sceneId: string) { + const scene = await validateSceneOwnership(userId, sceneId); + // Placeholder logic for image generation +} + +export async function uploadVideoAsset( + userId: string, + sceneId: string, + file: Express.Multer.File +): Promise<{ asset: SceneAsset; videoUrl: string }> { + const scene = await validateSceneOwnership(userId, sceneId); + let duration: number; + + try { + duration = await getVideoDuration(file.path); + } catch { + await fs.unlink(file.path); + throw new BadRequestError('Invalid or corrupted video file'); + } + + console.log('Video duration:', duration, 'Scene duration:', scene.duration); + console.log('Difference:', Math.abs(duration - (scene.duration || 0))); + + if (scene.duration !== undefined && Math.abs(duration - scene.duration) > 0.25) { + await fs.unlink(file.path); + throw new BadRequestError('Video duration does not match existing scene duration and cannot be uploaded'); + } + // TODO: Add video to cloud storage here and get the URL + const videoUrl = `/uploads/videos/${file.filename}`; + const asset = new SceneAssetModel({ + userId, + sceneId, + type: 'video', + url: videoUrl, + visibility: 'public', + format: file.mimetype.split('/')[1] || undefined, + version: await getNextVersionNumber(sceneId), + duration, + }); + await asset.save(); + + await fs.unlink(file.path); + + return { asset, videoUrl }; +} + +export async function uploadImageAsset( + userId: string, + sceneId: string, + file: Express.Multer.File +): Promise { + await validateSceneOwnership(userId, sceneId); + //TODO: Add Image to cloud storage and get URL + const imageUrl = `/uploads/images/${file.filename}`; + const asset = new SceneAssetModel({ + userId, + sceneId, + type: 'image', + url: imageUrl, + visibility: 'public', + format: file.mimetype.split('/')[1] || undefined, + version: await getNextVersionNumber(sceneId), + }); + await asset.save(); + + await fs.unlink(file.path); + + return asset; +} + +export async function setActiveAsset(userId: string, sceneId: string, assetId: string): Promise { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + const asset = await validateAssetOwnership(userId, assetId, session); + assertAssetNotDeleted(asset); + + await SceneModel.findByIdAndUpdate(sceneId, { activeAssetId: assetId }, { session }); + + return asset; + }); +} + +export async function softDeleteAsset(userId: string, assetId: string): Promise { + return withTransaction(async (session) => { + const asset = await validateAssetOwnership(userId, assetId, session); + assertAssetNotDeleted(asset); + + const activeAssetScenes = await SceneModel.find({ + activeAssetId: assetId, + }).session(session); + + if (activeAssetScenes.length > 0) { + throw new BadRequestError( + `Cannot delete an active asset. Please unset it as active from ${activeAssetScenes.map((scene) => scene._id).join(', ')} before deletion.` + ); + } + + await SceneAssetModel.findByIdAndUpdate(assetId, { deletedAt: new Date() }, { new: true, session }); + + await session.commitTransaction(); + return; + }); +} + +export async function forceDeleteActiveAsset(userId: string, assetId: string): Promise { + const asset = await validateAssetOwnership(userId, assetId); + const scene = await validateSceneOwnership(userId, asset.sceneId.toString()); + assertAssetNotDeleted(asset); + + if (scene.activeAssetId && scene.activeAssetId.equals(asset._id)) { + await SceneModel.findByIdAndUpdate( + asset.sceneId, + { + $unset: { activeAssetId: 1 }, + }, + { runValidators: true } + ); + } + await SceneAssetModel.findByIdAndUpdate(assetId, { deletedAt: new Date() }, { new: true }); + return; +} + +export async function permanentDeleteAsset(userId: string, assetId: string): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + try { + const asset = await validateAssetOwnership(userId, assetId, session); + assertAssetNotDeleted(asset); + const activeAssetScenes = await SceneModel.find({ + activeAssetId: assetId, + }).session(session); + for (const scene of activeAssetScenes) { + await SceneModel.findByIdAndUpdate(scene._id, { $unset: { activeAssetId: 1 } }, { session }); + } + const deletedAsset = await SceneAssetModel.findByIdAndUpdate( + assetId, + { deletedAt: new Date() }, + { new: true, session } + ); + await session.commitTransaction(); + return deletedAsset!; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function restoreAsset(userId: string, assetId: string): Promise { + const asset = await validateAssetOwnership(userId, assetId); + assertAssetIsDeleted(asset); + + const restoredAsset = await SceneAssetModel.findByIdAndUpdate( + assetId, + { $unset: { deletedAt: 1 } }, + { new: true } + ); + + if (!restoredAsset) { + throw new NotFoundError('Asset not found'); + } + + return restoredAsset; +} diff --git a/src/modules/scenes/scenes.controller.ts b/src/modules/scenes/scenes.controller.ts index e69de29..772b6b8 100644 --- a/src/modules/scenes/scenes.controller.ts +++ b/src/modules/scenes/scenes.controller.ts @@ -0,0 +1,335 @@ +import { Request, Response } from 'express'; +import { + createScene, + getSceneById, + getAllScenesForStory, + updateScene, + softDeleteScene, + permanentDeleteScene, + restoreScene, + bulkReorder, + generateSceneWithAI, + regenerateScene, + generateAllScenes, + regenerateAllScenes, + moveSceneByOne, + getSceneCount, + softdeleteAllScenes, + restoreAllDeletedScenes, + permanentDeleteAllScenes, + bulkRestoreScenes, + bulkSoftdeleteScenes, + bulkPermanentDeleteScenes, + updateSceneDuration, + getAllDeletedScenes, + reactivateScene, + getAllInactiveScenesForStory, + deactivateScene, +} from './scenes.service.js'; +import type { + CreateSceneInput, + UpdateSceneInput, + MoveSceneInput, + BulkReorderInput, + GenerateSceneInput, + RegenerateSceneInput, + GenerateAllScenesInput, + BulkRestoreInput, + DurationInput, +} from '@validation/scenes.schema.js'; + +// All SCENES CONTROLLERS +export const getAllStoryScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const scenes = await getAllScenesForStory(userId, storyId); + + res.status(200).json({ + message: 'Scenes retrieved successfully', + data: scenes, + }); +}; + +export const getAllInactiveStoryScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const scenes = await getAllInactiveScenesForStory(userId, storyId); + res.status(200).json({ + message: 'Inactive scenes retrieved successfully', + data: scenes, + }); +}; + +export const getAllDeletedScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const scenes = await getAllDeletedScenes(userId, storyId); + + res.status(200).json({ + message: 'Scenes retrieved successfully', + data: scenes, + }); +}; + +export const softDeleteAllScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const scenes = await softdeleteAllScenes(userId, storyId); + res.status(200).json({ + message: 'All scenes soft deleted successfully', + data: scenes, + }); +}; + +export const permanentDeleteAllScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const deletedCount = await permanentDeleteAllScenes(userId, storyId); + res.status(200).json({ + message: 'All deleted scenes permanently deleted successfully', + data: { deletedCount }, + }); +}; + +export const restoreAllDeletedScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const scenes = await restoreAllDeletedScenes(userId, storyId); + res.status(200).json({ + message: 'All deleted scenes restored successfully', + data: scenes, + }); +}; + +export const generateScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const { total } = req.validatedBody as GenerateAllScenesInput; + + const scenes = await generateAllScenes(userId, storyId, total); + + res.status(200).json({ + message: 'Scenes generated successfully', + data: scenes, + }); +}; + +export const regenerateScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const { extraPrompt } = (req.validatedBody as RegenerateSceneInput) || {}; + + const scenes = await regenerateAllScenes(userId, storyId, extraPrompt); + + res.status(200).json({ + message: 'Scenes regenerated successfully', + data: scenes, + }); +}; + +// BULK SCENES CONTROLLERS + +export const bulkReorderController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const payload = req.validatedBody as BulkReorderInput; + + const scenes = await bulkReorder(userId, storyId, payload); + + res.status(200).json({ + message: 'Scenes reordered successfully', + data: scenes, + }); +}; + +export const bulkRestoreScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const { sceneIds } = req.validatedBody as BulkRestoreInput; + const restoredScenes = await bulkRestoreScenes(userId, storyId, sceneIds); + res.status(200).json({ + message: 'Scenes restored successfully', + data: restoredScenes, + }); +}; + +export const bulkSoftDeleteScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const { sceneIds } = req.validatedBody as BulkRestoreInput; + const deletedScenes = await bulkSoftdeleteScenes(userId, storyId, sceneIds); + res.status(200).json({ + message: 'Scenes soft deleted successfully', + data: deletedScenes, + }); +}; + +export const bulkPermanentDeleteScenesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const { sceneIds } = req.validatedBody as BulkRestoreInput; + const deletedCount = await bulkPermanentDeleteScenes(userId, storyId, sceneIds); + res.status(200).json({ + message: 'Scenes permanently deleted successfully', + data: { deletedCount }, + }); +}; + +// SINGLE SCENE CONTROLLERS + +export const getSceneByIdController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { storyId, sceneId } = req.params; + + const scene = await getSceneById(userId, storyId, sceneId); + + res.status(200).json({ + message: 'Scene retrieved successfully', + data: scene, + }); +}; + +export const createSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const payload = req.validatedBody as CreateSceneInput; + + const scene = await createScene(userId, storyId, payload, payload.position); + + res.status(201).json({ + message: 'Scene created successfully', + data: scene, + }); +}; + +export const generateSingleSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const payload = req.validatedBody as GenerateSceneInput; + + const scene = await generateSceneWithAI(userId, storyId, payload); + + res.status(201).json({ + message: 'Scene generated successfully', + data: scene, + }); +}; + +export const regenerateSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + const payload = req.validatedBody as RegenerateSceneInput; + + const scene = await regenerateScene(userId, sceneId, payload); + + res.status(200).json({ + message: 'Scene regenerated successfully', + data: scene, + }); +}; + +export const updateSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + const payload = req.validatedBody as UpdateSceneInput; + + const scene = await updateScene(userId, sceneId, payload); + + res.status(200).json({ + message: 'Scene updated successfully', + data: scene, + }); +}; + +export const updateSceneDurationController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + const storyId = req.params.storyId; + const { duration } = req.validatedBody as DurationInput; + const scene = await updateSceneDuration(userId, storyId, sceneId, duration); + res.status(200).json({ + message: 'Scene duration updated successfully', + data: scene, + }); +}; + +export const softDeleteSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + + const deleted = await softDeleteScene(userId, sceneId); + + res.status(200).json({ + message: 'Scene deleted successfully', + data: { deleted }, + }); +}; + +export const permanentDeleteSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + const deleted = await permanentDeleteScene(userId, sceneId); + res.status(200).json({ + message: 'Scene permanently deleted successfully', + data: { deleted }, + }); +}; + +export const restoreSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + + const scene = await restoreScene(userId, sceneId); + + res.status(200).json({ + message: 'Scene restored successfully', + data: scene, + }); +}; + +export const reactivateSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + const scene = await reactivateScene(userId, sceneId); + res.status(200).json({ + message: 'Scene reactivated successfully', + data: scene, + }); +}; + +export const deactivateSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + const scene = await deactivateScene(userId, sceneId); + res.status(200).json({ + message: 'Scene deactivated successfully', + data: scene, + }); +}; + +export const moveSceneController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const sceneId = req.params.sceneId; + const { direction } = req.validatedBody as MoveSceneInput; + + const scene = await moveSceneByOne(userId, sceneId, direction); + + res.status(200).json({ + message: 'Scene moved successfully', + data: scene, + }); +}; + +export const getSceneCountController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const count = await getSceneCount(userId, storyId); + + res.status(200).json({ + message: 'Scene count retrieved successfully', + data: { count }, + }); +}; diff --git a/src/modules/scenes/scenes.private.routes.ts b/src/modules/scenes/scenes.private.routes.ts new file mode 100644 index 0000000..5c2e119 --- /dev/null +++ b/src/modules/scenes/scenes.private.routes.ts @@ -0,0 +1,209 @@ +import { Router } from 'express'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { validateParams } from '@validation/validateParams.js'; +import { validateBody } from '@validation/validateBody.js'; + +import { + storyIdParamSchema, + sceneAndStoryParamSchema, + createSceneSchema, + updateSceneSchema, + moveSceneSchema, + bulkReorderSchema, + bulkRestoreSchema, + generateSceneSchema, + regenerateSceneSchema, + generateAllScenesSchema, + durationSchema, +} from '@validation/scenes.schema.js'; + +import { + getAllStoryScenesController, + getAllInactiveStoryScenesController, + getAllDeletedScenesController, + getSceneByIdController, + createSceneController, + updateSceneController, + softDeleteSceneController, + permanentDeleteAllScenesController, + restoreSceneController, + moveSceneController, + bulkReorderController, + bulkRestoreScenesController, + bulkSoftDeleteScenesController, + bulkPermanentDeleteScenesController, + restoreAllDeletedScenesController, + softDeleteAllScenesController, + permanentDeleteSceneController, + generateScenesController, + regenerateScenesController, + generateSingleSceneController, + regenerateSceneController, + getSceneCountController, + updateSceneDurationController, + deactivateSceneController, + reactivateSceneController, +} from './scenes.controller.js'; + +const router = Router(); + +// ALL SCENES ROUTES FOR A STORY + +router.get('/:storyId', validateParams(storyIdParamSchema), asyncHandler(getAllStoryScenesController)); +router.get( + '/:storyId/inactive', + validateParams(storyIdParamSchema), + asyncHandler(getAllInactiveStoryScenesController) +); + +router.get( + '/:storyId/deleted', + validateParams(storyIdParamSchema), + asyncHandler(getAllDeletedScenesController) +); + +router.get('/:storyId/count', validateParams(storyIdParamSchema), asyncHandler(getSceneCountController)); + +router.post( + '/:storyId/scenes/restore-all', + validateParams(storyIdParamSchema), + asyncHandler(restoreAllDeletedScenesController) +); + +router.delete( + '/:storyId/scenes/soft', + validateParams(storyIdParamSchema), + asyncHandler(softDeleteAllScenesController) +); + +router.delete( + '/:storyId/scenes/permanent', + validateParams(storyIdParamSchema), + asyncHandler(permanentDeleteAllScenesController) +); + +// BULK SCENES ROUTES + +router.post( + '/:storyId/scenes/reorder', + validateParams(storyIdParamSchema), + validateBody(bulkReorderSchema), + asyncHandler(bulkReorderController) +); + +router.post( + '/:storyId/scenes/restore-bulk', + validateParams(storyIdParamSchema), + validateBody(bulkRestoreSchema), + asyncHandler(bulkRestoreScenesController) +); + +router.post( + '/:storyId/scenes/soft-delete-bulk', + validateParams(storyIdParamSchema), + validateBody(bulkRestoreSchema), + asyncHandler(bulkSoftDeleteScenesController) +); + +router.post( + '/:storyId/scenes/permanent-delete-bulk', + validateParams(storyIdParamSchema), + validateBody(bulkRestoreSchema), + asyncHandler(bulkPermanentDeleteScenesController) +); + +// SINGLE SCENE ROUTES + +router.post( + '/:storyId/generate', + validateParams(storyIdParamSchema), + validateBody(generateAllScenesSchema), + asyncHandler(generateScenesController) +); + +router.post( + '/:storyId/regenerate', + validateParams(storyIdParamSchema), + validateBody(regenerateSceneSchema), + asyncHandler(regenerateScenesController) +); + +router.get( + '/:storyId/scene/:sceneId', + validateParams(sceneAndStoryParamSchema), + asyncHandler(getSceneByIdController) +); + +router.post( + '/:storyId/scene', + validateParams(storyIdParamSchema), + validateBody(createSceneSchema), + asyncHandler(createSceneController) +); + +router.post( + '/:storyId/scene/generate', + validateParams(storyIdParamSchema), + validateBody(generateSceneSchema), + asyncHandler(generateSingleSceneController) +); + +router.patch( + '/:storyId/scene/:sceneId', + validateParams(sceneAndStoryParamSchema), + validateBody(updateSceneSchema), + asyncHandler(updateSceneController) +); + +router.patch( + '/:storyId/scene/:sceneId/duration', + validateParams(sceneAndStoryParamSchema), + validateBody(durationSchema), + asyncHandler(updateSceneDurationController) +); + +router.post( + '/:storyId/scene/:sceneId/deactivate', + validateParams(sceneAndStoryParamSchema), + asyncHandler(deactivateSceneController) +); + +router.post( + '/:storyId/scene/:sceneId/reactivate', + validateParams(sceneAndStoryParamSchema), + asyncHandler(reactivateSceneController) +); + +router.delete( + '/:storyId/scene/:sceneId/soft', + validateParams(sceneAndStoryParamSchema), + asyncHandler(softDeleteSceneController) +); + +router.delete( + '/:storyId/scene/:sceneId/permanent', + validateParams(sceneAndStoryParamSchema), + asyncHandler(permanentDeleteSceneController) +); + +router.post( + '/:storyId/scene/:sceneId/restore', + validateParams(sceneAndStoryParamSchema), + asyncHandler(restoreSceneController) +); + +router.patch( + '/:storyId/scene/:sceneId/move', + validateParams(sceneAndStoryParamSchema), + validateBody(moveSceneSchema), + asyncHandler(moveSceneController) +); + +router.post( + '/:storyId/scene/:sceneId/regenerate', + validateParams(sceneAndStoryParamSchema), + validateBody(regenerateSceneSchema), + asyncHandler(regenerateSceneController) +); + +export default router; diff --git a/src/modules/scenes/scenes.service.ts b/src/modules/scenes/scenes.service.ts index e69de29..5af28b0 100644 --- a/src/modules/scenes/scenes.service.ts +++ b/src/modules/scenes/scenes.service.ts @@ -0,0 +1,1001 @@ +import safeParseJSON from '@utils/safeParseJSON.js'; +import { SceneModel, Scene } from '@models/Scene.js'; +import { StoryModel } from '@models/Story.js'; +import { + NotFoundError, + ConflictError, + BadRequestError, + InternalServerError, +} from '@middleware/error/index.js'; +import mongoose, { ClientSession } from 'mongoose'; +import { SCENE_ORDER_GAP } from '@constants/sceneConsts.js'; +import type { + CreateSceneInput, + UpdateSceneInput, + BulkReorderInput, + RegenerateSceneInput, + GenerateSceneInput, + DurationInput, +} from '@validation/scenes.schema.js'; +import { singleScenePrompt } from '@libs/ai/prompts/singleScenePrompt.js'; +import { openRouterAI } from '@libs/ai/clients/openAI.js'; +import { ContextProfileModel } from '@models/ContextProfile.js'; +import { batchScenesPrompt } from '@libs/ai/prompts/batchScenesPrompt.js'; +import { validateStoryOwnership } from 'validators/validateStoryOwnership.js'; +import { withTransaction } from '@db/withTransaction.js'; +import { + assertHasDeletedScenes, + assertHasNonDeletedScenes, + assertSceneIsActive, + assertSceneIsDeleted, + assertSceneNotDeleted, +} from 'domain/assertions/assertSceneState.js'; +import { + validateSceneOwnership, + validateStorySceneOwnership, +} from 'validators/validateSceneOwnership.js'; +import e from 'express'; +import { validateUser } from 'validators/validateUser.js'; + +// -> Ordering Helpers +async function getNextOrderValue(storyId: string, session?: ClientSession): Promise { + const query = SceneModel.findOne({ storyId }).sort({ order: -1 }).select('order'); + + if (session) query.session(session); + + const lastScene = await query; + return lastScene ? lastScene.order + SCENE_ORDER_GAP : SCENE_ORDER_GAP; +} + +async function calculateOrderForPosition( + storyId: string, + position: number, + session?: ClientSession +): Promise { + const query = SceneModel.find({ storyId }).sort({ order: 1 }).select('order'); + + if (session) query.session(session); + + const scenes = await query; + + if (position >= scenes.length) { + return scenes.length > 0 ? scenes[scenes.length - 1].order + SCENE_ORDER_GAP : SCENE_ORDER_GAP; + } + + if (position === 0) { + const firstOrder = scenes[0]?.order ?? SCENE_ORDER_GAP; + const newOrder = Math.floor(firstOrder / 2); + return newOrder > 0 ? newOrder : null; + } + + const prevOrder = scenes[position - 1].order; + const nextOrder = scenes[position].order; + const midpoint = Math.floor((prevOrder + nextOrder) / 2); + + if (midpoint <= prevOrder || midpoint >= nextOrder) { + return null; + } + + return midpoint; +} + +async function reindexSceneOrders(storyId: string, session: ClientSession): Promise { + const scenes = await SceneModel.find({ storyId }).sort({ order: 1 }).select('_id').session(session); + + const bulkOps = scenes.map((scene, index) => ({ + updateOne: { + filter: { _id: scene._id }, + update: { $set: { order: (index + 1) * SCENE_ORDER_GAP } }, + }, + })); + + if (bulkOps.length > 0) { + await SceneModel.bulkWrite(bulkOps, { session }); + } +} + +// All scene services +export async function getSceneCount(userId: string, storyId: string): Promise { + await validateStoryOwnership(userId, storyId); + const count = await SceneModel.countDocuments({ + storyId, + userId, + deletedAt: { $exists: false }, + }); + return count; +} + +export async function getAllScenesForStory(userId: string, storyId: string): Promise { + await validateStoryOwnership(userId, storyId); + + const scenes = await SceneModel.find({ + storyId, + userId, + active: true, + deletedAt: { $exists: false }, + }).sort({ order: 1 }); + + return scenes; +} + +export async function getAllInactiveScenesForStory(userId: string, storyId: string): Promise { + await validateStoryOwnership(userId, storyId); + const scenes = await SceneModel.find({ + storyId, + userId, + active: false, + deletedAt: { $exists: false }, + }).sort({ order: 1 }); + return scenes; +} + +export async function getAllDeletedScenes(userId: string, storyId: string): Promise { + await validateStoryOwnership(userId, storyId); + const scenes = await SceneModel.find({ + storyId, + userId, + deletedAt: { $exists: true }, + }).sort({ order: 1 }); + return scenes; +} + +export async function generateAllScenes(userId: string, storyId: string, total: number): Promise { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + + const contextProfile = await ContextProfileModel.findOne({ + _id: story.contextProfileId, + }).session(session); + + const generateScenesPrompt = batchScenesPrompt({ + mode: 'generate', + storyTitle: story.title, + storyContent: { + summary: story.content.summary, + body: story.content.body, + keywords: story.content.keywords, + }, + totalScenes: total, + storyTimeLimit: story.timeLimit, + contextProfile, + intent: story.intent, + platform: story.platform, + }); + + let generatedScenesData: any; + + try { + const result = await openRouterAI(generateScenesPrompt); + const rawContent = result?.choices?.[0]?.message?.content; + + if (!rawContent || typeof rawContent !== 'string') { + throw new InternalServerError('AI generation failed'); + } + + generatedScenesData = safeParseJSON(rawContent); + } catch { + throw new InternalServerError('AI generation failed'); + } + + if (!generatedScenesData || !Array.isArray(generatedScenesData) || generatedScenesData.length !== total) { + throw new InternalServerError('AI returned invalid scene structure'); + } + + const existing = await SceneModel.find( + { storyId, userId, deletedAt: { $exists: false } }, + { _id: 1 } + ).session(session); + + const ops = existing.map((doc, i) => ({ + updateOne: { + filter: { _id: doc._id }, + update: { + $set: { + active: false, + order: -(Date.now() * 1000 + i), + }, + }, + }, + })); + + await SceneModel.bulkWrite(ops, { session }); + + const scenesToCreate = generatedScenesData.map((data: any, index: number) => ({ + userId, + storyId, + order: (index + 1) * SCENE_ORDER_GAP, + title: data.title, + description: data.description, + authorType: 'ai' as const, + imagePrompt: data.imagePrompt, + videoPrompt: data.videoPrompt, + duration: data.duration, + })); + + const scenes = (await SceneModel.insertMany(scenesToCreate, { + session, + ordered: true, + })) as Scene[]; + + return scenes; + }); +} + +export async function regenerateAllScenes( + userId: string, + storyId: string, + extraPrompt?: string +): Promise { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + + const existingScenes = await SceneModel.find({ + storyId, + userId, + deletedAt: { $exists: false }, + }) + .sort({ order: 1 }) + .lean() + .session(session); + + if (existingScenes.length === 0) { + throw new ConflictError('No scenes to regenerate'); + } + + const totalScenes = existingScenes.length; + + const contextProfile = await ContextProfileModel.findOne({ + _id: story.contextProfileId, + }).session(session); + + const regenerateScenesPrompt = batchScenesPrompt({ + mode: 'regenerate', + storyTitle: story.title, + storyContent: { + summary: story.content.summary, + body: story.content.body, + keywords: story.content.keywords, + }, + totalScenes, + storyTimeLimit: story.timeLimit, + contextProfile, + intent: story.intent, + platform: story.platform, + extraPrompt, + }); + + let regeneratedScenesData: any; + + try { + const result = await openRouterAI(regenerateScenesPrompt); + const rawContent = result?.choices?.[0]?.message?.content; + + if (!rawContent || typeof rawContent !== 'string') { + throw new InternalServerError('AI regeneration failed'); + } + + regeneratedScenesData = safeParseJSON(rawContent); + } catch { + throw new InternalServerError('AI regeneration failed'); + } + + if ( + !regeneratedScenesData || + !Array.isArray(regeneratedScenesData) || + regeneratedScenesData.length !== totalScenes + ) { + throw new InternalServerError('AI returned invalid scene structure'); + } + + const ops = existingScenes.map((doc, i) => ({ + updateOne: { + filter: { _id: doc._id }, + update: { + $set: { + active: false, + order: -(Date.now() * 1000 + i), + }, + }, + }, + })); + + await SceneModel.bulkWrite(ops, { session }); + + const scenesToCreate = regeneratedScenesData.map((data: any, index: number) => ({ + userId, + storyId, + order: (index + 1) * SCENE_ORDER_GAP, + title: data.title, + description: data.description, + authorType: 'ai' as const, + imagePrompt: data.imagePrompt, + videoPrompt: data.videoPrompt, + duration: data.duration, + })); + + const scenes = (await SceneModel.insertMany(scenesToCreate, { + session, + ordered: true, + })) as Scene[]; + + return scenes; + }); +} + +export async function restoreAllDeletedScenes(userId: string, storyId: string): Promise { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + const activeScenes = await SceneModel.find({ storyId, userId, deletedAt: { $exists: false } }) + .sort({ order: -1 }) + .lean() + .session(session); + const lastOrder = activeScenes[0]?.order ?? 0; + const scenesToRestore = await SceneModel.find({ + storyId, + userId, + deletedAt: { $exists: true }, + }).session(session); + + assertHasDeletedScenes(scenesToRestore); + + const bulkOps = scenesToRestore.map((scene, index) => ({ + updateOne: { + filter: { _id: scene._id }, + update: { + $unset: { deletedAt: '' }, + $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP, active: true }, + }, + }, + })); + await SceneModel.bulkWrite(bulkOps, { session }); + const restoredScenes = await SceneModel.find({ + storyId, + userId, + }) + .sort({ order: 1 }) + .lean() + .session(session); + return restoredScenes; + }); +} + +export async function softdeleteAllScenes(userId: string, storyId: string) { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + const scenesToDelete = await SceneModel.find({ storyId, userId, deletedAt: { $exists: false } }).session( + session + ); + assertHasNonDeletedScenes(scenesToDelete); + await SceneModel.updateMany( + { storyId, userId }, + { $set: { active: false, deletedAt: new Date(), order: -(Date.now() * 1000) } } + ).session(session); + return; + }); +} + +export async function permanentDeleteAllScenes(userId: string, storyId: string): Promise { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + const scenesToDelete = await SceneModel.find({ + storyId, + userId, + deletedAt: { $exists: true }, + }).session(session); + assertHasDeletedScenes(scenesToDelete); + await SceneModel.deleteMany({ storyId, userId }).session(session); + return; + }); +} + +// Bulk scene services +export async function bulkRestoreScenes( + userId: string, + storyId: string, + sceneIds: string[] +): Promise { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + const activeScenes = await SceneModel.find({ storyId, userId, deletedAt: { $exists: false } }) + .sort({ order: -1 }) + .lean() + .session(session); + const lastOrder = activeScenes[0]?.order ?? 0; + const scenesToRestore = await SceneModel.find({ + _id: { $in: sceneIds }, + storyId, + userId, + deletedAt: { $exists: true }, + }).session(session); + + assertHasDeletedScenes(scenesToRestore); + const bulkOps = scenesToRestore.map((scene, index) => ({ + updateOne: { + filter: { _id: scene._id }, + update: { + $unset: { deletedAt: '' }, + $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP, active: true }, + }, + }, + })); + await SceneModel.bulkWrite(bulkOps, { session }); + + const restoredScenes = await SceneModel.find({ + _id: { $in: sceneIds }, + storyId, + userId, + }) + .sort({ order: 1 }) + .lean() + .session(session); + return restoredScenes; + }); +} + +export async function bulkSoftdeleteScenes(userId: string, storyId: string, sceneIds: string[]) { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + const scenesToDelete = await SceneModel.find({ + _id: { $in: sceneIds }, + storyId, + userId, + deletedAt: { $exists: false }, + }).session(session); + assertHasNonDeletedScenes(scenesToDelete); + await SceneModel.updateMany( + { _id: { $in: sceneIds }, storyId, userId }, + { $set: { active: false, deletedAt: new Date(), order: -(Date.now() * 1000) } } + ).session(session); + return; + }); +} + +export async function bulkPermanentDeleteScenes( + userId: string, + storyId: string, + sceneIds: string[] +): Promise { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + const scenesToDelete = await SceneModel.find({ + _id: { $in: sceneIds }, + storyId, + userId, + deletedAt: { $exists: true }, + }).session(session); + assertHasDeletedScenes(scenesToDelete); + await SceneModel.deleteMany({ _id: { $in: sceneIds }, storyId, userId }).session(session); + return; + }); +} + +export async function bulkReorder( + userId: string, + storyId: string, + newOrderArray: BulkReorderInput +): Promise { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + + const sceneIds = newOrderArray.sceneIds; + + const uniqueIds = new Set(sceneIds); + if (uniqueIds.size !== sceneIds.length) { + const duplicates = sceneIds.filter((id, i) => sceneIds.indexOf(id) !== i); + throw new BadRequestError(`Duplicate scene IDs: ${[...new Set(duplicates)].join(', ')}`); + } + + const existingScenes = await SceneModel.find({ + _id: { $in: sceneIds }, + storyId, + userId, + deletedAt: { $exists: false }, + }).session(session); + + if (existingScenes.length !== sceneIds.length) { + throw new BadRequestError('Invalid scene IDs or scenes not in this story'); + } + + const tempOps = sceneIds.map((sceneId, index) => ({ + updateOne: { + filter: { _id: sceneId, storyId, userId }, + update: { $set: { order: -1 * (index + 1) } }, + }, + })); + + await SceneModel.bulkWrite(tempOps, { session }); + + const finalOps = sceneIds.map((sceneId, index) => ({ + updateOne: { + filter: { _id: sceneId, storyId, userId }, + update: { $set: { order: (index + 1) * SCENE_ORDER_GAP }, $unset: { deletedAt: '' } }, + }, + })); + + await SceneModel.bulkWrite(finalOps, { session }); + + const updatedScenes = await SceneModel.find({ + storyId, + userId, + deletedAt: { $exists: false }, + }) + .sort({ order: 1 }) + .lean() + .session(session); + + return updatedScenes; + }); +} + +// Single scene services +export async function getSceneById(userId: string, storyId: string, sceneId: string): Promise { + await validateStoryOwnership(userId, storyId); + + const scene = await validateStorySceneOwnership(userId, sceneId, storyId); + + return scene; +} + +export async function createScene( + userId: string, + storyId: string, + payload: CreateSceneInput, + position?: number +): Promise { + return withTransaction(async (session) => { + await validateStoryOwnership(userId, storyId, session); + + let orderValue: number; + + if (position === undefined || position === null) { + orderValue = await getNextOrderValue(storyId, session); + } else { + const calculatedOrder = await calculateOrderForPosition(storyId, position, session); + + if (calculatedOrder === null) { + await reindexSceneOrders(storyId, session); + const newOrder = await calculateOrderForPosition(storyId, position, session); + orderValue = newOrder ?? (position + 1) * SCENE_ORDER_GAP; + } else { + orderValue = calculatedOrder; + } + } + + const [scene] = await SceneModel.create( + [ + { + userId, + storyId, + order: orderValue, + title: payload.title, + description: payload.description, + authorType: 'user', + imagePrompt: payload.imagePrompt, + videoPrompt: payload.videoPrompt, + duration: payload.duration, + }, + ], + { session } + ); + + return scene; + }); +} + +export async function generateSceneWithAI( + userId: string, + storyId: string, + input?: GenerateSceneInput +): Promise { + const position = input?.position; + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + + //TODO: Check plan and limits here + + let orderValue: number; + if (position === undefined || position === null) { + orderValue = await getNextOrderValue(storyId, session); + } else { + const calculatedOrder = await calculateOrderForPosition(storyId, position, session); + if (calculatedOrder === null) { + await reindexSceneOrders(storyId, session); + const newOrder = await calculateOrderForPosition(storyId, position, session); + orderValue = newOrder ?? (position + 1) * SCENE_ORDER_GAP; + } else { + orderValue = calculatedOrder; + } + } + + const scenes = await SceneModel.find({ storyId, userId, deletedAt: { $exists: false } }) + .lean() + .session(session); + + const previousScenesSummary = scenes + .filter((s) => s.order < orderValue) + .map((s) => `${s.title}: ${s.description}`) + .join(' | '); + const nextScenesSummary = scenes + .filter((s) => s.order > orderValue) + .map((s) => `${s.title}: ${s.description}`) + .join(' | '); + + const prompt = singleScenePrompt({ + mode: 'generate', + storyTitle: story.title, + storyContent: { + summary: story.content.summary, + keywords: story.content.keywords, + tags: story.content.tags, + }, + sceneIndex: position !== undefined && position !== null ? position + 1 : scenes.length + 1, + totalScenes: scenes.length + 1, + timeLimit: 3, + previousScenesSummary, + nextScenesSummary, + intent: story.intent, + platform: story.platform, + }); + + let aiGeneratedContent: any; + try { + const result = await openRouterAI(prompt); + const rawContent = result?.choices?.[0]?.message?.content; + if (typeof rawContent !== 'string' || rawContent.trim().length === 0) { + throw new InternalServerError('AI generation failed'); + } + aiGeneratedContent = safeParseJSON(rawContent); + } catch (err) { + throw new InternalServerError('AI generation failed'); + } + if (!aiGeneratedContent) { + throw new InternalServerError('AI generation failed'); + } + if (!aiGeneratedContent.title || !aiGeneratedContent.description) { + throw new InternalServerError('AI generation returned incomplete data'); + } + + const [scene] = await SceneModel.create( + [ + { + userId, + storyId, + order: orderValue, + title: aiGeneratedContent.title, + description: aiGeneratedContent.description, + authorType: 'ai', + imagePrompt: aiGeneratedContent.imagePrompt, + videoPrompt: aiGeneratedContent.videoPrompt, + duration: aiGeneratedContent.duration, + }, + ], + { session } + ); + + return scene; + }); +} + +export async function regenerateScene( + userId: string, + sceneId: string, + input?: RegenerateSceneInput +): Promise { + return withTransaction(async (session) => { + const scene = await validateSceneOwnership(userId, sceneId, session); + assertSceneNotDeleted(scene); + + const story = await StoryModel.findById(scene.storyId).session(session); + if (!story) { + throw new NotFoundError('Parent story not found'); + } + + const contextProfile = await ContextProfileModel.findOne({ _id: story.contextProfileId }).session( + session + ); + + const scenes = await SceneModel.find({ + storyId: scene.storyId, + userId, + deletedAt: { $exists: false }, + }).session(session); + + const previousScenesSummary = scenes + .filter((s) => s.order < scene.order) + .map((s) => `${s.title}: ${s.description}`) + .join(' | '); + const nextScenesSummary = scenes + .filter((s) => s.order > scene.order) + .map((s) => `${s.title}: ${s.description}`) + .join(' | '); + + const sceneIndex = scenes.filter((s) => s.order < scene.order).length + 1; + + const regenerateScenePrompt = singleScenePrompt({ + mode: 'regenerate', + storyTitle: story.title, + storyContent: { + summary: story.content.summary, + keywords: story.content.keywords, + tags: story.content.tags, + }, + sceneIndex, + totalScenes: scenes.length, + timeLimit: 3, + previousScenesSummary, + nextScenesSummary, + contextProfile, + baseScene: `${scene.title}: ${scene.description}`, + extraPrompt: input?.extraPrompt, + intent: story.intent, + platform: story.platform, + }); + + let aiRegeneratedContent: any; + try { + const result = await openRouterAI(regenerateScenePrompt); + const rawContent = result?.choices?.[0]?.message?.content; + + if (typeof rawContent !== 'string' || rawContent.trim().length === 0) { + throw new InternalServerError('AI regeneration failed'); + } + aiRegeneratedContent = safeParseJSON(rawContent); + } catch (err) { + throw new InternalServerError('AI regeneration failed'); + } + + if (!aiRegeneratedContent) { + throw new InternalServerError('AI regeneration failed'); + } + + const updatedScene = await SceneModel.findByIdAndUpdate( + sceneId, + { + $set: { + title: aiRegeneratedContent.title, + description: aiRegeneratedContent.description, + imagePrompt: aiRegeneratedContent.imagePrompt, + videoPrompt: aiRegeneratedContent.videoPrompt, + duration: aiRegeneratedContent.duration, + authorType: 'ai', + }, + }, + { new: true, session } + ); + + if (!updatedScene) { + throw new NotFoundError('Failed to regenerate scene'); + } + + return updatedScene; + }); +} + +export async function updateScene( + userId: string, + sceneId: string, + updates: UpdateSceneInput +): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneNotDeleted(scene); + + const updateFields: any = {}; + if (updates.title !== undefined) updateFields.title = updates.title; + if (updates.description !== undefined) updateFields.description = updates.description; + if (updates.imagePrompt !== undefined) updateFields.imagePrompt = updates.imagePrompt; + if (updates.videoPrompt !== undefined) updateFields.videoPrompt = updates.videoPrompt; + + if (Object.keys(updateFields).length > 0) { + updateFields.authorType = 'user'; + } + + const updatedScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $set: updateFields }, + { new: true, runValidators: true } + ); + + if (!updatedScene) { + throw new NotFoundError('Scene not found'); + } + + return updatedScene; +} + +export async function updateSceneDuration( + userId: string, + storyId: string, + sceneId: string, + duration: number +): Promise { + return withTransaction(async (session) => { + const scene = await validateStorySceneOwnership(userId, sceneId, storyId, session); + assertSceneNotDeleted(scene); + const story = await validateStoryOwnership(userId, storyId, session); + const scenesTimeLimit = await SceneModel.aggregate([ + { + $match: { + storyId: new mongoose.Types.ObjectId(storyId), + userId: userId, + active: true, + deletedAt: { $exists: false }, + }, + }, + { $group: { _id: null, totalDuration: { $sum: '$duration' } } }, + ]).session(session); + const currentSceneDuration = scene.duration ?? 0; + const newTotalDuration = (scenesTimeLimit[0]?.totalDuration ?? 0) - currentSceneDuration + duration; + if (story?.timeLimit && newTotalDuration > story.timeLimit) { + throw new BadRequestError('Updating duration exceeds story time limit'); + } + const updatedScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $set: { duration } }, + { new: true, runValidators: true, session } + ); + if (!updatedScene) { + throw new NotFoundError('Scene not found'); + } + return updatedScene; + }); +} + +export async function moveSceneByOne( + userId: string, + sceneId: string, + direction: 'prev' | 'next' +): Promise<{ moved: Scene; swappedWith: Scene }> { + return withTransaction(async (session) => { + const scene = await validateSceneOwnership(userId, sceneId, session); + assertSceneNotDeleted(scene); + + const operator = direction === 'prev' ? '$lt' : '$gt'; + const sortOrder = direction === 'prev' ? -1 : 1; + + const neighbor = await SceneModel.findOne({ + storyId: scene.storyId, + userId, + deletedAt: { $exists: false }, + order: { [operator]: scene.order }, + _id: { $ne: sceneId }, + }) + .sort({ order: sortOrder }) + .session(session); + + if (!neighbor) { + throw new BadRequestError(`Cannot move scene ${direction}`); + } + + const tempOrder = scene.order; + + const tempSwapOrder = -Date.now(); + + await SceneModel.findByIdAndUpdate(sceneId, { $set: { order: tempSwapOrder } }, { session }); + + const updatedNeighbor = await SceneModel.findByIdAndUpdate( + neighbor._id, + { $set: { order: tempOrder } }, + { new: true, session } + ); + + const updatedScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $set: { order: neighbor.order } }, + { new: true, session } + ); + + if (!updatedScene || !updatedNeighbor) { + throw new NotFoundError('Failed to move scenes'); + } + + await session.commitTransaction(); + + return { + moved: updatedScene, + swappedWith: updatedNeighbor, + }; + }); +} + +export async function reactivateScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneNotDeleted(scene); + + const nextOrder = await getNextOrderValue(scene.storyId.toString()); + + const updatedScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $set: { active: true, order: nextOrder } }, + { new: true, runValidators: true } + ); + if (!updatedScene) { + throw new NotFoundError('Scene not found'); + } + return updatedScene; +} + +export async function deactivateScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneNotDeleted(scene); + assertSceneIsActive(scene); + const updatedScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $set: { active: false, order: -(Date.now() * 1000) } }, + { new: true, runValidators: true } + ); + if (!updatedScene) { + throw new NotFoundError('Scene not found'); + } + return updatedScene; +} + +export async function softDeleteScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneNotDeleted(scene); + + await SceneModel.findByIdAndUpdate(sceneId, { + $set: { deletedAt: new Date(), order: -Date.now(), active: false }, + }); + return true; +} + +export async function restoreScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneIsDeleted(scene); + + const newOrder = await getNextOrderValue(scene.storyId.toString()); + const restoredScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $unset: { deletedAt: '' }, $set: { order: newOrder, active: true } }, + { new: true, runValidators: true } + ); + if (!restoredScene) { + throw new NotFoundError('Scene not found'); + } + return restoredScene; +} + +export async function permanentDeleteScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneIsDeleted(scene); + await SceneModel.findByIdAndDelete(sceneId); + return true; +} + +// FUTURE IMPLEMENTATION: Permanent delete scene +export async function duplicateScene(userId: string, sceneId: string): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + const scene = await validateSceneOwnership(userId, sceneId, session); + assertSceneNotDeleted(scene); + + const newOrder = await getNextOrderValue(scene.storyId.toString(), session); + + const [duplicatedScene] = await SceneModel.create( + [ + { + userId, + storyId: scene.storyId, + order: newOrder, + title: scene.title ? `${scene.title} (Copy)` : undefined, + description: scene.description, + authorType: 'user', + imagePrompt: scene.imagePrompt, + videoPrompt: scene.videoPrompt, + duration: scene.duration, + }, + ], + { session } + ); + + await session.commitTransaction(); + return duplicatedScene; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} diff --git a/src/modules/story/story.controller.ts b/src/modules/story/story.controller.ts index e69de29..1f32e7d 100644 --- a/src/modules/story/story.controller.ts +++ b/src/modules/story/story.controller.ts @@ -0,0 +1,284 @@ +import { paginationResponse } from '@utils/paginationResponse.js'; +import { Request, Response } from 'express'; +import { + addStoryContextService, + archiveStory, + createStory, + softdeleteStory, + permanentDeleteStory, + getProjectArchivedStories, + getProjectDeletedStories, + getUserArchivedStories, + getUserDeletedStories, + generateStory, + getProjectStories, + getStoryById, + getUserStories, + regenerateStory, + restoreStory, + setStoryContextService, + unarchiveStory, + updateStory, + writeContent, +} from './story.service.js'; +import { + AddStoryContextInput, + CreateStoryInput, + RegenerateStoryInput, + SetStoryContextInput, + UpdateStoryInput, + WriteContentInput, +} from '@validation/story.schema.js'; + +export const getUserStoriesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const [stories, total] = await getUserStories(userId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: stories, + pagination: { + ...paginationRes, + }, + }); +}; + +export const getUserDeletedStoriesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const [stories, total] = await getUserDeletedStories(userId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: stories, + pagination: { + ...paginationRes, + }, + }); +}; + +export const getUserArchivedStoriesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const [stories, total] = await getUserArchivedStories(userId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: stories, + pagination: { + ...paginationRes, + }, + }); +}; + +export const getProjectStoriesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const projectId = req.params.projectId; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const [stories, total] = await getProjectStories(userId, projectId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: stories, + pagination: { + ...paginationRes, + }, + }); +}; + +export const getProjectDeletedStoriesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const projectId = req.params.projectId; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const [stories, total] = await getProjectDeletedStories(userId, projectId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: stories, + pagination: { + ...paginationRes, + }, + }); +}; + +export const getProjectArchivedStoriesController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const projectId = req.params.projectId; + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const [stories, total] = await getProjectArchivedStories(userId, projectId, pagination, sorting); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: stories, + pagination: { + ...paginationRes, + }, + }); +}; + +export const createStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const projectId = req.params.projectId; + const payload = req.validatedBody as CreateStoryInput; + + const story = await createStory(userId, projectId, payload); + + return res.status(201).json({ + message: 'Story created successfully', + story, + }); +}; + +export const getStoryByIdController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const story = await getStoryById(userId, storyId); + return res.status(200).json({ + story, + }); +}; + +export const addStoryContextController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const { context } = req.validatedBody as AddStoryContextInput; + const result = await addStoryContextService(userId, storyId, context); + res.status(201).json({ + message: 'Story context profile added', + data: result, + }); +}; + +export async function setStoryContextController(req: Request, res: Response) { + const userId = req.user!.id; + const payload = req.validatedBody as SetStoryContextInput; + + const result = await setStoryContextService(userId, req.params.storyId, payload); + + res.status(200).json({ + message: 'Story context updated', + data: result, + }); +} + +export const writeContentController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const payload = req.validatedBody as WriteContentInput; + + const story = await writeContent(userId, storyId, payload); + return res.status(200).json({ + message: 'Content added successfully', + data: story, + }); +}; + +export const generateStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const response = await generateStory(userId, storyId); + return res.status(200).json({ + message: 'Story generated successfully', + data: response, + }); +}; + +export const regenerateStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const extraPrompt = req.validatedBody as RegenerateStoryInput; + + const story = await regenerateStory(userId, storyId, extraPrompt); + + return res.status(200).json({ + message: 'Story regeneration initiated', + data: story, + }); +}; + +export const updateStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + const payload = req.validatedBody as UpdateStoryInput; + + const story = await updateStory(userId, storyId, payload); + + return res.status(200).json({ + message: 'Story updated successfully', + story, + }); +}; + +export const softdeleteStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const response = await softdeleteStory(userId, storyId); + if (!response) { + return res.status(409).json({ + message: 'Story could not be deleted', + }); + } + return res.status(200).json({ + message: 'Story deleted successfully', + data: { deleted: response }, + }); +}; + +export const permanentDeleteStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const response = await permanentDeleteStory(userId, storyId); + if (!response) { + return res.status(409).json({ + message: 'Story could not be deleted', + }); + } + return res.status(200).json({ + message: 'Story deleted successfully', + data: { deleted: response }, + }); +}; + +export const restoreStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const story = await restoreStory(userId, storyId); + return res.status(200).json({ + message: 'Story restored successfully', + data: story, + }); +}; + +export const archiveStoryStatusController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const response = await archiveStory(userId, storyId); + return res.status(200).json({ + message: 'Story archived successfully', + story: response, + }); +}; + +export const unarchiveStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const response = await unarchiveStory(userId, storyId); + return res.status(200).json({ + message: 'Story unarchived successfully', + ...response, + }); +}; + +export const rollbackStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + // to be implemented +}; diff --git a/src/modules/story/story.private.routes.ts b/src/modules/story/story.private.routes.ts new file mode 100644 index 0000000..e1c429b --- /dev/null +++ b/src/modules/story/story.private.routes.ts @@ -0,0 +1,123 @@ +import { Router } from 'express'; +import { + createStoryController, + softdeleteStoryController, + permanentDeleteStoryController, + getProjectStoriesController, + getProjectDeletedStoriesController, + getProjectArchivedStoriesController, + getStoryByIdController, + getUserStoriesController, + getUserArchivedStoriesController, + getUserDeletedStoriesController, + regenerateStoryController, + restoreStoryController, + unarchiveStoryController, + updateStoryController, + archiveStoryStatusController, + generateStoryController, + writeContentController, + setStoryContextController, + addStoryContextController, +} from './story.controller.js'; +import { paginationAndSortingMiddleware } from '@middleware/request/paginationAndSorting.js'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { projectIdParamSchema } from '@validation/project.schema.js'; +import { validateParams } from '@validation/validateParams.js'; +import { validateBody } from '@validation/validateBody.js'; +import { + addStoryContextSchema, + createStorySchema, + regenerateStorySchema, + setStoryContextSchema, + storyIdParamSchema, + updateStorySchema, + writeContentSchema, +} from '@validation/story.schema.js'; + +const router = Router(); + +router.get('/', paginationAndSortingMiddleware, asyncHandler(getUserStoriesController)); +router.get('/deleted', paginationAndSortingMiddleware, asyncHandler(getUserDeletedStoriesController)); +router.get('/archived', paginationAndSortingMiddleware, asyncHandler(getUserArchivedStoriesController)); +router.get( + '/project/:projectId', + validateParams(projectIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getProjectStoriesController) +); +router.get( + '/project/:projectId/deleted', + validateParams(projectIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getProjectDeletedStoriesController) +); +router.get( + '/project/:projectId/archived', + validateParams(projectIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getProjectArchivedStoriesController) +); +// router.post('/', asyncHandler(createStandaloneStoryController)); Future Scope + +router.post( + '/project/:projectId', + validateParams(projectIdParamSchema), + validateBody(createStorySchema), + asyncHandler(createStoryController) +); +router.get('/:storyId', validateParams(storyIdParamSchema), asyncHandler(getStoryByIdController)); +router.post( + '/:storyId/context-profile', + validateBody(addStoryContextSchema), + asyncHandler(addStoryContextController) +); +router.patch( + '/:storyId/context-profile', + validateParams(storyIdParamSchema), + validateBody(setStoryContextSchema), + asyncHandler(setStoryContextController) +); + +router.patch( + '/:storyId/content', + validateParams(storyIdParamSchema), + validateBody(writeContentSchema), + asyncHandler(writeContentController) +); +router.post('/:storyId/generate', validateParams(storyIdParamSchema), asyncHandler(generateStoryController)); +router.post( + '/:storyId/regenerate', + validateParams(storyIdParamSchema), + validateBody(regenerateStorySchema), + asyncHandler(regenerateStoryController) +); + +router.patch( + '/:storyId', + validateParams(storyIdParamSchema), + validateBody(updateStorySchema), + asyncHandler(updateStoryController) +); +router.delete('/:storyId/soft', validateParams(storyIdParamSchema), asyncHandler(softdeleteStoryController)); + +router.delete( + '/:storyId/permanent', + validateParams(storyIdParamSchema), + asyncHandler(permanentDeleteStoryController) +); + +router.patch('/:storyId/restore', validateParams(storyIdParamSchema), asyncHandler(restoreStoryController)); +router.patch( + '/:storyId/archive', + validateParams(storyIdParamSchema), + asyncHandler(archiveStoryStatusController) +); +router.patch( + '/:storyId/unarchive', + validateParams(storyIdParamSchema), + asyncHandler(unarchiveStoryController) +); +// router.patch('/:storyId/rollback', validateParams(storyIdParamSchema), asyncHandler(rollbackStoryController)); // TODO: Implemenet rollback logic in controller and service + +export default router; diff --git a/src/modules/story/story.service.ts b/src/modules/story/story.service.ts index e69de29..fd72b0d 100644 --- a/src/modules/story/story.service.ts +++ b/src/modules/story/story.service.ts @@ -0,0 +1,481 @@ +import { ConflictError, NotFoundError } from '@middleware/error/index.js'; +import { ContextProfileModel, ContextScope, GenreType } from '@models/ContextProfile.js'; +import { ProjectModel } from '@models/Project.js'; +import { StoryModel } from '@models/Story.js'; +import safeParseJSON from '@utils/safeParseJSON.js'; +import { + AddStoryContextInput, + CreateStoryInput, + RegenerateStoryInput, + SetStoryContextInput, +} from '@validation/story.schema.js'; +import { NARRATION_PROFILES } from 'constants/narrationProfiles.js'; +import { openRouterAI } from 'libs/ai/clients/openAI.js'; +import { generateStoryPrompt } from '@libs/ai/prompts/generateStoryPrompt.js'; +import { generateStoryRegenerationPrompt } from 'libs/ai/prompts/generateStoryRegenerationPrompt.js'; +import { Pagination, Sorting } from 'types/Pagination.js'; +import { isSameContextContract } from 'domain/policies/isSameContextContract.js'; +import { validateStoryOwnership } from 'validators/validateStoryOwnership.js'; +import { withTransaction } from '@db/withTransaction.js'; +import { + assertStoryIsActive, + assertStoryIsDeleted, + assertStoryNotDeleted, +} from 'domain/assertions/assertStoryState.js'; +import { consumeCredits } from '@modules/credit/credit.service.js'; + +export async function getUserStories(userId: string, pagination: Pagination, sorting: Sorting) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, status: { $in: ['active', 'draft'] } }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, status: { $in: ['active', 'draft'] } }) as Promise, + ]); + + return [stories, total]; +} + +export async function getUserDeletedStories(userId: string, pagination: Pagination, sorting: Sorting) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, status: 'delete' }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, status: 'delete' }) as Promise, + ]); + + return [stories, total]; +} + +export async function getUserArchivedStories(userId: string, pagination: Pagination, sorting: Sorting) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, status: 'archive' }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, status: 'archive' }) as Promise, + ]); + + return [stories, total]; +} + +export async function getProjectStories( + userId: string, + projectId: string, + pagination: Pagination, + sorting: Sorting +) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, projectId, status: { $in: ['active', 'draft'] } }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, projectId, status: { $in: ['active', 'draft'] } }) as Promise, + ]); + return [stories, total]; +} + +export async function getProjectDeletedStories( + userId: string, + projectId: string, + pagination: Pagination, + sorting: Sorting +) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, projectId, status: 'delete' }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, projectId, status: 'delete' }) as Promise, + ]); + return [stories, total]; +} + +export async function getProjectArchivedStories( + userId: string, + projectId: string, + pagination: Pagination, + sorting: Sorting +) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, projectId, status: 'archive' }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, projectId, status: 'archive' }) as Promise, + ]); + return [stories, total]; +} + +//TODO: Bulk Delete, Restore, Archive, Unarchive can be implemented in future + +//TODO: 31/01/2026 Implement hard time limit for Story based on permissions + +export async function createStory(userId: string, projectId: string, payload: CreateStoryInput) { + const project = await ProjectModel.findOne({ _id: projectId, userId }); + if (!project) { + throw new NotFoundError('Project not found'); + } + if (!project.defaultContextProfileId) { + throw new ConflictError('Project does not have a default context profile set'); + } + + const story = await StoryModel.create({ + userId, + projectId, + contextProfileId: project.defaultContextProfileId, + title: payload.title, + description: payload.description, + timeLimit: payload.timeLimit, + platform: payload.platform, + intent: payload.intent, + status: payload.status, + }); + return story; +} + +export async function getStoryById(userId: string, storyId: string) { + const story = await validateStoryOwnership(userId, storyId); + return story; +} + +export async function addStoryContextService( + userId: string, + storyId: string, + context: AddStoryContextInput['context'] +) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + assertStoryIsActive(story); + + const narrationProfile = NARRATION_PROFILES[context.genre as GenreType]; + + const oldContext = await ContextProfileModel.findById(story.contextProfileId).session(session); + + let comparison = false; + + if (oldContext) { + comparison = isSameContextContract(oldContext, context); + } + + if (comparison) { + throw new ConflictError('The new context is identical to the current one.'); + } + + const [newContext] = await ContextProfileModel.create( + [ + { + userId, + projectId: story.projectId, + name: context.name, + description: context.description, + genre: context.genre, + mood: context.mood, + style: context.style, + narrativeScope: context.narrativeScope, + parentContextId: oldContext?._id, + characters: context.characters, + environment: context.environment, + worldRules: context.worldRules, + narrativeConstraints: context.narrativeConstraints, + forbiddenElements: context.forbiddenElements, + narrationProfile, + scope: ContextScope.PROJECT, + isDefaultForProject: false, + lastUsedAt: new Date(), + }, + ], + { session } + ); + + story.contextProfileId = newContext._id; + await story.save({ session }); + + return { + story, + contextMeta: { + id: newContext._id.toString(), + scope: newContext.scope, + createdAt: newContext.createdAt, + }, + contextPayload: newContext, + }; + }); +} + +export async function setStoryContextService(userId: string, storyId: string, payload: SetStoryContextInput) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + assertStoryIsActive(story); + + const project = await ProjectModel.findById(story.projectId).session(session); + if (!project) throw new NotFoundError("Story's Project not found"); + + if (payload.mode === 'use-project') { + if (!project.defaultContextProfileId) { + throw new NotFoundError('Project does not have a default context profile set'); + } + if ( + project.defaultContextProfileId && + story.contextProfileId?.equals(project.defaultContextProfileId) + ) { + throw new ConflictError('Story is already using the project default context'); + } + + story.contextProfileId = project.defaultContextProfileId; + await story.save({ session }); + + const context = await ContextProfileModel.findById(project.defaultContextProfileId).session(session); + if (!context) { + throw new NotFoundError('Context profile not found'); + } + + return { + story, + contextMeta: { + id: context._id.toString(), + scope: context.scope, + createdAt: context.createdAt, + }, + }; + } + + if (payload.mode === 'use-global') { + const globalContext = await ContextProfileModel.findOne({ + _id: payload.globalContextId, + scope: ContextScope.GLOBAL, + active: true, + }).session(session); + + if (!globalContext) { + throw new NotFoundError('Global context not found'); + } + + if (story.contextProfileId?.equals(globalContext._id)) { + throw new ConflictError('Story is already using this global context'); + } + + story.contextProfileId = globalContext._id; + await story.save({ session }); + + return { + story, + contextMeta: { + id: globalContext._id.toString(), + scope: globalContext.scope, + createdAt: globalContext.createdAt, + }, + }; + } + throw new ConflictError('Invalid story context mode'); + }); +} + +export async function writeContent( + userId: string, + storyId: string, + payload: { + content: string; + summary: string; + keywords?: string[]; + tags?: string[]; + } +) { + const story = await validateStoryOwnership(userId, storyId); + assertStoryIsActive(story); + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId }, + { + $set: { + content: { + body: payload.content, + summary: payload.summary, + keywords: payload.keywords!, + tags: payload.tags!, + }, + authorType: 'user', + status: 'active', + }, + }, + { new: true } + ); + return updatedStory; +} + +export async function generateStory(userId: string, storyId: string) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + const contextProfile = await ContextProfileModel.findById(story.contextProfileId).session(session); + + console.log(userId) + const prompt = generateStoryPrompt({ + title: story.title, + description: story.description, + intent: story.intent, + platform: story.platform, + timeLimit: story.timeLimit, + contextProfile: contextProfile, + }); + + await consumeCredits(userId, 10, session); + let response; + try { + response = await openRouterAI(prompt); + } catch (err) { + throw new ConflictError('AI generation failed, please try again.'); + } + const rawcontent = response.choices[0].message?.content || ''; + if (!rawcontent) { + throw new ConflictError('AI generation returned empty content, please try again.'); + } + const content = safeParseJSON(rawcontent); + if (!content.story || !content.summary) { + throw new ConflictError('Error parsing AI generated content, please try again.'); + } + + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId }, + { + $set: { + content: { + body: content.story, + summary: content.summary, + keywords: content.keywords || [], + tags: content.tags || [], + }, + authorType: 'ai', + status: 'active', + }, + }, + { new: true, runValidators: true, session } + ); + return updatedStory; + }); +} + +export async function regenerateStory(userId: string, storyId: string, extraPrompt: RegenerateStoryInput) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + if (!extraPrompt || !extraPrompt.prompt) { + throw new ConflictError('No regeneration prompt provided.'); + } + + const contextProfile = await ContextProfileModel.findById(story.contextProfileId).session(session); + + const prompt = generateStoryRegenerationPrompt({ + title: story.title, + description: story.description, + existingSummary: story.content.summary, + intent: story.intent, + platform: story.platform, + timeLimit: story.timeLimit, + extraPrompt: extraPrompt.prompt, + contextProfile: contextProfile, + }); + await consumeCredits(userId, 5, session); + let response; + try { + response = await openRouterAI(prompt); + } catch (err) { + throw new ConflictError('AI regeneration failed, please try again.'); + } + const rawcontent = response.choices[0].message?.content || ''; + if (!rawcontent) { + throw new ConflictError('AI regeneration returned empty content, please try again.'); + } + const content = safeParseJSON(rawcontent); + if (!content.story || !content.summary) { + throw new ConflictError('Error parsing AI regenerated content, please try again.'); + } + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId }, + { + $set: { + content: { + body: content.story, + summary: content.summary, + keywords: content.keywords || [], + tags: content.tags || [], + }, + authorType: 'ai', + }, + }, + { + new: true, + runValidators: true, + session, + } + ); + return updatedStory; + }); +} + +export async function updateStory(userId: string, storyId: string, payload: Partial) { + await validateStoryOwnership(userId, storyId); + + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId }, + { $set: payload }, + { new: true } + ); + + // TODO: In future can give hard rule of creating a new story content after main story outline change except title + + return updatedStory; +} + +export async function softdeleteStory(userId: string, storyId: string): Promise { + const story = await validateStoryOwnership(userId, storyId); + assertStoryNotDeleted(story); + const result = await StoryModel.updateOne( + { _id: storyId, userId, status: { $ne: 'delete' } }, + { $set: { isDeleted: true, deletedAt: new Date(), status: 'delete' } } + ); + return result.modifiedCount > 0; +} + +export async function restoreStory(userId: string, storyId: string) { + const story = await validateStoryOwnership(userId, storyId); + assertStoryIsDeleted(story); + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId, status: 'delete' }, + { $set: { isDeleted: false, status: 'active' }, $unset: { deletedAt: '' } }, + { new: true, lean: true } + ); + return updatedStory; +} + +export async function permanentDeleteStory(userId: string, storyId: string): Promise { + const story = await validateStoryOwnership(userId, storyId); + assertStoryIsDeleted(story); + const result = await StoryModel.deleteOne({ _id: storyId, userId, status: 'delete' }); + return result.deletedCount > 0; +} + +export async function archiveStory(userId: string, storyId: string) { + const story = await validateStoryOwnership(userId, storyId); + assertStoryIsActive(story); + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId, status: 'active' }, + { $set: { status: 'archive' } }, + { new: true, lean: true } + ); + return updatedStory; +} + +export async function unarchiveStory(userId: string, storyId: string) { + const story = await validateStoryOwnership(userId, storyId); + assertStoryIsActive(story); + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId, status: 'archive' }, + { $set: { status: 'active' } }, + { new: true, lean: true } + ); + return updatedStory; +} + +// To be implemented in future +export async function rollbackStory(userId: string, storyId: string) { + return; +} diff --git a/src/modules/subscription/subscription.service.ts b/src/modules/subscription/subscription.service.ts new file mode 100644 index 0000000..782eaeb --- /dev/null +++ b/src/modules/subscription/subscription.service.ts @@ -0,0 +1,45 @@ +import mongoose, { Types } from 'mongoose'; +import { UserModel } from '@models/User.js'; +import { PlanModel } from '@models/Plan.js'; +import { CreditsModel } from '@models/Credits.js'; +import { InternalServerError } from '@middleware/error/index.js'; + +export async function assignFreePlan(userId: Types.ObjectId, session: mongoose.ClientSession): Promise { + const user = await UserModel.findById(userId).session(session); + if (!user) { + throw new InternalServerError('User not found while assigning free plan'); + } + + if (user.currentPlan) return; + + const freePlan = await PlanModel.findOne({ + key: 'free', + isActive: true, + }).session(session); + + if (!freePlan) { + throw new InternalServerError('Free plan missing from database'); + } + + user.currentPlan = freePlan._id; + user.planStartedAt = new Date(); + user.planEndsAt = null; + + await user.save({ session }); + + await CreditsModel.create( + [ + { + userId: user._id, + planKey: freePlan.key, + source: 'free_plan', + creditType: 'ai', + creditsGranted: freePlan.creditGrantAmount, + creditsUsed: 0, + validFrom: new Date(), + validTill: null, + }, + ], + { session } + ); +} diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index fb458a8..23fd8d7 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -1,7 +1,6 @@ import { DeleteAllSessionsType, - UpdateAccountType, - UpdateAvatarType, + DeleteSessionParamsType, UpdateEmailType, UpdateNotificationsType, UpdatePasswordType, @@ -10,6 +9,7 @@ import { } from "@validation/user.schema.js"; import type { NextFunction, Request, Response } from "express"; import { + deactivateAccount, deleteAccount, deleteAllSessions, deleteAvatar, @@ -19,7 +19,7 @@ import { getSecurity, getSessions, getSettings, - updateAccount, + reactivateAccount, updateAvatar, updateEmail, updateNotifications, @@ -27,16 +27,10 @@ import { updatePrivacySettings, updateProfile, } from "./user.service.js"; -import { AccountStatus } from "constants/accountStatus.js"; -import { UnauthenticatedError } from "@middleware/error/index.js"; export const getProfileController = async (req: Request, res: Response) => { - const userId = req.user?._id; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = req.user!.id; const user = await getProfile(userId); - return res.status(200).json({ id: user._id, email: user.email, @@ -44,7 +38,7 @@ export const getProfileController = async (req: Request, res: Response) => { displayName: user.displayName, avatarUrl: user.avatarUrl, bio: user.bio, - plan: user.plan, + plan: user.currentPlan, emailVerified: user.emailVerified, links: user.links, usage: user.usage, @@ -52,34 +46,18 @@ export const getProfileController = async (req: Request, res: Response) => { }; export const updateProfileController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const updateData = (req as unknown as { validatedBody?: UpdateProfileType }) - .validatedBody!; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = req.user!.id; + const updateData = req.validatedBody as UpdateProfileType; const updatedUser = await updateProfile(userId, updateData); - return res.status(200).json(updatedUser); }; export const updateAvatarController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const avatarData = (req as unknown as { validatedBody?: UpdateAvatarType }) - .validatedBody!; - if (!userId) { - throw new Error( - "Invariant violation: req.user is missing after auth middleware" - ); - } - - // Add Mullter or file upload handling logic here to get the avatar file data - + const userId = req.user!.id; + const avatarData = req.file; const updatedUser = await updateAvatar(userId, avatarData); return res.status(200).json(updatedUser); - - // Implementation for updating user avatar }; export const deleteAvatarController = async ( @@ -87,12 +65,7 @@ export const deleteAvatarController = async ( res: Response, next: NextFunction ) => { - const userId = req.user?._id; - if (!userId) { - throw new Error( - "Invariant violation: req.user is missing after auth middleware" - ); - } + const userId = req.user!.id; await deleteAvatar(userId); return res.status(204).send({ message: "Avatar deleted successfully", @@ -100,48 +73,26 @@ export const deleteAvatarController = async ( }; export const getSettingsController = async (req: Request, res: Response) => { - const userId = req.user?._id; - if (!userId) { - throw new Error( - "Invariant violation: req.user is missing after auth middleware" - ); - } + const userId = req.user!.id; const user = await getSettings(userId); return res.status(200).json(user); }; export const getSecurityController = async (req: Request, res: Response) => { - const userId = req.user?._id; - if (!userId) { - return new Error( - "Invariant violation: req.user is missing after auth middleware" - ); - } + const userId = req.user!.id; const user = await getSecurity(userId); - return res.status(200).json(user); }; export const getSessionsController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const sessionId = req.sessionId; - if (!userId || !sessionId) { - throw new Error( - "Invariant violation: req.user is missing after auth middleware" - ); - } + const userId = req.user!.id; + const sessionId = req.sessionId!; const sessions = await getSessions(userId, sessionId); return res.status(200).json(sessions); }; export const getBillingController = async (req: Request, res: Response) => { - const userId = req.user?._id; - if (!userId) { - throw new Error( - "Invariant violation: req.user is missing after auth middleware" - ); - } - + const userId = req.user!.id; const billingInfo = await getBilling(userId); return res.status(200).json(billingInfo); }; @@ -150,16 +101,10 @@ export const updateNotificationsController = async ( req: Request, res: Response ) => { - const userId = req.user?._id; - const notificationPrefs = ( - req.body as unknown as { validatedBody?: UpdateNotificationsType } - ).validatedBody!; - if (!userId) { - throw new Error("User ID not found in request"); - } - // Assuming updateNotifications is a service function to update notification preferences - const updatedUser = await updateNotifications(userId, notificationPrefs); + const userId = req.user!.id; + const notificationPrefs = req.validatedBody as UpdateNotificationsType; + const updatedUser = await updateNotifications(userId, notificationPrefs); return res.status(200).json({ id: updatedUser._id, notificationPrefs: updatedUser.notificationPrefs, @@ -170,13 +115,8 @@ export const updatePrivacySettingsController = async ( req: Request, res: Response ) => { - const userId = req.user?._id; - const privacyPrefs = ( - req.body as unknown as { validatedBody?: UpdatePrivacySettingsType } - ).validatedBody!; - if (!userId) { - return new Error("User ID not found in request"); - } + const userId = req.user!.id; + const privacyPrefs = req.validatedBody as UpdatePrivacySettingsType; const updatedUser = await updatePrivacySettings(userId, privacyPrefs); return res.status(200).json({ id: updatedUser._id, @@ -185,13 +125,11 @@ export const updatePrivacySettingsController = async ( }; export const updatePasswordController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const { currentPassword, newPassword } = ( - req.body as unknown as { validatedBody?: UpdatePasswordType } - ).validatedBody!; - if (!userId) { - throw new Error("User ID not found in request"); - } + const userId = req.user!.id; + const { currentPassword, newPassword } = + req.validatedBody as UpdatePasswordType; + + // TODO : Ask user if wanted to remove all sessions except current await updatePassword(userId, currentPassword, newPassword); return res.status(200).json({ message: "Password updated successfully", @@ -199,12 +137,9 @@ export const updatePasswordController = async (req: Request, res: Response) => { }; export const updateEmailController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const { newEmail } = (req as unknown as { validatedBody?: UpdateEmailType }) - .validatedBody!; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = req.user!.id; + const { newEmail } = req.validatedBody as UpdateEmailType; + await updateEmail(userId, newEmail); return res.status(200).json({ message: "Email update initiated. Please verify your new email address.", @@ -212,69 +147,55 @@ export const updateEmailController = async (req: Request, res: Response) => { }; export const deleteSessionController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const { sessionId } = req.params; - const currentSession = req.sessionId; - if (!userId) { - throw new Error("User ID not found in request"); - } + const userId = req.user!.id; + const { sessionId } = req.validatedParams as DeleteSessionParamsType; + const currentSession = req.sessionId!; if (currentSession === sessionId) { return res .status(400) .json({ message: "Cannot delete current active session" }); } await deleteSession(userId, sessionId); - return res.status(204).send({ - message: "Session deleted successfully", - }); + return res.status(204).json(); }; export const deleteAllSessionsController = async ( req: Request, res: Response ) => { - const { removeCurrent } = ( - req.body as unknown as { validatedBody?: DeleteAllSessionsType } - ).validatedBody!; - const userId = req.user?._id; - const currentSession = req.sessionId; - - if (!userId) { - throw new Error("User ID not found in request"); - } - if (!currentSession) { - throw new Error("Session ID not found in request"); - } + const { removeCurrent } = req.validatedBody as DeleteAllSessionsType; + const userId = req.user!.id; + const currentSession = req.sessionId!; await deleteAllSessions(userId, currentSession, removeCurrent); - return res.status(204).send(); + return res.status(204).json(); }; -export const deleteAccountController = async (req: Request, res: Response) => { - const userId = req.user?._id; - if (!userId) { - throw new Error("User ID not found in request"); - } - // Implementation for deleting user account - await deleteAccount(userId); - return res.status(204).send(); -}; +export const deactivateAccountController = async ( + req: Request, + res: Response +) => { + const userId = req.user!.id; + await deactivateAccount(userId); -export const updateAccountController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const sessionId = req.sessionId; - const { accountStatus } = ( - req.body as unknown as { validatedBody?: UpdateAccountType } - ).validatedBody!; - if (!userId) { - throw new Error("User ID not found in request"); - } - if (!sessionId) { - throw new Error("Session ID not found in request"); - } - const updatedUser = await updateAccount(userId, accountStatus, sessionId); + return res.status(200).json({ + message: "Account deactivated successfully", + }); +}; +export const reactivateAccountController = async ( + req: Request, + res: Response +) => { + const userId = req.user!.id; + const updatedUser = await reactivateAccount(userId); return res.status(200).json({ - message: "Account updated successfully", user: updatedUser, + message: "Account reactivated successfully", }); }; + +export const deleteAccountController = async (req: Request, res: Response) => { + const userId = req.user!.id; + await deleteAccount(userId); + return res.status(204).json(); +}; diff --git a/src/modules/user/user.routes.ts b/src/modules/user/user.routes.ts index 18dc2d5..2823bf3 100644 --- a/src/modules/user/user.routes.ts +++ b/src/modules/user/user.routes.ts @@ -1,7 +1,5 @@ import { Router } from "express"; import { asyncHandler } from "@utils/asyncHandler.js"; -import { requireAuth as auth } from "@middleware/auth/requireAuth.js"; -import { requireCsrf as csrf } from "@middleware/auth/requireCsrf.js"; import { deleteAvatarController, getBillingController, @@ -18,32 +16,34 @@ import { deleteSessionController, deleteAllSessionsController, deleteAccountController, - updateAccountController, + deactivateAccountController, + reactivateAccountController, } from "./user.controller.js"; import { deleteAllSessionsSchema, deleteSessionParamsSchema, - updateAccountSchema, - updateAvatarSchema, updateEmailSchema, updateNotificationsSchema, updatePasswordSchema, updatePrivacySettingsSchema, updateProfileSchema, - validateBody, - validateParams, } from "@validation/user.schema.js"; +import { validateBody } from "@validation/validateBody.js"; +import { validateParams } from "@validation/validateParams.js"; +import { avatarUpload } from "@middleware/multer/avatarUpload.js"; +import { requireActiveAccount } from "@middleware/security/requireActiveAccount.js"; const router = Router(); -router.use(auth); +router.patch("/account/reactivate", asyncHandler(reactivateAccountController)); + +router.use(requireActiveAccount); router.get("/profile", asyncHandler(getProfileController)); router.get("/settings", asyncHandler(getSettingsController)); router.get("/security", asyncHandler(getSecurityController)); router.get("/sessions", asyncHandler(getSessionsController)); router.get("/billing", asyncHandler(getBillingController)); - -router.use(csrf); + router.patch( "/profile", validateBody(updateProfileSchema), @@ -51,7 +51,7 @@ router.patch( ); router.patch( "/profile/avatar", - validateBody(updateAvatarSchema), + avatarUpload, asyncHandler(updateAvatarController) ); router.delete("/profile/avatar", asyncHandler(deleteAvatarController)); @@ -78,21 +78,18 @@ router.patch( router.delete( "/sessions/:sessionId", - validateBody(deleteAllSessionsSchema), + validateParams(deleteSessionParamsSchema), asyncHandler(deleteSessionController) ); router.delete( "/sessions", - validateParams(deleteSessionParamsSchema), + validateBody(deleteAllSessionsSchema), asyncHandler(deleteAllSessionsController) ); // router.patch("/billing/plan", asyncHandler() ) to be done after payment integration -router.delete("/account", asyncHandler(deleteAccountController)); -router.patch( - "/account", - validateBody(updateAccountSchema), - asyncHandler(updateAccountController) -); +router.patch("/account/deactivate", asyncHandler(deactivateAccountController)); +router.delete("/account/delete", asyncHandler(deleteAccountController)); +// Request Hard Account Data Deletion Route can be added here in the future export default router; diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 1f48874..e58b81e 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -1,106 +1,108 @@ -import { ACCOUNT_STATUSES, AccountStatus } from "constants/accountStatus.js"; -import bcrypt from "bcrypt"; +import bcrypt from 'bcrypt'; import { + BadRequestError, ConflictError, InternalServerError, NotFoundError, -} from "@middleware/error/index.js"; -import { Session, SessionModel } from "@models/Session.js"; -import { type User, UserModel } from "@models/User.js"; -import { returnUserData } from "@utils/returnUserData.js"; -import { UpdateAvatarType } from "@validation/user.schema.js"; -import mongoose, { ObjectIdSchemaDefinition } from "mongoose"; -import { generateVerificationToken, verifyToken } from "@utils/tokens.js"; -import transporter from "config/mail.js"; -import { verifyUpdatedEmailTemplate } from "./email/templlate/verifyUpdatedEmail.js"; - -export const getProfile = async ( - userId: ObjectIdSchemaDefinition -): Promise => { - const user = await UserModel.findById(userId).select( - "-passwordHash -emailVerificationToken -resetPasswordToken -createdAt -updatedAt" - ); + UnauthenticatedError, +} from '@middleware/error/index.js'; +import { SessionModel } from '@models/Session.js'; +import { type User, UserModel } from '@models/User.js'; +import { sanitizeUserResponse } from '@utils/sanitizeUserResponse.js'; +import { UpdateNotificationsType, UpdatePrivacySettingsType } from '@validation/user.schema.js'; +import { generateVerificationToken } from '@utils/tokens.js'; +import sendUpdateEmailLink from '@utils/emails/sender/sendUpdateEmailLink.js'; +import sendOldEmailVerificationForEmailUpdate from '@utils/emails/sender/sendOldEmailVerificationForEmailUpdate.js'; +import { withTransaction } from '@db/withTransaction.js'; + +export const getProfile = async (userId: string): Promise => { + const user = await UserModel.findById(userId) + .select('-passwordHash -emailVerificationToken -resetPasswordToken -createdAt -updatedAt') + .catch((err) => { + throw new InternalServerError('Could not fetch user profile', err.message); + }); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } return user; }; -export const updateProfile = async ( - userId: ObjectIdSchemaDefinition, - updateData: Partial -): Promise> => { +export const updateProfile = async (userId: string, updateData: Partial): Promise> => { const user = await UserModel.findByIdAndUpdate(userId, updateData, { new: true, }); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(user, "profile"); + const resUser = sanitizeUserResponse(user, 'profile'); return resUser; }; export const updateAvatar = async ( - userId: ObjectIdSchemaDefinition, - avatarData: UpdateAvatarType + userId: string, + avatarData: Express.Multer.File | undefined ): Promise> => { - // user will send a file not url so treat it here and store it in a location on cloud or locally localstack s3 - const avatarUrl = `/uploads/avatars/${userId.toString()}/${Date.now()}_${avatarData}`; - const user = await UserModel.findByIdAndUpdate( - userId, - { avatarUrl: avatarUrl }, - { new: true } - ); + if (!avatarData) { + throw new BadRequestError('Avatar file not found'); + } + const { filename, path } = avatarData; + + //TODO: Add logic to move the file from temp to cloud storage like s3 or similar + // For now, we will just use the filename as is + const avatarUrl = `${path}/${filename}`; + + const user = await UserModel.findByIdAndUpdate(userId, { avatarUrl: avatarUrl }, { new: true }); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(user, "profile"); + const resUser = sanitizeUserResponse(user, 'profile'); return resUser; }; -export const deleteAvatar = async ( - userId: ObjectIdSchemaDefinition -): Promise => { - const user = await UserModel.findByIdAndUpdate( - userId, - { $unset: { avatarUrl: "" } }, - { new: true } - ); +export const deleteAvatar = async (userId: string): Promise => { + const user = await UserModel.findById(userId); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } + const oldAvatarUrl = user.avatarUrl; + + /** TODO: + * Retrieves the current avatar URL from the user object before updating it. + * This variable stores the old avatar URL to enable cleanup of the previous avatar file + * from cloud storage if a new avatar is uploaded during the update process. + * If no avatar currently exists, this will be undefined or null, and the cleanup step should be skipped. + */ + if (!oldAvatarUrl) { + return; + } + + await UserModel.findByIdAndUpdate(userId, { $unset: { avatarUrl: '' } }, { new: true }); return; }; -export const getSettings = async ( - userId: ObjectIdSchemaDefinition -): Promise> => { - const user = await UserModel.findById(userId).select( - "emailNotifications privacySettings" - ); +export const getSettings = async (userId: string): Promise> => { + const user = await UserModel.findById(userId).select('emailNotifications privacySettings'); if (!user) { - throw new Error("User not found"); + throw new Error('User not found'); } - const resUser = returnUserData(user as User, "settings"); + const resUser = sanitizeUserResponse(user as User, 'settings'); return resUser; }; -export const getSecurity = async ( - userId: ObjectIdSchemaDefinition -): Promise> => { +export const getSecurity = async (userId: string): Promise> => { const user = await UserModel.findById(userId).select( - "email phoneNumber passwordHash emailVerified phoneVerified lastPasswordChangeAt twoFactorEnabled oauthProviders" + 'email phoneNumber passwordHash emailVerified phoneVerified lastPasswordChangeAt twoFactorEnabled oauthProviders' ); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(user as User, "security"); + const resUser = sanitizeUserResponse(user as User, 'security'); return resUser; }; export const getSessions = async ( - userId: ObjectIdSchemaDefinition, + userId: string, sessioId: string ): Promise< Array<{ @@ -115,22 +117,14 @@ export const getSessions = async ( }> > => { const sessions = await SessionModel.find({ userId: userId }); - if (!sessions) { - throw new InternalServerError("Could not fetch sessions"); - } const resSessions = sessions.map((session) => { return { sessionId: session.sessionId, current: session.sessionId === sessioId, - device: - session.device?.vendor + - " " + - session.device?.model + - " " + - session.device?.type, - browser: session.browser!.name + " " + session.browser!.version, - location: session.city + ", " + session.country, + device: session.device?.vendor + ' ' + session.device?.model + ' ' + session.device?.type, + browser: session.browser!.name + ' ' + session.browser!.version, + location: session.city + ', ' + session.country, createdAt: session.createdAt, lastUsedAt: session.lastUsedAt, revokedAt: session.revokedAt, @@ -139,144 +133,155 @@ export const getSessions = async ( return resSessions; }; -export const getBilling = async ( - userId: ObjectIdSchemaDefinition -): Promise> => { - const user = await UserModel.findById(userId).select("plan billingInfo"); +export const getBilling = async (userId: string): Promise> => { + const user = await UserModel.findById(userId).select('plan billingInfo'); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(user as User, "billing"); + const resUser = sanitizeUserResponse(user as User, 'billing'); return resUser; }; export const updateNotifications = async ( - userId: ObjectIdSchemaDefinition, - notificationPrefs: any + userId: string, + notificationPrefs: UpdateNotificationsType ): Promise> => { - const user = await UserModel.findByIdAndUpdate( - userId, - { emailNotifications: notificationPrefs }, - { new: true } - ); + const update: Record = {}; + + if (notificationPrefs.emailNotifications !== undefined) { + update['notificationPrefs.emailOnJobComplete'] = notificationPrefs.emailNotifications; + } + + if (notificationPrefs.pushNotifications !== undefined) { + update['notificationPrefs.inApp'] = notificationPrefs.pushNotifications; + } + + if (notificationPrefs.newsletter !== undefined) { + update['notificationPrefs.marketingEmails'] = notificationPrefs.newsletter; + } + + const user = await UserModel.findByIdAndUpdate(userId, { $set: update }, { new: true }); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(user as User, "settings"); + const resUser = sanitizeUserResponse(user as User, 'settings'); return resUser; }; export const updatePrivacySettings = async ( - userId: ObjectIdSchemaDefinition, - privacyPrefs: any + userId: string, + privacyPrefs: UpdatePrivacySettingsType ): Promise> => { - const user = await UserModel.findByIdAndUpdate( - userId, - { privacySettings: privacyPrefs }, - { new: true } - ); + const update: Record = {}; + if (privacyPrefs.profileVisibility !== undefined) { + update['privacyPrefs.profileVisibility'] = privacyPrefs.profileVisibility; + } + if (privacyPrefs.showEmailOnProfile !== undefined) { + update['privacyPrefs.showEmailOnProfile'] = privacyPrefs.showEmailOnProfile; + } + if (privacyPrefs.showLinksOnProfile !== undefined) { + update['privacyPrefs.showLinksOnProfile'] = privacyPrefs.showLinksOnProfile; + } + if (privacyPrefs.allowDiscoverability !== undefined) { + update['privacyPrefs.allowDiscoverability'] = privacyPrefs.allowDiscoverability; + } + + const user = await UserModel.findByIdAndUpdate(userId, { $set: update }, { new: true }); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(user as User, "settings"); + const resUser = sanitizeUserResponse(user as User, 'settings'); return resUser; }; export const updatePassword = async ( - userId: ObjectIdSchemaDefinition, + userId: string, currentPassword: string, newPassword: string ): Promise => { - const user = await UserModel.findById(userId); + const user = await UserModel.findById(userId).select('+passwordHash +changeHistory'); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } + const isMatch = await bcrypt.compare(currentPassword, user.passwordHash); if (!isMatch) { - throw new Error("Current password is incorrect"); + throw new UnauthenticatedError('Current password is incorrect'); } const hashedPassword = await bcrypt.hash(newPassword, 10); user.lastPasswordChangeAt = new Date(); user.passwordHash = hashedPassword; + user.changeHistory.push({ + field: 'password', + by: user._id, + from: '', + to: '', + reason: 'User initiated password change', + at: new Date(), + via: 'user', + }); await user.save(); return; }; -export const updateEmail = async ( - userId: ObjectIdSchemaDefinition, - newEmail: string -): Promise => { +export const updateEmail = async (userId: string, newEmail: string): Promise => { const user = await UserModel.findById(userId); if (!user) { - throw new NotFoundError("User not found"); + throw new NotFoundError('User not found'); } if (user.email === newEmail) { - throw new ConflictError("New email is the same as the current email"); + throw new ConflictError('New email is the same as the current email'); } const emailInUse = await UserModel.findOne({ email: newEmail }); if (emailInUse) { - throw new ConflictError("Email is already in use"); + throw new ConflictError('Email is already in use'); } const token = generateVerificationToken(); + const code = Math.floor(100000 + Math.random() * 900000) + .toString() + .slice(0, 6); + const codeHash = await bcrypt.hash(code, 10); - const updateEmaillUrl = `${ - process.env.APP_URL - }/verify-email-change?token=${encodeURIComponent( - token.raw - )}&userId=${encodeURIComponent( - user._id.toString() - )}&newEmail=${encodeURIComponent(newEmail)}`; - - const { subject, text, html } = verifyUpdatedEmailTemplate( - user.displayName ?? user.username ?? null, - updateEmaillUrl - ); + const updateEmailUrl = `${process.env.APP_URL}/verify-email-change?token=${encodeURIComponent(token.raw)}`; - try { - await transporter.sendMail({ - from: process.env.EMAIL_FROM, - to: newEmail, - subject: subject, - text: text, - html: html, - }); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : String(err); - throw new InternalServerError( - "Failed to send verification email", - errorMessage - ); - } user.pendingEmailChange = { newEmail: newEmail, + code: codeHash, tokenHash: token.hash, - expiresAt: new Date(Date.now() + 3600 * 1000), // 1 hour + expiresAt: new Date(Date.now() + 30 * 60 * 1000), // 30 minutes requestedAt: new Date(), - requestMethod: "self", + requestMethod: 'self', }; await user.save(); + + console.log('Update Email URL:', updateEmailUrl, 'code:', code); + // send verification code to old email + sendOldEmailVerificationForEmailUpdate(user, code); + sendUpdateEmailLink(user, newEmail, updateEmailUrl); return; }; -export const deleteSession = async ( - userId: ObjectIdSchemaDefinition, - sessionId: string -): Promise => { +export const deleteSession = async (userId: string, sessionId: string): Promise => { const session = await SessionModel.findOne({ userId: userId, sessionId: sessionId, }); if (!session) { - throw new Error("Session not found"); + throw new NotFoundError('Session not found'); + } + if (session.revokedAt) { + throw new BadRequestError('Session already revoked'); } + session.revokedAt = new Date(); + session.valid = false; await session.save(); return; }; export const deleteAllSessions = async ( - userId: ObjectIdSchemaDefinition, + userId: string, currentSessionId: string, removeCurrent: boolean | undefined ): Promise => { @@ -284,93 +289,125 @@ export const deleteAllSessions = async ( if (!removeCurrent) { filter.sessionId = { $ne: currentSessionId }; } - await SessionModel.updateMany(filter, { revokedAt: new Date() }).exec(); + await SessionModel.updateMany(filter, { revokedAt: new Date(), valid: false }) + .exec() + .catch((err) => { + throw new InternalServerError('Could not revoke sessions', err.message); + }); return; }; -export const deleteAccount = async ( - userId: ObjectIdSchemaDefinition -): Promise => { - const session = await mongoose.startSession(); - try { - session.startTransaction(); +export const deleteAccount = async (userId: string): Promise => { + return withTransaction(async (session) => { await UserModel.findByIdAndUpdate( userId, - { deletedAt: new Date(), accountStatus: "deleted" }, + { + deletedAt: new Date(), + accountStatus: 'delete', + $push: { + changeHistory: { + $each: [ + { + field: 'accountStatus', + from: 'active', + to: 'delete', + by: userId, + reason: 'User deleted account', + at: new Date(), + via: 'user', + }, + ], + $slice: -100, + }, + }, + }, { session } ); await SessionModel.deleteMany({ userId }, { session }); - await session.commitTransaction(); - } catch (err) { - await session.abortTransaction(); - throw err; - } finally { - session.endSession(); - } - return; + }); }; -export const updateAccount = async ( - userId: ObjectIdSchemaDefinition, - updateData: AccountStatus, - currentSessionId: string -): Promise> => { - const user = await UserModel.findById(userId); +export const reactivateAccount = async (userId: string): Promise> => { + const user = await UserModel.findById(userId).select('+changeHistory +role'); if (!user) { - throw new Error("User not found"); + throw new NotFoundError('User not found'); } - const latestStatusEvent = await UserModel.aggregate([ - { $match: { _id: userId } }, - { $unwind: "$changeHistory" }, - { $match: { "changeHistory.field": "accountStatus" } }, - { $sort: { "changeHistory.at": -1 } }, - { $limit: 1 }, - { $replaceRoot: { newRoot: "$changeHistory" } }, - ]); - let updatedUser; - const session = await mongoose.startSession(); - session.startTransaction(); - try { - if ( - user.role === "user" && - updateData !== "disabled" && - updateData !== "active" - ) { - throw new Error("Only admin can do this operation"); - } else if ( - user.accountStatus === "disabled" && - latestStatusEvent[0].via !== "user" && - updateData === "active" - ) { - throw new Error( - "Disabled by admin, account can only be activated by admin" - ); - } else { - updatedUser = await UserModel.findByIdAndUpdate( - userId, - { accountStatus: updateData }, - { new: true, session } - ); - - await SessionModel.deleteMany( - { - userId: user._id, - sessionId: { $ne: currentSessionId }, + if (user.accountStatus !== 'deactive' && user.accountStatus !== 'delete') { + throw new BadRequestError( + 'Account is not deactivated or deleted other than that cannot be reactivated. Contact support.' + ); + } + const updatedUser = await UserModel.findByIdAndUpdate( + userId, + { + accountStatus: 'active', + deletedAt: null, + $push: { + changeHistory: { + $each: [ + { + field: 'accountStatus', + from: user.accountStatus, + to: 'active', + by: user._id, + reason: 'Account reactivated', + at: new Date(), + via: user.role, + }, + ], + $slice: -100, }, - { session } - ); + }, + }, + { new: true } + ); + if (!updatedUser) { + throw new NotFoundError('User not found'); + } + const resUser = sanitizeUserResponse(updatedUser, 'profile'); + + return resUser; +}; + +export const deactivateAccount = async (userId: string): Promise> => { + return withTransaction(async (session) => { + const user = await UserModel.findById(userId).select('+changeHistory +role'); + if (!user) { + throw new NotFoundError('User not found'); } - await session.commitTransaction(); + const updatedUser = await UserModel.findByIdAndUpdate( + userId, + { + accountStatus: 'deactive', + $push: { + changeHistory: { + $each: [ + { + field: 'accountStatus', + from: user.accountStatus, + to: 'deactive', + by: user._id, + reason: 'Account status updated', + at: new Date(), + via: user.role, + }, + ], + $slice: -100, + }, + }, + }, + { new: true, session } + ); + await SessionModel.deleteMany( + { + userId: user._id, + }, + { session } + ); if (!updatedUser) { - throw new Error("User not found after update"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(updatedUser, "profile"); + const resUser = sanitizeUserResponse(updatedUser, 'profile'); return resUser; - } catch (err) { - await session.abortTransaction(); - throw err; - } - finally { - session.endSession(); - } + }); }; diff --git a/src/modules/videoConfig/index.ts b/src/modules/videoConfig/index.ts new file mode 100644 index 0000000..0cffd74 --- /dev/null +++ b/src/modules/videoConfig/index.ts @@ -0,0 +1,3 @@ +// export { default as videoConfigRoutes } from './videoConfig.routes.js'; +// export { default as videoConfigController } from './videoConfig.controller.js'; +// export { default as videoConfigService } from './videoConfig.service.js'; diff --git a/src/modules/videoConfig/videoConfig.controller.ts b/src/modules/videoConfig/videoConfig.controller.ts new file mode 100644 index 0000000..8ad3190 --- /dev/null +++ b/src/modules/videoConfig/videoConfig.controller.ts @@ -0,0 +1,379 @@ +// import { Request, Response, NextFunction } from 'express'; +// import { Types } from 'mongoose'; +// import videoConfigService, { createVideoConfig } from './videoConfig.service.js'; +// import { asyncHandler } from '@utils/asyncHandler.js'; +// import { CreateVideoConfigType } from '@validation/videoConfig.schema.js'; + +// // ============ Create Video Config ============ + +// export const createVideoConfigController = async (req: Request, res: Response) => { +// const userId = req.user?.id; +// const requestInput = req.validatedBody as CreateVideoConfigType + +// const videoConfig = await createVideoConfig({ +// userId, +// ...requestInput + +// }); + +// res.status(201).json({ +// success: true, +// message: 'Video configuration created successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Get Video Config By ID ============ + +// export const getVideoConfigById = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const populate = req.query.populate ? (req.query.populate as string).split(',') : undefined; + +// const videoConfig = await videoConfigService.getVideoConfigById(configId, userId, populate); + +// res.status(200).json({ +// success: true, +// data: videoConfig, +// }); +// }); + +// // ============ Get Video Configs ============ + +// export const getVideoConfigs = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); + +// const result = await videoConfigService.getVideoConfigs({ +// userId, +// storyId: req.query.storyId ? new Types.ObjectId(req.query.storyId as string) : undefined, +// projectId: req.query.projectId ? new Types.ObjectId(req.query.projectId as string) : undefined, +// isTemplate: req.query.isTemplate !== undefined ? req.query.isTemplate === 'true' : undefined, +// page: parseInt(req.query.page as string) || 1, +// limit: parseInt(req.query.limit as string) || 20, +// sortBy: req.query.sortBy as string, +// sortOrder: req.query.sortOrder as 'asc' | 'desc', +// }); + +// res.status(200).json({ +// success: true, +// data: result.data, +// pagination: result.pagination, +// }); +// }); + +// // ============ Update Video Config ============ + +// export const updateVideoConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// // Transform ObjectId strings if present +// const updates = { ...req.body }; +// if (updates.sceneOrder) { +// updates.sceneOrder = updates.sceneOrder.map((id: string) => new Types.ObjectId(id)); +// } +// if (updates.narration?.narrationId) { +// updates.narration.narrationId = new Types.ObjectId(updates.narration.narrationId); +// } +// if (updates.narration?.audioAssetId) { +// updates.narration.audioAssetId = new Types.ObjectId(updates.narration.audioAssetId); +// } + +// const videoConfig = await videoConfigService.updateVideoConfig(configId, userId, updates); + +// res.status(200).json({ +// success: true, +// message: 'Video configuration updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Delete Video Config ============ + +// export const deleteVideoConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// await videoConfigService.deleteVideoConfig(configId, userId); + +// res.status(200).json({ +// success: true, +// message: 'Video configuration deleted successfully', +// }); +// }); + +// // ============ Update Narration Config ============ + +// export const updateNarrationConfig = asyncHandler( +// async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const narrationConfig = { +// ...req.body, +// narrationId: new Types.ObjectId(req.body.narrationId), +// audioAssetId: req.body.audioAssetId ? new Types.ObjectId(req.body.audioAssetId) : undefined, +// }; + +// const videoConfig = await videoConfigService.updateNarrationConfig(configId, userId, narrationConfig); + +// res.status(200).json({ +// success: true, +// message: 'Narration configuration updated successfully', +// data: videoConfig, +// }); +// } +// ); + +// // ============ Update Caption Config ============ + +// export const updateCaptionConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateCaptionConfig(configId, userId, req.body); + +// res.status(200).json({ +// success: true, +// message: 'Caption configuration updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Add Sound Effect ============ + +// export const addSoundEffect = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const soundEffect = { +// ...req.body, +// audioAssetId: new Types.ObjectId(req.body.audioAssetId), +// }; + +// const videoConfig = await videoConfigService.addSoundEffect(configId, userId, soundEffect); + +// res.status(201).json({ +// success: true, +// message: 'Sound effect added successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Sound Effect ============ + +// export const updateSoundEffect = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); +// const index = parseInt(req.params.index); + +// const soundEffect = { +// ...req.body.soundEffect, +// audioAssetId: new Types.ObjectId(req.body.soundEffect.audioAssetId), +// }; + +// const videoConfig = await videoConfigService.updateSoundEffect(configId, userId, index, soundEffect); + +// res.status(200).json({ +// success: true, +// message: 'Sound effect updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Remove Sound Effect ============ + +// export const removeSoundEffect = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); +// const index = parseInt(req.params.index); + +// const videoConfig = await videoConfigService.removeSoundEffect(configId, userId, index); + +// res.status(200).json({ +// success: true, +// message: 'Sound effect removed successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Scene Order ============ + +// export const updateSceneOrder = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const sceneOrder = req.body.sceneOrder.map((id: string) => new Types.ObjectId(id)); +// const sceneTiming = req.body.sceneTiming?.map((timing: { sceneId: string }) => ({ +// ...timing, +// sceneId: new Types.ObjectId(timing.sceneId), +// })); + +// const videoConfig = await videoConfigService.updateSceneOrder(configId, userId, sceneOrder, sceneTiming); + +// res.status(200).json({ +// success: true, +// message: 'Scene order updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Transitions ============ + +// export const updateTransitions = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateTransitions(configId, userId, req.body.transitions); + +// res.status(200).json({ +// success: true, +// message: 'Transitions updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Output Settings ============ + +// export const updateOutputSettings = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateOutputSettings(configId, userId, req.body); + +// res.status(200).json({ +// success: true, +// message: 'Output settings updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Background Audio ============ + +// export const updateBackgroundAudio = asyncHandler( +// async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const backgroundAudio = { +// ...req.body, +// audioAssetId: req.body.audioAssetId ? new Types.ObjectId(req.body.audioAssetId) : undefined, +// }; + +// const videoConfig = await videoConfigService.updateBackgroundAudio(configId, userId, backgroundAudio); + +// res.status(200).json({ +// success: true, +// message: 'Background audio updated successfully', +// data: videoConfig, +// }); +// } +// ); + +// // ============ Update Watermark ============ + +// export const updateWatermark = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateWatermark(configId, userId, req.body); + +// res.status(200).json({ +// success: true, +// message: 'Watermark updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Validate For Rendering ============ + +// export const validateForRendering = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const result = await videoConfigService.validateForRendering(configId, userId); + +// res.status(200).json({ +// success: true, +// data: result, +// }); +// }); + +// // ============ Clone Video Config ============ + +// export const cloneVideoConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.cloneVideoConfig( +// configId, +// userId, +// req.body.name, +// req.body.description +// ); + +// res.status(201).json({ +// success: true, +// message: 'Video configuration cloned successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Get Templates ============ + +// export const getTemplates = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const page = parseInt(req.query.page as string) || 1; +// const limit = parseInt(req.query.limit as string) || 20; + +// const result = await videoConfigService.getTemplates(userId, page, limit); + +// res.status(200).json({ +// success: true, +// data: result.data, +// pagination: result.pagination, +// }); +// }); + +// // ============ Apply Template ============ + +// export const applyTemplate = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); + +// const videoConfig = await videoConfigService.applyTemplate( +// new Types.ObjectId(req.body.templateId), +// userId, +// new Types.ObjectId(req.body.storyId), +// new Types.ObjectId(req.body.projectId), +// req.body.name +// ); + +// res.status(201).json({ +// success: true, +// message: 'Template applied successfully', +// data: videoConfig, +// }); +// }); + +// export default { +// createVideoConfig, +// getVideoConfigById, +// getVideoConfigs, +// updateVideoConfig, +// deleteVideoConfig, +// updateNarrationConfig, +// updateCaptionConfig, +// addSoundEffect, +// updateSoundEffect, +// removeSoundEffect, +// updateSceneOrder, +// updateTransitions, +// updateOutputSettings, +// updateBackgroundAudio, +// updateWatermark, +// validateForRendering, +// cloneVideoConfig, +// getTemplates, +// applyTemplate, +// }; diff --git a/src/modules/videoConfig/videoConfig.routes.ts b/src/modules/videoConfig/videoConfig.routes.ts new file mode 100644 index 0000000..25202cf --- /dev/null +++ b/src/modules/videoConfig/videoConfig.routes.ts @@ -0,0 +1,107 @@ +// import { Router } from 'express'; +// import { validateBody } from '@validation/validateBody.js'; +// import { +// createVideoConfigSchema, +// updateVideoConfigSchema, +// updateNarrationConfigSchema, +// updateCaptionsConfigSchema, +// addSoundEffectSchema, +// updateSoundEffectSchema, +// updateSceneOrderSchema, +// updateTransitionsSchema, +// updateOutputSettingsSchema, +// updateBackgroundAudioSchema, +// updateWatermarkSchema, +// cloneVideoConfigSchema, +// applyTemplateSchema, +// } from '@validation/videoConfig.schema.js'; +// import { +// createVideoConfig, +// getVideoConfigById, +// getVideoConfigs, +// updateVideoConfig, +// deleteVideoConfig, +// updateNarrationConfig, +// updateCaptionConfig, +// addSoundEffect, +// updateSoundEffect, +// removeSoundEffect, +// updateSceneOrder, +// updateTransitions, +// updateOutputSettings, +// updateBackgroundAudio, +// updateWatermark, +// validateForRendering, +// cloneVideoConfig, +// getTemplates, +// applyTemplate, +// } from './videoConfig.controller.js'; +// import { asyncHandler } from '@utils/asyncHandler.js'; + +// const router = Router(); + +// router.post('/', validateBody(createVideoConfigSchema), asyncHandler(createVideoConfig)); + +// router.get('/', asyncHandler(getVideoConfigs)); + +// router.get('/templates', asyncHandler(getTemplates)); + +// router.post('/apply-template', validateBody(applyTemplateSchema), asyncHandler(applyTemplate)); + +// router.get('/:configId', asyncHandler(getVideoConfigById)); + +// router.patch('/:configId', validateBody(updateVideoConfigSchema), asyncHandler(updateVideoConfig)); + +// router.delete('/:configId', asyncHandler(deleteVideoConfig)); + +// router.patch( +// '/:configId/narration', +// validateBody(updateNarrationConfigSchema), +// asyncHandler(updateNarrationConfig) +// ); + +// router.patch( +// '/:configId/captions', +// validateBody(updateCaptionsConfigSchema), +// asyncHandler(updateCaptionConfig) +// ); + +// router.post('/:configId/sound-effects', validateBody(addSoundEffectSchema), asyncHandler(addSoundEffect)); + +// router.patch( +// '/:configId/sound-effects/:index', +// validateBody(updateSoundEffectSchema), +// asyncHandler(updateSoundEffect) +// ); + +// router.delete('/:configId/sound-effects/:index', asyncHandler(removeSoundEffect)); + +// router.patch('/:configId/scene-order', validateBody(updateSceneOrderSchema), asyncHandler(updateSceneOrder)); + +// router.patch( +// '/:configId/transitions', +// validateBody(updateTransitionsSchema), +// asyncHandler(updateTransitions) +// ); + +// router.patch( +// '/:configId/output-settings', +// validateBody(updateOutputSettingsSchema), +// asyncHandler(updateOutputSettings) +// ); + +// router.patch( +// '/:configId/background-audio', +// validateBody(updateBackgroundAudioSchema), +// asyncHandler(updateBackgroundAudio) +// ); + +// // Validate configuration for rendering +// router.post('/:configId/validate', asyncHandler(validateForRendering)); + +// // ============ Clone Routes ============ + +// // Clone a video configuration +// router.post('/:configId/clone', validateBody(cloneVideoConfigSchema), asyncHandler(cloneVideoConfig)); + +// export default router; diff --git a/src/modules/videoConfig/videoConfig.service.ts b/src/modules/videoConfig/videoConfig.service.ts new file mode 100644 index 0000000..6d9b7e3 --- /dev/null +++ b/src/modules/videoConfig/videoConfig.service.ts @@ -0,0 +1,639 @@ +// import { Types, FilterQuery, SortOrder } from 'mongoose'; +// import VideoConfig, { +// IVideoConfig, +// ISoundEffectConfig, +// ISceneTimingConfig, +// ITransitionConfig, +// INarrationConfig, +// ICaptionConfig, +// IOutputSettings, +// IBackgroundAudioConfig, +// IWatermarkConfig, +// } from '@models/VideoConfig.js'; +// import { AppError } from '../../middleware/error/appError'; +// import { VIDEO_CONFIG_ERROR_MESSAGES, MAX_SOUND_EFFECTS_PER_CONFIG } from '../../constants/videoConfigConsts'; +// import { validateVideoConfigOwnership } from '../../validators/validateVideoConfigOwnership'; + +// // ============ Types ============ + +// interface CreateVideoConfigInput { +// userId: Types.ObjectId; +// storyId: Types.ObjectId; +// projectId: Types.ObjectId; +// name: string; +// description?: string; +// sceneOrder: Types.ObjectId[]; +// sceneTiming?: ISceneTimingConfig[]; +// narration: INarrationConfig; +// captions?: ICaptionConfig; +// soundEffects?: ISoundEffectConfig[]; +// transitions?: ITransitionConfig[]; +// backgroundAudio?: IBackgroundAudioConfig; +// watermark?: IWatermarkConfig; +// outputSettings?: IOutputSettings; +// isTemplate?: boolean; +// templateName?: string; +// } + +// interface UpdateVideoConfigInput { +// name?: string; +// description?: string; +// sceneOrder?: Types.ObjectId[]; +// sceneTiming?: ISceneTimingConfig[]; +// narration?: INarrationConfig; +// captions?: ICaptionConfig; +// soundEffects?: ISoundEffectConfig[]; +// transitions?: ITransitionConfig[]; +// backgroundAudio?: IBackgroundAudioConfig; +// watermark?: IWatermarkConfig; +// outputSettings?: IOutputSettings; +// isTemplate?: boolean; +// templateName?: string; +// } + +// interface GetVideoConfigsQuery { +// userId: Types.ObjectId; +// storyId?: Types.ObjectId; +// projectId?: Types.ObjectId; +// isTemplate?: boolean; +// page?: number; +// limit?: number; +// sortBy?: string; +// sortOrder?: 'asc' | 'desc'; +// } + +// interface PaginatedResult { +// data: T[]; +// pagination: { +// total: number; +// page: number; +// limit: number; +// totalPages: number; +// hasNextPage: boolean; +// hasPrevPage: boolean; +// }; +// } + +// // ============ Service Functions ============ + +// /** +// * Create a new video configuration +// */ +// export async function createVideoConfig(input: CreateVideoConfigInput): Promise { +// const { +// userId, +// storyId, +// projectId, +// name, +// description, +// sceneOrder, +// sceneTiming, +// narration, +// captions, +// soundEffects, +// transitions, +// backgroundAudio, +// watermark, +// outputSettings, +// isTemplate, +// templateName, +// } = input; + +// // Validate sound effects count +// if (soundEffects && soundEffects.length > MAX_SOUND_EFFECTS_PER_CONFIG) { +// throw new AppError(VIDEO_CONFIG_ERROR_MESSAGES.TOO_MANY_SOUND_EFFECTS, 400); +// } + +// // Generate scene timing if not provided +// let finalSceneTiming = sceneTiming; +// if (!finalSceneTiming || finalSceneTiming.length === 0) { +// finalSceneTiming = sceneOrder.map((sceneId, index) => ({ +// sceneId, +// order: index, +// startTime: index * 5, // Default 5 seconds per scene +// duration: 5, +// })); +// } + +// // Calculate total duration from scene timing +// const totalDuration = calculateTotalDuration(finalSceneTiming); + +// const videoConfig = new VideoConfig({ +// userId, +// storyId, +// projectId, +// name, +// description, +// sceneOrder, +// sceneTiming: finalSceneTiming, +// totalDuration, +// narration, +// captions: captions || {}, +// soundEffects: soundEffects || [], +// videoEffects: [], // Video effects are stored but not used yet +// transitions: transitions || generateDefaultTransitions(sceneOrder.length), +// backgroundAudio: backgroundAudio || {}, +// watermark: watermark || {}, +// outputSettings: outputSettings || {}, +// isTemplate: isTemplate || false, +// templateName, +// }); + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Get a video configuration by ID +// */ +// export async function getVideoConfigById( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// populate?: string[] +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId, { +// populate, +// }); +// return videoConfig; +// } + +// /** +// * Get all video configurations for a user with pagination +// */ +// export async function getVideoConfigs(query: GetVideoConfigsQuery): Promise> { +// const { +// userId, +// storyId, +// projectId, +// isTemplate, +// page = 1, +// limit = 20, +// sortBy = 'createdAt', +// sortOrder = 'desc', +// } = query; + +// // Build filter +// const filter: FilterQuery = { userId }; + +// if (storyId) filter.storyId = storyId; +// if (projectId) filter.projectId = projectId; +// if (isTemplate !== undefined) filter.isTemplate = isTemplate; + +// // Build sort +// const sort: Record = { +// [sortBy]: sortOrder === 'asc' ? 1 : -1, +// }; + +// // Calculate skip +// const skip = (page - 1) * limit; + +// // Execute query +// const [data, total] = await Promise.all([ +// VideoConfig.find(filter).sort(sort).skip(skip).limit(limit).lean(), +// VideoConfig.countDocuments(filter), +// ]); + +// const totalPages = Math.ceil(total / limit); + +// return { +// data: data as IVideoConfig[], +// pagination: { +// total, +// page, +// limit, +// totalPages, +// hasNextPage: page < totalPages, +// hasPrevPage: page > 1, +// }, +// }; +// } + +// /** +// * Update a video configuration +// */ +// export async function updateVideoConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// updates: UpdateVideoConfigInput +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// // Validate sound effects count if provided +// if (updates.soundEffects && updates.soundEffects.length > MAX_SOUND_EFFECTS_PER_CONFIG) { +// throw new AppError(VIDEO_CONFIG_ERROR_MESSAGES.TOO_MANY_SOUND_EFFECTS, 400); +// } + +// // Apply updates +// Object.assign(videoConfig, updates); + +// // Recalculate total duration if scene timing changed +// if (updates.sceneTiming) { +// videoConfig.totalDuration = calculateTotalDuration(updates.sceneTiming); +// } + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Delete a video configuration +// */ +// export async function deleteVideoConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string +// ): Promise { +// await validateVideoConfigOwnership(configId, userId); +// await VideoConfig.findByIdAndDelete(configId); +// } + +// /** +// * Update narration configuration +// */ +// export async function updateNarrationConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// narrationConfig: INarrationConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.narration = narrationConfig; + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update caption configuration +// */ +// export async function updateCaptionConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// captionConfig: ICaptionConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.captions = captionConfig; + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Add a sound effect to a video configuration +// */ +// export async function addSoundEffect( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// soundEffect: ISoundEffectConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// // Check max sound effects +// if (videoConfig.soundEffects.length >= MAX_SOUND_EFFECTS_PER_CONFIG) { +// throw new AppError(VIDEO_CONFIG_ERROR_MESSAGES.TOO_MANY_SOUND_EFFECTS, 400); +// } + +// // Validate start time is within video duration +// if (soundEffect.startTime > videoConfig.totalDuration) { +// throw new AppError( +// `Sound effect start time (${soundEffect.startTime}s) exceeds video duration (${videoConfig.totalDuration}s)`, +// 400 +// ); +// } + +// videoConfig.soundEffects.push(soundEffect); +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update a sound effect in a video configuration +// */ +// export async function updateSoundEffect( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// index: number, +// soundEffect: ISoundEffectConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// if (index < 0 || index >= videoConfig.soundEffects.length) { +// throw new AppError('Sound effect index out of range', 400); +// } + +// videoConfig.soundEffects[index] = soundEffect; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Remove a sound effect from a video configuration +// */ +// export async function removeSoundEffect( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// index: number +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// if (index < 0 || index >= videoConfig.soundEffects.length) { +// throw new AppError('Sound effect index out of range', 400); +// } + +// videoConfig.soundEffects.splice(index, 1); +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update scene order and timing +// */ +// export async function updateSceneOrder( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// sceneOrder: Types.ObjectId[], +// sceneTiming?: ISceneTimingConfig[] +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.sceneOrder = sceneOrder; + +// if (sceneTiming) { +// videoConfig.sceneTiming = sceneTiming; +// videoConfig.totalDuration = calculateTotalDuration(sceneTiming); +// } else { +// // Generate new timing based on new order +// videoConfig.sceneTiming = sceneOrder.map((sceneId, index) => ({ +// sceneId, +// order: index, +// startTime: index * 5, +// duration: 5, +// })); +// videoConfig.totalDuration = calculateTotalDuration(videoConfig.sceneTiming); +// } + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update transitions +// */ +// export async function updateTransitions( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// transitions: ITransitionConfig[] +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.transitions = transitions; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update output settings +// */ +// export async function updateOutputSettings( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// outputSettings: IOutputSettings +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.outputSettings = outputSettings; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update background audio +// */ +// export async function updateBackgroundAudio( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// backgroundAudio: IBackgroundAudioConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.backgroundAudio = backgroundAudio; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update watermark settings +// */ +// export async function updateWatermark( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// watermark: IWatermarkConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.watermark = watermark; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Validate a video configuration for rendering +// */ +// export async function validateForRendering( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string +// ): Promise<{ isValid: boolean; errors: string[] }> { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId, { +// populate: ['sceneOrder'], +// }); + +// const errors: string[] = []; + +// // Check scene order +// if (!videoConfig.sceneOrder || videoConfig.sceneOrder.length === 0) { +// errors.push('At least one scene is required'); +// } + +// // Check narration +// if (!videoConfig.narration?.narrationId) { +// errors.push('Narration is required'); +// } + +// // Check total duration +// if (videoConfig.totalDuration <= 0) { +// errors.push('Total duration must be greater than 0'); +// } + +// // Check sound effects timing +// for (let i = 0; i < videoConfig.soundEffects.length; i++) { +// const effect = videoConfig.soundEffects[i]; +// if (effect.enabled && effect.startTime > videoConfig.totalDuration) { +// errors.push(`Sound effect "${effect.name}" starts after video ends`); +// } +// } + +// // Check narration timing +// const narration = videoConfig.narration; +// if (narration.enabled) { +// const effectiveStart = narration.startOffset; +// const effectiveEnd = videoConfig.totalDuration - narration.endOffset; + +// if (effectiveStart >= effectiveEnd) { +// errors.push('Narration start offset and end offset overlap'); +// } +// } + +// const isValid = errors.length === 0; + +// return { isValid, errors }; +// } + +// /** +// * Clone a video configuration +// */ +// export async function cloneVideoConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// newName: string, +// newDescription?: string +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// const clonedConfig = new VideoConfig({ +// userId: videoConfig.userId, +// storyId: videoConfig.storyId, +// projectId: videoConfig.projectId, +// name: newName, +// description: newDescription || videoConfig.description, +// sceneOrder: [...videoConfig.sceneOrder], +// sceneTiming: videoConfig.sceneTiming.map((t) => ({ ...t })), +// totalDuration: videoConfig.totalDuration, +// narration: { ...videoConfig.narration }, +// captions: { ...videoConfig.captions }, +// soundEffects: videoConfig.soundEffects.map((s) => ({ ...s })), +// videoEffects: videoConfig.videoEffects.map((v) => ({ ...v })), +// transitions: videoConfig.transitions.map((t) => ({ ...t })), +// backgroundAudio: { ...videoConfig.backgroundAudio }, +// watermark: { ...videoConfig.watermark }, +// outputSettings: { ...videoConfig.outputSettings }, +// isTemplate: false, +// version: 1, +// }); + +// await clonedConfig.save(); +// return clonedConfig; +// } + +// /** +// * Get templates for a user +// */ +// export async function getTemplates( +// userId: Types.ObjectId | string, +// page = 1, +// limit = 20 +// ): Promise> { +// return getVideoConfigs({ +// userId: new Types.ObjectId(userId), +// isTemplate: true, +// page, +// limit, +// }); +// } + +// /** +// * Apply a template to create a new video configuration +// */ +// export async function applyTemplate( +// templateId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// storyId: Types.ObjectId | string, +// projectId: Types.ObjectId | string, +// name: string +// ): Promise { +// const { videoConfig: template } = await validateVideoConfigOwnership(templateId, userId); + +// if (!template.isTemplate) { +// throw new AppError('The specified configuration is not a template', 400); +// } + +// const newConfig = new VideoConfig({ +// userId: new Types.ObjectId(userId), +// storyId: new Types.ObjectId(storyId), +// projectId: new Types.ObjectId(projectId), +// name, +// description: template.description, +// sceneOrder: [], // Will be populated separately +// sceneTiming: [], +// totalDuration: 0, +// narration: { ...template.narration, narrationId: undefined, audioAssetId: undefined }, +// captions: { ...template.captions }, +// soundEffects: [], // Sound effects need to be re-added +// videoEffects: template.videoEffects.map((v) => ({ ...v })), +// transitions: template.transitions.map((t) => ({ ...t })), +// backgroundAudio: { ...template.backgroundAudio, audioAssetId: undefined }, +// watermark: { ...template.watermark }, +// outputSettings: { ...template.outputSettings }, +// isTemplate: false, +// version: 1, +// }); + +// await newConfig.save(); +// return newConfig; +// } + +// // ============ Helper Functions ============ + +// /** +// * Calculate total duration from scene timing +// */ +// function calculateTotalDuration(sceneTiming: ISceneTimingConfig[]): number { +// if (!sceneTiming || sceneTiming.length === 0) { +// return 0; +// } + +// return sceneTiming.reduce((maxEnd, scene) => { +// const sceneEnd = scene.startTime + (scene.customDuration || scene.duration); +// return Math.max(maxEnd, sceneEnd); +// }, 0); +// } + +// /** +// * Generate default transitions between scenes +// */ +// function generateDefaultTransitions(sceneCount: number): ITransitionConfig[] { +// const transitions: ITransitionConfig[] = []; + +// for (let i = 0; i < sceneCount - 1; i++) { +// transitions.push({ +// fromSceneIndex: i, +// toSceneIndex: i + 1, +// type: 'fade', +// duration: 0.5, +// easing: 'ease-in-out', +// }); +// } + +// return transitions; +// } + +// export default { +// createVideoConfig, +// getVideoConfigById, +// getVideoConfigs, +// updateVideoConfig, +// deleteVideoConfig, +// updateNarrationConfig, +// updateCaptionConfig, +// addSoundEffect, +// updateSoundEffect, +// removeSoundEffect, +// updateSceneOrder, +// updateTransitions, +// updateOutputSettings, +// updateBackgroundAudio, +// updateWatermark, +// validateForRendering, +// cloneVideoConfig, +// getTemplates, +// applyTemplate, +// }; diff --git a/src/routes/api.ts b/src/routes/api.ts index 92f8010..0096905 100644 --- a/src/routes/api.ts +++ b/src/routes/api.ts @@ -1,10 +1,29 @@ -import { Router } from "express"; -import { default as authRouter } from "@modules/auth/auth.routes.js"; -import { default as userRouter } from "@modules/user/user.routes.js"; +import { Router } from 'express'; +import { default as authRouter } from '@modules/auth/auth.routes.js'; +import { authMiddleware } from '@middleware/auth/requireAuth.js'; +import { default as userRouter } from '@modules/user/user.routes.js'; +import { default as projectRouter } from '@modules/project/project.routes.js'; +import { default as storyRouter } from '@modules/story/story.private.routes.js'; +import { default as contextProfileRouter } from '@modules/contextProfile/contextProfile.routes.js'; +import { default as scenesRouter } from '@modules/scenes/scenes.private.routes.js'; +import { default as narrationRouter } from '@modules/narration/narration.routes.js'; +import { default as sceneAssetsRouter } from '@modules/sceneAssets/sceneAssets.private.routes.js'; + +import { csrfMiddleware } from '@middleware/security/requireCsrf.js'; +import { requireActiveAccount } from '@middleware/security/requireActiveAccount.js'; const apiRouter = Router(); -apiRouter.use("/auth", authRouter); -apiRouter.use("/user", userRouter); +// private routes +apiRouter.use('/auth', authRouter); +apiRouter.use(authMiddleware, csrfMiddleware); +apiRouter.use('/user', userRouter); +apiRouter.use(requireActiveAccount); +apiRouter.use('/projects', projectRouter); +apiRouter.use('/stories', storyRouter); +apiRouter.use('/context-profiles', contextProfileRouter); +apiRouter.use('/scenes', scenesRouter); +apiRouter.use('/assets', sceneAssetsRouter); +apiRouter.use('/narrations', narrationRouter); export default apiRouter; diff --git a/src/routes/index.ts b/src/routes/index.ts index b2910e2..3b66256 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,32 +1,35 @@ -import { Router } from "express"; -import type { Request, Response, NextFunction } from "express"; -import cors from "cors"; -import helmet from "helmet"; -import cookieParser from "cookie-parser"; -import getCorsConfig from "config/corsConfig.js"; -import devLogger from "@middleware/loggerMiddleware.js"; -import notFoundHandler from "@middleware/404/notFoundHandler.js"; -import errorHandler from "@middleware/error/globalErrorHandler.js"; - -import apiRouter from "@routes/api.js"; +import { Router } from 'express'; +import type { Request, Response, NextFunction } from 'express'; +import cors from 'cors'; +import helmet from 'helmet'; +import cookieParser from 'cookie-parser'; +import getCorsConfig from 'config/corsConfig.js'; +import { requestLogger } from '@middleware/loggerMiddleware.js'; +import notFoundHandler from '@middleware/404/notFoundHandler.js'; +import errorHandler from '@middleware/error/globalErrorHandler.js'; + +import apiRouter from '@routes/api.js'; const AppRouter = Router(); AppRouter.use(helmet()); const corsOptions = getCorsConfig(); AppRouter.use(cors(corsOptions)); - AppRouter.use(cookieParser()); -// Basic logger -AppRouter.use(devLogger); +AppRouter.use(requestLogger); + +AppRouter.use((_req, res, next) => { + res.setHeader('X-Debug-Server', process.pid.toString()); + next(); +}); // Health route -AppRouter.get("/health", (_req: Request, res: Response) => { - res.status(200).json({ status: "ok" }); +AppRouter.get('/health', (_req: Request, res: Response) => { + res.status(200).json({ status: 'ok' }); }); -AppRouter.use("/api", apiRouter); +AppRouter.use('/api', apiRouter); AppRouter.use(notFoundHandler); diff --git a/src/security/guards/ensureActiveAccount.ts b/src/security/guards/ensureActiveAccount.ts new file mode 100644 index 0000000..735bbd7 --- /dev/null +++ b/src/security/guards/ensureActiveAccount.ts @@ -0,0 +1,9 @@ +import type { User } from "@models/User.js"; + +const ensureActiveAccount = (user:User)=>{ + if(user.accountStatus !== "active") { + return false; + } + return true; +} ; +export default ensureActiveAccount; \ No newline at end of file diff --git a/src/security/guards/getAccountBlockResponse.ts b/src/security/guards/getAccountBlockResponse.ts new file mode 100644 index 0000000..e630312 --- /dev/null +++ b/src/security/guards/getAccountBlockResponse.ts @@ -0,0 +1,6 @@ +import { AccountStatus } from '@constants/userConsts.js'; +import { accountStatusResponses } from '@domain/policies/accountStatusResponses.js'; + +export function getAccountBlockResponse(status: AccountStatus | null | undefined) { + return accountStatusResponses(status); +} diff --git a/src/server.ts b/src/server.ts index a56e295..66481a0 100644 --- a/src/server.ts +++ b/src/server.ts @@ -17,9 +17,7 @@ app.use(AppRouter); const startServer = async () => { try { // Wait for DB first - await connectDB(); - - // Start server only if DB connected + await connectDB(); app.listen(process.env.PORT, () => { console.log(`🚀 Server running on port ${process.env.PORT}`); console.log(`at http://localhost:${process.env.PORT}`); diff --git a/src/types/Context.ts b/src/types/Context.ts new file mode 100644 index 0000000..a5d1854 --- /dev/null +++ b/src/types/Context.ts @@ -0,0 +1,25 @@ +import { + EnvironmentProfile, + GenreType, + MoodType, + NarrativeScope, + StyleType, +} from "@models/ContextProfile.js"; + +type CreateContextInput = { + userId: string; + projectId?: string; + name: string; + description?: string; + genre: GenreType; + mood: MoodType; + style: StyleType; + narrativeScope?: NarrativeScope; + environment: EnvironmentProfile; + worldRules?: string; + narrativeConstraints?: string; + characters?: any[]; + forbiddenElements?: any[]; + makeGlobal?: boolean; + setAsProjectDefault?: boolean; +}; diff --git a/src/types/Pagination.ts b/src/types/Pagination.ts new file mode 100644 index 0000000..79f95e5 --- /dev/null +++ b/src/types/Pagination.ts @@ -0,0 +1,10 @@ +export interface Pagination { + page: number; + limit: number; + skip: number; +} + +export interface Sorting { + sortBy: string; + sortOrder: 1 | -1; +} diff --git a/src/types/express.d.ts b/src/types/express.d.ts index 03e776c..d2b67e1 100644 --- a/src/types/express.d.ts +++ b/src/types/express.d.ts @@ -1,10 +1,23 @@ -import { type User } from "@models/User.ts"; // whatever your user type is +import { type User } from '@models/User.ts'; // whatever your user type is +import type { Pagination, Sorting } from '@middleware/request/paginationAndSorting.js'; +import { type AccountStatus, Role } from '@constants/userConsts.ts'; + +type AuthenticatedUser = { + id: string; + role: Role; + accountStatus?: AccountStatus; +}; declare global { namespace Express { interface Request { - user?: User; + user?: AuthenticatedUser; sessionId?: string; + pagination?: Pagination; + sorting?: Sorting; + validatedBody?: unknown; + validatedParams?: unknown; + accountStatus?: string; } } } diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 0000000..c27e895 --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,18 @@ +export type StoryContent = { + summary?: string; + body?: string; + keywords?: string[]; + tags?: string[]; +}; + +export type Plan = 'free' | 'pro_basic' | 'pro_standard' | 'premium_standard' | 'premium_best'; + +export type AIMode = + | 'story' + | 'scenes' + | 'narration_text' + | 'narration_audio' + | 'image_text' + | 'image_image' + | 'video_image' + | 'video_text'; diff --git a/src/utils/arraysEqual.ts b/src/utils/arraysEqual.ts new file mode 100644 index 0000000..8454ef2 --- /dev/null +++ b/src/utils/arraysEqual.ts @@ -0,0 +1,13 @@ +export function arraysEqual(a: T[], b: T[]): boolean { + if (a.length !== b.length) { + return false; + } + + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + + return true; +} diff --git a/src/utils/asyncHandler.ts b/src/utils/asyncHandler.ts index 6555e77..e567d9a 100644 --- a/src/utils/asyncHandler.ts +++ b/src/utils/asyncHandler.ts @@ -1,7 +1,7 @@ import type { Request, Response, NextFunction, RequestHandler } from "express"; - + export const asyncHandler = - (fn: RequestHandler) => + (fn: RequestHandler) => (req: Request, res: Response, next: NextFunction) => { Promise.resolve(fn(req, res, next)).catch(next); }; diff --git a/src/utils/createUsername.ts b/src/utils/createUsername.ts deleted file mode 100644 index 2e4a7fb..0000000 --- a/src/utils/createUsername.ts +++ /dev/null @@ -1,21 +0,0 @@ -import crypto from "crypto"; -import { UserModel } from "@models/User.js"; - -export const createUsername = async (email: string): Promise => { - const base = email.split("@")[0].toLowerCase().replace(/[^a-z0-9]/g, ""); - - // Fallback if base becomes empty - const root = base || "user"; - - // Retry up to 10 times before failing - for (let i = 0; i < 10; i++) { - const suffix = crypto.randomBytes(3).toString("hex"); // 6 hex chars - const username = `${root}${suffix}`; - - const exists = await UserModel.exists({ username }); - if (!exists) return username; - } - - // If all 10 attempts failed (extremely rare), use a timestamp fallback - return `${root}${Date.now().toString(36)}`; -}; diff --git a/src/utils/emails/sender/sendEmailVerificationLink.ts b/src/utils/emails/sender/sendEmailVerificationLink.ts new file mode 100644 index 0000000..4bbe2cb --- /dev/null +++ b/src/utils/emails/sender/sendEmailVerificationLink.ts @@ -0,0 +1,31 @@ +import { User } from "@models/User.js"; +import transporter from "config/mail.js"; +import { emailVerificationTemplate } from "../templates/emailVerification.js"; +import logger from "@utils/logger.js"; + +const sendVerificationEmail = async ( + user: Partial, + verifyEmailUrl: string +) => { + const { subject, text, html } = emailVerificationTemplate( + user.displayName ?? user.username ?? null, + verifyEmailUrl + ); + + try { + await transporter.sendMail({ + from: process.env.EMAIL_FROM, + to: user.email, + subject: subject, + text: text, + html: html, + }); + } catch (err) { + logger.error( + `Failed to send email verification to ${user.email}: ${ + (err as Error).message + }` + ); + } +}; +export default sendVerificationEmail; diff --git a/src/utils/emails/sender/sendOldEmailVerificationForEmailUpdate.ts b/src/utils/emails/sender/sendOldEmailVerificationForEmailUpdate.ts new file mode 100644 index 0000000..aa7d9b4 --- /dev/null +++ b/src/utils/emails/sender/sendOldEmailVerificationForEmailUpdate.ts @@ -0,0 +1,34 @@ +import transporter from "config/mail.js"; +import { verifyOldEmailForEmailUpdate } from "../templates/verifyOldEmailForEmailUpdate.js"; +import logger from "@utils/logger.js"; +import { User } from "@models/User.js"; + +const sendOldEmailVerificationForEmailUpdate = async ( + user: Partial, + verificationCode: string +): Promise => { + const { subject, text, html } = verifyOldEmailForEmailUpdate( + user.displayName ?? user.username ?? null, + verificationCode + ); + + try { + await transporter.sendMail({ + from: process.env.EMAIL_FROM, + to: user.email, // OLD email + subject, + text, + html, + }); + } catch (err) { + logger.error( + { + email: user.email, + err, + }, + "Failed to send old email verification code" + ); + } +}; + +export default sendOldEmailVerificationForEmailUpdate; diff --git a/src/utils/emails/sender/sendPasswordUpdatedEmail.ts b/src/utils/emails/sender/sendPasswordUpdatedEmail.ts new file mode 100644 index 0000000..af1865d --- /dev/null +++ b/src/utils/emails/sender/sendPasswordUpdatedEmail.ts @@ -0,0 +1,26 @@ +import { User } from "@models/User.js"; +import transporter from "config/mail.js"; +import { passwordChangedNotificationTemplate } from "../templates/passwordChangedNotification.js"; +import logger from "@utils/logger.js"; + +const sendPasswordUpdatedEmail = async (user: User) => { + const { subject, text, html } = passwordChangedNotificationTemplate( + user.displayName || user.username || null + ); + try { + await transporter.sendMail({ + from: process.env.EMAIL_FROM, + to: user.email, + subject: subject, + text: text, + html: html, + }); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : String(err); + logger.error( + `Failed to send password updated email to ${user.email}: ${errorMessage}` + ); + } +}; + +export default sendPasswordUpdatedEmail; diff --git a/src/utils/emails/sender/sendResetLink.ts b/src/utils/emails/sender/sendResetLink.ts new file mode 100644 index 0000000..768ad3b --- /dev/null +++ b/src/utils/emails/sender/sendResetLink.ts @@ -0,0 +1,28 @@ +import { User } from "@models/User.js"; +import transporter from "config/mail.js"; +import { RESET_EXP_MIN } from "constants/authConsts.js"; +import { resetPasswordTemplate } from "../templates/resetPassword.js"; +import logger from "@utils/logger.js"; + +const sendResetLink = async (user: User, resetUrl: string) => { + const { subject, text, html } = resetPasswordTemplate( + user.displayName || user.username || user.email.split("@")[0], + resetUrl, + RESET_EXP_MIN + ); + try { + await transporter.sendMail({ + from: process.env.EMAIL_FROM, + to: user.email, + subject, + text, + html, + }); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : String(err); + logger.error( + `Failed to send reset password email to ${user.email}: ${errorMessage}` + ); + } +}; +export default sendResetLink; diff --git a/src/utils/emails/sender/sendUpdateEmailLink.ts b/src/utils/emails/sender/sendUpdateEmailLink.ts new file mode 100644 index 0000000..5a77736 --- /dev/null +++ b/src/utils/emails/sender/sendUpdateEmailLink.ts @@ -0,0 +1,36 @@ +import transporter from "config/mail.js"; +import { verifyUpdatedEmailTemplate } from "../templates/verifyUpdatedEmail.js"; +import { InternalServerError } from "@middleware/error/index.js"; +import { User } from "@models/User.js"; +import logger from "@utils/logger.js"; + +const sendUpdateEmailLink = async ( + user: Partial, + newEmail: string, + updateEmailUrl: string +): Promise => { + const { subject, text, html } = verifyUpdatedEmailTemplate( + user.displayName ?? user.username ?? null, + updateEmailUrl + ); + + try { + await transporter.sendMail({ + from: process.env.EMAIL_FROM, + to: newEmail, + subject: subject, + text: text, + html: html, + }); + } catch (error) { + logger.error( + { + email: newEmail, + error, + }, + "Failed to send update email link" + ); + } +}; + +export default sendUpdateEmailLink; diff --git a/src/utils/emails/sender/sendWelcomeEmail.ts b/src/utils/emails/sender/sendWelcomeEmail.ts new file mode 100644 index 0000000..e95f788 --- /dev/null +++ b/src/utils/emails/sender/sendWelcomeEmail.ts @@ -0,0 +1,26 @@ +import { newAccountTemplate } from "../templates/newAccount.js"; +import transporter from "config/mail.js"; + +const sendWelcomeEmail = async ( + email: string, + displayName?: string, + username?: string +) => { + const { subject, text, html } = newAccountTemplate( + displayName || username || email.split("@")[0] + ); + try { + await transporter.sendMail({ + from: process.env.EMAIL_FROM, + to: email, + subject, + text, + html, + }); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : String(err); + console.error(`Failed to send welcome email:${errorMessage}`); + } +}; + +export default sendWelcomeEmail; diff --git a/src/modules/auth/emails/templates/emailVerification.ts b/src/utils/emails/templates/emailVerification.ts similarity index 100% rename from src/modules/auth/emails/templates/emailVerification.ts rename to src/utils/emails/templates/emailVerification.ts diff --git a/src/modules/auth/emails/templates/newAccount.ts b/src/utils/emails/templates/newAccount.ts similarity index 100% rename from src/modules/auth/emails/templates/newAccount.ts rename to src/utils/emails/templates/newAccount.ts diff --git a/src/modules/auth/emails/passwordChangedNotification.ts b/src/utils/emails/templates/passwordChangedNotification.ts similarity index 100% rename from src/modules/auth/emails/passwordChangedNotification.ts rename to src/utils/emails/templates/passwordChangedNotification.ts diff --git a/src/modules/auth/emails/templates/resetPassword.ts b/src/utils/emails/templates/resetPassword.ts similarity index 100% rename from src/modules/auth/emails/templates/resetPassword.ts rename to src/utils/emails/templates/resetPassword.ts diff --git a/src/utils/emails/templates/verifyOldEmailForEmailUpdate.ts b/src/utils/emails/templates/verifyOldEmailForEmailUpdate.ts new file mode 100644 index 0000000..0c6404b --- /dev/null +++ b/src/utils/emails/templates/verifyOldEmailForEmailUpdate.ts @@ -0,0 +1,76 @@ +export function verifyOldEmailForEmailUpdate( + displayName: string | null, + verificationCode: string +) { + const subject = "Security check: confirm email change · Cinetegrate 🔐"; + + const text = ` +Hi ${displayName ?? ""}, + +We received a request to change the email address on your Cinetegrate account. + +To confirm this change, please enter the verification code below when prompted: + +Verification code: +${verificationCode} + +This code is valid for 10 minutes. + +If you did NOT request this change, someone may be trying to access your account. +We recommend reviewing your security settings immediately. + +— Cinetegrate Security Team + `.trim(); + + const html = ` +
+

+ Confirm email change + · Security Check 🔐 +

+ +

+ Hi ${displayName ?? ""}, +

+ +

+ We received a request to change the email address associated with your + Cinetegrate account. +

+ +

+ To approve this change, please enter the verification code below when prompted: +

+ +
+ ${verificationCode} +
+ +

+ This code is valid for 10 minutes. +

+ +

+ If you did NOT request this change, do not share this code with anyone. + Review your account security immediately. +

+ +

+ Cinetegrate Security Team +

+
+ `; + + return { subject, text, html }; +} diff --git a/src/modules/user/email/templlate/verifyUpdatedEmail.ts b/src/utils/emails/templates/verifyUpdatedEmail.ts similarity index 97% rename from src/modules/user/email/templlate/verifyUpdatedEmail.ts rename to src/utils/emails/templates/verifyUpdatedEmail.ts index c28d1b7..3debddb 100644 --- a/src/modules/user/email/templlate/verifyUpdatedEmail.ts +++ b/src/utils/emails/templates/verifyUpdatedEmail.ts @@ -35,7 +35,7 @@ Your existing email address will remain unchanged.

To complete this change, please confirm your new email address by clicking the button below. - This link will expire in 1 hour. + This link will expire in 30 minutes.

diff --git a/src/utils/generateAllCookieTokens.ts b/src/utils/generateAllCookieTokens.ts new file mode 100644 index 0000000..e39d39a --- /dev/null +++ b/src/utils/generateAllCookieTokens.ts @@ -0,0 +1,10 @@ +import { Types } from "mongoose"; +import { generateAccessToken, generateCsrfToken, generateRefreshToken } from "./tokens.js"; +import { AccountStatus } from "@constants/userConsts.js"; + +export const generateAllCookieTokens = (userId:Types.ObjectId, sessionId:string, role:string, accountStatus:AccountStatus) => { + const accessToken = generateAccessToken(userId, sessionId, role, accountStatus); + const refreshToken = generateRefreshToken(userId, sessionId); + const csrfToken = generateCsrfToken(); + return { accessToken, refreshToken, csrfToken }; +} \ No newline at end of file diff --git a/src/utils/getCreditCost.ts b/src/utils/getCreditCost.ts new file mode 100644 index 0000000..7cd7a3f --- /dev/null +++ b/src/utils/getCreditCost.ts @@ -0,0 +1,9 @@ +import { ActionType, CREDIT_PRICING } from 'config/creditPricing.js'; + +export function getCreditCost(action: ActionType, grade: number): number { + const cost = CREDIT_PRICING[action]?.[grade]; + if (cost === undefined) { + throw new Error(`No pricing for ${action} grade ${grade}`); + } + return cost; +} diff --git a/src/utils/getIpInfo.ts b/src/utils/getIpInfo.ts index 7ffd1f1..3003f3c 100644 --- a/src/utils/getIpInfo.ts +++ b/src/utils/getIpInfo.ts @@ -1,11 +1,34 @@ -import { fetch } from "undici"; +import { fetch } from 'undici'; + +interface IpInfo { + ipVersion: number; + ipAddress: string; + latitude: number; + longitude: number; + countryName: string; + countryCode: string; + capital: string; + phoneCodes: number[]; + timeZones: string[]; + zipCode: string; + cityName: string; + regionName: string; + continent: string; + continentCode: string; + currencies: string[]; + languages: string[]; + asn: string; + asnOrganization: string; + isProxy: boolean; +} export async function getIpInfo(ip: string) { try { const res = await fetch(`https://free.freeipapi.com/api/json/${ip}`); - const data = await res.json(); - return data; + const data = (await res.json()) as IpInfo; + return { success: true, ...data }; } catch (e) { - return { city: "Unknown", country: "Unknown" }; + console.error('Error fetching IP info:', e); + return { success: false, message: 'Failed to fetch IP info' }; } } diff --git a/src/utils/getVideoDuration.ts b/src/utils/getVideoDuration.ts new file mode 100644 index 0000000..bd2102e --- /dev/null +++ b/src/utils/getVideoDuration.ts @@ -0,0 +1,20 @@ +import { InternalServerError } from '@middleware/error/index.js'; +import ffmpeg from 'fluent-ffmpeg'; + +export function getVideoDuration(filePath: string): Promise { + return new Promise((resolve, reject) => { + ffmpeg.ffprobe(filePath, (err, metadata) => { + if (err) { + return reject(new InternalServerError('FFPROBE_FAILED')); + } + + const duration = metadata?.format?.duration; + + if (typeof duration !== 'number' || Number.isNaN(duration) || duration <= 0) { + return reject(new InternalServerError('INVALID_VIDEO_DURATION')); + } + + resolve(duration); + }); + }); +} diff --git a/src/utils/hashSceneOrder.ts b/src/utils/hashSceneOrder.ts new file mode 100644 index 0000000..cc0de5c --- /dev/null +++ b/src/utils/hashSceneOrder.ts @@ -0,0 +1,15 @@ +import * as crypto from 'crypto'; +import { Types } from 'mongoose'; + +export function hashSceneOrder(sceneIds: Types.ObjectId[]): string { + const orderString = sceneIds.join('|'); + return crypto.createHash('sha256').update(orderString).digest('hex'); +} + +export function verifySceneOrder(sceneIds: Types.ObjectId[], hash: string): boolean { + return hashSceneOrder(sceneIds) === hash; +} + +export function shortHashSceneOrder(sceneIds: Types.ObjectId[]): string { + return hashSceneOrder(sceneIds).substring(0, 8); +} diff --git a/src/utils/logger.ts b/src/utils/logger.ts new file mode 100644 index 0000000..b36a398 --- /dev/null +++ b/src/utils/logger.ts @@ -0,0 +1,44 @@ +import pino from "pino"; + +const isProduction = process.env.NODE_ENV === "production"; + +const logger = pino({ + level: process.env.LOG_LEVEL || "info", + + formatters: { + level(label) { + return { level: label }; + }, + }, + + timestamp: () => `,"time":"${new Date().toISOString()}"`, + + redact: { + paths: [ + "password", + "passwordHash", + "token", + "accessToken", + "refreshToken", + "csrfToken", + "authorization", + "headers.authorization", + ], + censor: "[REDACTED]", + }, + + ...(isProduction + ? {} + : { + transport: { + target: "pino-pretty", + options: { + colorize: true, + translateTime: "yyyy-mm-dd HH:MM:ss", + ignore: "pid,hostname", + }, + }, + }), +}); + +export default logger; diff --git a/src/utils/paginationResponse.ts b/src/utils/paginationResponse.ts new file mode 100644 index 0000000..73aa1a8 --- /dev/null +++ b/src/utils/paginationResponse.ts @@ -0,0 +1,12 @@ +import { Pagination } from 'types/Pagination.js'; + +export function paginationResponse(pagination: Pagination, totalItems: number) { + return { + page: pagination.page, + limit: pagination.limit, + total: totalItems || 0, + totalPages: Math.ceil(totalItems / pagination.limit), + hasNext: pagination.page * pagination.limit < totalItems, + hasPrev: pagination.page > 1, + }; +} diff --git a/src/utils/safeParseJSON.ts b/src/utils/safeParseJSON.ts new file mode 100644 index 0000000..4c2bfc8 --- /dev/null +++ b/src/utils/safeParseJSON.ts @@ -0,0 +1,12 @@ +function safeParseJSON(text: string) { + const cleaned = text + .trim() + .replace(/^```json/i, '') + .replace(/^```/, '') + .replace(/```$/, '') + .trim(); + + return JSON.parse(cleaned); +} + +export default safeParseJSON; diff --git a/src/utils/sanitizeProjectResponse.ts b/src/utils/sanitizeProjectResponse.ts new file mode 100644 index 0000000..a4870f6 --- /dev/null +++ b/src/utils/sanitizeProjectResponse.ts @@ -0,0 +1,42 @@ +import { Project } from '@models/Project.js'; + +interface ProjectResponse { + project: Project; + type: 'getProjects' | 'getProjectById'; +} + +const sanitizeProjectResponse = ({ project, type = 'getProjectById' }: ProjectResponse) => { + switch (type) { + case 'getProjects': + return { + _id: project._id, + title: project.title, + description: project.description, + visibility: project.visibility, + status: project.status, + createdAt: project.createdAt, + updatedAt: project.updatedAt, + }; + case 'getProjectById': + return { + _id: project._id, + title: project.title, + description: project.description, + visibility: project.visibility, + status: project.status, + defaultContextProfileId: project.defaultContextProfileId, + contextProfileId: project.defaultContextProfileId, + generationCounts: project.generationCounts, + createdAt: project.createdAt, + updatedAt: project.updatedAt, + }; + default: + return project; + } +}; + +const sanitizeProjects = (projects: Project[]) => { + return projects.map((project) => sanitizeProjectResponse({ project, type: 'getProjects' })); +}; + +export { sanitizeProjectResponse, sanitizeProjects }; diff --git a/src/utils/returnUserData.ts b/src/utils/sanitizeUserResponse.ts similarity index 80% rename from src/utils/returnUserData.ts rename to src/utils/sanitizeUserResponse.ts index 60d9529..e24ef54 100644 --- a/src/utils/returnUserData.ts +++ b/src/utils/sanitizeUserResponse.ts @@ -1,15 +1,10 @@ -import type { User } from "@models/User.js"; +import type { User } from '@models/User.js'; -type UserReturnType = - | "profile" - | "settings" - | "security" - | "billing" - | "account"; +type UserReturnType = 'profile' | 'settings' | 'security' | 'billing' | 'account'; -export const returnUserData = (user: User, type: UserReturnType) => { +export const sanitizeUserResponse = (user: User, type: UserReturnType) => { switch (type) { - case "profile": + case 'profile': return { _id: user._id, email: user.email, @@ -18,12 +13,13 @@ export const returnUserData = (user: User, type: UserReturnType) => { avatarUrl: user.avatarUrl ?? null, bio: user.bio ?? null, links: user.links ?? {}, - plan: user.plan, + plan: user.currentPlan, emailVerified: user.emailVerified, usage: user.usage, + accountStatus: user.accountStatus, }; - case "settings": + case 'settings': return { _id: user._id, email: user.email, @@ -31,14 +27,14 @@ export const returnUserData = (user: User, type: UserReturnType) => { displayName: user.displayName, avatarUrl: user.avatarUrl ?? null, bio: user.bio ?? null, - plan: user.plan, + plan: user.currentPlan, privacyPrefs: user.privacyPrefs ?? {}, notificationPrefs: user.notificationPrefs ?? {}, usage: user.usage, links: user.links ?? {}, }; - case "security": + case 'security': return { email: user.email, phoneNumber: user.phoneNumber ?? null, @@ -50,10 +46,10 @@ export const returnUserData = (user: User, type: UserReturnType) => { providers: user.oauthProviders ?? [], }; - case "billing": + case 'billing': return { - plan: user.plan, - billingStatus: user.billingStatus ?? "none", + plan: user.currentPlan, + billingStatus: user.billingStatus ?? 'none', billingProvider: user.billingProvider ?? null, billingCustomerId: user.billingCustomerId ?? null, subscriptionId: user.subscriptionId ?? null, @@ -63,7 +59,7 @@ export const returnUserData = (user: User, type: UserReturnType) => { usage: user.usage, }; - case "account": + case 'account': return { _id: user._id, email: user.email, @@ -73,7 +69,7 @@ export const returnUserData = (user: User, type: UserReturnType) => { role: user.role, status: user.accountStatus, // enum: active, suspended, banned, deleted createdAt: user.createdAt, - }; + }; default: return { _id: user._id, diff --git a/src/utils/tokens.ts b/src/utils/tokens.ts index 285befa..58516fb 100644 --- a/src/utils/tokens.ts +++ b/src/utils/tokens.ts @@ -1,6 +1,8 @@ import jwt, { type SignOptions } from "jsonwebtoken"; import crypto from "crypto"; -import type { ObjectIdSchemaDefinition } from "mongoose"; +import type { Types } from "mongoose"; +import { UnauthenticatedError } from "@middleware/error/index.js"; +import { AccountStatus } from "@constants/userConsts.js"; const ACCESS_TOKEN_EXPIRES_IN: SignOptions["expiresIn"] = process.env .ACCESS_TOKEN_EXPIRES_IN as SignOptions["expiresIn"]; @@ -28,12 +30,24 @@ export function verifyToken(rawToken: string, tokenHash: string) { tokenHashBuffer.length !== providedHashBuffer.length || !crypto.timingSafeEqual(tokenHashBuffer, providedHashBuffer) ) { - throw new Error("Invalid or expired token"); + throw new UnauthenticatedError("Invalid or expired token"); } return true; } +export function compareHashTokens(hash1: string, hash2: string): boolean { + const hash1Buffer = Buffer.from(hash1, "hex"); + const hash2Buffer = Buffer.from(hash2, "hex"); + if ( + hash1Buffer.length !== hash2Buffer.length || + !crypto.timingSafeEqual(hash1Buffer, hash2Buffer) + ) { + return false; + } + return true; +} + export function hashToken(rawToken: string) { return crypto.createHash("sha256").update(rawToken).digest("hex"); } @@ -41,17 +55,15 @@ export function hashToken(rawToken: string) { export function generateSessionId() { return crypto.randomBytes(32).toString("hex"); } -export function generateAccessToken( - userId: ObjectIdSchemaDefinition, - sessionId: string -) { - return jwt.sign({ userId, sessionId }, ACCESS_TOKEN_SECRET, { +export function generateAccessToken(userId: Types.ObjectId, sessionId: string, role: string, accountStatus?: AccountStatus) { + return jwt.sign({ userId, sessionId, role, accountStatus }, ACCESS_TOKEN_SECRET, { expiresIn: ACCESS_TOKEN_EXPIRES_IN, }); } export function generateRefreshToken( - userId: ObjectIdSchemaDefinition, - sessionId: string + userId: Types.ObjectId, + sessionId: string, + reduceTime: boolean = false ) { return jwt.sign({ userId, sessionId }, REFRESH_TOKEN_SECRET, { expiresIn: REFRESH_TOKEN_EXPIRES_IN, @@ -59,10 +71,6 @@ export function generateRefreshToken( } export function generateCsrfToken() { - const token = crypto.randomBytes(24).toString("hex"); - const signed = crypto - .createHmac("sha256", process.env.CSRF_SECRET!) - .update(token) - .digest("hex"); - return `${token}.${signed}`; + const token = crypto.randomBytes(24).toString("hex"); + return token; } diff --git a/src/validation/audio.schema.ts b/src/validation/audio.schema.ts new file mode 100644 index 0000000..5b18377 --- /dev/null +++ b/src/validation/audio.schema.ts @@ -0,0 +1,125 @@ +import { z } from 'zod'; +import { + MAX_AUDIO_PROMPT_LENGTH, + MAX_AUDIO_URL_LENGTH, + audioTypes, + audioGenerationSources, + audioFormats, + MIN_AUDIO_DURATION, + MAX_AUDIO_DURATION, + MAX_VOICE_ID_LENGTH, +} from '@constants/audioAssetConsts.js'; + +// PARAM SCHEMAS + +export const audioAssetIdParamSchema = z + .object({ + audioAssetId: z.string().length(24, 'Invalid audio asset ID'), + }) + .strict(); + +export const narrationIdParamSchema = z + .object({ + narrationId: z.string().length(24, 'Invalid narration ID'), + }) + .strict(); + +export const audioAssetAndNarrationParamSchema = z + .object({ + narrationId: z.string().length(24, 'Invalid narration ID'), + audioAssetId: z.string().length(24, 'Invalid audio asset ID'), + }) + .strict(); + +// BODY SCHEMAS + +export const generateAudioAssetSchema = z + .object({ + voiceId: z + .string() + .min(1, 'Voice ID is required') + .max(MAX_VOICE_ID_LENGTH, `Voice ID cannot exceed ${MAX_VOICE_ID_LENGTH} characters`), + prompt: z + .string() + .max(MAX_AUDIO_PROMPT_LENGTH, `Prompt cannot exceed ${MAX_AUDIO_PROMPT_LENGTH} characters`) + .trim() + .optional(), + }) + .strict(); + +export const regenerateAudioAssetSchema = z + .object({ + voiceId: z + .string() + .min(1, 'Voice ID is required') + .max(MAX_VOICE_ID_LENGTH, `Voice ID cannot exceed ${MAX_VOICE_ID_LENGTH} characters`) + .optional(), + extraPrompt: z.string().max(500, 'Extra prompt is too long').optional(), + }) + .strict(); + +export const uploadAudioAssetSchema = z + .object({ + type: z.enum(audioTypes, { message: 'Audio type must be "narration", "background", or "effect"' }), + duration: z + .number() + .min(MIN_AUDIO_DURATION, `Duration must be at least ${MIN_AUDIO_DURATION} seconds`) + .max(MAX_AUDIO_DURATION, `Duration cannot exceed ${MAX_AUDIO_DURATION} seconds`) + .optional(), + }) + .strict(); + +export const updateAudioAssetSchema = z + .object({ + prompt: z + .string() + .max(MAX_AUDIO_PROMPT_LENGTH, `Prompt cannot exceed ${MAX_AUDIO_PROMPT_LENGTH} characters`) + .trim() + .optional() + .nullable(), + voiceId: z + .string() + .max(MAX_VOICE_ID_LENGTH, `Voice ID cannot exceed ${MAX_VOICE_ID_LENGTH} characters`) + .optional() + .nullable(), + }) + .strict() + .refine((data) => Object.keys(data).length > 0, { + message: 'At least one field must be provided for update', + }); + +export const setActiveAudioAssetSchema = z + .object({ + audioAssetId: z.string().length(24, 'Invalid audio asset ID'), + }) + .strict(); + +export const bulkDeleteAudioAssetsSchema = z + .object({ + audioAssetIds: z + .array(z.string().length(24, 'Invalid audio asset ID')) + .min(1, 'At least one audio asset ID is required') + .max(50, 'Cannot delete more than 50 audio assets at once'), + }) + .strict(); + +export const bulkRestoreAudioAssetsSchema = z + .object({ + audioAssetIds: z + .array(z.string().length(24, 'Invalid audio asset ID')) + .min(1, 'At least one audio asset ID is required') + .max(50, 'Cannot restore more than 50 audio assets at once'), + }) + .strict(); + +// Type exports +export type AudioAssetIdParam = z.infer; +export type NarrationIdParam = z.infer; +export type AudioAssetAndNarrationParam = z.infer; +export type GenerateAudioAssetInput = z.infer; +export type RegenerateAudioAssetInput = z.infer; +export type UploadAudioAssetInput = z.infer; +export type UpdateAudioAssetInput = z.infer; +export type SetActiveAudioAssetInput = z.infer; +export type BulkDeleteAudioAssetsInput = z.infer; +export type BulkRestoreAudioAssetsInput = z.infer; diff --git a/src/validation/auth.schema.ts b/src/validation/auth.schema.ts index 831db77..e171067 100644 --- a/src/validation/auth.schema.ts +++ b/src/validation/auth.schema.ts @@ -1,6 +1,6 @@ // src/validation/auth.schema.ts -import { z } from "zod"; -import type { Request, Response, NextFunction } from "express"; +import { z } from 'zod'; +import type { Request, Response, NextFunction } from 'express'; /** * Password policy: @@ -11,14 +11,11 @@ const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/; const registerSchema = z .object({ - email: z.email({ message: "Invalid email address" }), + email: z.email({ message: 'Invalid email address' }), - password: z - .string() - .min(8, { message: "Password must be at least 8 characters" }) - .regex(passwordRegex, { - message: "Password must contain at least one letter and one number", - }), + password: z.string().min(8, { message: 'Password must be at least 8 characters' }).regex(passwordRegex, { + message: 'Password must contain at least one letter and one number', + }), confirmPassword: z.string(), @@ -30,49 +27,49 @@ const registerSchema = z .min(3) .max(30) .regex(/^[a-z0-9\-_]+$/, { - message: - "Username may contain letters, numbers, dash and underscore only", + message: 'Username may contain letters, numbers, dash and underscore only', }), - displayName: z.string().trim().min(1).max(80), + name: z.string().trim().min(1, 'Name is required').max(80, 'Name is too long'), }) .superRefine((data, ctx) => { if (data.password !== data.confirmPassword) { ctx.addIssue({ code: z.ZodIssueCode.custom, - path: ["confirmPassword"], - message: "Passwords do not match", + path: ['confirmPassword'], + message: 'Passwords do not match', }); } }) .strict(); -const loginSchema = z.object({ - email: z.email(), - password: z.string().min(1, "Password is required"), -}).strict(); +const loginSchema = z + .object({ + email: z.email(), + password: z.string().min(1, 'Password is required'), + }) + .strict(); -const forgotPasswordSchema = z.object({ - email: z.string().trim().toLowerCase().email(), -}).strict(); +const forgotPasswordSchema = z + .object({ + email: z.string().trim().toLowerCase().email(), + }) + .strict(); const resetPasswordSchema = z .object({ token: z.string().min(10), // whatever length you expect - password: z - .string() - .min(8, { message: "Password must be at least 8 characters" }) - .regex(passwordRegex, { - message: "Password must contain at least one letter and one number", - }), + password: z.string().min(8, { message: 'Password must be at least 8 characters' }).regex(passwordRegex, { + message: 'Password must contain at least one letter and one number', + }), confirmPassword: z.string(), }) .superRefine((data, ctx) => { if (data.password !== data.confirmPassword) { ctx.addIssue({ code: z.ZodIssueCode.custom, - path: ["confirmPassword"], - message: "Passwords do not match", + path: ['confirmPassword'], + message: 'Passwords do not match', }); } }) @@ -84,11 +81,19 @@ const verifyEmailSchema = z }) .strict(); +const verifyUpdateEmailSchema = z + .object({ + verificationToken: z.string().min(10), + code: z.string().length(6, { message: 'Code must be 6 characters long' }), + }) + .strict(); + type LoginInput = z.infer; type RegisterInput = z.infer; type ResetPasswordInput = z.infer; type ForgetPasswordInput = z.infer; type VerifyEmailInput = z.infer; +type VerifyUpdateEmailInput = z.infer; export type { LoginInput, @@ -96,6 +101,7 @@ export type { ResetPasswordInput, ForgetPasswordInput, VerifyEmailInput, + VerifyUpdateEmailInput, }; export { loginSchema, @@ -103,28 +109,5 @@ export { resetPasswordSchema, forgotPasswordSchema, verifyEmailSchema, + verifyUpdateEmailSchema, }; - -export function validateBody(schema: T) { - return async (req: Request, _res: Response, next: NextFunction) => { - try { - // parseAsync to allow async refinements in future - const parsed = await schema.parseAsync(req.body); - // attach to request for typed access in controllers - (req as unknown as { validatedBody?: z.infer }).validatedBody = parsed; - next(); - } catch (err) { - if (err instanceof z.ZodError) { - // map Zod errors to a clean JSON shape - const errors = err.issues.map((e) => ({ - path: e.path.join("."), - message: e.message, - })); - return _res - .status(400) - .json({ error: "validation_error", details: errors }); - } - next(err); - } - }; -} diff --git a/src/validation/contextProfile.schema.ts b/src/validation/contextProfile.schema.ts new file mode 100644 index 0000000..d5dad7d --- /dev/null +++ b/src/validation/contextProfile.schema.ts @@ -0,0 +1,55 @@ +import { z } from "zod"; +import { + GenreType, + MoodType, + StyleType, + EnvironmentType, + CameraMotion, + NarrativeScope, +} from "@models/ContextProfile.js"; + +export const createContextProfileSchema = z.object({ + projectId: z.string().optional(), + + name: z.string().min(1).max(100), + description: z.string().max(600).optional(), + + genre: z.nativeEnum(GenreType), + mood: z.nativeEnum(MoodType), + style: z.nativeEnum(StyleType), + narrativeScope: z.nativeEnum(NarrativeScope).optional(), + + environment: z.object({ + type: z.nativeEnum(EnvironmentType), + cameraMotion: z.nativeEnum(CameraMotion), + description: z.string().max(300).optional(), + }), + + worldRules: z.string().max(1000).optional(), + narrativeConstraints: z.string().max(1000).optional(), + + characters: z + .array( + z.object({ + name: z.string().min(1), + description: z.string().max(300).optional(), + }) + ) + .max(20) + .optional(), + + forbiddenElements: z + .array( + z.object({ + label: z.string().min(1), + severity: z.enum(["hard", "soft"]).optional(), + }) + ) + .optional(), + + // 🔒 Explicit intent only + makeGlobal: z.boolean().optional(), + setAsProjectDefault: z.boolean().optional(), +}); + +export type CreateContextProfileInput = z.infer; \ No newline at end of file diff --git a/src/validation/narration.schema.ts b/src/validation/narration.schema.ts new file mode 100644 index 0000000..fd4c0c8 --- /dev/null +++ b/src/validation/narration.schema.ts @@ -0,0 +1,79 @@ +import { z } from 'zod'; + +// Constants +const MAX_NARRATION_LENGTH = 20000; + +// Narration segment schema +export const narrationSegmentSchema = z + .object({ + startTime: z.number().min(0, 'Start time must be non-negative'), + endTime: z.number().min(0, 'End time must be non-negative'), + duration: z.number().min(0, 'Duration must be non-negative'), + character: z.string().min(1, 'Character is required').max(100, 'Character name is too long'), + targetWordCount: z.number().int().min(0, 'Target word count must be non-negative'), + minWords: z.number().int().min(0, 'Min words must be non-negative'), + maxWords: z.number().int().min(0, 'Max words must be non-negative'), + narration: z + .string() + .min(1, 'Narration text is required') + .max(MAX_NARRATION_LENGTH, `Narration text is too long (max ${MAX_NARRATION_LENGTH} characters)`), + }) + .strict() + .refine((data) => data.endTime > data.startTime, { + message: 'End time must be greater than start time', + }) + .refine((data) => data.maxWords >= data.minWords, { + message: 'Max words must be greater than or equal to min words', + }); + +export const regenerateNarrationSchema = z + .object({ + extraPrompt: z.string().max(500, 'Extra prompt is too long'), + }) + .strict(); + +export const uploadNarrationJSONSchema = z + .object({ + narrationSegments: z + .array(narrationSegmentSchema) + .min(1, 'At least one narration segment is required') + .max(100, 'Too many narration segments (max 100)'), + totalDuration: z.number().min(0.1, 'Total duration must be greater than 0').optional(), + }) + .strict(); + +export const updateNarrationSegmentsSchema = z + .object({ + narrationSegments: z + .array(narrationSegmentSchema) + .min(1, 'At least one narration segment is required') + .max(100, 'Too many narration segments (max 100)'), + }) + .strict(); + +export const narrationIdParamSchema = z + .object({ + narrationId: z.string().length(24, 'Invalid narration ID'), + }) + .strict(); + +export const storyIdParamSchema = z + .object({ + storyId: z.string().length(24, 'Invalid story ID'), + }) + .strict(); + +export const storyNarrationParamSchema = z + .object({ + storyId: z.string().length(24, 'Invalid story ID'), + narrationId: z.string().length(24, 'Invalid narration ID'), + }) + .strict(); + +export type NarrationSegmentInput = z.infer; +export type RegenerateNarrationInput = z.infer; +export type UploadNarrationJSONInput = z.infer; +export type UpdateNarrationSegmentsInput = z.infer; +export type NarrationIdParam = z.infer; +export type StoryIdParam = z.infer; +export type StoryNarrationParam = z.infer; diff --git a/src/validation/project.schema.ts b/src/validation/project.schema.ts index e69de29..115e678 100644 --- a/src/validation/project.schema.ts +++ b/src/validation/project.schema.ts @@ -0,0 +1,111 @@ +import { + CameraMotion, + EnvironmentType, + GenreType, + MoodType, + NarrativeScope, + StyleType, +} from '@models/ContextProfile.js'; +import { z } from 'zod'; + +export const createProjectSchema = z + .object({ + title: z.string().min(5, 'Title is required').max(255, 'Title is too long'), + description: z.string().min(5, 'Description is required').max(500, 'Description is too long'), + status: z.enum(['active', 'draft']), + visibility: z.enum(['public', 'private']).optional(), + }) + .strict(); + +export const updateProjectSchema = z + .object({ + title: z.string().min(5, 'Title is required').max(255, 'Title is too long').optional(), + description: z.string().max(500, 'Description is too long').optional(), + }) + .strict() + .refine((data) => Object.keys(data).length > 0, 'At least one field must be provided'); +export const updateProjectVisibilitySchema = z + .object({ + visibility: z.enum(['public', 'private']), + }) + .strict(); +export const updateProjectStatusSchema = z + .object({ + status: z.enum(['active', 'draft', 'archive']), + }) + .strict(); + +export const updateManyIdsSchema = z + .object({ + projectIds: z + .array(z.string().length(24, 'Invalid project ID')) + .min(1, 'At least one project ID is required'), + }) + .strict(); + +export type CreateProjectInput = z.infer; +export type UpdateProjectInput = z.infer; +export type UpdateProjectVisibilityInput = z.infer; +export type UpdateProjectStatusInput = z.infer; +export const projectIdParamSchema = z + .object({ + projectId: z.string().length(24, 'Invalid project ID'), + }) + .strict(); + +const newProjectContextSchema = z.object({ + mode: z.literal('new'), + + data: z.object({ + name: z.string().min(1).max(100), + description: z.string().max(600).optional(), + + genre: z.enum(GenreType), + mood: z.enum(MoodType), + style: z.enum(StyleType), + + narrativeScope: z.enum(NarrativeScope).optional(), + + environment: z.object({ + type: z.enum(EnvironmentType), + cameraMotion: z.enum(CameraMotion), + description: z.string().max(300).optional(), + }), + + worldRules: z.string().max(1000).optional(), + narrativeConstraints: z.string().max(1000).optional(), + + characters: z + .array( + z.object({ + name: z.string().min(1), + description: z.string().max(300).optional(), + }) + ) + .max(20) + .optional(), + + forbiddenElements: z + .array( + z.object({ + label: z.string().min(1), + severity: z.enum(['hard', 'soft']).optional(), + }) + ) + .optional(), + }), +}); + +const useGlobalProjectContextSchema = z.object({ + mode: z.literal('use-global'), + globalContextId: z.string().min(1), +}); + +export const createProjectContextProfileSchema = z.discriminatedUnion('mode', [ + newProjectContextSchema, + useGlobalProjectContextSchema, +]); + +export type ProjectIdParam = z.infer; +export type UpdateManyIdsInput = z.infer; +export type CreateProjectContextInput = z.infer; diff --git a/src/validation/sceneAssets.schema.ts b/src/validation/sceneAssets.schema.ts new file mode 100644 index 0000000..64f42d4 --- /dev/null +++ b/src/validation/sceneAssets.schema.ts @@ -0,0 +1,140 @@ +import { z } from 'zod'; +import { + MAX_ASSET_PROMPT_LENGTH, + MAX_ASSET_URL_LENGTH, + assetTypes, + visibilityTypes, + generationSources, + allFormats, + MIN_DIMENSION, + MAX_DIMENSION, + MIN_ASSET_DURATION, + MAX_ASSET_DURATION, +} from '@constants/sceneAssetConsts.js'; + +// PARAM SCHEMAS + +export const sceneAssetIdParamSchema = z + .object({ + assetId: z.string().length(24, 'Invalid asset ID'), + }) + .strict(); + +export const sceneIdParamSchema = z + .object({ + sceneId: z.string().length(24, 'Invalid scene ID'), + }) + .strict(); + +export const sceneAssetAndSceneParamSchema = z + .object({ + sceneId: z.string().length(24, 'Invalid scene ID'), + assetId: z.string().length(24, 'Invalid asset ID'), + }) + .strict(); + +// BODY SCHEMAS + +export const createSceneAssetSchema = z + .object({ + type: z.enum(assetTypes, { message: 'Asset type must be either "image" or "video"' }), + url: z + .string() + .min(1, 'URL is required') + .max(MAX_ASSET_URL_LENGTH, `URL cannot exceed ${MAX_ASSET_URL_LENGTH} characters`) + .url('Invalid URL format'), + visibility: z.enum(visibilityTypes, { message: 'Visibility must be either "private" or "public"' }).optional(), + prompt: z + .string() + .max(MAX_ASSET_PROMPT_LENGTH, `Prompt cannot exceed ${MAX_ASSET_PROMPT_LENGTH} characters`) + .trim() + .optional(), + generationSource: z + .enum(generationSources, { message: 'Generation source must be either "ai" or "user"' }) + .optional(), + format: z.enum(allFormats, { message: 'Invalid asset format' }).optional(), + width: z + .number() + .int('Width must be an integer') + .min(MIN_DIMENSION, `Width must be at least ${MIN_DIMENSION}`) + .max(MAX_DIMENSION, `Width cannot exceed ${MAX_DIMENSION}`) + .optional(), + height: z + .number() + .int('Height must be an integer') + .min(MIN_DIMENSION, `Height must be at least ${MIN_DIMENSION}`) + .max(MAX_DIMENSION, `Height cannot exceed ${MAX_DIMENSION}`) + .optional(), + duration: z + .number() + .min(MIN_ASSET_DURATION, `Duration must be at least ${MIN_ASSET_DURATION} seconds`) + .max(MAX_ASSET_DURATION, `Duration cannot exceed ${MAX_ASSET_DURATION} seconds`) + .optional(), + }) + .strict(); + +export const updateSceneAssetSchema = z + .object({ + visibility: z.enum(visibilityTypes, { message: 'Visibility must be either "private" or "public"' }).optional(), + prompt: z + .string() + .max(MAX_ASSET_PROMPT_LENGTH, `Prompt cannot exceed ${MAX_ASSET_PROMPT_LENGTH} characters`) + .trim() + .optional() + .nullable(), + width: z + .number() + .int('Width must be an integer') + .min(MIN_DIMENSION, `Width must be at least ${MIN_DIMENSION}`) + .max(MAX_DIMENSION, `Width cannot exceed ${MAX_DIMENSION}`) + .optional(), + height: z + .number() + .int('Height must be an integer') + .min(MIN_DIMENSION, `Height must be at least ${MIN_DIMENSION}`) + .max(MAX_DIMENSION, `Height cannot exceed ${MAX_DIMENSION}`) + .optional(), + duration: z + .number() + .min(MIN_ASSET_DURATION, `Duration must be at least ${MIN_ASSET_DURATION} seconds`) + .max(MAX_ASSET_DURATION, `Duration cannot exceed ${MAX_ASSET_DURATION} seconds`) + .optional(), + }) + .strict() + .refine((data) => Object.keys(data).length > 0, { + message: 'At least one field must be provided for update', + }); + +export const bulkDeleteAssetsSchema = z + .object({ + assetIds: z + .array(z.string().length(24, 'Invalid asset ID')) + .min(1, 'At least one asset ID is required') + .max(50, 'Cannot delete more than 50 assets at once'), + }) + .strict(); + +export const bulkRestoreAssetsSchema = z + .object({ + assetIds: z + .array(z.string().length(24, 'Invalid asset ID')) + .min(1, 'At least one asset ID is required') + .max(50, 'Cannot restore more than 50 assets at once'), + }) + .strict(); + +export const setActiveAssetSchema = z + .object({ + assetId: z.string().length(24, 'Invalid asset ID'), + }) + .strict(); + +// Type exports +export type SceneAssetIdParam = z.infer; +export type SceneIdParam = z.infer; +export type SceneAssetAndSceneParam = z.infer; +export type CreateSceneAssetInput = z.infer; +export type UpdateSceneAssetInput = z.infer; +export type BulkDeleteAssetsInput = z.infer; +export type BulkRestoreAssetsInput = z.infer; +export type SetActiveAssetInput = z.infer; diff --git a/src/validation/scenes.schema.ts b/src/validation/scenes.schema.ts index e69de29..cec0b4a 100644 --- a/src/validation/scenes.schema.ts +++ b/src/validation/scenes.schema.ts @@ -0,0 +1,221 @@ +import { z } from 'zod'; +import { + MAX_SCENE_TITLE_LENGTH, + MAX_SCENE_DESCRIPTION_LENGTH, + MAX_SCENE_PROMPT_LENGTH, + MIN_SCENE_DURATION, + MAX_SCENE_DURATION, + MAX_SCENES_PER_STORY, + MAX_EXTRA_PROMPT_LENGTH, + sceneAuthorType, +} from '@constants/sceneConsts.js'; + +// PARAM SCHEMAS + +export const sceneIdParamSchema = z + .object({ + sceneId: z.string().length(24, 'Invalid scene ID'), + }) + .strict(); + +export const storyIdParamSchema = z + .object({ + storyId: z.string().length(24, 'Invalid story ID'), + }) + .strict(); + +export const sceneAndStoryParamSchema = z + .object({ + storyId: z.string().length(24, 'Invalid story ID'), + sceneId: z.string().length(24, 'Invalid scene ID'), + }) + .strict(); + +export const createSceneSchema = z + .object({ + title: z + .string() + .max(MAX_SCENE_TITLE_LENGTH, `Title cannot exceed ${MAX_SCENE_TITLE_LENGTH} characters`) + .trim() + .optional(), + description: z + .string() + .min(1, 'Description is required') + .max(MAX_SCENE_DESCRIPTION_LENGTH, `Description cannot exceed ${MAX_SCENE_DESCRIPTION_LENGTH} characters`) + .trim(), + imagePrompt: z + .string() + .min(1, 'Image prompt is required') + .max(MAX_SCENE_PROMPT_LENGTH, `Image prompt cannot exceed ${MAX_SCENE_PROMPT_LENGTH} characters`) + .trim(), + videoPrompt: z + .string() + .max(MAX_SCENE_PROMPT_LENGTH, `Video prompt cannot exceed ${MAX_SCENE_PROMPT_LENGTH} characters`) + .trim() + .optional(), + duration: z + .number() + .min(MIN_SCENE_DURATION, `Duration must be at least ${MIN_SCENE_DURATION} second`) + .max(MAX_SCENE_DURATION, `Duration cannot exceed ${MAX_SCENE_DURATION} seconds`) + .optional(), + position: z.number().int('Position must be an integer').min(0, 'Position cannot be negative').optional(), + }) + .strict(); + +export const generateAllScenesSchema = z + .object({ + total: z + .number() + .int('Number of scenes must be an integer') + .min(1, 'At least one scene must be generated') + .max(MAX_SCENES_PER_STORY, `Cannot generate more than ${MAX_SCENES_PER_STORY} scenes`), + }) + .strict(); + +export const updateSceneSchema = z + .object({ + title: z + .string() + .max(MAX_SCENE_TITLE_LENGTH, `Title cannot exceed ${MAX_SCENE_TITLE_LENGTH} characters`) + .trim() + .optional(), + description: z + .string() + .min(1, 'Description cannot be empty') + .max(MAX_SCENE_DESCRIPTION_LENGTH, `Description cannot exceed ${MAX_SCENE_DESCRIPTION_LENGTH} characters`) + .trim() + .optional(), + imagePrompt: z + .string() + .min(1, 'Image prompt cannot be empty') + .max(MAX_SCENE_PROMPT_LENGTH, `Image prompt cannot exceed ${MAX_SCENE_PROMPT_LENGTH} characters`) + .trim() + .optional(), + videoPrompt: z + .string() + .max(MAX_SCENE_PROMPT_LENGTH, `Video prompt cannot exceed ${MAX_SCENE_PROMPT_LENGTH} characters`) + .trim() + .optional() + .nullable(), + }) + .strict() + .refine((data) => Object.keys(data).length > 0, { + message: 'At least one field must be provided for update', + }); + +export const durationSchema = z + .object({ + duration: z + .number() + .min(MIN_SCENE_DURATION, `Duration must be at least ${MIN_SCENE_DURATION} second`) + .max(MAX_SCENE_DURATION, `Duration cannot exceed ${MAX_SCENE_DURATION} seconds`), + }) + .strict(); + +export const moveSceneSchema = z + .object({ + direction: z.enum(['prev', 'next'], 'Direction must be either "prev" or "next"'), + }) + .strict(); + +export const bulkReorderSchema = z + .object({ + sceneIds: z + .array(z.string().length(24, 'Invalid scene ID')) + .min(1, 'At least one scene ID required') + .max(MAX_SCENES_PER_STORY, `Cannot exceed ${MAX_SCENES_PER_STORY} scenes`), + }) + .strict() + .refine( + (data) => { + const uniqueIds = new Set(data.sceneIds); + return uniqueIds.size === data.sceneIds.length; + }, + { message: 'Duplicate scene IDs are not allowed' } + ); + +export const bulkRestoreSchema = z + .object({ + sceneIds: z + .array(z.string().length(24, 'Invalid scene ID')) + .min(1, 'At least one scene ID required') + .max(MAX_SCENES_PER_STORY, `Cannot exceed ${MAX_SCENES_PER_STORY} scenes`), + }) + .strict() + .refine( + (data) => { + const uniqueIds = new Set(data.sceneIds); + return uniqueIds.size === data.sceneIds.length; + }, + { message: 'Duplicate scene IDs are not allowed' } + ); + +// ============================================================================ +// ASSET HANDLING SCHEMAS +// ============================================================================ + +export const setActiveAssetSchema = z + .object({ + assetId: z.string().length(24, 'Invalid asset ID'), + }) + .strict(); + +// ============================================================================ +// AI GENERATION SCHEMAS +// ============================================================================ + +export const generateSceneSchema = z + .object({ + position: z.number().int('Position must be an integer').min(0, 'Position cannot be negative').optional(), + }) + .strict() + .optional(); + +export const regenerateSceneSchema = z + .object({ + extraPrompt: z + .string() + .max(MAX_EXTRA_PROMPT_LENGTH, `Extra prompt cannot exceed ${MAX_EXTRA_PROMPT_LENGTH} characters`) + .trim() + .optional(), + }) + .strict() + .optional(); + +// ============================================================================ +// QUERY SCHEMAS (for optional query parameters) +// ============================================================================ + +export const getScenesQuerySchema = z + .object({ + includeDeleted: z + .string() + .transform((val) => val === 'true') + .optional(), + }) + .strict() + .optional(); + +// ============================================================================ +// TYPE EXPORTS +// ============================================================================ + +export type SceneIdParam = z.infer; +export type StoryIdParam = z.infer; +export type SceneAndStoryParam = z.infer; + +export type CreateSceneInput = z.infer; +export type GenerateAllScenesInput = z.infer; +export type UpdateSceneInput = z.infer; +export type DurationInput = z.infer; + +export type MoveSceneInput = z.infer; +export type BulkReorderInput = z.infer; +export type BulkRestoreInput = z.infer; + +export type SetActiveAssetInput = z.infer; + +export type GenerateSceneInput = z.infer; +export type RegenerateSceneInput = z.infer; + +export type GetScenesQuery = z.infer; diff --git a/src/validation/story.schema.ts b/src/validation/story.schema.ts index e69de29..69c90f8 100644 --- a/src/validation/story.schema.ts +++ b/src/validation/story.schema.ts @@ -0,0 +1,125 @@ +import { maxTimeLimit, minTimeLimit, platform, storyIntent } from '@constants/storyConsts.js'; +import { + CameraMotion, + EnvironmentType, + GenreType, + MoodType, + NarrativeScope, + StyleType, +} from '@models/ContextProfile.js'; +import { z } from 'zod'; + +export const createStorySchema = z + .object({ + title: z.string().min(5, 'Title is required').max(255, 'Title is too long'), + description: z.string().min(5, 'Description is required').max(500, 'Description is too long'), + timeLimit: z + .number() + .min(minTimeLimit, 'Time limit must be at least 10 seconds') + .max(maxTimeLimit, `Time limit cannot exceed ${maxTimeLimit} seconds`), + platform: z.enum([...platform]).optional(), + intent: z.enum([...storyIntent]).optional(), + status: z.enum(['draft', 'active']), + }) + .strict(); + +export const writeContentSchema = z + .object({ + content: z.string().min(20, 'Content is too short').max(5000, 'Content is too long'), + summary: z.string().min(10, 'Summary is too short').max(500, 'Summary is too long'), + keywords: z.array(z.string().max(30, 'Keyword is too long')).max(10, 'Too many keywords').optional(), + tags: z.array(z.string().max(30, 'Tag is too long')).max(10, 'Too many tags').optional(), + }) + .strict(); + +export const regenerateStorySchema = z + .object({ + prompt: z.string().max(200, 'Prompt is too long'), + }) + .strict(); + +export const updateStorySchema = z + .object({ + title: z.string().min(5, 'Title is required').max(255, 'Title is too long').optional(), + description: z.string().min(5, 'Description is required').max(1000, 'Description is too long').optional(), + timeLimit: z + .number() + .min(minTimeLimit, 'Time limit must be at least 10 seconds') + .max(maxTimeLimit, `Time limit cannot exceed ${maxTimeLimit} seconds`) + .optional(), + platform: z.enum([...platform]).optional(), + intent: z.enum([...storyIntent]).optional(), + }) + .strict(); + +export const storyIdParamSchema = z + .object({ + storyId: z.string().length(24, 'Invalid story ID'), + }) + .strict(); + +export const setStoryContextSchema = z.discriminatedUnion('mode', [ + z + .object({ + mode: z.literal('use-project'), + }) + .strict(), + + z + .object({ + mode: z.literal('use-global'), + globalContextId: z.string().min(1), + }) + .strict(), +]); + +export const addStoryContextSchema = z + .object({ + context: z.object({ + name: z.string().min(1).max(100), + description: z.string().max(600).optional(), + + genre: z.enum(GenreType), + mood: z.enum(MoodType), + style: z.enum(StyleType), + narrativeScope: z.enum(NarrativeScope).optional(), + + environment: z.object({ + type: z.enum(EnvironmentType), + cameraMotion: z.enum(CameraMotion), + description: z.string().max(300).optional(), + }), + + worldRules: z.string().max(500).optional(), + narrativeConstraints: z.string().max(500).optional(), + + characters: z + .array( + z.object({ + name: z.string().min(1).max(50), + description: z.string().max(250).optional(), + }) + ) + .max(10) + .optional(), + + forbiddenElements: z + .array( + z.object({ + label: z.string().min(1).max(100), + severity: z.enum(['hard', 'soft']), + }) + ) + .max(50) + .optional(), + }), + }) + .strict(); + +export type StoryIdParam = z.infer; +export type CreateStoryInput = z.infer; +export type RegenerateStoryInput = z.infer; +export type UpdateStoryInput = z.infer; +export type WriteContentInput = z.infer; +export type SetStoryContextInput = z.infer; +export type AddStoryContextInput = z.infer; diff --git a/src/validation/user.schema.ts b/src/validation/user.schema.ts index cca8f12..671dee8 100644 --- a/src/validation/user.schema.ts +++ b/src/validation/user.schema.ts @@ -1,7 +1,5 @@ // src/validation/user.schema.ts -import { z } from "zod"; -import type { Request, Response, NextFunction } from "express"; -import { ACCOUNT_STATUSES } from "constants/accountStatus.js"; +import { z } from "zod"; /* ------------------------- Body Schemas @@ -54,8 +52,9 @@ export const updateNotificationsSchema = z export const updatePrivacySettingsSchema = z .object({ profileVisibility: z.enum(["public", "private", "unlisted"]).optional(), - showActivityStatus: z.boolean().optional(), - // extend as needed + showEmailOnProfile: z.boolean().optional(), + showLinksOnProfile: z.boolean().optional(), + allowDiscoverability: z.boolean().optional(), }) .strict(); @@ -91,16 +90,7 @@ export const deleteSessionParamsSchema = z sessionId: z.string().min(1), }) .strict(); - -export const updateAccountSchema = z - .object({ - accountStatus: z.enum(ACCOUNT_STATUSES), - }) - .strict(); -/* ------------------------- - Types - -------------------------*/ - + export type UpdateAvatarType = z.infer; export type UpdateProfileType = z.infer; export type UpdateNotificationsType = z.infer; @@ -111,53 +101,4 @@ export type UpdatePasswordType = z.infer; export type UpdateEmailType = z.infer; export type DeleteAllSessionsType = z.infer; export type DeleteSessionParamsType = z.infer; -export type UpdateAccountType = z.infer; - -/* ------------------------- - Middleware helpers - -------------------------*/ - -// Attach validatedBody to req.validatedBody -export function validateBody(schema: T) { - return async (req: Request, res: Response, next: NextFunction) => { - try { - const parsed = await schema.parseAsync(req.body); - (req as unknown as { validatedBody?: z.infer }).validatedBody = parsed; - return next(); - } catch (err) { - if (err instanceof z.ZodError) { - const errors = err.issues.map((e) => ({ - path: e.path.join("."), - message: e.message, - })); - return res - .status(400) - .json({ error: "validation_error", details: errors }); - } - return next(err); - } - }; -} - -// Validate route params (attach to req.validatedParams) -export function validateParams(schema: T) { - return async (req: Request, res: Response, next: NextFunction) => { - try { - const parsed = await schema.parseAsync(req.params); - (req as unknown as { validatedParams?: z.infer }).validatedParams = - parsed; - return next(); - } catch (err) { - if (err instanceof z.ZodError) { - const errors = err.issues.map((e) => ({ - path: e.path.join("."), - message: e.message, - })); - return res - .status(400) - .json({ error: "validation_error", details: errors }); - } - return next(err); - } - }; -} + \ No newline at end of file diff --git a/src/validation/validateBody.ts b/src/validation/validateBody.ts new file mode 100644 index 0000000..fd5231f --- /dev/null +++ b/src/validation/validateBody.ts @@ -0,0 +1,19 @@ +// src/validation/validateBody.ts +import { ZodSchema } from "zod"; +import type { RequestHandler } from "express"; + +export const validateBody = + (schema: ZodSchema): RequestHandler => + (req, res, next) => { + const result = schema.safeParse(req.body); + + if (!result.success) { + return res.status(422).json({ + error: "validation_error", + issues: result.error.flatten(), + }); + } + + req.validatedBody = result.data; + next(); + }; diff --git a/src/validation/validateParams.ts b/src/validation/validateParams.ts new file mode 100644 index 0000000..e20758d --- /dev/null +++ b/src/validation/validateParams.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; +import type { Request, Response, NextFunction } from "express"; + +export function validateParams(schema: T) { + return async (req: Request, res: Response, next: NextFunction) => { + try { + const parsed = await schema.parseAsync(req.params); + (req as unknown as { validatedParams?: z.infer }).validatedParams = + parsed; + return next(); + } catch (err) { + if (err instanceof z.ZodError) { + const errors = err.issues.map((e) => ({ + path: e.path.join("."), + message: e.message, + })); + return res + .status(400) + .json({ error: "validation_error", details: errors }); + } + return next(err); + } + }; +} diff --git a/src/validation/videoConfig.schema.ts b/src/validation/videoConfig.schema.ts new file mode 100644 index 0000000..22b44ba --- /dev/null +++ b/src/validation/videoConfig.schema.ts @@ -0,0 +1,263 @@ +import { z } from 'zod'; +import { + MIN_VOLUME, + MAX_VOLUME, + MIN_FADE_DURATION, + MAX_FADE_DURATION, + MIN_SOUND_EFFECT_USE_PERCENTAGE, + MAX_SOUND_EFFECT_USE_PERCENTAGE, + MAX_SOUND_EFFECTS_PER_CONFIG, + MIN_CAPTION_FONT_SIZE, + MAX_CAPTION_FONT_SIZE, + MAX_CAPTION_OFFSET, + MIN_TRANSITION_DURATION, + MAX_TRANSITION_DURATION, + MAX_NARRATION_START_OFFSET, + MAX_NARRATION_END_OFFSET, + MIN_WATERMARK_OPACITY, + MAX_WATERMARK_OPACITY, + MIN_WATERMARK_SIZE, + MAX_WATERMARK_SIZE, + MAX_WATERMARK_TEXT_LENGTH, +} from '../constants/videoConfigConsts.js'; + +const objectIdSchema = z.string().regex(/^[a-fA-F0-9]{24}$/); + +const volumeSchema = z.number().min(MIN_VOLUME).max(MAX_VOLUME); + +const fadeDurationSchema = z.number().min(MIN_FADE_DURATION).max(MAX_FADE_DURATION); + +const verticalPositionSchema = z.enum(['top', 'middle', 'bottom']); + +const horizontalPositionSchema = z.enum(['left', 'center', 'right']); + +const easingSchema = z.enum(['linear', 'ease-in', 'ease-out', 'ease-in-out', 'bounce']); + +const narrationConfigSchema = z.object({ + narrationId: objectIdSchema, + audioAssetId: objectIdSchema.optional(), + volume: volumeSchema.default(100), + startOffset: z.number().min(0).max(MAX_NARRATION_START_OFFSET).default(0), + endOffset: z.number().min(0).max(MAX_NARRATION_END_OFFSET).default(0), + fadeInDuration: fadeDurationSchema.default(0), + fadeOutDuration: fadeDurationSchema.default(0), + enabled: z.boolean().default(true), +}); + +const captionStyleSchema = z.object({ + fontSize: z.number().min(MIN_CAPTION_FONT_SIZE).max(MAX_CAPTION_FONT_SIZE).default(24), + fontFamily: z.string().max(100).default('Arial'), + fontColor: z + .string() + .regex(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) + .default('#FFFFFF'), + fontWeight: z.enum(['normal', 'bold', 'light']).default('bold'), + backgroundColor: z + .string() + .regex(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) + .default('#000000'), + backgroundOpacity: volumeSchema.default(50), + textShadow: z.boolean().default(true), + textOutline: z.boolean().default(false), + outlineColor: z + .string() + .regex(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) + .default('#000000'), + outlineWidth: z.number().min(0).max(10).default(2), +}); + +const captionAnimationSchema = z.object({ + type: z.enum(['none', 'fade', 'slide', 'typewriter', 'bounce']).default('fade'), + duration: z.number().min(0).max(5).default(0.3), +}); + +const captionConfigSchema = z.object({ + enabled: z.boolean().default(true), + position: z.object({ + vertical: verticalPositionSchema.default('bottom'), + horizontal: horizontalPositionSchema.default('center'), + }), + offset: z.object({ + x: z.number().min(-MAX_CAPTION_OFFSET).max(MAX_CAPTION_OFFSET).default(0), + y: z.number().min(-MAX_CAPTION_OFFSET).max(MAX_CAPTION_OFFSET).default(0), + }), + style: captionStyleSchema, + animation: captionAnimationSchema, +}); + +const soundEffectConfigSchema = z.object({ + audioAssetId: objectIdSchema, + name: z.string().trim().max(200), + startTime: z.number().min(0), + duration: z.number().min(0).optional(), + volume: volumeSchema.default(100), + trimStart: z.number().min(0).default(0), + usePercentage: z + .number() + .min(MIN_SOUND_EFFECT_USE_PERCENTAGE) + .max(MAX_SOUND_EFFECT_USE_PERCENTAGE) + .default(100), + loop: z.boolean().default(false), + loopCount: z.number().min(1).optional(), + fadeInDuration: fadeDurationSchema.default(0), + fadeOutDuration: fadeDurationSchema.default(0), + enabled: z.boolean().default(true), +}); + +const transitionConfigSchema = z.object({ + fromSceneIndex: z.number().min(0), + toSceneIndex: z.number().min(0), + type: z + .enum([ + 'none', + 'fade', + 'dissolve', + 'wipe_left', + 'wipe_right', + 'wipe_up', + 'wipe_down', + 'slide_left', + 'slide_right', + 'zoom_in', + 'zoom_out', + 'blur', + ]) + .default('fade'), + duration: z.number().min(MIN_TRANSITION_DURATION).max(MAX_TRANSITION_DURATION).default(0.5), + easing: easingSchema.default('ease-in-out'), +}); + +const sceneTimingConfigSchema = z.object({ + sceneId: objectIdSchema, + order: z.number().min(0), + startTime: z.number().min(0), + duration: z.number().min(0), + customDuration: z.number().min(0).optional(), +}); + +const resolutionSchema = z.object({ + width: z.number().min(320).max(7680).default(1920), + height: z.number().min(240).max(4320).default(1080), + preset: z.enum(['720p', '1080p', '1440p', '4k', 'custom']).default('1080p'), +}); + +const outputSettingsSchema = z.object({ + resolution: resolutionSchema, + aspectRatio: z.enum(['16:9', '9:16', '1:1', '4:3', '21:9', 'custom']).default('16:9'), + frameRate: z + .enum({ + '24': 24, + '30': 30, + '60': 60, + }) + .default(30), + quality: z.enum(['low', 'medium', 'high', 'ultra']).default('high'), + format: z.enum(['mp4', 'webm', 'mov']).default('mp4'), + bitrate: z.number().min(500).max(100000).optional(), +}); + +const backgroundAudioConfigSchema = z.object({ + audioAssetId: objectIdSchema.optional(), + volume: volumeSchema.default(30), + fadeInDuration: fadeDurationSchema.default(2), + fadeOutDuration: fadeDurationSchema.default(2), + loop: z.boolean().default(true), + enabled: z.boolean().default(false), +}); + +const watermarkConfigSchema = z.object({ + enabled: z.boolean().default(false), + imageUrl: z.string().url().max(2000).optional(), + text: z.string().max(MAX_WATERMARK_TEXT_LENGTH).optional(), + position: z.object({ + vertical: verticalPositionSchema.default('bottom'), + horizontal: horizontalPositionSchema.default('right'), + }), + offset: z.object({ + x: z.number().default(10), + y: z.number().default(10), + }), + opacity: z.number().min(MIN_WATERMARK_OPACITY).max(MAX_WATERMARK_OPACITY).default(70), + size: z.number().min(MIN_WATERMARK_SIZE).max(MAX_WATERMARK_SIZE).default(10), +}); + +export const createVideoConfigSchema = z.object({ + storyId: objectIdSchema, + projectId: objectIdSchema, + name: z.string().trim().min(1).max(200), + description: z.string().trim().max(1000).optional(), + soundEffects: z.array(soundEffectConfigSchema).max(MAX_SOUND_EFFECTS_PER_CONFIG).optional(), + transitions: z.array(transitionConfigSchema).optional(), + backgroundAudio: backgroundAudioConfigSchema.optional(), + outputSettings: outputSettingsSchema.optional(), + isTemplate: z.boolean().default(false), + templateName: z.string().trim().max(100).optional(), +}); + +export const updateVideoConfigSchema = z + .object({ + name: z.string().trim().min(1).max(200).optional(), + description: z.string().trim().max(1000).optional(), + sceneOrder: z.array(objectIdSchema).min(1).optional(), + sceneTiming: z.array(sceneTimingConfigSchema).optional(), + narration: narrationConfigSchema.optional(), + captions: captionConfigSchema.optional(), + soundEffects: z.array(soundEffectConfigSchema).max(MAX_SOUND_EFFECTS_PER_CONFIG).optional(), + transitions: z.array(transitionConfigSchema).optional(), + backgroundAudio: backgroundAudioConfigSchema.optional(), + watermark: watermarkConfigSchema.optional(), + outputSettings: outputSettingsSchema.optional(), + isTemplate: z.boolean().optional(), + templateName: z.string().trim().max(100).optional(), + }) + .strict(); + +export const updateNarrationConfigSchema = narrationConfigSchema; +export const updateCaptionsConfigSchema = captionConfigSchema; +export const addSoundEffectSchema = soundEffectConfigSchema; + +export const updateSoundEffectSchema = z.object({ + index: z.number().min(0), + soundEffect: soundEffectConfigSchema, +}); + +export const updateSceneOrderSchema = z.object({ + sceneOrder: z.array(objectIdSchema).min(1), + sceneTiming: z.array(sceneTimingConfigSchema).optional(), +}); + +export const updateTransitionsSchema = z.object({ + transitions: z.array(transitionConfigSchema), +}); + +export const updateOutputSettingsSchema = outputSettingsSchema; +export const updateBackgroundAudioSchema = backgroundAudioConfigSchema; +export const updateWatermarkSchema = watermarkConfigSchema; + +export const getVideoConfigsQuerySchema = z.object({ + storyId: objectIdSchema.optional(), + projectId: objectIdSchema.optional(), + isTemplate: z.boolean().optional(), + page: z.number().min(1).default(1), + limit: z.number().min(1).max(100).default(20), + sortBy: z.enum(['createdAt', 'updatedAt', 'name', 'totalDuration']).default('createdAt'), + sortOrder: z.enum(['asc', 'desc']).default('desc'), +}); + +export const validateForRenderingSchema = z.object({ + configId: objectIdSchema, +}); + +export const cloneVideoConfigSchema = z.object({ + name: z.string().trim().min(1).max(200), + description: z.string().trim().max(1000).optional(), +}); + +export const applyTemplateSchema = z.object({ + templateId: objectIdSchema, + storyId: objectIdSchema, + projectId: objectIdSchema, + name: z.string().trim().min(1).max(200), +}); + +export type CreateVideoConfigType = z.infer; diff --git a/src/validators/validateAssetOwnership.ts b/src/validators/validateAssetOwnership.ts new file mode 100644 index 0000000..12bba57 --- /dev/null +++ b/src/validators/validateAssetOwnership.ts @@ -0,0 +1,22 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { SceneAsset, SceneAssetModel } from '@models/SceneAssets.js'; +import { ClientSession } from 'mongoose'; + +export async function validateAssetOwnership( + userId: string, + assetId: string, + session?: ClientSession +): Promise { + const query = SceneAssetModel.findOne({ + _id: assetId, + userId, + }); + + if (session) query.session(session); + + const asset = await query; + if (!asset) { + throw new NotFoundError('Asset not found or access denied'); + } + return asset; +} diff --git a/src/validators/validateAudioAssetOwnership.ts b/src/validators/validateAudioAssetOwnership.ts new file mode 100644 index 0000000..bb1831b --- /dev/null +++ b/src/validators/validateAudioAssetOwnership.ts @@ -0,0 +1,22 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { AudioAsset, AudioAssetModel } from '@models/AudioAsset.js'; +import { ClientSession } from 'mongoose'; + +export async function validateAudioAssetOwnership( + userId: string, + audioAssetId: string, + session?: ClientSession +): Promise { + const query = AudioAssetModel.findOne({ + _id: audioAssetId, + userId, + }); + + if (session) query.session(session); + + const audioAsset = await query; + if (!audioAsset) { + throw new NotFoundError('Audio asset not found or access denied'); + } + return audioAsset; +} diff --git a/src/validators/validateNarrationOwnership.ts b/src/validators/validateNarrationOwnership.ts new file mode 100644 index 0000000..2168fea --- /dev/null +++ b/src/validators/validateNarrationOwnership.ts @@ -0,0 +1,22 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { StoryNarration, StoryNarrationModel } from '@models/Narration.js'; +import { ClientSession } from 'mongoose'; + +export async function validateNarrationOwnership( + userId: string, + narrationId: string, + session?: ClientSession +): Promise { + const query = StoryNarrationModel.findOne({ + _id: narrationId, + userId, + }); + + if (session) query.session(session); + + const narration = await query; + if (!narration) { + throw new NotFoundError('Narration not found or access denied'); + } + return narration; +} diff --git a/src/validators/validateSceneOwnership.ts b/src/validators/validateSceneOwnership.ts new file mode 100644 index 0000000..b6c7aaf --- /dev/null +++ b/src/validators/validateSceneOwnership.ts @@ -0,0 +1,43 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { Scene, SceneModel } from '@models/Scene.js'; +import { ClientSession } from 'mongoose'; + +export async function validateSceneOwnership( + userId: string, + sceneId: string, + session?: ClientSession +): Promise { + const query = SceneModel.findOne({ + _id: sceneId, + userId, + }); + + if (session) query.session(session); + + const scene = await query; + if (!scene) { + throw new NotFoundError('Scene not found or access denied'); + } + return scene; +} + +export async function validateStorySceneOwnership( + userId: string, + sceneId: string, + storyId: string, + session?: ClientSession +): Promise { + const query = SceneModel.findOne({ + _id: sceneId, + userId, + storyId, + }); + + if (session) query.session(session); + + const scene = await query; + if (!scene) { + throw new NotFoundError('Scene not found or access denied'); + } + return scene; +} diff --git a/src/validators/validateStoryOwnership.ts b/src/validators/validateStoryOwnership.ts new file mode 100644 index 0000000..7b80a33 --- /dev/null +++ b/src/validators/validateStoryOwnership.ts @@ -0,0 +1,26 @@ +import { ClientSession } from 'mongoose'; +import { StoryModel } from '@models/Story.js'; +import { NotFoundError } from '@middleware/error/index.js'; +import { Story } from '@models/Story.js'; + +export async function validateStoryOwnership( + userId: string, + storyId: string, + session?: ClientSession +): Promise { + const query = StoryModel.findOne({ + _id: storyId, + userId, + }); + + if (session) { + query.session(session); + } + + const story = await query; + if (!story) { + throw new NotFoundError('Story not found or access denied'); + } + + return story; +} diff --git a/src/validators/validateUser.ts b/src/validators/validateUser.ts new file mode 100644 index 0000000..650a2cf --- /dev/null +++ b/src/validators/validateUser.ts @@ -0,0 +1,13 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { User, UserModel } from '@models/User.js'; +import { ClientSession } from 'mongoose'; + +export async function validateUser(userId: string, session?: ClientSession): Promise { + const query = UserModel.findById(userId); + if (session) query.session(session); + const user = await query; + if (!user) { + throw new NotFoundError('User not found'); + } + return user; +} diff --git a/src/validators/validateVideoConfigOwnership.ts b/src/validators/validateVideoConfigOwnership.ts new file mode 100644 index 0000000..20cf679 --- /dev/null +++ b/src/validators/validateVideoConfigOwnership.ts @@ -0,0 +1,48 @@ +import { Types } from 'mongoose'; +import VideoConfig, { IVideoConfig } from '@models/VideoConfig.js'; +import { VIDEO_CONFIG_ERROR_MESSAGES } from '@constants/videoConfigConsts.js'; +import { NotFoundError, UnauthorizedError } from '@middleware/error/index.js'; + +interface ValidateVideoConfigOwnershipResult { + videoConfig: IVideoConfig; +} + +export async function validateVideoConfigOwnership( + configId: string | Types.ObjectId, + userId: string | Types.ObjectId, + options: { + populate?: string | string[]; + } = {} +): Promise { + const { populate } = options; + + let query = VideoConfig.findById(configId); + + if (populate) { + if (Array.isArray(populate)) { + populate.forEach((field) => { + query = query.populate(field); + }); + } else { + query = query.populate(populate); + } + } + + const videoConfig = await query.exec(); + + if (!videoConfig) { + throw new NotFoundError(VIDEO_CONFIG_ERROR_MESSAGES.NOT_FOUND); + } + + // Check ownership + const configUserId = videoConfig.userId.toString(); + const requestUserId = userId.toString(); + + if (configUserId !== requestUserId) { + throw new UnauthorizedError(VIDEO_CONFIG_ERROR_MESSAGES.UNAUTHORIZED); + } + + return { videoConfig }; +} + +export default validateVideoConfigOwnership; diff --git a/tsconfig.json b/tsconfig.json index 44f6cc7..b4cbacc 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,7 +5,7 @@ "moduleResolution": "NodeNext", "rootDir": "./src", - "outDir": "./dist", + "outDir": "src/dist", "strict": true, "esModuleInterop": true, @@ -21,8 +21,13 @@ "@db/*": ["db/*"], "@models/*": ["models/*"], "@routes/*":["routes/*"], - "@validation/*":["validation/*"] + "@validation/*":["validation/*"], + "@validators/*": ["validators/*"], + "@libs/*": ["libs/*"], + "@constants/*": ["constants/*"], + "@security/*": ["security/*"], + "@domain/*": ["domain/*"], } }, - "include": ["src"] + "include": ["src", "dist"] } \ No newline at end of file