From c6c1f36414c41d59efe72333757c86a344d2fbf7 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Sun, 14 Dec 2025 01:48:37 +0530 Subject: [PATCH 01/14] Add CI to run build on PRs --- .github/workflows/ci.yml | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..685a38c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,29 @@ +name: Backend CI + +on: + pull_request: + branches: + - main + push: + branches: + - main + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Build project + run: npm run build From b765132c822d4f72de48f6c4065618bc316f469f Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Mon, 15 Dec 2025 02:12:22 +0530 Subject: [PATCH 02/14] Resolve Audit & Improve User Routes (Updates, Avatar Upload, Error Handling) #6, Added a new custom Error --- .gitignore | 4 + package-lock.json | 175 ++++++++++++++++++++- package.json | 2 + src/middleware/avatarUpload.ts | 27 ++++ src/middleware/error/AppError.ts | 1 - src/middleware/error/errorCodes.ts | 3 + src/middleware/error/globalErrorHandler.ts | 2 +- src/middleware/error/index.ts | 6 + src/middleware/multer.ts | 37 +++++ src/models/User.ts | 15 +- src/modules/auth/auth.service.ts | 35 ++++- src/modules/user/user.controller.ts | 73 ++++----- src/modules/user/user.routes.ts | 7 +- src/modules/user/user.service.ts | 150 ++++++++++++++---- src/utils/returnUserData.ts | 3 +- src/validation/user.schema.ts | 5 +- 16 files changed, 460 insertions(+), 85 deletions(-) create mode 100644 src/middleware/avatarUpload.ts create mode 100644 src/middleware/multer.ts diff --git a/.gitignore b/.gitignore index fb1fc80..3859b7d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,10 @@ Design # Node modules node_modules/ +# Temporary files +npm-temp/ +temp/ + # Environment variables .env .env.local diff --git a/package-lock.json b/package-lock.json index 74f6612..cc0ac7d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "@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", @@ -19,6 +20,7 @@ "helmet": "^8.1.0", "jsonwebtoken": "^9.0.2", "mongoose": "^9.0.0", + "multer": "^2.0.2", "nodemailer": "^7.0.11", "ua-parser-js": "^2.0.6", "undici": "^7.16.0", @@ -2790,6 +2792,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 +2894,12 @@ "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/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -2986,6 +3003,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", @@ -3056,6 +3090,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", @@ -3881,12 +3930,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 +4051,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", @@ -4210,6 +4331,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", @@ -4439,6 +4574,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", @@ -4573,6 +4725,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 +4827,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", @@ -4706,6 +4870,15 @@ "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..74ce481 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "@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", @@ -19,6 +20,7 @@ "helmet": "^8.1.0", "jsonwebtoken": "^9.0.2", "mongoose": "^9.0.0", + "multer": "^2.0.2", "nodemailer": "^7.0.11", "ua-parser-js": "^2.0.6", "undici": "^7.16.0", diff --git a/src/middleware/avatarUpload.ts b/src/middleware/avatarUpload.ts new file mode 100644 index 0000000..b584375 --- /dev/null +++ b/src/middleware/avatarUpload.ts @@ -0,0 +1,27 @@ +import { Request, Response, NextFunction } from "express"; +import multer from "multer"; +import { upload } from "./multer.js"; +import { 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 limit", err) + ); + } + return res.status(400).json({ + message: err.message, + }); + } + + return next(err); + }); +}; diff --git a/src/middleware/error/AppError.ts b/src/middleware/error/AppError.ts index 527bc03..9fecc94 100644 --- a/src/middleware/error/AppError.ts +++ b/src/middleware/error/AppError.ts @@ -1,4 +1,3 @@ -// src/errors/AppError.ts export class AppError extends Error { statusCode: number; code: string; 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..6a88f51 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -3,7 +3,7 @@ import { NextFunction, Request, Response } from "express"; import { AppError } from "./appError.js"; const errorHandler = ( - err: Error, + err: unknown, req: Request, res: Response, next: NextFunction diff --git a/src/middleware/error/index.ts b/src/middleware/error/index.ts index c4e5547..d45f113 100644 --- a/src/middleware/error/index.ts +++ b/src/middleware/error/index.ts @@ -58,6 +58,12 @@ export class GoneError extends AppError { } } +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) { diff --git a/src/middleware/multer.ts b/src/middleware/multer.ts new file mode 100644 index 0000000..8378230 --- /dev/null +++ b/src/middleware/multer.ts @@ -0,0 +1,37 @@ +import { Request } from "express"; +import multer from "multer"; +import { BadRequestError } from "./error/index.js"; +import path from "path"; + +const storage = multer.diskStorage({ + destination: function ( + req: Request, + file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + cb(null, "./temp/uploads"); + }, + filename: function (req, file, cb) { + const ext = path.extname(file.originalname); + const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); + console.log("file", file, "uniqueSuffix", uniqueSuffix); + console.log("req", req.user); + cb(null, file.fieldname + "-" + uniqueSuffix + ext); + }, +}); + +const fileFilter: multer.Options["fileFilter"] = (req, file, cb) => { + if (!file.mimetype.startsWith("image/")) { + cb(new BadRequestError("Only image files are allowed")); + return; + } + cb(null, true); +}; + +const upload = multer({ + storage, + fileFilter, + limits: { fileSize: 1 * 1024 * 1024 }, +}); + +export { upload }; diff --git a/src/models/User.ts b/src/models/User.ts index c6f0cd0..401ce4a 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -31,7 +31,7 @@ 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 @@ -292,13 +292,22 @@ const userSchema = new Schema( // 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 }, diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 17c592d..1334287 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -194,6 +194,13 @@ export async function createPasswordResetRequest(email: string) { const expiresAt = new Date(Date.now() + RESET_EXP_MIN * 60 * 1000); user.passwordReset = { tokenHash: hash, expiresAt, requestedAt: new Date() }; + user.changeHistory.push({ + field: "password", + by: user._id, + reason: "User requested password reset", + at: new Date(), + via: "user", + }); await user.save(); const resetUrl = `${ @@ -253,6 +260,16 @@ export async function resetPassword(rawToken: string, newPassword: string) { try { user.passwordHash = hashedPassword; user.passwordReset = undefined; + user.lastPasswordChangeAt = new Date(); + user.changeHistory.push({ + field: "password", + by: user._id, + oldValue: "", + newValue: "", + reason: "User reset the password via password reset", + at: new Date(), + via: "user", + }); await user.save({ session }); await SessionModel.deleteMany({ userId: user._id }, { session }); } catch (err) { @@ -343,6 +360,13 @@ export async function emailVerification( expiresAt: new Date(Date.now() + 3600 * 1000), // 1 hour requestedAt: new Date(), }; + user.changeHistory.push({ + field: "email", + by: user._id, + reason: "User requested email verification", + at: new Date(), + via: "user", + }); await user.save(); try { await transporter.sendMail({ @@ -386,6 +410,13 @@ export async function verifyEmail(verificationToken: string): Promise { } user.emailVerified = true; user.emailVerification = undefined; + user.changeHistory.push({ + field: "email", + by: user._id, + reason: "User verified their email", + at: new Date(), + via: "user", + }); await user.save(); return; } @@ -398,7 +429,7 @@ export async function verifyUpdateEmail( "pendingEmailChange.tokenHash": hash, }).select("+pendingEmailChange +changeHistory"); if (!user) { - return; + return; } if ( !user.pendingEmailChange || @@ -426,7 +457,7 @@ export async function verifyUpdateEmail( from: user.email, to: user.pendingEmailChange.newEmail, by: user._id, - reason: "User requested email change", + reason: "User verified email change", at: new Date(), via: "user", }); diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index fb458a8..b0c53c5 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -1,5 +1,6 @@ import { DeleteAllSessionsType, + DeleteSessionParamsType, UpdateAccountType, UpdateAvatarType, UpdateEmailType, @@ -28,7 +29,10 @@ import { updateProfile, } from "./user.service.js"; import { AccountStatus } from "constants/accountStatus.js"; -import { UnauthenticatedError } from "@middleware/error/index.js"; +import { + NotFoundError, + UnauthenticatedError, +} from "@middleware/error/index.js"; export const getProfileController = async (req: Request, res: Response) => { const userId = req.user?._id; @@ -66,16 +70,14 @@ export const updateProfileController = async (req: Request, res: Response) => { export const updateAvatarController = async (req: Request, res: Response) => { const userId = req.user?._id; - const avatarData = (req as unknown as { validatedBody?: UpdateAvatarType }) - .validatedBody!; + const avatarData = req.file; if (!userId) { - throw new Error( - "Invariant violation: req.user is missing after auth middleware" - ); + throw new UnauthenticatedError("Authentication required"); } - - // Add Mullter or file upload handling logic here to get the avatar file data - + if (!avatarData) { + throw new NotFoundError("Avatar file not found"); + } + const updatedUser = await updateAvatar(userId, avatarData); return res.status(200).json(updatedUser); @@ -89,9 +91,7 @@ export const deleteAvatarController = async ( ) => { const userId = req.user?._id; if (!userId) { - throw new Error( - "Invariant violation: req.user is missing after auth middleware" - ); + throw new UnauthenticatedError("Authentication required"); } await deleteAvatar(userId); return res.status(204).send({ @@ -102,9 +102,7 @@ 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" - ); + throw new UnauthenticatedError("Authentication required"); } const user = await getSettings(userId); return res.status(200).json(user); @@ -113,9 +111,7 @@ export const getSettingsController = async (req: Request, res: Response) => { 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" - ); + throw new UnauthenticatedError("Authentication required"); } const user = await getSecurity(userId); @@ -126,9 +122,7 @@ 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" - ); + throw new UnauthenticatedError("Authentication required"); } const sessions = await getSessions(userId, sessionId); return res.status(200).json(sessions); @@ -137,9 +131,7 @@ export const getSessionsController = async (req: Request, res: Response) => { 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" - ); + throw new UnauthenticatedError("Authentication required"); } const billingInfo = await getBilling(userId); @@ -152,10 +144,10 @@ export const updateNotificationsController = async ( ) => { const userId = req.user?._id; const notificationPrefs = ( - req.body as unknown as { validatedBody?: UpdateNotificationsType } + req as unknown as { validatedBody?: UpdateNotificationsType } ).validatedBody!; if (!userId) { - throw new Error("User ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } // Assuming updateNotifications is a service function to update notification preferences const updatedUser = await updateNotifications(userId, notificationPrefs); @@ -172,10 +164,10 @@ export const updatePrivacySettingsController = async ( ) => { const userId = req.user?._id; const privacyPrefs = ( - req.body as unknown as { validatedBody?: UpdatePrivacySettingsType } + req as unknown as { validatedBody?: UpdatePrivacySettingsType } ).validatedBody!; if (!userId) { - return new Error("User ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } const updatedUser = await updatePrivacySettings(userId, privacyPrefs); return res.status(200).json({ @@ -187,11 +179,12 @@ 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 } + req as unknown as { validatedBody?: UpdatePasswordType } ).validatedBody!; if (!userId) { - throw new Error("User ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } + // 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", @@ -213,10 +206,12 @@ 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 { sessionId } = ( + req as unknown as { validatedParams?: DeleteSessionParamsType } + ).validatedParams!; const currentSession = req.sessionId; if (!userId) { - throw new Error("User ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } if (currentSession === sessionId) { return res @@ -234,16 +229,16 @@ export const deleteAllSessionsController = async ( res: Response ) => { const { removeCurrent } = ( - req.body as unknown as { validatedBody?: DeleteAllSessionsType } + req 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"); + throw new UnauthenticatedError("Authentication required"); } if (!currentSession) { - throw new Error("Session ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } await deleteAllSessions(userId, currentSession, removeCurrent); return res.status(204).send(); @@ -252,7 +247,7 @@ export const deleteAllSessionsController = async ( export const deleteAccountController = async (req: Request, res: Response) => { const userId = req.user?._id; if (!userId) { - throw new Error("User ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } // Implementation for deleting user account await deleteAccount(userId); @@ -263,13 +258,13 @@ 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 } + req as unknown as { validatedBody?: UpdateAccountType } ).validatedBody!; if (!userId) { - throw new Error("User ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } if (!sessionId) { - throw new Error("Session ID not found in request"); + throw new UnauthenticatedError("Authentication required"); } const updatedUser = await updateAccount(userId, accountStatus, sessionId); diff --git a/src/modules/user/user.routes.ts b/src/modules/user/user.routes.ts index 18dc2d5..c4493f6 100644 --- a/src/modules/user/user.routes.ts +++ b/src/modules/user/user.routes.ts @@ -33,6 +33,7 @@ import { validateBody, validateParams, } from "@validation/user.schema.js"; +import { avatarUpload } from "@middleware/avatarUpload.js"; const router = Router(); @@ -51,7 +52,7 @@ router.patch( ); router.patch( "/profile/avatar", - validateBody(updateAvatarSchema), + avatarUpload, asyncHandler(updateAvatarController) ); router.delete("/profile/avatar", asyncHandler(deleteAvatarController)); @@ -78,12 +79,12 @@ 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 diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 1f48874..8cd89f0 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -2,13 +2,18 @@ import { ACCOUNT_STATUSES, AccountStatus } from "constants/accountStatus.js"; import bcrypt from "bcrypt"; import { ConflictError, + ForbiddenError, 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 { + UpdateAvatarType, + UpdateNotificationsType, + UpdatePrivacySettingsType, +} from "@validation/user.schema.js"; import mongoose, { ObjectIdSchemaDefinition } from "mongoose"; import { generateVerificationToken, verifyToken } from "@utils/tokens.js"; import transporter from "config/mail.js"; @@ -21,7 +26,7 @@ export const getProfile = async ( "-passwordHash -emailVerificationToken -resetPasswordToken -createdAt -updatedAt" ); if (!user) { - throw new Error("User not found"); + throw new NotFoundError("User not found"); } return user; }; @@ -35,7 +40,7 @@ export const updateProfile = async ( }); if (!user) { - throw new Error("User not found"); + throw new NotFoundError("User not found"); } const resUser = returnUserData(user, "profile"); return resUser; @@ -43,17 +48,21 @@ export const updateProfile = async ( export const updateAvatar = async ( userId: ObjectIdSchemaDefinition, - avatarData: UpdateAvatarType + avatarData: Express.Multer.File ): 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 { 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 = `/uploads/avatars/${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"); return resUser; @@ -62,14 +71,21 @@ export const updateAvatar = async ( export const deleteAvatar = async ( userId: ObjectIdSchemaDefinition ): Promise => { - const user = await UserModel.findByIdAndUpdate( + const user = await UserModel.findById(userId); + if (!user) { + throw new NotFoundError("User not found"); + } + const oldAvatarUrl = user.avatarUrl; + if (!oldAvatarUrl) { + return; + } + //TODO Add logic to delete the avatar file from storage if necessary + + await UserModel.findByIdAndUpdate( userId, { $unset: { avatarUrl: "" } }, { new: true } ); - if (!user) { - throw new Error("User not found"); - } return; }; @@ -93,7 +109,7 @@ export const getSecurity = async ( "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"); return resUser; @@ -144,7 +160,7 @@ export const getBilling = async ( ): 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"); return resUser; @@ -152,15 +168,30 @@ export const getBilling = async ( export const updateNotifications = async ( userId: ObjectIdSchemaDefinition, - notificationPrefs: any + notificationPrefs: UpdateNotificationsType ): Promise> => { + 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, - { emailNotifications: notificationPrefs }, + { $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"); return resUser; @@ -168,15 +199,30 @@ export const updateNotifications = async ( export const updatePrivacySettings = async ( userId: ObjectIdSchemaDefinition, - privacyPrefs: any + privacyPrefs: UpdatePrivacySettingsType ): Promise> => { + 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, - { privacySettings: privacyPrefs }, + { $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"); return resUser; @@ -187,17 +233,29 @@ export const updatePassword = async ( 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 ConflictError("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, + oldValue: "", + newValue: "", + reason: "User initiated password change", + at: new Date(), + via: "user", + }); await user.save(); return; }; @@ -268,7 +326,7 @@ export const deleteSession = async ( }); if (!session) { - throw new Error("Session not found"); + throw new NotFoundError("Session not found"); } session.revokedAt = new Date(); await session.save(); @@ -296,7 +354,21 @@ export const deleteAccount = async ( session.startTransaction(); await UserModel.findByIdAndUpdate( userId, - { deletedAt: new Date(), accountStatus: "deleted" }, + { + deletedAt: new Date(), + accountStatus: "deleted", + $push: { + changeHistory: { + field: "accountStatus", + from: "active", + to: "deleted", + by: userId, + reason: "User deleted account", + at: new Date(), + via: "user", + }, + }, + }, { session } ); await SessionModel.deleteMany({ userId }, { session }); @@ -315,9 +387,9 @@ export const updateAccount = async ( updateData: AccountStatus, currentSessionId: string ): Promise> => { - const user = await UserModel.findById(userId); + 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 } }, @@ -328,6 +400,7 @@ export const updateAccount = async ( { $replaceRoot: { newRoot: "$changeHistory" } }, ]); let updatedUser; + const session = await mongoose.startSession(); session.startTransaction(); try { @@ -336,19 +409,33 @@ export const updateAccount = async ( updateData !== "disabled" && updateData !== "active" ) { - throw new Error("Only admin can do this operation"); + throw new ForbiddenError("Only admin can do this operation"); } else if ( + latestStatusEvent[0] && user.accountStatus === "disabled" && latestStatusEvent[0].via !== "user" && updateData === "active" ) { - throw new Error( + throw new ForbiddenError( "Disabled by admin, account can only be activated by admin" ); } else { updatedUser = await UserModel.findByIdAndUpdate( userId, - { accountStatus: updateData }, + { + accountStatus: updateData, + $push: { + changeHistory: { + field: "accountStatus", + from: user.accountStatus, + to: updateData, + by: user._id, + reason: "Account status updated", + at: new Date(), + via: user.role, + }, + }, + }, { new: true, session } ); @@ -362,15 +449,14 @@ export const updateAccount = async ( } await session.commitTransaction(); if (!updatedUser) { - throw new Error("User not found after update"); + throw new NotFoundError("User not found"); } const resUser = returnUserData(updatedUser, "profile"); return resUser; } catch (err) { await session.abortTransaction(); throw err; - } - finally { + } finally { session.endSession(); } }; diff --git a/src/utils/returnUserData.ts b/src/utils/returnUserData.ts index 60d9529..f8769bc 100644 --- a/src/utils/returnUserData.ts +++ b/src/utils/returnUserData.ts @@ -21,6 +21,7 @@ export const returnUserData = (user: User, type: UserReturnType) => { plan: user.plan, emailVerified: user.emailVerified, usage: user.usage, + accountStatus: user.accountStatus, }; case "settings": @@ -73,7 +74,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/validation/user.schema.ts b/src/validation/user.schema.ts index cca8f12..f935bef 100644 --- a/src/validation/user.schema.ts +++ b/src/validation/user.schema.ts @@ -54,8 +54,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(); From c7705b0c1e646170fa5e67a351f9d1ebaf352290 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Mon, 15 Dec 2025 19:52:33 +0530 Subject: [PATCH 03/14] Applied Suggested changes by Copilot --- src/middleware/avatarUpload.ts | 5 +---- src/middleware/multer.ts | 24 +++++++++++++++--------- src/modules/auth/auth.service.ts | 4 ++-- src/modules/user/user.controller.ts | 7 ++----- src/modules/user/user.service.ts | 18 ++++++++++++------ 5 files changed, 32 insertions(+), 26 deletions(-) diff --git a/src/middleware/avatarUpload.ts b/src/middleware/avatarUpload.ts index b584375..e38ddad 100644 --- a/src/middleware/avatarUpload.ts +++ b/src/middleware/avatarUpload.ts @@ -17,11 +17,8 @@ export const avatarUpload = ( new PayloadTooLargeError("Avatar file size exceeds the limit", err) ); } - return res.status(400).json({ - message: err.message, - }); + return next(new Error("Multer error during file upload", err)); } - return next(err); }); }; diff --git a/src/middleware/multer.ts b/src/middleware/multer.ts index 8378230..4f282f0 100644 --- a/src/middleware/multer.ts +++ b/src/middleware/multer.ts @@ -1,7 +1,6 @@ import { Request } from "express"; import multer from "multer"; -import { BadRequestError } from "./error/index.js"; -import path from "path"; +import { BadRequestError } from "./error/index.js"; const storage = multer.diskStorage({ destination: function ( @@ -11,20 +10,27 @@ const storage = multer.diskStorage({ ) { cb(null, "./temp/uploads"); }, - filename: function (req, file, cb) { - const ext = path.extname(file.originalname); + filename: function (req, file, cb) { const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); - console.log("file", file, "uniqueSuffix", uniqueSuffix); - console.log("req", req.user); - cb(null, file.fieldname + "-" + uniqueSuffix + ext); + cb(null, file.fieldname + "-" + uniqueSuffix ); }, }); +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 (!file.mimetype.startsWith("image/")) { - cb(new BadRequestError("Only image files are allowed")); + if (!file.mimetype.startsWith("image/") || !allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError("Only image files (jpg, jpeg, png, gif, webp) are allowed")); + return; + } + + const fileExtension = file.originalname.substring(file.originalname.lastIndexOf(".")).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError("Only image files (jpg, jpeg, png, gif, webp) are allowed")); return; } + cb(null, true); }; diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 1334287..0decd59 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -264,8 +264,8 @@ export async function resetPassword(rawToken: string, newPassword: string) { user.changeHistory.push({ field: "password", by: user._id, - oldValue: "", - newValue: "", + from: "", + to: "", reason: "User reset the password via password reset", at: new Date(), via: "user", diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index b0c53c5..8396d62 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -2,7 +2,6 @@ import { DeleteAllSessionsType, DeleteSessionParamsType, UpdateAccountType, - UpdateAvatarType, UpdateEmailType, UpdateNotificationsType, UpdatePasswordType, @@ -30,6 +29,7 @@ import { } from "./user.service.js"; import { AccountStatus } from "constants/accountStatus.js"; import { + BadRequestError, NotFoundError, UnauthenticatedError, } from "@middleware/error/index.js"; @@ -75,13 +75,10 @@ export const updateAvatarController = async (req: Request, res: Response) => { throw new UnauthenticatedError("Authentication required"); } if (!avatarData) { - throw new NotFoundError("Avatar file not found"); + throw new BadRequestError("Avatar file not found"); } - const updatedUser = await updateAvatar(userId, avatarData); return res.status(200).json(updatedUser); - - // Implementation for updating user avatar }; export const deleteAvatarController = async ( diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 8cd89f0..51ca91a 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -5,12 +5,12 @@ import { ForbiddenError, InternalServerError, NotFoundError, + UnauthenticatedError, } from "@middleware/error/index.js"; -import { Session, SessionModel } from "@models/Session.js"; +import { SessionModel } from "@models/Session.js"; import { type User, UserModel } from "@models/User.js"; import { returnUserData } from "@utils/returnUserData.js"; import { - UpdateAvatarType, UpdateNotificationsType, UpdatePrivacySettingsType, } from "@validation/user.schema.js"; @@ -54,7 +54,7 @@ export const updateAvatar = async ( //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 = `/uploads/avatars/${filename}`; + const avatarUrl = `${path}/${filename}`; const user = await UserModel.findByIdAndUpdate( userId, @@ -75,6 +75,12 @@ export const deleteAvatar = async ( if (!user) { throw new NotFoundError("User not found"); } + /** + * 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. + */ const oldAvatarUrl = user.avatarUrl; if (!oldAvatarUrl) { return; @@ -242,7 +248,7 @@ export const updatePassword = async ( const isMatch = await bcrypt.compare(currentPassword, user.passwordHash); if (!isMatch) { - throw new ConflictError("Current password is incorrect"); + throw new UnauthenticatedError("Current password is incorrect"); } const hashedPassword = await bcrypt.hash(newPassword, 10); user.lastPasswordChangeAt = new Date(); @@ -250,8 +256,8 @@ export const updatePassword = async ( user.changeHistory.push({ field: "password", by: user._id, - oldValue: "", - newValue: "", + from: "", + to: "", reason: "User initiated password change", at: new Date(), via: "user", From d6564996779e921cdec9635db39c1fbfe4b17e2c Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Wed, 17 Dec 2025 20:43:06 +0530 Subject: [PATCH 04/14] Added the Models to the backend, Resolve Issue8: Refactor and finalize core data models for story-centric AI generation #8 --- src/middleware/avatarUpload.ts | 7 +- src/middleware/multer.ts | 56 ++++++++---- src/models/AudioAsset.ts | 72 +++++++++++++++ src/models/ContextProfile.ts | 135 ++++++++++++++++++++++++++++ src/models/ContextProfileHistory.ts | 134 +++++++++++++++++++++++++++ src/models/FinalVideo.ts | 88 ++++++++++++++++++ src/models/Project.ts | 63 +++++++++++++ src/models/Scene.ts | 128 ++++++++++++++++++++++++++ src/models/SceneAssets.ts | 74 +++++++++++++++ src/models/Story.ts | 113 +++++++++++++++++++++++ src/modules/auth/auth.service.ts | 4 +- src/modules/user/user.controller.ts | 2 - 12 files changed, 855 insertions(+), 21 deletions(-) create mode 100644 src/models/AudioAsset.ts create mode 100644 src/models/ContextProfile.ts create mode 100644 src/models/ContextProfileHistory.ts create mode 100644 src/models/FinalVideo.ts create mode 100644 src/models/SceneAssets.ts diff --git a/src/middleware/avatarUpload.ts b/src/middleware/avatarUpload.ts index e38ddad..01e8ceb 100644 --- a/src/middleware/avatarUpload.ts +++ b/src/middleware/avatarUpload.ts @@ -14,10 +14,13 @@ export const avatarUpload = ( if (err instanceof multer.MulterError) { if (err.code === "LIMIT_FILE_SIZE") { return next( - new PayloadTooLargeError("Avatar file size exceeds the limit", err) + new PayloadTooLargeError( + "Avatar file size exceeds the 2MB limit", + err + ) ); } - return next(new Error("Multer error during file upload", err)); + return next(new Error("Multer error during file upload", { cause: err })); } return next(err); }); diff --git a/src/middleware/multer.ts b/src/middleware/multer.ts index 4f282f0..38a6495 100644 --- a/src/middleware/multer.ts +++ b/src/middleware/multer.ts @@ -1,43 +1,69 @@ import { Request } from "express"; +import fs from "fs"; import multer from "multer"; -import { BadRequestError } from "./error/index.js"; +import { BadRequestError } from "./error/index.js"; const storage = multer.diskStorage({ destination: function ( - req: Request, - file: Express.Multer.File, + _req: Request, + _file: Express.Multer.File, cb: (error: Error | null, destination: string) => void ) { - cb(null, "./temp/uploads"); + const uploadPath = "./temp/uploads"; + if (!fs.existsSync(uploadPath)) { + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + return cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + } + cb(null, uploadPath); }, - filename: function (req, file, cb) { + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const fileExtension = file.originalname + .substring(file.originalname.lastIndexOf(".")) + .toLowerCase(); const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); - cb(null, file.fieldname + "-" + uniqueSuffix ); + 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 (!file.mimetype.startsWith("image/") || !allowedMimetypes.includes(file.mimetype)) { - cb(new BadRequestError("Only image files (jpg, jpeg, png, gif, webp) are allowed")); +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 fileExtension = file.originalname.substring(file.originalname.lastIndexOf(".")).toLowerCase(); - if (!allowedExtensions.includes(fileExtension)) { - cb(new BadRequestError("Only image files (jpg, jpeg, png, gif, webp) are allowed")); + const lastDotIndex = file.originalname.lastIndexOf("."); + + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension) || lastDotIndex <= 0) { + cb( + new BadRequestError( + "Only image files (jpg, jpeg, png, gif, webp) are allowed" + ) + ); return; } - cb(null, true); }; const upload = multer({ storage, fileFilter, - limits: { fileSize: 1 * 1024 * 1024 }, + limits: { fileSize: 2 * 1024 * 1024 }, }); export { upload }; diff --git a/src/models/AudioAsset.ts b/src/models/AudioAsset.ts new file mode 100644 index 0000000..0e8181d --- /dev/null +++ b/src/models/AudioAsset.ts @@ -0,0 +1,72 @@ +import { Schema, model, Document, Types } from "mongoose"; + +export interface AudioAsset extends Document { + userId: Types.ObjectId; + type: "narration" | "background" | "effect"; + url: string; + prompt?: string; // for AI-generated audio + generationSource: "ai" | "upload"; + // resolved (actual) metadata + voiceId?: string; + language?: string; + accent?: string; + tone?: string; + pacing?: string; + duration?: number; // seconds + format?: string; // mp3, wav, etc. + saved: boolean; // saved to library or not + createdAt: Date; + updatedAt: Date; +} + +const audioAssetSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + index: true, + }, + + type: { + type: String, + enum: ["narration", "background", "effect"], + required: true, + }, + + url: { + type: String, + required: true, + }, + + prompt: { + type: String, + }, + + generationSource: { + type: String, + enum: ["ai", "upload"], + default: "ai", + }, + + duration: { + type: Number, + }, + + format: { + type: String, + }, + + saved: { + type: Boolean, + default: false, + index: true, + }, + }, + { timestamps: true } +); + +export const AudioAssetModel = model( + "AudioAsset", + audioAssetSchema +); diff --git a/src/models/ContextProfile.ts b/src/models/ContextProfile.ts new file mode 100644 index 0000000..5c8cc91 --- /dev/null +++ b/src/models/ContextProfile.ts @@ -0,0 +1,135 @@ +import { Schema, model, Document, Types } from "mongoose"; + +interface videoDefaults { + fps?: number; + quality?: string; +} + +export interface AudioDefaults { + voiceId?: string; // provider-specific voice identifier + gender?: "male" | "female" | "neutral"; + language?: string; // en-US, hi-IN, etc. + accent?: string; // optional locale/accent + tone?: "neutral" | "calm" | "dramatic" | "eerie"; + pacing?: "slow" | "medium" | "fast"; + emotionBias?: "flat" | "expressive" | "subtle"; +} + +export interface ContextProfile extends Document { + userId: Types.ObjectId; + name: string; // e.g. "Dark Horror Universe" + description?: string; // human-readable intent + genre?: string; // horror, sci-fi, drama + tone?: string; // dark, light, serious + mood?: string; // eerie, hopeful, tense + style?: string; // cinematic, poetic, minimal + worldRules?: string; // invariants of the universe + characters?: { + name: string; + description?: string; + }[]; + + narrativeConstraints?: string; // POV, tense, length rules + forbiddenElements?: string[]; // things AI must avoid + audioDefaults?: AudioDefaults; + videoConfigDefaults?: videoDefaults; + + active: boolean; // active for project usage + version: number; // increments on edit + + createdAt: Date; + updatedAt: Date; +} + +const contextProfileSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + index: true, + }, + + name: { + type: String, + required: true, + trim: true, + }, + + description: { + type: String, + maxlength: 1000, + trim: true, + }, + + genre: String, + tone: String, + mood: String, + style: String, + + worldRules: { + type: String, + maxlength: 5000, + }, + + characters: [ + { + name: { type: String, required: true }, + description: { type: String }, + }, + ], + + narrativeConstraints: { + type: String, + maxlength: 3000, + }, + + forbiddenElements: { + type: [String], + default: [], + }, + + audioDefaults: { + voiceId: String, + gender: { + type: String, + enum: ["male", "female", "neutral"], + }, + language: String, + accent: String, + tone: { + type: String, + enum: ["neutral", "calm", "dramatic", "eerie"], + }, + pacing: { + type: String, + enum: ["slow", "medium", "fast"], + }, + emotionBias: { + type: String, + enum: ["flat", "expressive", "subtle"], + }, + }, + + videoConfigDefaults: { + fps: Number, + quality: String, + }, + + active: { + type: Boolean, + default: true, + }, + + version: { + type: Number, + default: 1, + }, + }, + { timestamps: true } +); + +export const ContextProfileModel = model( + "ContextProfile", + contextProfileSchema +); diff --git a/src/models/ContextProfileHistory.ts b/src/models/ContextProfileHistory.ts new file mode 100644 index 0000000..185b9cd --- /dev/null +++ b/src/models/ContextProfileHistory.ts @@ -0,0 +1,134 @@ +import { Schema, model, Document, Types } from "mongoose"; + +interface videoDefaults { + fps?: number; + quality?: string; +} + +export interface AudioDefaults { + voiceId?: string; // provider-specific voice identifier + gender?: "male" | "female" | "neutral"; + language?: string; // en-US, hi-IN, etc. + accent?: string; // optional locale/accent + tone?: "neutral" | "calm" | "dramatic" | "eerie"; + pacing?: "slow" | "medium" | "fast"; + emotionBias?: "flat" | "expressive" | "subtle"; +} + +export interface ContextProfileHistory extends Document { + contextProfileId: Types.ObjectId; + userId: Types.ObjectId; + version: number; // version being archived + snapshot: { + name: string; + description?: string; + genre?: string; + tone?: string; + mood?: string; + style?: string; + worldRules?: string; + characters?: { + name: string; + description?: string; + }[]; + narrativeConstraints?: string; + forbiddenElements?: string[]; + audioDefaults?: AudioDefaults; + videoConfigDefaults?: videoDefaults; + }; + + changeReason?: string; // optional user/system note + changedAt: Date; +} + +const contextProfileHistorySchema = new Schema( + { + contextProfileId: { + type: Schema.Types.ObjectId, + ref: "ContextProfile", + required: true, + index: true, + }, + + userId: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + index: true, + }, + + version: { + type: Number, + required: true, + }, + + snapshot: { + name: { type: String, required: true }, + description: { type: String }, + + genre: String, + tone: String, + mood: String, + style: String, + + worldRules: String, + + characters: [ + { + name: { type: String, required: true }, + description: { type: String }, + }, + ], + + narrativeConstraints: String, + + forbiddenElements: { + type: [String], + default: [], + }, + audioDefaults: { + voiceId: String, + gender: { + type: String, + enum: ["male", "female", "neutral"], + }, + language: String, + accent: String, + tone: { + type: String, + enum: ["neutral", "calm", "dramatic", "eerie"], + }, + pacing: { + type: String, + enum: ["slow", "medium", "fast"], + }, + emotionBias: { + type: String, + enum: ["flat", "expressive", "subtle"], + }, + }, + + videoConfigDefaults: { + fps: Number, + quality: String, + }, + }, + + changeReason: { + type: String, + maxlength: 1000, + }, + + changedAt: { + type: Date, + default: Date.now, + index: true, + }, + }, + { timestamps: false } +); + +export const ContextProfileHistoryModel = model( + "ContextProfileHistory", + contextProfileHistorySchema +); diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts new file mode 100644 index 0000000..32b755e --- /dev/null +++ b/src/models/FinalVideo.ts @@ -0,0 +1,88 @@ +import { Schema, model, Document, Types } from "mongoose"; + +interface renderConfig { + fps?: number; + resolution?: string; // 1080p, 4k + bitrate?: number; + codec?: string; // h264, h265 + quality?: "low" | "medium" | "high"; +} + +export interface FinalVideo extends Document { + userId: Types.ObjectId; + projectId: Types.ObjectId; + storyId: Types.ObjectId; + videoUrl: string; // final rendered file + lastError?: { message: string; code?: number; count?: number }; + backgroundAudioAssetId?: Types.ObjectId; + narrationAudioAssetId?: Types.ObjectId; + sceneAssetIds: Types.ObjectId[]; // resolved visuals in order + duration?: number; + resolution?: string; + format?: string; + status: "rendering" | "completed" | "failed"; + createdAt: Date; + updatedAt: Date; +} + +const finalVideoSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + index: 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, + required: true, + }, + lastError: { + type: { + message: String, + code: Number, + count: Number, + }, + }, + backgroundAudioAssetId: { + type: Schema.Types.ObjectId, + ref: "AudioAsset", + }, + narrationAudioAssetId: { + type: Schema.Types.ObjectId, + ref: "AudioAsset", + }, + sceneAssetIds: { + type: [Schema.Types.ObjectId], + ref: "SceneAsset", + required: true, + }, + duration: Number, + resolution: String, + format: String, + status: { + type: String, + enum: ["rendering", "completed", "failed"], + default: "rendering", + index: true, + }, + }, + { timestamps: true } +); + +export const FinalVideoModel = model( + "FinalVideo", + finalVideoSchema +); diff --git a/src/models/Project.ts b/src/models/Project.ts index e69de29..9626718 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -0,0 +1,63 @@ +import { Schema, model, Document, Types, HydratedDocument } from "mongoose"; +export interface ProjectType extends Document { + userId: Types.ObjectId; + title: string; + description?: string; + status: "active" | "drafted" | "archived" | "deleted"; + visibility: "public" | "private"; + contextProfileId?: Types.ObjectId; + activeStoryId?: Types.ObjectId; + activeStoryGeneratedAt?: Date; + generationCounts: { + storiesGenerated: number; + scenesGenerated: number; + sceneAssetsGenerated: number; + audiosGenerated: number; + videosGenerated: number; + }; +} + +const projectSchema = new Schema( + { + title: { + type: String, + required: true, + trim: true, + }, + description: { + type: String, + maxlength: 1000, + trim: true, + }, + userId: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + }, + status: { + type: String, + enum: ["active", "drafted", "archived", "deleted"], + default: "active", + }, + visibility: { + type: String, + enum: ["public", "private"], + default: "private", + }, + contextProfileId: { type: Schema.Types.ObjectId, ref: "Context" }, + activeStoryId: { type: Schema.Types.ObjectId, ref: "Story" }, + activeStoryGeneratedAt: { type: Date }, + 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 } +); + +export type Project = HydratedDocument; + +export const ProjectModel = model("Project", projectSchema); diff --git a/src/models/Scene.ts b/src/models/Scene.ts index e69de29..60d7e22 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -0,0 +1,128 @@ +import { Schema, model, Document, Types } from "mongoose"; + +export interface SceneAssetHistoryEntry { + assetId: Types.ObjectId; + replacedAt: Date; +} + +export interface SceneEditHistoryEntry { + title?: string; + description?: string; + imagePrompt?: string; + duration?: number; + editedAt: Date; +} + +export interface Scene extends Document { + userId: Types.ObjectId; + storyId: Types.ObjectId; + order: number; + title?: string; + description: string; + imagePrompt: string; + lastGeneratedAt?: Date; + duration?: number; + generationSource: "ai" | "manual"; + activeAssetId?: Types.ObjectId; + assetHistory: SceneAssetHistoryEntry[]; // max 3 (enforced in service) + editHistory: SceneEditHistoryEntry[]; // max 3 (enforced in service) + contextProfileId?: Types.ObjectId; + contextProfileVersion?: number; + 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, + index: true, + }, + + order: { + type: Number, + required: true, + }, + + title: { + type: String, + trim: true, + maxlength: 200, + }, + + description: { + type: String, + required: true, + }, + + imagePrompt: { + type: String, + }, + lastGeneratedAt: { + type: Date, + }, + duration: { + type: Number, + }, + + generationSource: { + type: String, + enum: ["ai", "manual"], + default: "ai", + }, + + activeAssetId: { + type: Schema.Types.ObjectId, + ref: "SceneAsset", + }, + + assetHistory: { + type: [ + { + assetId: { + type: Schema.Types.ObjectId, + ref: "SceneAsset", + required: true, + }, + replacedAt: { + type: Date, + default: Date.now, + }, + }, + ], + default: [], + }, + editHistory: { + type: [ + { + title: { type: String }, + description: { type: String }, + imagePrompt: { type: String }, + duration: { type: Number }, + editedAt: { type: Date, default: Date.now }, + }, + ], + default: [], + }, + contextProfileId: { + type: Schema.Types.ObjectId, + ref: "ContextProfile", + }, + + contextProfileVersion: { + type: Number, + }, + }, + { timestamps: true } +); + +export const SceneModel = model("Scene", sceneSchema); diff --git a/src/models/SceneAssets.ts b/src/models/SceneAssets.ts new file mode 100644 index 0000000..2c2ea69 --- /dev/null +++ b/src/models/SceneAssets.ts @@ -0,0 +1,74 @@ +import { Schema, model, Document, Types } from "mongoose"; + +export interface SceneAsset extends Document { + userId: Types.ObjectId; + projectId?: Types.ObjectId; + type: "image" | "video"; + url: string; + visibility: "private" | "public"; + prompt?: string; + generationSource: "ai" | "upload"; + saved: boolean; + active: boolean; + width?: number; + height?: number; + duration?: number; + createdAt: Date; + updatedAt: Date; +} + +const sceneAssetSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: "User", + required: true, + index: true, + }, + projectId: { + type: Schema.Types.ObjectId, + ref: "Project", + index: true, + }, + type: { + type: String, + enum: ["image", "video" ], + required: true, + }, + url: { + type: String, + required: true, + }, + visibility: { + type: String, + default: "public", + }, + prompt: { + type: String, + }, + generationSource: { + type: String, + enum: ["ai", "upload"], + default: "ai", + }, + saved: { + type: Boolean, + default: false, + index: true, + }, + active: { + type: Boolean, + default: true, + index: true, + }, + width: Number, + height: Number, + duration: Number, + }, + { timestamps: true } +); + +export const SceneAssetModel = model( + "SceneAsset", + sceneAssetSchema +); diff --git a/src/models/Story.ts b/src/models/Story.ts index e69de29..458f2dd 100644 --- a/src/models/Story.ts +++ b/src/models/Story.ts @@ -0,0 +1,113 @@ +import { Schema, model, Document, Types } from "mongoose"; + +export interface StoryHistoryEntry { + title?: string; + content?: string; + audioAssetId?: Types.ObjectId; + editedAt: Date; +} + +export interface Story extends Document { + userId: Types.ObjectId; + projectId?: Types.ObjectId; + title: string; + content: string; + lastGeneratedAt?: Date; + audioAssetId?: Types.ObjectId; // current narration audio + backgroundAudioAssetId?: Types.ObjectId; // current background audio + effectAudioAssetsId?: Types.ObjectId[]; // current effect audio + finalVideoId?: Types.ObjectId; // current Final video output + status: "active" | "rejected" | "archived"; + selected: boolean; + generationSource: "ai" | "manual"; + contextProfileId?: Types.ObjectId; + contextProfileVersion?: number; + history: StoryHistoryEntry[]; // max 3 (enforced in service) + 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, + }, + content: { + type: String, + required: true, + }, + lastGeneratedAt: { + type: Date, + }, + audioAssetId: { + type: Schema.Types.ObjectId, + ref: "AudioAsset", + }, + backgroundAudioAssetId: { + type: Schema.Types.ObjectId, + ref: "AudioAsset", + }, + effectAudioAssetsId: [ + { + type: Schema.Types.ObjectId, + ref: "AudioAsset", + }, + ], + finalVideoId: { + type: Schema.Types.ObjectId, + ref: "FinalVideo", + }, + status: { + type: String, + enum: ["active", "rejected", "archived"], + default: "active", + }, + selected: { + type: Boolean, + default: false, + }, + generationSource: { + type: String, + enum: ["ai", "manual"], + default: "ai", + }, + contextProfileId: { + type: Schema.Types.ObjectId, + ref: "ContextProfile", + }, + contextProfileVersion: { + type: Number, + }, + history: { + type: [ + { + title: { type: String }, + content: { type: String }, + audioAssetId: { + type: Schema.Types.ObjectId, + ref: "AudioAsset", + }, + editedAt: { type: Date, default: Date.now }, + }, + ], + default: [], + }, + }, + { timestamps: true } +); + +export const StoryModel = model("Story", storySchema); diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 0decd59..8f2c288 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -264,8 +264,8 @@ export async function resetPassword(rawToken: string, newPassword: string) { user.changeHistory.push({ field: "password", by: user._id, - from: "", - to: "", + from: null, + to: null, reason: "User reset the password via password reset", at: new Date(), via: "user", diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index 8396d62..b3cb003 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -27,10 +27,8 @@ import { updatePrivacySettings, updateProfile, } from "./user.service.js"; -import { AccountStatus } from "constants/accountStatus.js"; import { BadRequestError, - NotFoundError, UnauthenticatedError, } from "@middleware/error/index.js"; From ed8dac2484d071519d73b976581699c9dbcbc1a3 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Wed, 17 Dec 2025 21:30:35 +0530 Subject: [PATCH 05/14] Resolve AI Chat suggestions of PR #9 --- src/middleware/multer.ts | 7 ++++--- src/models/AudioAsset.ts | 25 ++++++++++++++++--------- src/models/ContextProfile.ts | 14 +++++++++----- src/models/ContextProfileHistory.ts | 4 ++-- src/models/FinalVideo.ts | 21 ++++++++++++++------- src/models/Project.ts | 2 +- src/models/Scene.ts | 15 +++++++++++++-- src/models/SceneAssets.ts | 1 + src/models/Story.ts | 11 ++++++++--- 9 files changed, 68 insertions(+), 32 deletions(-) diff --git a/src/middleware/multer.ts b/src/middleware/multer.ts index 38a6495..16507e3 100644 --- a/src/middleware/multer.ts +++ b/src/middleware/multer.ts @@ -13,13 +13,14 @@ const storage = multer.diskStorage({ if (!fs.existsSync(uploadPath)) { fs.mkdir(uploadPath, { recursive: true }, (err) => { if (err) { - return cb(err, uploadPath); + cb(err, uploadPath); } else { cb(null, uploadPath); } }); + } else { + cb(null, uploadPath); } - cb(null, uploadPath); }, filename: function ( _req: Request, @@ -49,7 +50,7 @@ const fileFilter: multer.Options["fileFilter"] = (_req, file, cb) => { const lastDotIndex = file.originalname.lastIndexOf("."); const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); - if (!allowedExtensions.includes(fileExtension) || lastDotIndex <= 0) { + if (!allowedExtensions.includes(fileExtension) || lastDotIndex < 0) { cb( new BadRequestError( "Only image files (jpg, jpeg, png, gif, webp) are allowed" diff --git a/src/models/AudioAsset.ts b/src/models/AudioAsset.ts index 0e8181d..21906c3 100644 --- a/src/models/AudioAsset.ts +++ b/src/models/AudioAsset.ts @@ -5,8 +5,7 @@ export interface AudioAsset extends Document { type: "narration" | "background" | "effect"; url: string; prompt?: string; // for AI-generated audio - generationSource: "ai" | "upload"; - // resolved (actual) metadata + generationSource: "ai" | "upload"; voiceId?: string; language?: string; accent?: string; @@ -27,36 +26,44 @@ const audioAssetSchema = new Schema( required: true, index: true, }, - type: { type: String, enum: ["narration", "background", "effect"], required: true, }, - url: { type: String, required: true, }, - prompt: { type: String, }, - generationSource: { type: String, enum: ["ai", "upload"], default: "ai", }, - + voiceId: { + type: String, + }, + language: { + type: String, + }, + accent: { + type: String, + }, + tone: { + type: String, + }, + pacing: { + type: String, + }, duration: { type: Number, }, - format: { type: String, }, - saved: { type: Boolean, default: false, diff --git a/src/models/ContextProfile.ts b/src/models/ContextProfile.ts index 5c8cc91..df2ca33 100644 --- a/src/models/ContextProfile.ts +++ b/src/models/ContextProfile.ts @@ -1,6 +1,6 @@ import { Schema, model, Document, Types } from "mongoose"; -interface videoDefaults { +interface VideoDefaults { fps?: number; quality?: string; } @@ -16,7 +16,7 @@ export interface AudioDefaults { } export interface ContextProfile extends Document { - userId: Types.ObjectId; + userId: Types.ObjectId; name: string; // e.g. "Dark Horror Universe" description?: string; // human-readable intent genre?: string; // horror, sci-fi, drama @@ -32,7 +32,7 @@ export interface ContextProfile extends Document { narrativeConstraints?: string; // POV, tense, length rules forbiddenElements?: string[]; // things AI must avoid audioDefaults?: AudioDefaults; - videoConfigDefaults?: videoDefaults; + videoConfigDefaults?: VideoDefaults; active: boolean; // active for project usage version: number; // increments on edit @@ -95,8 +95,12 @@ const contextProfileSchema = new Schema( type: String, enum: ["male", "female", "neutral"], }, - language: String, - accent: String, + language: { + type: String, + }, + accent: { + type: String, + }, tone: { type: String, enum: ["neutral", "calm", "dramatic", "eerie"], diff --git a/src/models/ContextProfileHistory.ts b/src/models/ContextProfileHistory.ts index 185b9cd..7590a15 100644 --- a/src/models/ContextProfileHistory.ts +++ b/src/models/ContextProfileHistory.ts @@ -1,6 +1,6 @@ import { Schema, model, Document, Types } from "mongoose"; -interface videoDefaults { +interface VideoDefaults { fps?: number; quality?: string; } @@ -34,7 +34,7 @@ export interface ContextProfileHistory extends Document { narrativeConstraints?: string; forbiddenElements?: string[]; audioDefaults?: AudioDefaults; - videoConfigDefaults?: videoDefaults; + videoConfigDefaults?: VideoDefaults; }; changeReason?: string; // optional user/system note diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts index 32b755e..ea6c9cb 100644 --- a/src/models/FinalVideo.ts +++ b/src/models/FinalVideo.ts @@ -1,11 +1,11 @@ import { Schema, model, Document, Types } from "mongoose"; -interface renderConfig { +interface RenderConfig { fps?: number; resolution?: string; // 1080p, 4k bitrate?: number; codec?: string; // h264, h265 - quality?: "low" | "medium" | "high"; + quality?: "480p" | "720p" | "1080p" | "1440p"; } export interface FinalVideo extends Document { @@ -18,8 +18,7 @@ export interface FinalVideo extends Document { narrationAudioAssetId?: Types.ObjectId; sceneAssetIds: Types.ObjectId[]; // resolved visuals in order duration?: number; - resolution?: string; - format?: string; + renderConfig?: RenderConfig; status: "rendering" | "completed" | "failed"; createdAt: Date; updatedAt: Date; @@ -65,13 +64,21 @@ const finalVideoSchema = new Schema( ref: "AudioAsset", }, sceneAssetIds: { - type: [Schema.Types.ObjectId], + type: [{ type: Schema.Types.ObjectId, ref: "SceneAsset" }], ref: "SceneAsset", required: true, }, duration: Number, - resolution: String, - format: String, + renderConfig: { + fps: Number, + resolution: String, + bitrate: Number, + codec: String, + quality: { + type: String, + enum: ["480p", "720p", "1080p", "1440p"], + }, + }, status: { type: String, enum: ["rendering", "completed", "failed"], diff --git a/src/models/Project.ts b/src/models/Project.ts index 9626718..33827b7 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -44,7 +44,7 @@ const projectSchema = new Schema( enum: ["public", "private"], default: "private", }, - contextProfileId: { type: Schema.Types.ObjectId, ref: "Context" }, + contextProfileId: { type: Schema.Types.ObjectId, ref: "ContextProfile" }, activeStoryId: { type: Schema.Types.ObjectId, ref: "Story" }, activeStoryGeneratedAt: { type: Date }, generationCounts: { diff --git a/src/models/Scene.ts b/src/models/Scene.ts index 60d7e22..3a401e1 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -24,8 +24,8 @@ export interface Scene extends Document { duration?: number; generationSource: "ai" | "manual"; activeAssetId?: Types.ObjectId; - assetHistory: SceneAssetHistoryEntry[]; // max 3 (enforced in service) - editHistory: SceneEditHistoryEntry[]; // max 3 (enforced in service) + assetHistory: SceneAssetHistoryEntry[]; // max 3 (enforced in service too) + editHistory: SceneEditHistoryEntry[]; // max 3 (enforced in service too) contextProfileId?: Types.ObjectId; contextProfileVersion?: number; createdAt: Date; @@ -66,6 +66,7 @@ const sceneSchema = new Schema( imagePrompt: { type: String, + required: true, }, lastGeneratedAt: { type: Date, @@ -100,6 +101,11 @@ const sceneSchema = new Schema( }, ], default: [], + maxlength: 3, + validate: { + validator: (v: SceneAssetHistoryEntry[]) => v.length <= 3, + message: "Scene assetHistory cannot exceed 3 entries", + }, }, editHistory: { type: [ @@ -112,6 +118,11 @@ const sceneSchema = new Schema( }, ], default: [], + maxlength: 3, + validate: { + validator: (v: SceneEditHistoryEntry[]) => v.length <= 3, + message: "Scene editHistory cannot exceed 3 entries", + }, }, contextProfileId: { type: Schema.Types.ObjectId, diff --git a/src/models/SceneAssets.ts b/src/models/SceneAssets.ts index 2c2ea69..4e3e673 100644 --- a/src/models/SceneAssets.ts +++ b/src/models/SceneAssets.ts @@ -41,6 +41,7 @@ const sceneAssetSchema = new Schema( }, visibility: { type: String, + enum: ["private", "public"], default: "public", }, prompt: { diff --git a/src/models/Story.ts b/src/models/Story.ts index 458f2dd..2b6c00d 100644 --- a/src/models/Story.ts +++ b/src/models/Story.ts @@ -15,14 +15,14 @@ export interface Story extends Document { lastGeneratedAt?: Date; audioAssetId?: Types.ObjectId; // current narration audio backgroundAudioAssetId?: Types.ObjectId; // current background audio - effectAudioAssetsId?: Types.ObjectId[]; // current effect audio + effectAudioAssetsId?: Types.ObjectId[]; // effect audios finalVideoId?: Types.ObjectId; // current Final video output status: "active" | "rejected" | "archived"; selected: boolean; generationSource: "ai" | "manual"; contextProfileId?: Types.ObjectId; contextProfileVersion?: number; - history: StoryHistoryEntry[]; // max 3 (enforced in service) + editHistory: StoryHistoryEntry[]; // max 3 (enforced in service too) createdAt: Date; updatedAt: Date; } @@ -92,7 +92,7 @@ const storySchema = new Schema( contextProfileVersion: { type: Number, }, - history: { + editHistory: { type: [ { title: { type: String }, @@ -105,6 +105,11 @@ const storySchema = new Schema( }, ], default: [], + maxlength: 3, + validate: { + validator: (v: StoryHistoryEntry[]) => v.length <= 3, + message: "Story editHistory cannot exceed 3 entries", + }, }, }, { timestamps: true } From 7fe90557e7e62a97e20be0fcfd1d5a801eeadd07 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Thu, 18 Dec 2025 01:17:52 +0530 Subject: [PATCH 06/14] 2nd Time Resolved AI Chat suggestions of PR #9 --- src/middleware/multer.ts | 13 ++++++++++--- src/models/FinalVideo.ts | 38 +++++++++++++++++++++++++++++++++++--- src/models/Project.ts | 1 + src/models/Scene.ts | 3 +-- src/models/Story.ts | 35 +++++++++++++++++++++++++++++++---- 5 files changed, 78 insertions(+), 12 deletions(-) diff --git a/src/middleware/multer.ts b/src/middleware/multer.ts index 16507e3..8ebc88c 100644 --- a/src/middleware/multer.ts +++ b/src/middleware/multer.ts @@ -48,9 +48,16 @@ const fileFilter: multer.Options["fileFilter"] = (_req, file, cb) => { 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) || lastDotIndex < 0) { + if (!allowedExtensions.includes(fileExtension)) { cb( new BadRequestError( "Only image files (jpg, jpeg, png, gif, webp) are allowed" @@ -67,4 +74,4 @@ const upload = multer({ limits: { fileSize: 2 * 1024 * 1024 }, }); -export { upload }; +export { upload }; \ No newline at end of file diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts index ea6c9cb..658400a 100644 --- a/src/models/FinalVideo.ts +++ b/src/models/FinalVideo.ts @@ -1,4 +1,5 @@ import { Schema, model, Document, Types } from "mongoose"; +import { property } from "zod"; interface RenderConfig { fps?: number; @@ -12,7 +13,7 @@ export interface FinalVideo extends Document { userId: Types.ObjectId; projectId: Types.ObjectId; storyId: Types.ObjectId; - videoUrl: string; // final rendered file + videoUrl?: string; // final rendered file lastError?: { message: string; code?: number; count?: number }; backgroundAudioAssetId?: Types.ObjectId; narrationAudioAssetId?: Types.ObjectId; @@ -24,6 +25,39 @@ export interface FinalVideo extends Document { updatedAt: Date; } +/** + * Represents a FinalVideo document in the Cinetegrate system. + * + * A FinalVideo is the rendered output of the AI video generation process. It contains + * the final video file, associated audio assets, scene compositions, and rendering configuration. + * + * @property {ObjectId} userId - Reference to the User who owns this video. Required and indexed for efficient queries. + * @property {ObjectId} projectId - Reference to the parent Project. Required and indexed for efficient queries. + * @property {ObjectId} storyId - Reference to the source Story. Required and indexed for efficient queries. + * @property {string} videoUrl - URL to the final rendered video file. + * @property {Object} lastError - Error information from failed rendering attempts. Contains message, code, and count of consecutive failures. + * @property {string} lastError.message - Error message describing the failure. + * @property {number} lastError.code - Error code for programmatic handling. + * @property {number} lastError.count - Count of consecutive failures. + * @property {ObjectId} backgroundAudioAssetId - Reference to the background music AudioAsset. + * @property {ObjectId} narrationAudioAssetId - Reference to the narration/voiceover AudioAsset. + * @property {ObjectId[]} sceneAssetIds - Ordered array of SceneAsset references representing visual compositions. Required. + * @property {number} duration - Total duration of the final video in seconds. + * @property {Object} renderConfig - Configuration parameters for video rendering. + * @property {number} renderConfig.fps - Frames per second for output video. + * @property {string} renderConfig.resolution - Output resolution. Values: "480p" | "720p" | "1080p" | "1440p". + * @property {number} renderConfig.bitrate - Bitrate in kbps for encoding. + * @property {string} renderConfig.codec - Video codec used. Values: "h264" | "h265". + * @property {string} status - Rendering lifecycle state. Values: "rendering" | "completed" | "failed". Default: "rendering". Indexed for efficient status queries. + * @property {Date} createdAt - Timestamp of document creation. Automatically managed. + * @property {Date} updatedAt - Timestamp of last document update. Automatically managed. + * + * @remarks + * - The sceneAssetIds array maintains scene order critical to final video composition. + * - lastError tracking enables robust retry logic and failure diagnostics. + * - renderConfig provides comprehensive control over output quality and format. + */ + const finalVideoSchema = new Schema( { userId: { @@ -46,7 +80,6 @@ const finalVideoSchema = new Schema( }, videoUrl: { type: String, - required: true, }, lastError: { type: { @@ -65,7 +98,6 @@ const finalVideoSchema = new Schema( }, sceneAssetIds: { type: [{ type: Schema.Types.ObjectId, ref: "SceneAsset" }], - ref: "SceneAsset", required: true, }, duration: Number, diff --git a/src/models/Project.ts b/src/models/Project.ts index 33827b7..037f2da 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -33,6 +33,7 @@ const projectSchema = new Schema( type: Schema.Types.ObjectId, ref: "User", required: true, + index: true, }, status: { type: String, diff --git a/src/models/Scene.ts b/src/models/Scene.ts index 3a401e1..afefe53 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -51,6 +51,7 @@ const sceneSchema = new Schema( order: { type: Number, required: true, + min: 0, }, title: { @@ -101,7 +102,6 @@ const sceneSchema = new Schema( }, ], default: [], - maxlength: 3, validate: { validator: (v: SceneAssetHistoryEntry[]) => v.length <= 3, message: "Scene assetHistory cannot exceed 3 entries", @@ -118,7 +118,6 @@ const sceneSchema = new Schema( }, ], default: [], - maxlength: 3, validate: { validator: (v: SceneEditHistoryEntry[]) => v.length <= 3, message: "Scene editHistory cannot exceed 3 entries", diff --git a/src/models/Story.ts b/src/models/Story.ts index 2b6c00d..ecdbcb8 100644 --- a/src/models/Story.ts +++ b/src/models/Story.ts @@ -15,7 +15,7 @@ export interface Story extends Document { lastGeneratedAt?: Date; audioAssetId?: Types.ObjectId; // current narration audio backgroundAudioAssetId?: Types.ObjectId; // current background audio - effectAudioAssetsId?: Types.ObjectId[]; // effect audios + effectAudioAssetIds?: Types.ObjectId[]; // effect audios finalVideoId?: Types.ObjectId; // current Final video output status: "active" | "rejected" | "archived"; selected: boolean; @@ -27,6 +27,34 @@ export interface Story extends Document { updatedAt: Date; } +/** + * Represents a Story document in the Cinetegrate system. + * + * A Story is the core narrative unit that drives AI video generation. It encapsulates + * the creative content along with associated media assets and generation metadata. + * + * @property {ObjectId} userId - Reference to the User who owns this story. Required and indexed for efficient queries. + * @property {ObjectId} projectId - Optional reference to the parent Project. Allows stories to be organized within projects. + * @property {string} title - The story title. Max 200 characters, trimmed whitespace. + * @property {string} content - The main narrative content. This is the primary input for AI video generation. + * @property {Date} lastGeneratedAt - Timestamp of the most recent video generation from this story. + * @property {ObjectId} audioAssetId - Reference to the primary AudioAsset (narration/voiceover). + * @property {ObjectId} backgroundAudioAssetId - Reference to background music AudioAsset. + * @property {ObjectId[]} effectAudioAssetIds - Array of references to sound effect AudioAssets. + * @property {ObjectId} finalVideoId - Reference to the generated FinalVideo output. + * @property {string} status - Story lifecycle state. Values: "active" | "rejected" | "archived". Default: "active". + * @property {boolean} selected - Flag indicating if story is selected for current workflow. Default: false. + * @property {string} generationSource - Origin of story content. Values: "ai" | "manual". Default: "ai". + * @property {ObjectId} contextProfileId - Reference to the ContextProfile used for generation. Enables version tracking and safe regeneration. + * @property {number} contextProfileVersion - Version number of the ContextProfile at time of generation. Used to detect profile changes and trigger regeneration workflows. + * @property {StoryHistoryEntry[]} editHistory - Array of up to 3 previous edits, tracking title, content, audio changes, and edit timestamps. Validates maximum 3 entries. Default: []. + * + * @remarks + * - The contextProfileId and contextProfileVersion pair work together to support safe regeneration scenarios. + * When a ContextProfile is updated, stories using older versions can be identified and re-generated with current context. + * - editHistory provides audit trail and rollback capability while maintaining storage efficiency with a strict 3-entry limit. + * - Timestamps are automatically managed for createdAt and updatedAt via the schema timestamps option. + */ const storySchema = new Schema( { userId: { @@ -61,7 +89,7 @@ const storySchema = new Schema( type: Schema.Types.ObjectId, ref: "AudioAsset", }, - effectAudioAssetsId: [ + effectAudioAssetIds: [ { type: Schema.Types.ObjectId, ref: "AudioAsset", @@ -104,8 +132,7 @@ const storySchema = new Schema( editedAt: { type: Date, default: Date.now }, }, ], - default: [], - maxlength: 3, + default: [], validate: { validator: (v: StoryHistoryEntry[]) => v.length <= 3, message: "Story editHistory cannot exceed 3 entries", From 98f4f7591d08c273fa9324079a31fff23bc388a9 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Thu, 18 Dec 2025 01:46:47 +0530 Subject: [PATCH 07/14] 3rd Time Resolved AI Chat suggestions of PR #9 --- src/middleware/multer.ts | 28 +++++++++++++--------------- src/models/ContextProfile.ts | 2 +- src/models/ContextProfileHistory.ts | 24 ++++++++---------------- src/models/FinalVideo.ts | 18 +++++++----------- src/models/Scene.ts | 3 ++- src/models/SceneAssets.ts | 2 +- 6 files changed, 32 insertions(+), 45 deletions(-) diff --git a/src/middleware/multer.ts b/src/middleware/multer.ts index 8ebc88c..4ee7fbd 100644 --- a/src/middleware/multer.ts +++ b/src/middleware/multer.ts @@ -10,26 +10,24 @@ const storage = multer.diskStorage({ cb: (error: Error | null, destination: string) => void ) { const uploadPath = "./temp/uploads"; - if (!fs.existsSync(uploadPath)) { - fs.mkdir(uploadPath, { recursive: true }, (err) => { - if (err) { - cb(err, uploadPath); - } else { - cb(null, uploadPath); - } - }); - } else { - cb(null, uploadPath); - } + 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 fileExtension = file.originalname - .substring(file.originalname.lastIndexOf(".")) - .toLowerCase(); + 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); }, @@ -74,4 +72,4 @@ const upload = multer({ limits: { fileSize: 2 * 1024 * 1024 }, }); -export { upload }; \ No newline at end of file +export { upload }; diff --git a/src/models/ContextProfile.ts b/src/models/ContextProfile.ts index df2ca33..338c82f 100644 --- a/src/models/ContextProfile.ts +++ b/src/models/ContextProfile.ts @@ -1,6 +1,6 @@ import { Schema, model, Document, Types } from "mongoose"; -interface VideoDefaults { +export interface VideoDefaults { fps?: number; quality?: string; } diff --git a/src/models/ContextProfileHistory.ts b/src/models/ContextProfileHistory.ts index 7590a15..e5bc21f 100644 --- a/src/models/ContextProfileHistory.ts +++ b/src/models/ContextProfileHistory.ts @@ -1,23 +1,9 @@ import { Schema, model, Document, Types } from "mongoose"; - -interface VideoDefaults { - fps?: number; - quality?: string; -} - -export interface AudioDefaults { - voiceId?: string; // provider-specific voice identifier - gender?: "male" | "female" | "neutral"; - language?: string; // en-US, hi-IN, etc. - accent?: string; // optional locale/accent - tone?: "neutral" | "calm" | "dramatic" | "eerie"; - pacing?: "slow" | "medium" | "fast"; - emotionBias?: "flat" | "expressive" | "subtle"; -} +import { VideoDefaults, AudioDefaults } from "./ContextProfile.js"; export interface ContextProfileHistory extends Document { contextProfileId: Types.ObjectId; - userId: Types.ObjectId; + userId: Types.ObjectId; version: number; // version being archived snapshot: { name: string; @@ -128,6 +114,12 @@ const contextProfileHistorySchema = new Schema( { timestamps: false } ); +// Add compound index for efficient version history queries +contextProfileHistorySchema.index({ contextProfileId: 1, version: 1 }); + +// Optional: Add index for time-based queries +contextProfileHistorySchema.index({ contextProfileId: 1, changedAt: -1 }); + export const ContextProfileHistoryModel = model( "ContextProfileHistory", contextProfileHistorySchema diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts index 658400a..39722f2 100644 --- a/src/models/FinalVideo.ts +++ b/src/models/FinalVideo.ts @@ -1,12 +1,10 @@ import { Schema, model, Document, Types } from "mongoose"; -import { property } from "zod"; interface RenderConfig { fps?: number; - resolution?: string; // 1080p, 4k + resolution?: "480p" | "720p" | "1080p" | "1440p"; bitrate?: number; - codec?: string; // h264, h265 - quality?: "480p" | "720p" | "1080p" | "1440p"; + codec?: string; // h264, h265 ; } export interface FinalVideo extends Document { @@ -64,19 +62,16 @@ const finalVideoSchema = new Schema( type: Schema.Types.ObjectId, ref: "User", required: true, - index: 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, @@ -103,13 +98,12 @@ const finalVideoSchema = new Schema( duration: Number, renderConfig: { fps: Number, - resolution: String, - bitrate: Number, - codec: String, - quality: { + resolution: { type: String, enum: ["480p", "720p", "1080p", "1440p"], }, + bitrate: Number, + codec: String, }, status: { type: String, @@ -121,6 +115,8 @@ const finalVideoSchema = new Schema( { timestamps: true } ); +finalVideoSchema.index({ userId: 1, status: 1 }); + export const FinalVideoModel = model( "FinalVideo", finalVideoSchema diff --git a/src/models/Scene.ts b/src/models/Scene.ts index afefe53..23fc4e4 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -45,7 +45,6 @@ const sceneSchema = new Schema( type: Schema.Types.ObjectId, ref: "Story", required: true, - index: true, }, order: { @@ -135,4 +134,6 @@ const sceneSchema = new Schema( { timestamps: true } ); +sceneSchema.index({ storyId: 1, order: 1 }, { unique: true }); + export const SceneModel = model("Scene", sceneSchema); diff --git a/src/models/SceneAssets.ts b/src/models/SceneAssets.ts index 4e3e673..590e042 100644 --- a/src/models/SceneAssets.ts +++ b/src/models/SceneAssets.ts @@ -32,7 +32,7 @@ const sceneAssetSchema = new Schema( }, type: { type: String, - enum: ["image", "video" ], + enum: ["image", "video"], required: true, }, url: { From 84afa8ad3f74fd2308f659e615757480a33a8a87 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Thu, 1 Jan 2026 01:40:42 +0530 Subject: [PATCH 08/14] Added Projects Module + Improve Security + Improve Pagination --- .postman/config.json | 12 + package-lock.json | 264 ++++ package.json | 2 + .../Ai Vid Gen.postman_collection.json | 192 +++ .../car-care-new.postman_collection.json | 447 +++++++ .../natours.postman_collection.json | 1072 +++++++++++++++++ postman/environments/natours | 0 .../globals/workspace.postman_globals.json | 7 + src/config/corsConfig.ts | 1 + .../{accountStatus.ts => authConsts.ts} | 11 +- src/db/connect.ts | 9 +- src/middleware/auth/requireAuth.ts | 18 +- src/middleware/auth/requireCsrf.ts | 36 - src/middleware/error/globalErrorHandler.ts | 15 +- src/middleware/loggerMiddleware.ts | 105 +- src/middleware/paginationAndSorting.ts | 53 + .../security/accountStatusMiddleware.ts | 41 + src/middleware/security/requireCsrf.ts | 35 + src/middleware/{auth => security}/roles.ts | 0 src/models/FinalVideo.ts | 2 + src/models/Project.ts | 15 +- src/models/Session.ts | 3 + src/models/Story.ts | 6 + src/models/User.ts | 62 +- src/modules/auth/auth.controller.ts | 52 +- src/modules/auth/auth.routes.ts | 32 +- src/modules/auth/auth.service.ts | 630 ++++++---- src/modules/project/project.controller.ts | 194 +++ src/modules/project/project.routes.ts | 96 ++ src/modules/project/project.service.ts | 269 +++++ src/modules/project/rules/projectStatus.ts | 30 + .../utils/transitionManyProjectsByIds.ts | 69 ++ .../project/utils/transitionProjectById.ts | 47 + src/modules/user/user.controller.ts | 184 +-- src/modules/user/user.routes.ts | 26 +- src/modules/user/user.service.ts | 261 ++-- src/routes/api.ts | 11 + src/routes/index.ts | 4 +- src/types/Pagination.ts | 10 + src/types/RequestTypes.ts | 21 + src/types/express.d.ts | 4 + src/types/index.ts | 1 + src/utils/asyncHandler.ts | 4 +- .../sender/sendEmailVerificationLink.ts | 32 + .../sendOldEmailVerificationForEmailUpdate.ts | 34 + .../emails/sender/sendPasswordUpdatedEmail.ts | 26 + src/utils/emails/sender/sendResetLink.ts | 29 + src/utils/emails/sender/sendUpdateEmaiLink.ts | 36 + src/utils/emails/sender/sendWelcomeEmail.ts | 26 + .../emails/templates/emailVerification.ts | 0 .../emails/templates/newAccount.ts | 0 .../templates}/passwordChangedNotification.ts | 0 .../emails/templates/resetPassword.ts | 0 .../templates/verifyOldEmailForEmailUpdate.ts | 76 ++ .../emails/templates}/verifyUpdatedEmail.ts | 2 +- src/utils/getIpInfo.ts | 27 +- src/utils/logger.ts | 44 + src/utils/paginationResponse.ts | 13 + src/utils/sanitizeProjectResponse.ts | 48 + src/utils/tokens.ts | 29 +- src/validation/auth.schema.ts | 58 +- src/validation/project.schema.ts | 62 + src/validation/user.schema.ts | 54 +- src/validation/validateBody.ts | 19 + src/validation/validateParams.ts | 24 + tsconfig.json | 2 +- 66 files changed, 4204 insertions(+), 790 deletions(-) create mode 100644 .postman/config.json create mode 100644 postman/collections/Ai Vid Gen.postman_collection.json create mode 100644 postman/collections/car-care-new.postman_collection.json create mode 100644 postman/collections/natours.postman_collection.json create mode 100644 postman/environments/natours create mode 100644 postman/globals/workspace.postman_globals.json rename src/constants/{accountStatus.ts => authConsts.ts} (53%) delete mode 100644 src/middleware/auth/requireCsrf.ts create mode 100644 src/middleware/paginationAndSorting.ts create mode 100644 src/middleware/security/accountStatusMiddleware.ts create mode 100644 src/middleware/security/requireCsrf.ts rename src/middleware/{auth => security}/roles.ts (100%) create mode 100644 src/modules/project/rules/projectStatus.ts create mode 100644 src/modules/project/utils/transitionManyProjectsByIds.ts create mode 100644 src/modules/project/utils/transitionProjectById.ts create mode 100644 src/types/Pagination.ts create mode 100644 src/types/RequestTypes.ts create mode 100644 src/types/index.ts create mode 100644 src/utils/emails/sender/sendEmailVerificationLink.ts create mode 100644 src/utils/emails/sender/sendOldEmailVerificationForEmailUpdate.ts create mode 100644 src/utils/emails/sender/sendPasswordUpdatedEmail.ts create mode 100644 src/utils/emails/sender/sendResetLink.ts create mode 100644 src/utils/emails/sender/sendUpdateEmaiLink.ts create mode 100644 src/utils/emails/sender/sendWelcomeEmail.ts rename src/{modules/auth => utils}/emails/templates/emailVerification.ts (100%) rename src/{modules/auth => utils}/emails/templates/newAccount.ts (100%) rename src/{modules/auth/emails => utils/emails/templates}/passwordChangedNotification.ts (100%) rename src/{modules/auth => utils}/emails/templates/resetPassword.ts (100%) create mode 100644 src/utils/emails/templates/verifyOldEmailForEmailUpdate.ts rename src/{modules/user/email/templlate => utils/emails/templates}/verifyUpdatedEmail.ts (97%) create mode 100644 src/utils/logger.ts create mode 100644 src/utils/paginationResponse.ts create mode 100644 src/utils/sanitizeProjectResponse.ts create mode 100644 src/validation/validateBody.ts create mode 100644 src/validation/validateParams.ts diff --git a/.postman/config.json b/.postman/config.json new file mode 100644 index 0000000..bffa66c --- /dev/null +++ b/.postman/config.json @@ -0,0 +1,12 @@ +{ + "workspace": { + "id": "a89b5db0-53ef-4ccd-805d-30769d8cbd88" + }, + "entities": { + "collections": [], + "environments": [], + "specs": [], + "flows": [], + "globals": [] + } +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index cc0ac7d..0efc437 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,6 +22,7 @@ "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" @@ -34,6 +35,7 @@ "@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" @@ -1965,6 +1967,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", @@ -2900,6 +2908,15 @@ "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", "license": "MIT" }, + "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", @@ -3083,6 +3100,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", @@ -3177,6 +3201,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", @@ -3273,6 +3307,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", @@ -3403,6 +3447,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", @@ -3615,6 +3673,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", @@ -3745,6 +3810,16 @@ ], "license": "MIT" }, + "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", @@ -4210,6 +4285,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", @@ -4263,6 +4347,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", @@ -4283,6 +4455,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", @@ -4307,6 +4490,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", @@ -4358,6 +4547,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", @@ -4404,12 +4602,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", @@ -4556,6 +4780,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", @@ -4565,6 +4798,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", @@ -4601,6 +4843,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", @@ -4626,6 +4881,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", diff --git a/package.json b/package.json index 74ce481..4730a85 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "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" @@ -34,6 +35,7 @@ "@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/postman/collections/Ai Vid Gen.postman_collection.json b/postman/collections/Ai Vid Gen.postman_collection.json new file mode 100644 index 0000000..ed44dd0 --- /dev/null +++ b/postman/collections/Ai Vid Gen.postman_collection.json @@ -0,0 +1,192 @@ +{ + "info": { + "_postman_id": "686c8ae3-4106-46cb-b479-5d833c80e93f", + "name": "Ai Vid Gen", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "{{base_url}}/projects/:projectId", + "id": "b3a36768-c57c-41af-a525-50063fd5e759", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"title\":\" huyasgdiujsagtyfcij\",\r\n \"status\":\"delete\",\r\n \"visibility\":\"private\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{base_url}}/projects/:projectId", + "host": [ + "{{base_url}}" + ], + "path": [ + "projects", + ":projectId" + ], + "variable": [ + { + "key": "projectId", + "value": "6943ffeaf0739e8ec0331c86", + "uuid": "0aa39b46-8347-4689-ab96-433780a82888" + } + ] + } + }, + "response": [] + }, + { + "name": "{{base_url}}/auth/refresh-token", + "id": "038c970e-2a09-48c3-a6ac-9516b300ff18", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "noauth" + }, + "method": "POST", + "header": [ + { + "key": "X-Forwarded-For", + "value": "49.37.182.221", + "type": "text", + "uuid": "3b4f68c9-6d59-4d55-93d1-fcad469eae33" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{base_url}}/auth/refresh-token", + "host": [ + "{{base_url}}" + ], + "path": [ + "auth", + "refresh-token" + ] + } + }, + "response": [] + }, + { + "name": "{{base_url}}/projects/:projectId", + "id": "9686111c-4b6f-44fa-996c-a29438e26077", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"title\":\" huyasgdiujsagtyfcij\",\r\n \"status\":\"delete\",\r\n \"visibility\":\"private\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{base_url}}/projects/:projectId", + "host": [ + "{{base_url}}" + ], + "path": [ + "projects", + ":projectId" + ], + "variable": [ + { + "key": "projectId", + "value": "6943ffeaf0739e8ec0331c86", + "uuid": "0aa39b46-8347-4689-ab96-433780a82888" + } + ] + } + }, + "response": [] + }, + { + "name": "{{base_url}}/projects/:projectId", + "id": "05e443b9-60d3-40f8-8a1b-31fdf5a57767", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"bio\":\"Chuddu Mall\",\r\n \"links\":{\r\n \"website\":\"https://gmail.com\",\r\n \"facebook\": \"https://gmail.com\",\r\n \"instagram\":\"https://gitmail.com\"\r\n }\r\n}" + }, + "url": { + "raw": "{{base_url}}/projects/:projectId", + "host": [ + "{{base_url}}" + ], + "path": [ + "projects", + ":projectId" + ], + "variable": [ + { + "key": "projectId", + "value": "6943ffeaf0739e8ec0331c86", + "uuid": "64bcac29-bb8f-4d3b-b46c-ce58c93d989a" + } + ] + } + }, + "response": [] + }, + { + "name": "{{base_url}}/projects/:projectId", + "id": "2436b647-3a4a-4faa-8768-beb78e1da5a2", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "DELETE", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"bio\":\"Chuddu Mall\",\r\n \"links\":{\r\n \"website\":\"https://gmail.com\",\r\n \"facebook\": \"https://gmail.com\",\r\n \"instagram\":\"https://gitmail.com\"\r\n }\r\n}" + }, + "url": { + "raw": "{{base_url}}/projects/:projectId", + "host": [ + "{{base_url}}" + ], + "path": [ + "projects", + ":projectId" + ], + "variable": [ + { + "key": "projectId", + "value": "69440d53032f4c583116b396", + "uuid": "81d17213-7105-428f-ba06-16d21b4c5ef7" + } + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/postman/collections/car-care-new.postman_collection.json b/postman/collections/car-care-new.postman_collection.json new file mode 100644 index 0000000..5adadd7 --- /dev/null +++ b/postman/collections/car-care-new.postman_collection.json @@ -0,0 +1,447 @@ +{ + "info": { + "_postman_id": "dcf6a138-dd1d-497f-8d84-8e40279eab5c", + "name": "car-care-new", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "AWS Sign In", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "// Parse the JSON response", + "let response = pm.response.json();", + "", + "// Set the environment variable", + "pm.environment.set(\"access_token\", response.AuthenticationResult.AccessToken);", + "" + ], + "type": "text/javascript", + "id": "ac28718b-2500-452d-9dcd-81ecd0f163a8" + } + } + ], + "id": "3ad83c89-bcf8-4300-9deb-741f27a2c9b5", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-amz-json-1.1", + "type": "text" + }, + { + "key": "X-Amz-Target", + "value": "AWSCognitoIdentityProviderService.InitiateAuth", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"AuthFlow\": \"USER_PASSWORD_AUTH\",\n \"ClientId\": \"1uhm1plej95vc3sh4e13t6pjfg\",\n \"AuthParameters\": {\n \"USERNAME\": \"+971561256408\",\n \"PASSWORD\": \"StrongPassword123!\"\n }\n}\n", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "https://cognito-idp.me-central-1.amazonaws.com/me-central-1_UiGgOFjxy", + "protocol": "https", + "host": [ + "cognito-idp", + "me-central-1", + "amazonaws", + "com" + ], + "path": [ + "me-central-1_UiGgOFjxy" + ] + } + }, + "response": [] + }, + { + "name": "Get All Brands", + "id": "29f1d262-a768-4bb4-b6fd-afdf6cc34768", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/api/brands", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "api", + "brands" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "Get All Models for a Brand", + "id": "4f8f5c7d-6de5-4680-a890-768cc38fb7bd", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/api/carmodel/brands/4/models", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "api", + "carmodel", + "brands", + "4", + "models" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "Get All Variants for a model", + "id": "17c8d112-dc3c-4c3b-bf61-17e0e9d5f2b4", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/api/carvariant/all/car-model/1", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "api", + "carvariant", + "all", + "car-model", + "1" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "Get car Variant by car variant id", + "id": "76f917e4-bdda-4387-a227-f74a791b0c0b", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/api/carvariant/1", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "api", + "carvariant", + "1" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "Get All Region Specs", + "id": "815afaaf-551d-4898-a024-52a82e396a4b", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/api/regionspec", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "api", + "regionspec" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "Add User Car", + "id": "bbcaa5e7-ee46-48b9-9145-6a8dff20011f", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"userId\": 1,\n \"brandId\": 4,\n \"brandName\": \"Audi\",\n \"modelId\": 1,\n \"modelName\": \"A3\",\n \"variantId\": 1,\n \"variantName\": \"Audi Q5 2.0 TFSI\",\n \"regionSpecId\": 1,\n \"regionName\": \"GCC\",\n \"makeYear\": 2024,\n \"makeMonth\": 1,\n \"chassisNumber\": \"AS/1122-2236\",\n \"plateNumber\": \"AUH29743\",\n \"carNickName\": \"Audi A3\",\n \"mileage\": 20000,\n \"mileageUnit\": \"MILES\",\n \"drivingConditionType\": \"EXTREME\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{car-care-host}}/user/cars", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "user", + "cars" + ] + } + }, + "response": [] + }, + { + "name": "Get User Car by Car Id", + "id": "dc59d5fb-7d26-4919-bf01-29efbe76a86c", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/user/cars/42", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "user", + "cars", + "42" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "update car", + "id": "b0d40778-a1f9-4f14-a846-fd489bfb72c2", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "PUT", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"carId\": 1,\n \"chassisNumber\": \"AS/1122-2236\",\n \"plateNumber\": \"AUH297466\",\n \"carNickName\": \"Audi A3\",\n \"mileage\": 20000,\n \"mileageUnit\":\"MILES\",\n \"drivingConditionType\": \"EXTREME\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{car-care-host}}/user/cars", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "user", + "cars" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "Get User Cars", + "id": "7b0316f1-f0d8-4b7f-a067-eed83610a02c", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/user/cars", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "user", + "cars" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + }, + { + "name": "Get Service Schedules", + "id": "2124bc8c-bb99-4b4f-9b00-abecbf6dd2de", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{car-care-host}}/user/cars", + "host": [ + "{{car-care-host}}" + ], + "path": [ + "user", + "cars" + ], + "query": [ + { + "key": "", + "value": null, + "disabled": true + } + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/postman/collections/natours.postman_collection.json b/postman/collections/natours.postman_collection.json new file mode 100644 index 0000000..9e73f2c --- /dev/null +++ b/postman/collections/natours.postman_collection.json @@ -0,0 +1,1072 @@ +{ + "info": { + "_postman_id": "48a7c9d1-ff78-4257-a965-182a158c44b4", + "name": "natours", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "tours", + "item": [ + { + "name": "Get All Tours", + "id": "647080d1-d1a1-4356-b62b-4de9e8d25876", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "Authorization", + "value": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY3MTUwZDEwYTI3ZmNmYzE1YmVkNTY1YSIsImlhdCI6MTcyOTQzMjg0OSwiZXhwIjoxNzM3MjA4ODQ5fQ.JKWA2lz_z6d5z30MVIZJuztx4KQtU7Vh8fIG5r5hdqE", + "type": "text", + "disabled": true + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/tours", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours" + ] + }, + "description": "### GET /api/v1/tours\n\nThis endpoint retrieves a list of tours. \n \n**Request** \nNo request body is required for this endpoint.\n\n**Request Body**\n\n- name (string, required): The name of the tour.\n \n- rating (string, required): The rating of the tour.\n \n- price (string, required): The price of the tour.\n \n\n**Response** \nThe response is a JSON object with the following schema:\n\n``` json\n{\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n },\n \"results\": {\n \"type\": \"integer\"\n },\n \"data\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"startLocation\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"_id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"duration\": {\n \"type\": \"integer\"\n },\n \"maxGroupSize\": {\n \"type\": \"integer\"\n },\n \"difficulty\": {\n \"type\": \"string\"\n },\n \"ratingsAverage\": {\n \"type\": \"number\"\n },\n \"ratingsQuantity\": {\n \"type\": \"integer\"\n },\n \"price\": {\n \"type\": \"integer\"\n },\n \"priceDiscount\": {\n \"type\": \"integer\"\n },\n \"imageCover\": {\n \"type\": \"string\"\n },\n \"images\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"createdAt\": {\n \"type\": \"string\"\n },\n \"startDates\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"secretTour\": {\n \"type\": \"boolean\"\n },\n \"guides\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"locations\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"slug\": {\n \"type\": \"string\"\n },\n \"durationWeeks\": {\n \"type\": \"integer\"\n },\n \"id\": {\n \"type\": \"string\"\n }\n }\n }\n }\n }\n}\n\n ```" + }, + "response": [] + }, + { + "name": "Get a Tour", + "id": "57d31b41-ff35-4c18-b2ad-090a45eb70ed", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/tours/67253239fedc2a345921157a", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "67253239fedc2a345921157a" + ] + }, + "description": "### GET /api/v1/tours/67253239fedc2a345921157a\n\nThis endpoint retrieves details of a specific tour.\n\n**Request** \nNo request body is required for this endpoint.\n\n**Response** \nThe response will be a JSON object with the following schema:\n\n``` json\n{\n \"type\": \"object\",\n \"properties\": {\n \"status\": { \"type\": \"string\" },\n \"data\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": {\n \"type\": \"object\",\n \"properties\": {\n \"startLocation\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"type\": \"string\" },\n \"coordinates\": { \"type\": \"array\" }\n }\n },\n \"_id\": { \"type\": \"string\" },\n \"name\": { \"type\": \"string\" },\n \"duration\": { \"type\": \"number\" },\n \"maxGroupSize\": { \"type\": \"number\" },\n \"difficulty\": { \"type\": \"string\" },\n \"ratingsAverage\": { \"type\": \"number\" },\n \"ratingsQuantity\": { \"type\": \"number\" },\n \"price\": { \"type\": \"number\" },\n \"priceDiscount\": { \"type\": \"number\" },\n \"imageCover\": { \"type\": \"string\" },\n \"images\": { \"type\": \"array\" },\n \"createdAt\": { \"type\": \"string\" },\n \"startDates\": { \"type\": \"array\" },\n \"secretTour\": { \"type\": \"boolean\" },\n \"guides\": { \"type\": \"array\" },\n \"locations\": { \"type\": \"array\" },\n \"slug\": { \"type\": \"string\" },\n \"__v\": { \"type\": \"number\" },\n \"durationWeeks\": { \"type\": \"number\" },\n \"reviews\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"_id\": { \"type\": \"string\" },\n \"review\": { \"type\": \"string\" },\n \"rating\": { \"type\": \"number\" },\n \"tour\": { \"type\": \"string\" },\n \"user\": {\n \"type\": \"object\",\n \"properties\": {\n \"_id\": { \"type\": \"string\" },\n \"name\": { \"type\": \"string\" }\n }\n },\n \"createdAt\": { \"type\": \"string\" },\n \"__v\": { \"type\": \"number\" },\n \"id\": { \"type\": \"string\" }\n }\n }\n },\n \"id\": { \"type\": \"string\" }\n }\n }\n }\n }\n }\n}\n\n ```" + }, + "response": [] + }, + { + "name": "Get Tour Stats", + "id": "41dee70d-1bf0-43d0-818a-dd13cb11a76e", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/tours/tour-stats", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "tour-stats" + ] + }, + "description": "### Get Tour Stats\n\nThis endpoint retrieves statistics for tours.\n\n#### Request Body\n\nThis is a GET request and does not require a request body.\n\n#### Response\n\n- **status** (string, required): The status of the response.\n \n- **data** (array, required): An array containing tour statistics.\n \n - **_id** (string, required): The ID of the tour.\n \n - **numTours** (integer, required): The number of tours.\n \n - **numRating** (integer, required): The number of ratings for the tour.\n \n - **avgRating** (integer, required): The average rating for the tour.\n \n - **avgPrice** (integer, required): The average price of the tour.\n \n - **minPrice** (integer, required): The minimum price of the tour.\n \n - **maxPrice** (integer, required): The maximum price of the tour.\n \n\n#### Example\n\n``` json\n{\n \"status\": \"\",\n \"data\": [\n {\n \"_id\": \"\",\n \"numTours\": 0,\n \"numRating\": 0,\n \"avgRating\": 0,\n \"avgPrice\": 0,\n \"minPrice\": 0,\n \"maxPrice\": 0\n }\n ]\n}\n\n ```" + }, + "response": [] + }, + { + "name": "Monthly Plan", + "id": "95285122-31a1-4015-a4d5-36f01b0be9c3", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/tours/monthly-plan/2021", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "monthly-plan", + "2021" + ] + }, + "description": "# Get Monthly Plan for Tours\n\nThis endpoint retrieves the monthly plan for tours for the year 2021.\n\n## Request\n\n- Method: GET\n \n- URL: {{URL}}/api/v1/tours/monthly-plan/2021\n \n\n## Response\n\nThe response for this request is a JSON object representing the monthly plan for tours in the year 2021. You can expect the following properties in the response:\n\n- `month`: (string) The month for which the plan is provided.\n \n- `numTours`: (number) The number of tours planned for the month.\n \n- `numReviews`: (number) The number of reviews received for the tours in the month.\n \n- `avgRating`: (number) The average rating for the tours in the month.\n \n\nExample response:\n\n``` json\n{\n \"month\": \"January\",\n \"numTours\": 10,\n \"numReviews\": 56,\n \"avgRating\": 4.5\n}\n\n ```" + }, + "response": [] + }, + { + "name": "Create Tour", + "id": "ead32a97-6003-48b4-bee9-11ffe69de6f0", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"name\": \"Test Tour tesla 1121\",\r\n \"duration\": 5,\r\n \"maxGroupSize\": 25,\r\n \"difficulty\": \"easy\",\r\n \"price\": 397,\r\n \"priceDiscount\": 300,\r\n \"imageCover\": \"tour-1-cover.jpg\"\r\n }", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/tours", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours" + ] + }, + "description": "### Create a New Tour\n\nThis endpoint is used to create a new tour.\n\n#### Request Body\n\n- name (string): The name of the tour.\n \n- duration (number): The duration of the tour in days.\n \n- maxGroupSize (number): The maximum group size for the tour.\n \n- difficulty (string): The difficulty level of the tour.\n \n- price (number): The price of the tour.\n \n- priceDiscount (number): The discount price of the tour.\n \n- imageCover (string): The cover image of the tour.\n \n\n#### Response\n\nThe response will be in JSON format with the following schema:\n\n``` json\n{\n \"status\": \"\",\n \"data\": {\n \"data\": {\n \"name\": \"\",\n \"duration\": 0,\n \"maxGroupSize\": 0,\n \"difficulty\": \"\",\n \"ratingsAverage\": 0,\n \"ratingsQuantity\": 0,\n \"price\": 0,\n \"priceDiscount\": 0,\n \"imageCover\": \"\",\n \"images\": [],\n \"createdAt\": \"\",\n \"startDates\": [],\n \"secretTour\": true,\n \"startLocation\": {\n \"type\": \"\",\n \"coordinates\": []\n },\n \"guides\": [],\n \"_id\": \"\",\n \"locations\": [],\n \"slug\": \"\",\n \"__v\": 0,\n \"durationWeeks\": 0,\n \"id\": \"\"\n }\n }\n}\n\n ```" + }, + "response": [] + }, + { + "name": "Delete Tour", + "id": "6dee8a10-7328-488c-88ae-3adbef7d6acb", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "DELETE", + "header": [], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/tours/671f73da3b34e3fe4a132e12", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "671f73da3b34e3fe4a132e12" + ] + }, + "description": "This endpoint sends an HTTP DELETE request to the specified URL to delete a specific tour with the given ID. The request does not contain a request body.\n\nThe response to this request will not include a response body, but will indicate the success or failure of the deletion operation through the HTTP status code and any relevant headers." + }, + "response": [] + }, + { + "name": "Update Tour", + "id": "a21eb7a3-646e-4da8-a074-121a06ef0943", + "request": { + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"name\": \"TEST For the factory update \",\r\n \"difficulty\": \"easy\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/tours/671ffc31db87a4fee8927187", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "671ffc31db87a4fee8927187" + ] + }, + "description": "This endpoint makes an HTTP PATCH request to update a specific tour identified by the provided ID. The request body should contain the updated tour details such as name and difficulty.\n\n### Response\n\nThe response of this request is a JSON schema representing the updated tour object." + }, + "response": [] + }, + { + "name": "Tour Within Radius", + "id": "b2a53f1a-a3d2-4c11-bc7c-a3e799717e11", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/tours/tour-within/200/center/34.111745,-118.113491/unit/mi", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "tour-within", + "200", + "center", + "34.111745,-118.113491", + "unit", + "mi" + ] + }, + "description": "This endpoint retrieves tour data within a specified distance from a geographical center point. The request should include the distance in miles, latitude, and longitude of the center point. The response will be in JSON format and will contain the schema for the tour data." + }, + "response": [] + }, + { + "name": "Distance of All tours", + "id": "d564445a-4504-4c39-ade9-b8a58a6ae71f", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/tours/distances/34.111745,-118.113491/unit/km", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "distances", + "34.111745,-118.113491", + "unit", + "km" + ] + }, + "description": "This endpoint retrieves the distances of tours from a specific location in kilometers. The response of this request is a JSON schema representing the distances of tours in kilometers." + }, + "response": [] + } + ], + "id": "ec719748-0041-432e-8a89-613d2f6b8f9b", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "id": "d9697309-a6d5-4cf3-a5ed-2e3dc00993d6", + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "10f34a2d-8a6e-490a-a287-43ded9b0d98f", + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + } + ] + }, + { + "name": "Tour/Reviews", + "item": [ + { + "name": "Create Review", + "id": "6f58d174-5ffe-47ef-8e61-201a84ae5b4f", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"rating\": 3,\r\n \"review\":\"Bhakk Bekar Nikla Salla Bekar Test\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/tours/67253239fedc2a345921157a/reviews", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "67253239fedc2a345921157a", + "reviews" + ] + } + }, + "response": [] + }, + { + "name": "Get All Reviews", + "id": "ab923947-9e97-4675-8382-7e1a3795cc3c", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/tours/5c88fa8cf4afda39709c2955/reviews", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "tours", + "5c88fa8cf4afda39709c2955", + "reviews" + ] + } + }, + "response": [] + } + ], + "id": "11e450c1-1f21-46ae-9a6e-c6e34e9abaab" + }, + { + "name": "reviews", + "item": [ + { + "name": "Post review", + "id": "df30e873-9767-492c-8db6-57530909df03", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"review\":\"lallalallalalalallalalalala\",\r\n \"rating\": 4,\r\n \"tour\": \"67253239fedc2a345921157a\",\r\n \"user\" : \"67154d2dc39c57af2e25645e\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/reviews", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "reviews" + ] + } + }, + "response": [] + }, + { + "name": "Get All Reviews", + "id": "1930f56e-6275-4f43-bff8-654d18a6e606", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/reviews/", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "reviews", + "" + ] + } + }, + "response": [] + }, + { + "name": "Delete Review", + "id": "14d21587-111a-4766-b5a2-c2997e8f95ee", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "DELETE", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/reviews/6725360605d436ee1e7cf1d9", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "reviews", + "6725360605d436ee1e7cf1d9" + ] + } + }, + "response": [] + }, + { + "name": "Update Review", + "id": "39a3c133-6390-47ac-85ad-2256c9826ed7", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"review\":\"Fool \",\r\n \"rating\":1\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/reviews/6725360605d436ee1e7cf1d9", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "reviews", + "6725360605d436ee1e7cf1d9" + ] + } + }, + "response": [] + } + ], + "id": "c46f0ceb-bb34-4038-bbff-29e643e0113f" + }, + { + "name": "users", + "item": [ + { + "name": "Get All USers", + "id": "1ebc0a6b-f5e5-47ef-a312-8b03c351a14f", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/users", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users" + ] + } + }, + "response": [] + }, + { + "name": "Update Current User", + "id": "88fd75a6-6bbc-448c-9337-e4cb90e35876", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"email\": \"dono@momo.co\"\r\n ,\"name\":\"
Blah Blah Blah
\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/users/updateMe", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "updateMe" + ] + } + }, + "response": [] + }, + { + "name": "Delete Current User", + "id": "30584c8e-48b5-4208-85c4-a4e1883e38d8", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "DELETE", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/users/deleteMe", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "deleteMe" + ] + } + }, + "response": [] + }, + { + "name": "Delete User", + "id": "e2a08665-8046-4d44-b4a9-94100a8a175d", + "request": { + "method": "GET", + "header": [] + }, + "response": [] + }, + { + "name": "Get Current User", + "id": "909e219e-c7fd-46ae-b99c-ad7c0e349910", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/users/me", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "me" + ] + } + }, + "response": [] + } + ], + "id": "bd1d9ee5-68b6-4829-ac50-71e85f138c02", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "id": "bea72fed-1d27-4763-bab8-b4ae3c5315c2", + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "2be820cd-6a7c-4984-bad6-164ed4215467", + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + } + ] + }, + { + "name": "Authentication", + "item": [ + { + "name": "login", + "event": [ + { + "listen": "test", + "script": { + "id": "e2cb5a69-60e4-4804-bf14-3c741bb857da", + "exec": [ + "pm.environment.set(\"jwt\", pm.response.json().token);" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "id": "b8f72b32-9d14-4a8e-b0f5-ac2493af4db0", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"email\":\"test@tetsing.son\",\r\n \"password\": \"Azeem1234\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/users/login", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "login" + ] + } + }, + "response": [] + }, + { + "name": "Sign Up", + "event": [ + { + "listen": "test", + "script": { + "id": "cb5242ec-a7f7-4c2a-807a-30784e220ddf", + "exec": [ + "pm.environment.set(\"jwt\", pm.response.json().token);" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "id": "a7d6c03d-282a-42b0-b97e-1c1d34c46881", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"name\":\"Test 2 Name\",\r\n \"email\": \"test@Tetsing.don\",\r\n \"password\":\"test12test\",\r\n \"passwordConfirm\":\"test12test\",\r\n \"passwordChangedAt\": \"2024-01-01\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/users/signup", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "signup" + ] + } + }, + "response": [] + }, + { + "name": "Forgot Password", + "id": "6be9669d-4dea-4dc4-876f-36d78b4506b9", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"email\":\"test@tetsing.von\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/users/forgotPassword", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "forgotPassword" + ] + } + }, + "response": [] + }, + { + "name": "Reset Password", + "event": [ + { + "listen": "test", + "script": { + "id": "6d06a8b2-8145-41ce-aa58-c4144f591e0f", + "exec": [ + "pm.environment.set(\"jwt\", pm.response.json().token);" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "id": "8a8dc136-0afb-4595-bea7-4c459f20a129", + "request": { + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"password\":\"myluckisfucked101\",\r\n \"passwordConfirm\":\"myluckisfucked101\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/users/resetPassword/fcf9fe1f0dd01a3f9a6929e4492d04ded615cb7858c24dc1f18e3e390f199767", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "resetPassword", + "fcf9fe1f0dd01a3f9a6929e4492d04ded615cb7858c24dc1f18e3e390f199767" + ] + } + }, + "response": [] + }, + { + "name": "Update Password", + "event": [ + { + "listen": "test", + "script": { + "id": "33549756-4d86-4630-85da-29f8542ab181", + "exec": [ + "pm.environment.set(\"jwt\", pm.response.json().token);\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "id": "8f36d52b-2ec3-48bb-891f-0119dcacb3f8", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"passwordCurrent\": \"KingKong10111\",\r\n \"passwordUpdate\": \"KingKong101111\",\r\n \"passwordConfirm\":\"KingKong101111\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{URL}}/api/v1/users/updatePassword", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "users", + "updatePassword" + ] + } + }, + "response": [] + } + ], + "id": "f34a6161-f02e-4e17-8abb-21cee7cfd3a2" + }, + { + "name": "Bookings", + "item": [ + { + "name": "Create Booking Session Stripe", + "id": "a05e41b5-957e-4736-928b-da371a706810", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "{{URL}}/api/v1/bookings/checkout-session/5c88fa8cf4afda39709c2961", + "host": [ + "{{URL}}" + ], + "path": [ + "api", + "v1", + "bookings", + "checkout-session", + "5c88fa8cf4afda39709c2961" + ] + } + }, + "response": [] + }, + { + "name": "Get All The Meals", + "id": "baff3a2d-5a5e-4379-b1e3-2245f2cf2942", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text", + "disabled": true + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"model\": \"ai/deepseek-rl-distill-llama\",\r\n \"messages\": [\r\n {\r\n \"role\": \"system\",\r\n \"content\": \"You are a Meal Plan Generator AI. Always respond ONLY in strict JSON format. Do not add any explanations, comments, or Markdown. Only return valid JSON.\"\r\n },\r\n {\r\n \"role\": \"user\",\r\n \"content\": \"Create a 1-month vegetarian meal plan for weight loss. Include weekly plans with meals (breakfast, lunch, dinner, snacks) and structure the response in JSON.\"\r\n },\r\n {\r\n \"role\": \"user\",\r\n \"content\": \"Example Input: Generate a 1-month meal plan for weight loss with the following preferences.\",\r\n \"metadata\": {\r\n \"meal_plan_duration\": \"1 Month\",\r\n \"goal\": \"Weight Loss - 5 kg\",\r\n \"preferences\": {\r\n \"diet_type\": \"Vegetarian\",\r\n \"high_protein\": true,\r\n \"low_sugar\": true,\r\n \"dairy_free\": true,\r\n \"location\": \"Delhi India\",\r\n \"budget\": \"Low to Medium\"\r\n }\r\n }\r\n },\r\n {\r\n \"role\": \"asiistant\",\r\n \"content\": \"Example Output : Please use english based on the location as english is different in every country\",\r\n \"metadata\": {\r\n \"weekly_plan\": [\r\n {\r\n \"week\": 1,\r\n \"days\": [\r\n {\r\n \"day\": \"Monday\",\r\n \"meals\": {\r\n \"breakfast\": \"Quinoa porridge with almond milk and chia seeds\",\r\n \"lunch\": \"Grilled tofu salad with mixed greens, chickpeas, and olive oil dressing\",\r\n \"dinner\": \"Stir-fried vegetables with tempeh and brown rice\",\r\n \"snacks\": [\r\n \"Handful of almonds\",\r\n \"Carrot and cucumber sticks with hummus\"\r\n ]\r\n }\r\n },\r\n {\r\n \"day\": \"Tuesday\",\r\n \"meals\": {\r\n \"breakfast\": \"Oats smoothie bowl with peanut butter and flaxseeds\",\r\n \"lunch\": \"Lentil soup with whole-grain toast\",\r\n \"dinner\": \"Vegetable quinoa with steamed broccoli\",\r\n \"snacks\": [\r\n \"Roasted chickpeas\",\r\n \"Apple slices with almond butter\"\r\n ]\r\n }\r\n }\r\n // ... Continue for remaining days of the week\r\n ]\r\n },\r\n {\r\n \"week\": 2,\r\n \"days\": [\r\n // Another week plan...\r\n ]\r\n }\r\n // ... Continue up to week 4\r\n ]\r\n }\r\n }\r\n ],\r\n \"stream\": false,\r\n \"response_format\": {\r\n \"type\": \"json_object\"\r\n }\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "http://localhost:8000/api/chat", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8000", + "path": [ + "api", + "chat" + ] + } + }, + "response": [] + } + ], + "id": "eb592ee7-94a0-4699-a564-680455f406da", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "id": "faf2fb7d-54b4-43e5-a7b5-9376cb8f2b37", + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "id": "6a195d30-6dc9-4826-bfb2-b2c6f9bf5ac8", + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + } + ] + } + ] +} \ No newline at end of file diff --git a/postman/environments/natours b/postman/environments/natours new file mode 100644 index 0000000..e69de29 diff --git a/postman/globals/workspace.postman_globals.json b/postman/globals/workspace.postman_globals.json new file mode 100644 index 0000000..391e574 --- /dev/null +++ b/postman/globals/workspace.postman_globals.json @@ -0,0 +1,7 @@ +{ + "id": "9434ce11-52c8-495e-9fea-5287073598ed", + "name": "Globals", + "values": [], + "_postman_variable_scope": "globals", + "_postman_exported_at": "2025-12-20T13:21:58.356Z" +} \ No newline at end of file diff --git a/src/config/corsConfig.ts b/src/config/corsConfig.ts index 73d6050..01b159c 100644 --- a/src/config/corsConfig.ts +++ b/src/config/corsConfig.ts @@ -26,6 +26,7 @@ const getCorsConfig = (): CorsOptions => { methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], + // Allow cookies or authorization headers to be sent credentials: true, diff --git a/src/constants/accountStatus.ts b/src/constants/authConsts.ts similarity index 53% rename from src/constants/accountStatus.ts rename to src/constants/authConsts.ts index f1e44be..d492f6f 100644 --- a/src/constants/accountStatus.ts +++ b/src/constants/authConsts.ts @@ -1,10 +1,15 @@ // constants/accountStatus.ts export const ACCOUNT_STATUSES = [ "active", - "suspended", + "inactive", + "suspend", + "deactive", "banned", - "disabled", - "deleted", + "delete", ] as const; +export const RESET_EXP_MIN = Number( + process.env.PASSWORD_RESET_EXPIRES_MIN || 10 +); + export type AccountStatus = (typeof ACCOUNT_STATUSES)[number]; 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/middleware/auth/requireAuth.ts b/src/middleware/auth/requireAuth.ts index bcf9b07..cbff4c7 100644 --- a/src/middleware/auth/requireAuth.ts +++ b/src/middleware/auth/requireAuth.ts @@ -3,21 +3,18 @@ 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 { UnauthenticatedError } from "@middleware/error/index.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; @@ -27,7 +24,7 @@ export const requireAuth = async ( sessionId: string; }; } catch (err) { - throw new UnauthenticatedError("Invalid or expired token"); + throw new UnauthenticatedError("Authentication required"); } // find user with this session @@ -36,16 +33,17 @@ export const requireAuth = async ( }); if (!user) { - throw new NotFoundError("User not found"); + throw new UnauthenticatedError("Authentication required"); } const session = await SessionModel.findOne({ sessionId: decoded.sessionId, userId: decoded.userId, + valid: true, }); if (!session || session.revokedAt) { - throw new UnauthenticatedError("Session revoked or not found"); + throw new UnauthenticatedError("Authentication required"); } // ✅ update lastUsedAt for this session 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/error/globalErrorHandler.ts b/src/middleware/error/globalErrorHandler.ts index 6a88f51..df41806 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -1,6 +1,7 @@ // src/middleware/errorHandler.ts import { NextFunction, Request, Response } from "express"; import { AppError } from "./appError.js"; +import logger from "@utils/logger.js"; const errorHandler = ( err: unknown, @@ -8,17 +9,21 @@ const errorHandler = ( res: Response, next: NextFunction ) => { - console.error("ERROR:", err); - // If it's a known error (instance of AppError) if (err instanceof AppError) { - return res.status(err.statusCode).json({ - status: "error", + logger.error({ message: err.message, - code: err.code, details: err.details, stack: err.stack, + request: { + method: req.method, + url: req.originalUrl, + headers: req.headers, + body: req.body, + }, }); + + return res.status(err.statusCode).json(err.serialize()); } return res.status(500).json({ diff --git a/src/middleware/loggerMiddleware.ts b/src/middleware/loggerMiddleware.ts index 9c5b575..ce2441e 100644 --- a/src/middleware/loggerMiddleware.ts +++ b/src/middleware/loggerMiddleware.ts @@ -1,44 +1,75 @@ -// middleware/devLogger.ts -import type { Request, Response, NextFunction } from 'express'; - -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(); -}; +import type { Request, Response, NextFunction } from "express"; +import { randomUUID } from "crypto"; +import logger from "@utils/logger.js"; + +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(); + (req as any).requestId = requestId; + res.setHeader("X-Request-Id", requestId); + + // DEV: log incoming request (optional, low noise) + if (isDev) { + logger.debug( + { + requestId, + method: req.method, + path: req.originalUrl, + }, + "Incoming request" + ); + } + + res.on("finish", () => { + const durationNs = process.hrtime.bigint() - start; + const durationMs = Number(durationNs) / 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 -}; + /* ---------- DEV: pretty output ---------- */ + if (isDev) { + const color = getStatusColor(res.statusCode); + + // still goes through pino-pretty (NOT console.log) + logger.info( + logData, + `${color}$ ${req.method} ${req.originalUrl} ${res.statusCode} ${logData.durationMs}ms\x1b[0m` + ); + return; + } + + /* ---------- PROD: structured only ---------- */ + 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/paginationAndSorting.ts b/src/middleware/paginationAndSorting.ts new file mode 100644 index 0000000..23e2926 --- /dev/null +++ b/src/middleware/paginationAndSorting.ts @@ -0,0 +1,53 @@ +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/accountStatusMiddleware.ts b/src/middleware/security/accountStatusMiddleware.ts new file mode 100644 index 0000000..d7e8d0f --- /dev/null +++ b/src/middleware/security/accountStatusMiddleware.ts @@ -0,0 +1,41 @@ +import type { Request, Response, NextFunction } from "express"; +import type { AuthenticatedRequest } from "types/RequestTypes.js"; +import { ForbiddenError } from "@middleware/error/index.js"; + +export function requireActiveAccount( + req: Request, + _res: Response, + next: NextFunction +) { + const status = (req as unknown as AuthenticatedRequest).user.accountStatus; + if (status !== "active") { + throw new ForbiddenError(`Account is ${status}. Reactivation required.`); + } + next(); +} + +export function blockBannedAccounts( + req: Request, + _res: Response, + next: NextFunction +) { + const status = (req as unknown as AuthenticatedRequest).user.accountStatus; + if (status === "banned") { + throw new ForbiddenError("This account has been permanently banned."); + } + + next(); +} + +export function allowOnlyInactiveAccounts( + req: Request, + _res: Response, + next: NextFunction +) { + const status = (req as unknown as AuthenticatedRequest).user.accountStatus; + + if (status === "active") { + throw new ForbiddenError("Account is already active."); + } + next(); +} diff --git a/src/middleware/security/requireCsrf.ts b/src/middleware/security/requireCsrf.ts new file mode 100644 index 0000000..b5a7c23 --- /dev/null +++ b/src/middleware/security/requireCsrf.ts @@ -0,0 +1,35 @@ +import type { Request, Response, NextFunction } from "express"; +import crypto from "crypto"; +import { BadRequestError } from "@middleware/error/index.js"; +import { SessionModel } from "@models/Session.js"; +import { AuthenticatedRequest } from "types/RequestTypes.js"; +import { compareHashTokens, hashToken } from "@utils/tokens.js"; + +export const csrfMiddleware = async ( + req: Request, + res: Response, + next: NextFunction +) => { + const csrfCookie = req.cookies["csrf-token"]; + const csrfToken = req.headers["x-csrf-token"]; + if (!csrfToken || !csrfCookie) { + throw new BadRequestError( + "Invalid CSRF token" + ); + } + + const session = await SessionModel.findOne({ + csrfTokenHash: hashToken(csrfCookie), + }).select("+csrfTokenHash"); + + if (!session) { + throw new BadRequestError("Invalid CSRF token"); + } + const hashCsrfToken = hashToken(csrfToken as string); + const isValid = compareHashTokens(session.csrfTokenHash, hashCsrfToken); + if (!isValid) { + throw new BadRequestError("Invalid CSRF token"); + } + + next(); +}; diff --git a/src/middleware/auth/roles.ts b/src/middleware/security/roles.ts similarity index 100% rename from src/middleware/auth/roles.ts rename to src/middleware/security/roles.ts diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts index 39722f2..ec6d7f5 100644 --- a/src/models/FinalVideo.ts +++ b/src/models/FinalVideo.ts @@ -67,11 +67,13 @@ const finalVideoSchema = new Schema( type: Schema.Types.ObjectId, ref: "Project", required: true, + indexe: true, }, storyId: { type: Schema.Types.ObjectId, ref: "Story", required: true, + index: true, }, videoUrl: { type: String, diff --git a/src/models/Project.ts b/src/models/Project.ts index 037f2da..2a7408c 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -2,8 +2,8 @@ import { Schema, model, Document, Types, HydratedDocument } from "mongoose"; export interface ProjectType extends Document { userId: Types.ObjectId; title: string; - description?: string; - status: "active" | "drafted" | "archived" | "deleted"; + description: string; + status: "active" | "draft" | "archive" | "delete"; visibility: "public" | "private"; contextProfileId?: Types.ObjectId; activeStoryId?: Types.ObjectId; @@ -15,6 +15,8 @@ export interface ProjectType extends Document { audiosGenerated: number; videosGenerated: number; }; + createdAt: Date; + updatedAt: Date; } const projectSchema = new Schema( @@ -22,22 +24,23 @@ const projectSchema = new Schema( title: { type: String, required: true, + maxlength: 255, trim: true, }, description: { type: String, - maxlength: 1000, + required: true, + maxlength: 500, trim: true, }, userId: { type: Schema.Types.ObjectId, ref: "User", required: true, - index: true, }, status: { type: String, - enum: ["active", "drafted", "archived", "deleted"], + enum: ["active", "draft", "archive", "delete"], default: "active", }, visibility: { @@ -59,6 +62,8 @@ const projectSchema = new Schema( { 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/Session.ts b/src/models/Session.ts index eb73f3f..eba3062 100644 --- a/src/models/Session.ts +++ b/src/models/Session.ts @@ -30,9 +30,12 @@ const sessionSchema = new Schema({ isp: { type: String }, cpu: { type: String }, engine: { type: String }, + refreshTokenHash: { type: String, required: true }, + csrfTokenHash: { type: String, 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 diff --git a/src/models/Story.ts b/src/models/Story.ts index ecdbcb8..01d4dae 100644 --- a/src/models/Story.ts +++ b/src/models/Story.ts @@ -1,3 +1,4 @@ +import { User } from '@models/User.js'; import { Schema, model, Document, Types } from "mongoose"; export interface StoryHistoryEntry { @@ -23,6 +24,7 @@ export interface Story extends Document { contextProfileId?: Types.ObjectId; contextProfileVersion?: number; editHistory: StoryHistoryEntry[]; // max 3 (enforced in service too) + savedBy: Types.ObjectId[]; createdAt: Date; updatedAt: Date; } @@ -138,6 +140,10 @@ const storySchema = new Schema( message: "Story editHistory cannot exceed 3 entries", }, }, + savedBy:[{ + type: Schema.Types.ObjectId, + ref: "User" + }] }, { timestamps: true } ); diff --git a/src/models/User.ts b/src/models/User.ts index 401ce4a..cfc5442 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -1,4 +1,4 @@ -import { ACCOUNT_STATUSES } from "constants/accountStatus.js"; +import { ACCOUNT_STATUSES } from "constants/authConsts.js"; import { Schema, model, @@ -19,6 +19,7 @@ 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" @@ -84,25 +85,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 +179,7 @@ const userSchema = new Schema( type: String, trim: true, maxlength: 80, + required: true, }, username: { type: String, @@ -184,6 +189,7 @@ const userSchema = new Schema( index: true, sparse: true, // allows null without unique conflict unique: true, + required: true, }, avatarUrl: { type: String, @@ -270,12 +276,6 @@ const userSchema = new Schema( accountStatus: { type: String, enum: ACCOUNT_STATUSES, default: "active" }, - changeHistory: { - type: [changeMetaSchema], - default: [], - select: false, - }, - // Billing billingCustomerId: { type: String }, billingProvider: { type: String }, // "stripe" | "razorpay" | etc @@ -287,8 +287,7 @@ const userSchema = new Schema( }, currentPeriodEnd: { type: Date }, trialEndsAt: { type: Date }, - cancelAtPeriodEnd: { type: Boolean, default: false }, - + cancelAtPeriodEnd: { type: Boolean, default: false }, // Notification settings notificationPrefs: { type: notificationPrefsSchema, @@ -297,8 +296,7 @@ const userSchema = new Schema( inApp: true, marketingEmails: false, }), - }, - + }, // Privacy prefs privacyPrefs: { type: privacyPrefsSchema, @@ -316,6 +314,12 @@ const userSchema = new Schema( deletedAt: { type: Date, }, + changeHistory: { + type: [changeMetaSchema], + default: [], + select: false, + cap: 100, + }, }, { timestamps: true, diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index 76a7769..ceeb95e 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -1,8 +1,9 @@ +import { AccountStatus } from "constants/authConsts.js"; import type { CookieOptions } from "express"; import type { Request, Response } from "express"; import { createPasswordResetRequest, - emailVerification, + sendEmailVerification, loginUser, logoutUser, refreshTokens, @@ -16,8 +17,9 @@ import type { LoginInput, ForgetPasswordInput, VerifyEmailInput, + VerifyUpdateEmailInput, } from "@validation/auth.schema.js"; -import { UnauthenticatedError } from "@middleware/error/index.js"; +import { AuthenticatedRequest, ValidatedRequest } from "types/RequestTypes.js"; const CookieOptions: CookieOptions = { httpOnly: true, @@ -27,8 +29,7 @@ const CookieOptions: CookieOptions = { }; export const registerController = async (req: Request, res: Response) => { - const body = (req as unknown as { validatedBody?: RegisterInput }) - .validatedBody!; + const body = (req as ValidatedRequest).validatedBody; const userAgent: string = req.headers["user-agent"] || "unknown"; const ip = @@ -70,9 +71,7 @@ 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 body = (req as ValidatedRequest).validatedBody; const userAgent: string = req.headers["user-agent"] || "unknown"; const ip = req.headers["x-forwarded-for"] || @@ -83,7 +82,7 @@ export const loginController = async (req: Request, res: Response) => { const payload = { ...body, userAgent, ip }; const result = await loginUser(payload); - const { user, accessToken, refreshToken, csrfToken } = result; + const { user, accessToken, refreshToken, csrfToken, accountStatus } = result; return res .status(200) @@ -107,13 +106,13 @@ export const loginController = async (req: Request, res: Response) => { username: user.username, displayName: user.displayName, avatar: user.avatarUrl, + accountStatus: accountStatus, }, }); }; export const forgotPasswordController = async (req: Request, res: Response) => { - const payload = (req as unknown as { validatedBody?: ForgetPasswordInput }) - .validatedBody!; + const payload = (req as ValidatedRequest).validatedBody; await createPasswordResetRequest(payload.email); return res.status(200).json({ status: "success", @@ -123,7 +122,9 @@ export const forgotPasswordController = async (req: Request, res: Response) => { }; export const resetPasswordController = async (req: Request, res: Response) => { - const { token, password } = (req as any).validatedBody; + const { token, password } = ( + req as ValidatedRequest<{ token: string; password: string }> + ).validatedBody; await resetPassword(token, password); return res.status(200).json({ status: "success", @@ -133,11 +134,17 @@ export const resetPasswordController = async (req: Request, res: Response) => { export const refreshTokenController = async (req: Request, res: Response) => { 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" }); } - const result = await refreshTokens(reqRefreshToken); + const result = await refreshTokens(reqRefreshToken, userAgent, ip); const { accessToken, refreshToken, csrfToken } = result; return res .status(200) @@ -161,21 +168,17 @@ export const emailVerificationController = async ( req: Request, res: Response ) => { - const userId = req.user?._id; + const userId = (req as AuthenticatedRequest).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", }); }; export const verifyEmailController = async (req: Request, res: Response) => { - const { verificationToken } = ( - req as unknown as { validatedBody?: VerifyEmailInput } - ).validatedBody!; + const { verificationToken } = (req as ValidatedRequest) + .validatedBody; await verifyEmail(verificationToken); return res.status(200).json({ @@ -187,10 +190,11 @@ export const verifyEmailChangeController = async ( req: Request, res: Response ) => { - const { verificationToken } = ( - req as unknown as { validatedBody?: VerifyEmailInput } - ).validatedBody!; - await verifyUpdateEmail(verificationToken); + const { verificationToken, code } = ( + req as ValidatedRequest + ).validatedBody; + const currentSessionId = (req as AuthenticatedRequest).sessionId; + await verifyUpdateEmail(verificationToken, code, currentSessionId); return res.status(200).json({ message: "Email change verified successfully", }); diff --git a/src/modules/auth/auth.routes.ts b/src/modules/auth/auth.routes.ts index 98329bf..64ebc18 100644 --- a/src/modules/auth/auth.routes.ts +++ b/src/modules/auth/auth.routes.ts @@ -15,15 +15,17 @@ import { loginSchema, registerSchema, resetPasswordSchema, - validateBody, verifyEmailSchema, + verifyUpdateEmailSchema, } from "@validation/auth.schema.js"; +import { validateBody } from "@validation/validateBody.js"; import { asyncHandler } from "@utils/asyncHandler.js"; -import { requireAuth as auth } from "@middleware/auth/requireAuth.js"; +import { authMiddleware } from "@middleware/auth/requireAuth.js"; +import { csrfMiddleware } from "@middleware/security/requireCsrf.js"; +import { requireActiveAccount } from "@middleware/security/accountStatusMiddleware.js"; const router = Router(); -// POST /api/auth/register router.post( "/register", validateBody(registerSchema), @@ -43,26 +45,40 @@ router.post( asyncHandler(resetPasswordController) ); -router.post("/refresh-token", asyncHandler(refreshTokenController)); +router.post( + "/refresh-token", + csrfMiddleware, + asyncHandler(refreshTokenController) +); router.post( "/email/verification", - auth, + authMiddleware, + requireActiveAccount, asyncHandler(emailVerificationController) ); router.post( "/email/verify", + authMiddleware, + requireActiveAccount, validateBody(verifyEmailSchema), asyncHandler(verifyEmailController) ); router.post( "/email/verify-change", - validateBody(verifyEmailSchema), + authMiddleware, + requireActiveAccount, + 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 8f2c288..54f4350 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -1,10 +1,12 @@ import jwt from "jsonwebtoken"; import bcrypt from "bcrypt"; import crypto from "crypto"; -import mongoose, { ObjectIdSchemaDefinition } from "mongoose"; +import mongoose, { Types } from "mongoose"; +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 { + compareHashTokens, generateAccessToken, generateCsrfToken, generateRefreshToken, @@ -12,70 +14,55 @@ import { hashToken, verifyToken, } from "@utils/tokens.js"; -import transporter from "config/mail.js"; -import type { - LoginInput, - RegisterInput, - ResetPasswordInput, -} from "@validation/auth.schema.js"; +import type { LoginInput, RegisterInput } 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"; import { + BadRequestError, ConflictError, + ForbiddenError, InternalServerError, NotFoundError, UnauthenticatedError, } from "@middleware/error/index.js"; -import { emailVerificationTemplate } from "./emails/templates/emailVerification.js"; -import { passwordChangedNotificationTemplate } from "./emails/passwordChangedNotification.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"; type LoginInputWithMeta = LoginInput & { userAgent: string; ip: string | string[] | undefined; }; - -type LoginOutput = { +type SignOutput = { user: User; accessToken: string; refreshToken: string; csrfToken: string; + accountStatus?: 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 { +): Promise { const { email, password, displayName, username, userAgent, ip } = input; - // Check if email exists - const existing = await UserModel.findOne({ email }); + 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); @@ -83,66 +70,74 @@ export async function registerUser( 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], - }); - - 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 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] - ); + const session = await mongoose.startSession(); + session.startTransaction(); try { - transporter.sendMail({ - from: process.env.EMAIL_FROM, - to: email, - subject, - text, - html, - }); + const result: User[] = await UserModel.create( + [ + { + email, + passwordHash, + username: username + ? username.toLowerCase() + : `${await createUsername(email)}`, + displayName: displayName ?? email.split("@")[0], + }, + ], + { session } + ); + const user: User = result[0]; + + const sessionId: string = crypto.randomBytes(32).toString("hex"); + const accessToken = generateAccessToken(user._id, sessionId); + const refreshToken = generateRefreshToken(user._id, sessionId); + const csrfToken = generateCsrfToken(); + 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[0], + lat: ipData.latitude, + lng: ipData.longitude, + isp: ipData.asnOrganisation, + refreshTokenHash: hashToken(refreshToken), + csrfTokenHash: hashToken(csrfToken), + createdAt: Date.now(), + lastUsedAt: Date.now(), + }, + ], + { session } + ); + await session.commitTransaction(); + // enqueue welcome email + sendWelcomeEmail(user.email, user.displayName, user.username); + return { user, accessToken, refreshToken, csrfToken }; } catch (err) { + await session.abortTransaction(); const errorMessage = err instanceof Error ? err.message : String(err); - throw new InternalServerError( - "Failed to send new account email", - errorMessage - ); + console.error(err); + throw new InternalServerError("Failed to register user", errorMessage); + } finally { + session.endSession(); } - return { user, accessToken, refreshToken, csrfToken }; } export async function loginUser( input: LoginInputWithMeta -): Promise { +): Promise { const { email, password, userAgent, ip } = input; - const user = await UserModel.findOne({ email }).select("+passwordHash"); + const user: User | null = await UserModel.findOne({ email }).select( + "+passwordHash +changeHistory" + ); if (!user) { throw new UnauthenticatedError("Email or Password does not match!"); } @@ -151,57 +146,158 @@ export async function loginUser( if (!passedTest) { throw new UnauthenticatedError("Email or Password does not match!"); } + const lastStatusChange = user.changeHistory + .filter((change) => change.field === "accountStatus") + .sort((a, b) => b.at.getTime() - a.at.getTime())[0]; + if (user.accountStatus === "banned") { + throw new ForbiddenError("This account has been permanently banned."); + } + if (user.accountStatus === "deactive" || user.accountStatus === "suspend") { + if (lastStatusChange.via === "admin") { + throw new ForbiddenError( + `Account is ${user.accountStatus} by admin. Please contact support.` + ); + } + } 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({ + const accessToken = generateAccessToken(user._id, sessionId); + const refreshToken = generateRefreshToken(user._id, sessionId); + const csrfToken = generateCsrfToken(); + 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], + timezone: ipData.timeZones[0], lat: ipData.latitude, lng: ipData.longitude, - isp: ipData.asnOrganisation, - + isp: ipData.asnOrganization, + refreshTokenHash: hashToken(refreshToken), + csrfTokenHash: hashToken(csrfToken), createdAt: Date.now(), lastUsedAt: Date.now(), }); - const accessToken = generateAccessToken(user._id, sessionId); - const refreshToken = generateRefreshToken(user._id, sessionId); - const csrfToken = generateCsrfToken(); return { user, accessToken, refreshToken, csrfToken }; } +export async function refreshTokens( + refreshToken: string, + userAgent: string, + ip: string | string[] | undefined +): 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 session = await SessionModel.findOne({ + sessionId: decoded.sessionId, + userId: decoded.userId, + }).select("+refreshTokenHash +valid +revokedAt"); + + const user: User | null = await UserModel.findOne({ + _id: decoded.userId, + }); + + if ( + !decoded || + !user || + !session || + !session.valid || + session.revokedAt || + !session.refreshTokenHash + ) { + throw new UnauthenticatedError("Authentication failed"); + } + + const refreshCookieHash = hashToken(refreshToken); + const isValidToken = compareHashTokens( + refreshCookieHash, + session.refreshTokenHash + ); + + if ( + !isValidToken || + // session.userAgent !== userAgent || + // session.country !== ipData.countryName || + user.accountStatus !== "active" + ) { + await SessionModel.updateOne( + { _id: session._id }, + { valid: false, revokedAt: new Date() } + ).exec(); + throw new UnauthenticatedError( + "Authentication failed:Session Revoked due to malicious behaviour" + ); + } + + const accessToken = generateAccessToken(user._id, session.sessionId); + const newRefreshToken = generateRefreshToken(user._id, session.sessionId); + const csrfToken = generateCsrfToken(); + + + await SessionModel.updateOne( + { _id: session._id }, + { + lastUsedAt: new Date(), + refreshTokenHash: hashToken(newRefreshToken), + csrfTokenHash: hashToken(csrfToken), + } + ) + + return { accessToken, refreshToken: newRefreshToken, csrfToken }; +} + 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() }; - user.changeHistory.push({ - field: "password", - by: user._id, - reason: "User requested password reset", - at: new Date(), - via: "user", - }); - 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 @@ -209,69 +305,83 @@ export async function createPasswordResetRequest(email: string) { 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({ + const user: User | null = await UserModel.findOne({ "passwordReset.tokenHash": hash, - }).select("+passwordReset +passwordHash"); + }).select("+passwordReset +passwordHash +changeHistory +accountStatus"); if ( !user || !user.passwordReset?.tokenHash || - !user.passwordReset.expiresAt + !user.passwordReset.expiresAt || + user.accountStatus !== "active" ) { - throw new ConflictError("Invalid or expired token"); // generic message OK + throw new BadRequestError("Invalid or expired token"); } - if (user.passwordReset.expiresAt.getTime() < Date.now()) { + + const removePasswordReset = async () => { user.passwordReset = undefined; await user.save(); - throw new ConflictError("Invalid or expired token"); + throw new BadRequestError("Invalid or expired token"); + }; + + if (user.passwordReset.expiresAt.getTime() < Date.now()) { + removePasswordReset(); } const isValid = verifyToken(rawToken, user.passwordReset.tokenHash); if (!isValid) { - throw new ConflictError("Invalid or expired token"); + removePasswordReset(); } + const hashedPassword = await bcrypt.hash(newPassword, 10); + const session = await mongoose.startSession(); session.startTransaction(); try { - user.passwordHash = hashedPassword; - user.passwordReset = undefined; - user.lastPasswordChangeAt = new Date(); - user.changeHistory.push({ - field: "password", - by: user._id, - from: null, - to: null, - reason: "User reset the password via password reset", - at: new Date(), - via: "user", - }); - await user.save({ session }); - await SessionModel.deleteMany({ userId: user._id }, { session }); + 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 } + ); + await SessionModel.updateMany( + { userId: user._id }, + { + valid: false, + revokedAt: new Date(), + }, + { session } + ); + await session.commitTransaction(); + // enqueue password changed email + sendPasswordUpdatedEmail(user); + return; } catch (err) { await session.abortTransaction(); const errorMessage = err instanceof Error ? err.message : String(err); @@ -279,66 +389,14 @@ export async function resetPassword(rawToken: string, newPassword: string) { } 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 - ); - } - 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 (!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 }; -} - -export async function emailVerification( - userId: ObjectIdSchemaDefinition +export async function sendEmailVerification( + userId: Types.ObjectId ): Promise { - const user = await UserModel.findById(userId); + const user: User | null = await UserModel.findById(userId).select( + "+emailVerification +changeHistory" + ); if (!user) { throw new NotFoundError("User not found"); } @@ -351,44 +409,43 @@ export async function emailVerification( process.env.APP_URL }/verify-email?token=${encodeURIComponent(token.raw)}`; - const { subject, text, html } = emailVerificationTemplate( - user.displayName ?? user.username ?? null, - verifyEmailUrl + 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(), - }; - user.changeHistory.push({ - field: "email", - by: user._id, - reason: "User requested email verification", - at: new Date(), - via: "user", - }); - 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({ + const user: User | null = await UserModel.findOne({ "emailVerification.tokenHash": hash, - }).select("+emailVerification"); + }).select("+emailVerification +changeHistory"); if (!user) { - return; + throw new BadRequestError("Invalid or expired verification token"); } if ( @@ -399,73 +456,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 ); if (!isValid) { - throw new ConflictError("Invalid or expired verification token"); + throw new BadRequestError("Invalid or expired verification token"); } - user.emailVerified = true; - user.emailVerification = undefined; - user.changeHistory.push({ - field: "email", - by: user._id, - reason: "User verified their email", - at: new Date(), - via: "user", - }); - 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({ + const user: User | null = await UserModel.findOne({ "pendingEmailChange.tokenHash": hash, }).select("+pendingEmailChange +changeHistory"); if (!user) { - return; + throw new BadRequestError("Invalid or expired verification token"); } if ( !user.pendingEmailChange || !user.pendingEmailChange.expiresAt || user.pendingEmailChange.expiresAt!.getTime() < Date.now() || !user.pendingEmailChange.tokenHash || - !user.pendingEmailChange.newEmail + !user.pendingEmailChange.newEmail || + !user.pendingEmailChange.code ) { user.pendingEmailChange = 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.pendingEmailChange.tokenHash ); if (!isValid) { - throw new ConflictError("Invalid or expired verification token"); + 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"); } 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 verified 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 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 } + ); + + await SessionModel.updateMany( + { userId: user._id, sessionId: { $ne: currentSessionId } }, + { + valid: false, + revokedAt: new Date(), + }, + { session } + ); await session.commitTransaction(); } catch (error) { await session.abortTransaction(); @@ -478,7 +576,6 @@ export async function verifyUpdateEmail( } finally { session.endSession(); } - return; } @@ -495,12 +592,13 @@ export async function logoutUser(refreshToken: string) { const session = await SessionModel.findOne({ sessionId: decoded.sessionId, userId: decoded.userId, + valid: true, }); if (!session) { throw new NotFoundError("Session not found"); } session.revokedAt = new Date(); + session.valid = false; await session.save(); - return; } diff --git a/src/modules/project/project.controller.ts b/src/modules/project/project.controller.ts index e69de29..1e7099f 100644 --- a/src/modules/project/project.controller.ts +++ b/src/modules/project/project.controller.ts @@ -0,0 +1,194 @@ +import { Request, Response } from "express"; +import { + createProject, + deleteProjectById, + getArchivedProjects, + getDeletedProjects, + getProjectById, + getProjects, + restoreManyProjectsByIds, + restoreProjectById, + unarchiveManyProjectsByIds, + unarchiveProjectById, + updateProjectById, + updateProjectStatus, + updateProjectVisibility, +} from "./project.service.js"; +import { Types } from "mongoose"; +import { + CreateProjectInput, + UpdateProjectInput, + UpdateManyIdsInput, +} from "@validation/project.schema.js"; +import { paginationResponse } from "@utils/paginationResponse.js"; +import { PaginatedRequest } from "types/RequestTypes.js"; + +export const getProjectsController = async (req: Request, res: Response) => { + const {pagination, sorting} = (req as PaginatedRequest); + const [projects, total] = await getProjects( + req.user?._id!, + 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, sorting} = (req as PaginatedRequest); + const [projects, total] = await getDeletedProjects( + req.user?._id!, + 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, sorting} = (req as PaginatedRequest); + const [projects, total] = await getArchivedProjects( + req.user?._id!, + pagination, + sorting + ); + const paginationRes = paginationResponse(pagination, total as number); + return res.status(200).json({ + items: projects, + pagination: { + ...paginationRes, + }, + }); +}; + +export const postProjectController = async (req: Request, res: Response) => { + const input = (req as unknown as { validatedBody?: CreateProjectInput }) + .validatedBody!; + const newProject = await createProject(req.user?._id!, 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 project = await getProjectById(projectId, req.user?._id!); + return res.status(200).json(project); +}; + +export const updateProjectByIdController = async ( + req: Request, + res: Response +) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const updates = (req as unknown as { validatedBody?: UpdateProjectInput }) + .validatedBody!; + const updatedProject = await updateProjectById( + projectId, + req.user?._id!, + 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 response = await deleteProjectById(projectId, req.user?._id!); + return res.status(200).json(response); +}; + +export const updateProjectStatusController = async ( + req: Request, + res: Response +) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const { status } = req.body; + console.log("Status:", status, "Project ID:", projectId); + const updatedProject = await updateProjectStatus( + projectId, + req.user?._id!, + 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 updatedProject = await updateProjectVisibility( + projectId, + req.user?._id!, + 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 restoredProject = await restoreProjectById(projectId, req.user?._id!); + return res.status(200).json(restoredProject); +}; + +export const unarchiveProjectByIdController = async ( + req: Request, + res: Response +) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const unarchivedProject = await unarchiveProjectById( + projectId, + req.user?._id! + ); + return res.status(200).json(unarchivedProject); +}; + +export const restoreManyProjectsController = async ( + req: Request, + res: Response +) => { + const { projectIds } = ( + req as unknown as { validatedBody?: UpdateManyIdsInput } + ).validatedBody!; + const restoredProjects = await restoreManyProjectsByIds( + projectIds, + req.user?._id! + ); + + return res.status(200).json(restoredProjects); +}; + +export const unarchiveManyProjectsController = async ( + req: Request, + res: Response +) => { + const { projectIds } = ( + req as unknown as { validatedBody?: UpdateManyIdsInput } + ).validatedBody!; + const unarchivedProjects = await unarchiveManyProjectsByIds( + projectIds, + req.user?._id! + ); + + return res.status(200).json(unarchivedProjects); +}; diff --git a/src/modules/project/project.routes.ts b/src/modules/project/project.routes.ts index e69de29..94ede3c 100644 --- a/src/modules/project/project.routes.ts +++ b/src/modules/project/project.routes.ts @@ -0,0 +1,96 @@ +import { Router } from "express"; +import { + deleteProjectByIdController, + getArchivedProjectsController, + getDeletedProjectsController, + getProjectByIdController, + getProjectsController, + postProjectController, + restoreManyProjectsController, + restoreProjectByIdController, + unarchiveManyProjectsController, + unarchiveProjectByIdController, + updateProjectByIdController, + updateProjectStatusController, + updateProjectVisibilityController, +} from "./project.controller.js"; +import { asyncHandler } from "@utils/asyncHandler.js"; +import { validateBody } from "@validation/validateBody.js"; +import { + createProjectSchema, + projectIdParamSchema, + updateManyIdsSchema, + updateProjectSchema, + updateProjectStatusSchema, + updateProjectVisibilitySchema, +} from "@validation/project.schema.js"; +import { validateParams } from "@validation/validateParams.js"; + +const router = Router(); + +router.get("/", asyncHandler(getProjectsController)); +router.post( + "/", + validateBody(createProjectSchema), + asyncHandler(postProjectController) +); +router.get("/deleted", asyncHandler(getDeletedProjectsController)); +router.get("/archived", asyncHandler(getArchivedProjectsController)); +router.patch( + "/restore", + validateBody(updateManyIdsSchema), + asyncHandler(restoreManyProjectsController) +); +router.patch( + "/unarchive", + validateBody(updateManyIdsSchema), + asyncHandler(unarchiveManyProjectsController) +); + + + +router.get( + "/:projectId", + validateParams(projectIdParamSchema), + asyncHandler(getProjectByIdController) +); +router.patch( + "/:projectId", + validateParams(projectIdParamSchema), + validateBody(updateProjectSchema), + asyncHandler(updateProjectByIdController) +); +router.delete( + "/:projectId", + validateParams(projectIdParamSchema), + asyncHandler(deleteProjectByIdController) +); +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) +); +// Routes which go from a single project +// router.use("/projects/:projectId", contextRouter); +// router.use("/projects/:projectId", storyRouter); +// router.use("/projects/:projectId", assetRouter); +// router.use("/projects/:projectId", videosRouter); // finally videos routes + +export default router; diff --git a/src/modules/project/project.service.ts b/src/modules/project/project.service.ts index e69de29..f4b7ce7 100644 --- a/src/modules/project/project.service.ts +++ b/src/modules/project/project.service.ts @@ -0,0 +1,269 @@ +import { + BadRequestError, + InternalServerError, + NotFoundError, +} from "@middleware/error/index.js"; +import type { + CreateProjectInput, + UpdateProjectInput, +} from "@validation/project.schema.js"; +import { ProjectModel, ProjectType } from "@models/Project.js"; +import { + sanitizeProjectResponse, + sanitizeProjects, +} from "@utils/sanitizeProjectResponse.js"; +import { 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"; + +export async function getProjects( + userId: Types.ObjectId | string, + pagination: Pagination, + sorting: Sorting +) { + const filter = { userId, status: { $in: ACTIVE_STATUSES } }; + 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 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 createProject( + userId: Types.ObjectId | string, + projectInput: CreateProjectInput +) { + const newProject = await ProjectModel.create({ + userId: userId, + title: projectInput.title, + description: projectInput.description, + visibility: projectInput.visibility || "private", + status: projectInput.status, + }); + 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 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 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; +} + +export const restoreManyProjectsByIds = async ( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string +) => { + const result = await transitionManyProjectsByIds( + projectIds, + userId, + "delete", + "active" + ); + return result; +}; + +export const unarchiveManyProjectsByIds = async ( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string +) => { + const result = await transitionManyProjectsByIds( + projectIds, + userId, + "archive", + "active" + ); + return result; +}; + +// Future Possible Functions: ArchiveManyProjectsByIds, DeleteManyProjectsByIds +// Remember to handle visibility changes when archiving or deleting projects \ No newline at end of file diff --git a/src/modules/project/rules/projectStatus.ts b/src/modules/project/rules/projectStatus.ts new file mode 100644 index 0000000..891c566 --- /dev/null +++ b/src/modules/project/rules/projectStatus.ts @@ -0,0 +1,30 @@ +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 = Exclude< + ProjectStatus, + "draft" +>; + + +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..3b649c2 --- /dev/null +++ b/src/modules/project/utils/transitionManyProjectsByIds.ts @@ -0,0 +1,69 @@ +import { ProjectModel } from "@models/Project.js"; +import { Types } from "mongoose"; +import { TransitionableManyProjectStatus } from "../rules/projectStatus.js"; + + +export const transitionManyProjectsByIds = async ( + projectIds: (Types.ObjectId | string)[], + userId: Types.ObjectId | string, + fromStatus: TransitionableManyProjectStatus, + toStatus: TransitionableManyProjectStatus +) => { + 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 (status !== fromStatus) { + results.push({ + id: idStr, + message: `Project not in ${fromStatus} state`, + }); + 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..2a59a2d --- /dev/null +++ b/src/modules/project/utils/transitionProjectById.ts @@ -0,0 +1,47 @@ +import { 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}` + ); + } + + project.status = toStatus; + + if (toStatus === "archive" || toStatus === "delete") { + project.visibility = "private"; + } + + await project.save(); + + return sanitizeProjectResponse({ + project, + type: "getProjectById", + }); +} diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index b3cb003..70d2f87 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -1,7 +1,6 @@ import { DeleteAllSessionsType, DeleteSessionParamsType, - UpdateAccountType, 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,18 +27,12 @@ import { updatePrivacySettings, updateProfile, } from "./user.service.js"; -import { - BadRequestError, - UnauthenticatedError, -} from "@middleware/error/index.js"; +import { AuthenticatedRequest, ValidatedRequest } from "../../types/index.js"; +import { ValidatedParamsRequest } from "types/RequestTypes.js"; export const getProfileController = async (req: Request, res: Response) => { - const userId = req.user?._id; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = (req as AuthenticatedRequest).user._id; const user = await getProfile(userId); - return res.status(200).json({ id: user._id, email: user.email, @@ -54,27 +48,16 @@ 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 as AuthenticatedRequest).user._id; + const updateData = (req as ValidatedRequest).validatedBody; 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 userId = (req as AuthenticatedRequest).user._id; const avatarData = req.file; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } - if (!avatarData) { - throw new BadRequestError("Avatar file not found"); - } const updatedUser = await updateAvatar(userId, avatarData); return res.status(200).json(updatedUser); }; @@ -84,10 +67,7 @@ export const deleteAvatarController = async ( res: Response, next: NextFunction ) => { - const userId = req.user?._id; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = (req as AuthenticatedRequest).user._id; await deleteAvatar(userId); return res.status(204).send({ message: "Avatar deleted successfully", @@ -95,40 +75,26 @@ export const deleteAvatarController = async ( }; export const getSettingsController = async (req: Request, res: Response) => { - const userId = req.user?._id; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = (req as AuthenticatedRequest).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) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = (req as AuthenticatedRequest).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 UnauthenticatedError("Authentication required"); - } + const userId = (req as AuthenticatedRequest).user._id; + const sessionId = (req as AuthenticatedRequest).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 UnauthenticatedError("Authentication required"); - } - + const userId = (req as AuthenticatedRequest).user._id; const billingInfo = await getBilling(userId); return res.status(200).json(billingInfo); }; @@ -137,16 +103,11 @@ export const updateNotificationsController = async ( req: Request, res: Response ) => { - const userId = req.user?._id; - const notificationPrefs = ( - req as unknown as { validatedBody?: UpdateNotificationsType } - ).validatedBody!; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } - // Assuming updateNotifications is a service function to update notification preferences - const updatedUser = await updateNotifications(userId, notificationPrefs); + const userId = (req as AuthenticatedRequest).user._id; + const notificationPrefs = (req as ValidatedRequest) + .validatedBody; + const updatedUser = await updateNotifications(userId, notificationPrefs); return res.status(200).json({ id: updatedUser._id, notificationPrefs: updatedUser.notificationPrefs, @@ -157,13 +118,9 @@ export const updatePrivacySettingsController = async ( req: Request, res: Response ) => { - const userId = req.user?._id; - const privacyPrefs = ( - req as unknown as { validatedBody?: UpdatePrivacySettingsType } - ).validatedBody!; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = (req as AuthenticatedRequest).user._id; + const privacyPrefs = (req as ValidatedRequest) + .validatedBody!; const updatedUser = await updatePrivacySettings(userId, privacyPrefs); return res.status(200).json({ id: updatedUser._id, @@ -172,13 +129,11 @@ export const updatePrivacySettingsController = async ( }; export const updatePasswordController = async (req: Request, res: Response) => { - const userId = req.user?._id; + const userId = (req as AuthenticatedRequest).user._id; const { currentPassword, newPassword } = ( - req as unknown as { validatedBody?: UpdatePasswordType } - ).validatedBody!; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + req as ValidatedRequest + ).validatedBody; + // TODO : Ask user if wanted to remove all sessions except current await updatePassword(userId, currentPassword, newPassword); return res.status(200).json({ @@ -187,12 +142,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 as AuthenticatedRequest).user._id; + const { newEmail } = (req as ValidatedRequest).validatedBody; + await updateEmail(userId, newEmail); return res.status(200).json({ message: "Email update initiated. Please verify your new email address.", @@ -200,71 +152,57 @@ export const updateEmailController = async (req: Request, res: Response) => { }; export const deleteSessionController = async (req: Request, res: Response) => { - const userId = req.user?._id; - const { sessionId } = ( - req as unknown as { validatedParams?: DeleteSessionParamsType } - ).validatedParams!; - const currentSession = req.sessionId; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } + const userId = (req as AuthenticatedRequest).user._id; + const { sessionId } = (req as ValidatedParamsRequest) + .validatedParams; + const currentSession = (req as AuthenticatedRequest).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 as unknown as { validatedBody?: DeleteAllSessionsType } - ).validatedBody!; - const userId = req.user?._id; - const currentSession = req.sessionId; - - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } - if (!currentSession) { - throw new UnauthenticatedError("Authentication required"); - } + const { removeCurrent } = (req as ValidatedRequest) + .validatedBody; + const userId = (req as AuthenticatedRequest).user._id; + const currentSession = (req as AuthenticatedRequest).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 UnauthenticatedError("Authentication required"); - } - // Implementation for deleting user account - await deleteAccount(userId); - return res.status(204).send(); -}; +export const deactivateAccountController = async ( + req: Request, + res: Response +) => { + const userId = (req as AuthenticatedRequest).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 as unknown as { validatedBody?: UpdateAccountType } - ).validatedBody!; - if (!userId) { - throw new UnauthenticatedError("Authentication required"); - } - if (!sessionId) { - throw new UnauthenticatedError("Authentication required"); - } - 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 as AuthenticatedRequest).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 as AuthenticatedRequest).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 c4493f6..980f4ae 100644 --- a/src/modules/user/user.routes.ts +++ b/src/modules/user/user.routes.ts @@ -1,7 +1,6 @@ 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 { csrfMiddleware } from "@middleware/security/requireCsrf.js"; import { deleteAvatarController, getBillingController, @@ -18,33 +17,34 @@ import { deleteSessionController, deleteAllSessionsController, deleteAccountController, - updateAccountController, + deactivateAccountController, } 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/avatarUpload.js"; +import { requireActiveAccount } from "@middleware/security/accountStatusMiddleware.js"; const router = Router(); -router.use(auth); +router.patch("/account/reactivate", asyncHandler(deleteAccountController)); + +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.use(csrfMiddleware); router.patch( "/profile", validateBody(updateProfileSchema), @@ -89,11 +89,7 @@ router.delete( ); // 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)); export default router; diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 51ca91a..17a4543 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -1,6 +1,7 @@ -import { ACCOUNT_STATUSES, AccountStatus } from "constants/accountStatus.js"; +import { AccountStatus } from "constants/authConsts.js"; import bcrypt from "bcrypt"; import { + BadRequestError, ConflictError, ForbiddenError, InternalServerError, @@ -14,17 +15,24 @@ import { UpdateNotificationsType, UpdatePrivacySettingsType, } from "@validation/user.schema.js"; -import mongoose, { ObjectIdSchemaDefinition } from "mongoose"; +import mongoose, { Types } 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" - ); +import { verifyUpdatedEmailTemplate } from "../../utils/emails/templates/verifyUpdatedEmail.js"; +import sendUpdateEmailLink from "@utils/emails/sender/sendUpdateEmaiLink.js"; +import sendOldEmailVerificationForEmailUpdate from "@utils/emails/sender/sendOldEmailVerificationForEmailUpdate.js"; + +export const getProfile = async (userId: Types.ObjectId): 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 NotFoundError("User not found"); } @@ -32,7 +40,7 @@ export const getProfile = async ( }; export const updateProfile = async ( - userId: ObjectIdSchemaDefinition, + userId: Types.ObjectId, updateData: Partial ): Promise> => { const user = await UserModel.findByIdAndUpdate(userId, updateData, { @@ -47,9 +55,12 @@ export const updateProfile = async ( }; export const updateAvatar = async ( - userId: ObjectIdSchemaDefinition, - avatarData: Express.Multer.File + userId: Types.ObjectId, + avatarData: Express.Multer.File | undefined ): Promise> => { + 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 @@ -68,9 +79,7 @@ export const updateAvatar = async ( return resUser; }; -export const deleteAvatar = async ( - userId: ObjectIdSchemaDefinition -): Promise => { +export const deleteAvatar = async (userId: Types.ObjectId): Promise => { const user = await UserModel.findById(userId); if (!user) { throw new NotFoundError("User not found"); @@ -96,7 +105,7 @@ export const deleteAvatar = async ( }; export const getSettings = async ( - userId: ObjectIdSchemaDefinition + userId: Types.ObjectId ): Promise> => { const user = await UserModel.findById(userId).select( "emailNotifications privacySettings" @@ -109,7 +118,7 @@ export const getSettings = async ( }; export const getSecurity = async ( - userId: ObjectIdSchemaDefinition + userId: Types.ObjectId ): Promise> => { const user = await UserModel.findById(userId).select( "email phoneNumber passwordHash emailVerified phoneVerified lastPasswordChangeAt twoFactorEnabled oauthProviders" @@ -122,7 +131,7 @@ export const getSecurity = async ( }; export const getSessions = async ( - userId: ObjectIdSchemaDefinition, + userId: Types.ObjectId, sessioId: string ): Promise< Array<{ @@ -137,9 +146,6 @@ 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 { @@ -162,7 +168,7 @@ export const getSessions = async ( }; export const getBilling = async ( - userId: ObjectIdSchemaDefinition + userId: Types.ObjectId ): Promise> => { const user = await UserModel.findById(userId).select("plan billingInfo"); if (!user) { @@ -173,7 +179,7 @@ export const getBilling = async ( }; export const updateNotifications = async ( - userId: ObjectIdSchemaDefinition, + userId: Types.ObjectId, notificationPrefs: UpdateNotificationsType ): Promise> => { const update: Record = {}; @@ -204,7 +210,7 @@ export const updateNotifications = async ( }; export const updatePrivacySettings = async ( - userId: ObjectIdSchemaDefinition, + userId: Types.ObjectId, privacyPrefs: UpdatePrivacySettingsType ): Promise> => { const update: Record = {}; @@ -235,7 +241,7 @@ export const updatePrivacySettings = async ( }; export const updatePassword = async ( - userId: ObjectIdSchemaDefinition, + userId: Types.ObjectId, currentPassword: string, newPassword: string ): Promise => { @@ -267,7 +273,7 @@ export const updatePassword = async ( }; export const updateEmail = async ( - userId: ObjectIdSchemaDefinition, + userId: Types.ObjectId, newEmail: string ): Promise => { const user = await UserModel.findById(userId); @@ -282,48 +288,34 @@ export const updateEmail = async ( 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 = `${ + const updateEmailUrl = `${ 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 - ); + }/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", }; 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, + userId: Types.ObjectId, sessionId: string ): Promise => { const session = await SessionModel.findOne({ @@ -334,13 +326,18 @@ export const deleteSession = async ( if (!session) { 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: Types.ObjectId, currentSessionId: string, removeCurrent: boolean | undefined ): Promise => { @@ -348,30 +345,37 @@ 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 => { +export const deleteAccount = async (userId: Types.ObjectId): Promise => { const session = await mongoose.startSession(); + session.startTransaction(); try { - session.startTransaction(); await UserModel.findByIdAndUpdate( userId, { deletedAt: new Date(), - accountStatus: "deleted", + accountStatus: "delete", $push: { changeHistory: { - field: "accountStatus", - from: "active", - to: "deleted", - by: userId, - reason: "User deleted account", - at: new Date(), - via: "user", + $each: [ + { + field: "accountStatus", + from: "active", + to: "delete", + by: userId, + reason: "User deleted account", + at: new Date(), + via: "user", + }, + ], + $slice: -100, }, }, }, @@ -381,78 +385,91 @@ export const deleteAccount = async ( await session.commitTransaction(); } catch (err) { await session.abortTransaction(); - throw err; + throw new InternalServerError("Could not delete account", String(err)); } finally { session.endSession(); } return; }; -export const updateAccount = async ( - userId: ObjectIdSchemaDefinition, - updateData: AccountStatus, - currentSessionId: string +export const reactivateAccount = async ( + userId: Types.ObjectId ): Promise> => { const user = await UserModel.findById(userId).select("+changeHistory +role"); if (!user) { 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 ForbiddenError("Only admin can do this operation"); - } else if ( - latestStatusEvent[0] && - user.accountStatus === "disabled" && - latestStatusEvent[0].via !== "user" && - updateData === "active" - ) { - throw new ForbiddenError( - "Disabled by admin, account can only be activated by admin" - ); - } else { - updatedUser = await UserModel.findByIdAndUpdate( - userId, - { - accountStatus: updateData, - $push: { - changeHistory: { + const updatedUser = await UserModel.findByIdAndUpdate( + userId, + { + accountStatus: "active", + deletedAt: null, + $push: { + changeHistory: { + $each: [ + { field: "accountStatus", from: user.accountStatus, - to: updateData, + to: "active", by: user._id, - reason: "Account status updated", + reason: "Account reactivated", at: new Date(), via: user.role, }, - }, + ], + $slice: -100, }, - { new: true, session } - ); + }, + }, + { new: true } + ); + if (!updatedUser) { + throw new NotFoundError("User not found"); + } + const resUser = returnUserData(updatedUser, "profile"); + return resUser; +}; + +export const deactivateAccount = async ( + userId: Types.ObjectId +): Promise> => { + const user = await UserModel.findById(userId).select("+changeHistory +role"); + if (!user) { + throw new NotFoundError("User not found"); + } - await SessionModel.deleteMany( - { - userId: user._id, - sessionId: { $ne: currentSessionId }, + const session = await mongoose.startSession(); + session.startTransaction(); + try { + 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, + }, }, - { session } - ); - } + }, + { new: true, session } + ); + await SessionModel.deleteMany( + { + userId: user._id, + }, + { session } + ); await session.commitTransaction(); if (!updatedUser) { throw new NotFoundError("User not found"); @@ -461,7 +478,7 @@ export const updateAccount = async ( return resUser; } catch (err) { await session.abortTransaction(); - throw err; + throw new InternalServerError("Could not update account", String(err)); } finally { session.endSession(); } diff --git a/src/routes/api.ts b/src/routes/api.ts index 92f8010..2b6d875 100644 --- a/src/routes/api.ts +++ b/src/routes/api.ts @@ -1,10 +1,21 @@ 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 { paginationAndSortingMiddleware } from "@middleware/paginationAndSorting.js"; +import { blockBannedAccounts } from "@middleware/security/accountStatusMiddleware.js"; const apiRouter = Router(); apiRouter.use("/auth", authRouter); +apiRouter.use(authMiddleware, blockBannedAccounts); apiRouter.use("/user", userRouter); +apiRouter.use( + "/projects", + authMiddleware, + paginationAndSortingMiddleware, + projectRouter +); export default apiRouter; diff --git a/src/routes/index.ts b/src/routes/index.ts index b2910e2..50932e2 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -4,7 +4,7 @@ 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 { requestLogger } from "@middleware/loggerMiddleware.js"; import notFoundHandler from "@middleware/404/notFoundHandler.js"; import errorHandler from "@middleware/error/globalErrorHandler.js"; @@ -19,7 +19,7 @@ AppRouter.use(cors(corsOptions)); AppRouter.use(cookieParser()); // Basic logger -AppRouter.use(devLogger); +AppRouter.use(requestLogger); // Health route AppRouter.get("/health", (_req: Request, res: Response) => { 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/RequestTypes.ts b/src/types/RequestTypes.ts new file mode 100644 index 0000000..9c322f4 --- /dev/null +++ b/src/types/RequestTypes.ts @@ -0,0 +1,21 @@ +import { User } from "@models/User.js"; +import { Request } from "express"; +import { Pagination, Sorting } from "./Pagination.js"; + +export interface AuthenticatedRequest extends Request { + user: User; + sessionId: string; +} + +export interface ValidatedRequest extends Request { + validatedBody: T; +} + +export interface ValidatedParamsRequest extends Request { + validatedParams: T; +} + +export interface PaginatedRequest extends Request { + pagination: Pagination; + sorting: Sorting; +} \ No newline at end of file diff --git a/src/types/express.d.ts b/src/types/express.d.ts index 03e776c..ba85473 100644 --- a/src/types/express.d.ts +++ b/src/types/express.d.ts @@ -1,10 +1,14 @@ import { type User } from "@models/User.ts"; // whatever your user type is +import type { Pagination, Sorting } from "@middleware/paginationAndSorting.js"; declare global { namespace Express { interface Request { user?: User; sessionId?: string; + pagination?: Pagination; + sorting?: Sorting; + validatedBody?: unknown; } } } diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 0000000..9ab68b4 --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1 @@ +export type { AuthenticatedRequest, ValidatedRequest, ValidatedParamsRequest, PaginatedRequest } from "./RequestTypes.js"; 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/emails/sender/sendEmailVerificationLink.ts b/src/utils/emails/sender/sendEmailVerificationLink.ts new file mode 100644 index 0000000..ebe5aca --- /dev/null +++ b/src/utils/emails/sender/sendEmailVerificationLink.ts @@ -0,0 +1,32 @@ +import { InternalServerError } from "@middleware/error/index.js"; +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..0bb799e --- /dev/null +++ b/src/utils/emails/sender/sendResetLink.ts @@ -0,0 +1,29 @@ +import { InternalServerError } from "@middleware/error/index.js"; +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/sendUpdateEmaiLink.ts b/src/utils/emails/sender/sendUpdateEmaiLink.ts new file mode 100644 index 0000000..5a77736 --- /dev/null +++ b/src/utils/emails/sender/sendUpdateEmaiLink.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/getIpInfo.ts b/src/utils/getIpInfo.ts index 7ffd1f1..ca40b68 100644 --- a/src/utils/getIpInfo.ts +++ b/src/utils/getIpInfo.ts @@ -1,9 +1,34 @@ 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(); + const data = (await res.json()) as IpInfo; + if (!data || !data.cityName || !data.countryName) { + return { city: "Unknown", country: "Unknown" }; + } return data; } catch (e) { return { city: "Unknown", country: "Unknown" }; 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..88518d9 --- /dev/null +++ b/src/utils/paginationResponse.ts @@ -0,0 +1,13 @@ + +import { Pagination } from "types/Pagination.js"; + +export function paginationResponse(pagination: Pagination, totalItems: number) { + return { + page: pagination.page, + limit: pagination.limit, + totalItems: totalItems, + totalPages: Math.ceil(totalItems / pagination.limit), + hasNext: pagination.page * pagination.limit < totalItems, + hasPrev: pagination.page > 1, + }; +} diff --git a/src/utils/sanitizeProjectResponse.ts b/src/utils/sanitizeProjectResponse.ts new file mode 100644 index 0000000..a1e3bb0 --- /dev/null +++ b/src/utils/sanitizeProjectResponse.ts @@ -0,0 +1,48 @@ +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, + contextProfileId: project.contextProfileId, + activeStoryId: project.activeStoryId, + activeStoryGeneratedAt: project.activeStoryGeneratedAt, + 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/tokens.ts b/src/utils/tokens.ts index 285befa..2a48203 100644 --- a/src/utils/tokens.ts +++ b/src/utils/tokens.ts @@ -1,6 +1,6 @@ import jwt, { type SignOptions } from "jsonwebtoken"; import crypto from "crypto"; -import type { ObjectIdSchemaDefinition } from "mongoose"; +import type { Types } from "mongoose"; const ACCESS_TOKEN_EXPIRES_IN: SignOptions["expiresIn"] = process.env .ACCESS_TOKEN_EXPIRES_IN as SignOptions["expiresIn"]; @@ -34,6 +34,18 @@ export function verifyToken(rawToken: string, tokenHash: string) { 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,16 +53,13 @@ export function hashToken(rawToken: string) { export function generateSessionId() { return crypto.randomBytes(32).toString("hex"); } -export function generateAccessToken( - userId: ObjectIdSchemaDefinition, - sessionId: string -) { +export function generateAccessToken(userId: Types.ObjectId, sessionId: string) { return jwt.sign({ userId, sessionId }, ACCESS_TOKEN_SECRET, { expiresIn: ACCESS_TOKEN_EXPIRES_IN, }); } export function generateRefreshToken( - userId: ObjectIdSchemaDefinition, + userId: Types.ObjectId, sessionId: string ) { return jwt.sign({ userId, sessionId }, REFRESH_TOKEN_SECRET, { @@ -59,10 +68,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/auth.schema.ts b/src/validation/auth.schema.ts index 831db77..1cb2960 100644 --- a/src/validation/auth.schema.ts +++ b/src/validation/auth.schema.ts @@ -34,7 +34,11 @@ const registerSchema = z "Username may contain letters, numbers, dash and underscore only", }), - displayName: z.string().trim().min(1).max(80), + displayName: z + .string() + .trim() + .min(1, "Display name is required") + .max(80, "Display name is too long"), }) .superRefine((data, ctx) => { if (data.password !== data.confirmPassword) { @@ -47,14 +51,18 @@ const registerSchema = z }) .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({ @@ -84,11 +92,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 +112,7 @@ export type { ResetPasswordInput, ForgetPasswordInput, VerifyEmailInput, + VerifyUpdateEmailInput, }; export { loginSchema, @@ -103,28 +120,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/project.schema.ts b/src/validation/project.schema.ts index e69de29..c2064f1 100644 --- a/src/validation/project.schema.ts +++ b/src/validation/project.schema.ts @@ -0,0 +1,62 @@ +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", "archive", "delete"]), + 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 projectIdParamSchema = z + .object({ + projectId: z.string().length(24, "Invalid project ID"), + }) + .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< + typeof updateProjectVisibilitySchema +>; +export type UpdateProjectStatusInput = z.infer< + typeof updateProjectStatusSchema +>; +export type ProjectIdParam = z.infer; +export type UpdateManyIdsInput = z.infer; diff --git a/src/validation/user.schema.ts b/src/validation/user.schema.ts index f935bef..cb8aa79 100644 --- a/src/validation/user.schema.ts +++ b/src/validation/user.schema.ts @@ -1,7 +1,6 @@ // src/validation/user.schema.ts import { z } from "zod"; -import type { Request, Response, NextFunction } from "express"; -import { ACCOUNT_STATUSES } from "constants/accountStatus.js"; +import { ACCOUNT_STATUSES } from "constants/authConsts.js"; /* ------------------------- Body Schemas @@ -93,11 +92,6 @@ export const deleteSessionParamsSchema = z }) .strict(); -export const updateAccountSchema = z - .object({ - accountStatus: z.enum(ACCOUNT_STATUSES), - }) - .strict(); /* ------------------------- Types -------------------------*/ @@ -112,53 +106,7 @@ 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); - } - }; -} 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/tsconfig.json b/tsconfig.json index 44f6cc7..b4a6870 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,7 +21,7 @@ "@db/*": ["db/*"], "@models/*": ["models/*"], "@routes/*":["routes/*"], - "@validation/*":["validation/*"] + "@validation/*":["validation/*"], } }, "include": ["src"] From 846f5d7f8eb3be94dbf9bcfd3bf8563974e73d3f Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Sat, 10 Jan 2026 06:17:19 +0530 Subject: [PATCH 09/14] Added Story Module + Improve Some Auth and Modeling + DRY implementations + AI related code added --- example.env | 18 + .../Ai Vid Gen.postman_collection.json | 192 --- .../car-care-new.postman_collection.json | 447 ------- .../natours.postman_collection.json | 1072 ----------------- .../globals/workspace.postman_globals.json | 7 - src/config/corsConfig.ts | 12 +- src/constants/authConsts.ts | 12 +- src/constants/globalConts.ts | 6 + src/constants/narrationProfiles.ts | 224 ++++ src/constants/storyConsts.ts | 42 + src/constants/userConts.ts | 19 + src/libs/ai/clients/openAI.ts | 41 + src/libs/ai/constants/calculateWordLimits.ts | 36 + src/libs/ai/constants/globalSafetyRules.ts | 55 + .../ai/constants/storyGenerationFormat.ts | 29 + src/libs/ai/prompts/generateStoryPrompt.ts | 76 ++ .../generateStoryRegenerationPrompt.ts | 105 ++ .../prompts/utils/buildStoryContextSection.ts | 79 ++ .../libs/ai/utils/costEstimator.ts | 0 .../ai/utils/tokenCounter.ts} | 0 src/libs/{ => aws}/s3.ts | 0 src/middleware/auth/requireAuth.ts | 43 +- src/middleware/error/appError.ts | 17 +- src/middleware/error/globalErrorHandler.ts | 3 +- .../requireActiveAccountFresh.ts} | 0 .../security/accountStatusMiddleware.ts | 41 - .../security/requireActiveAccount.ts | 11 + src/middleware/security/requireCsrf.ts | 49 +- src/middleware/security/roles.ts | 21 - src/models/Bookmark.ts | 41 + src/models/ContextProfile.ts | 326 ++++- src/models/ContextProfileHistory.ts | 35 +- src/models/FinalVideo.ts | 2 +- src/models/Project.ts | 12 +- src/models/Scene.ts | 99 +- src/models/Session.ts | 4 +- src/models/Story.ts | 174 ++- src/modules/auth/auth.controller.ts | 55 +- src/modules/auth/auth.routes.ts | 21 +- src/modules/auth/auth.service.ts | 273 ++--- src/modules/auth/utils/createUserSession.ts | 54 + .../contextProfile.controller.ts | 31 + .../contextProfile/contextProfile.routes.ts | 17 + .../contextProfile/contextProfile.service.ts | 56 + src/modules/project/project.controller.ts | 80 +- src/modules/project/project.routes.ts | 28 +- src/modules/project/project.service.ts | 87 +- src/modules/scenes/scenes.private.routes.ts | 0 src/modules/story/story.controller.ts | 238 ++++ src/modules/story/story.private.routes.ts | 38 + src/modules/story/story.service.ts | 435 +++++++ src/modules/user/user.controller.ts | 64 +- src/modules/user/user.routes.ts | 12 +- src/modules/user/user.service.ts | 50 +- src/routes/api.ts | 24 +- src/routes/index.ts | 7 +- src/security/guards/ensureActiveAccount.ts | 9 + .../guards/getAccountBlockResponse.ts | 6 + .../policies/accountStatusResponses.ts | 48 + src/server.ts | 4 +- src/types/RequestTypes.ts | 21 - src/types/express.d.ts | 13 +- src/types/index.ts | 1 - src/utils/buildSessionMetadata.ts | 0 .../sender/sendEmailVerificationLink.ts | 1 - src/utils/emails/sender/sendResetLink.ts | 1 - ...dateEmaiLink.ts => sendUpdateEmailLink.ts} | 0 src/utils/generateAllCookieTokens.ts | 10 + src/utils/safeParseJSON.ts | 12 + src/utils/sanitizeProjectResponse.ts | 4 +- src/utils/tokens.ts | 11 +- src/validation/contextProfile.schema.ts | 55 + src/validation/project.schema.ts | 76 +- src/validation/story.schema.ts | 88 ++ src/validation/user.schema.ts | 3 +- tsconfig.json | 2 + 76 files changed, 2804 insertions(+), 2481 deletions(-) create mode 100644 example.env delete mode 100644 postman/collections/Ai Vid Gen.postman_collection.json delete mode 100644 postman/collections/car-care-new.postman_collection.json delete mode 100644 postman/collections/natours.postman_collection.json delete mode 100644 postman/globals/workspace.postman_globals.json create mode 100644 src/constants/globalConts.ts create mode 100644 src/constants/narrationProfiles.ts create mode 100644 src/constants/storyConsts.ts create mode 100644 src/constants/userConts.ts create mode 100644 src/libs/ai/clients/openAI.ts create mode 100644 src/libs/ai/constants/calculateWordLimits.ts create mode 100644 src/libs/ai/constants/globalSafetyRules.ts create mode 100644 src/libs/ai/constants/storyGenerationFormat.ts create mode 100644 src/libs/ai/prompts/generateStoryPrompt.ts create mode 100644 src/libs/ai/prompts/generateStoryRegenerationPrompt.ts create mode 100644 src/libs/ai/prompts/utils/buildStoryContextSection.ts rename postman/environments/natours => src/libs/ai/utils/costEstimator.ts (100%) rename src/{modules/scenes/scenes.routes.ts => libs/ai/utils/tokenCounter.ts} (100%) rename src/libs/{ => aws}/s3.ts (100%) rename src/{modules/story/story.routes.ts => middleware/requireActiveAccountFresh.ts} (100%) delete mode 100644 src/middleware/security/accountStatusMiddleware.ts create mode 100644 src/middleware/security/requireActiveAccount.ts delete mode 100644 src/middleware/security/roles.ts create mode 100644 src/models/Bookmark.ts create mode 100644 src/modules/auth/utils/createUserSession.ts create mode 100644 src/modules/contextProfile/contextProfile.controller.ts create mode 100644 src/modules/contextProfile/contextProfile.routes.ts create mode 100644 src/modules/contextProfile/contextProfile.service.ts create mode 100644 src/modules/scenes/scenes.private.routes.ts create mode 100644 src/modules/story/story.private.routes.ts create mode 100644 src/security/guards/ensureActiveAccount.ts create mode 100644 src/security/guards/getAccountBlockResponse.ts create mode 100644 src/security/policies/accountStatusResponses.ts delete mode 100644 src/types/RequestTypes.ts create mode 100644 src/utils/buildSessionMetadata.ts rename src/utils/emails/sender/{sendUpdateEmaiLink.ts => sendUpdateEmailLink.ts} (100%) create mode 100644 src/utils/generateAllCookieTokens.ts create mode 100644 src/utils/safeParseJSON.ts create mode 100644 src/validation/contextProfile.schema.ts 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/postman/collections/Ai Vid Gen.postman_collection.json b/postman/collections/Ai Vid Gen.postman_collection.json deleted file mode 100644 index ed44dd0..0000000 --- a/postman/collections/Ai Vid Gen.postman_collection.json +++ /dev/null @@ -1,192 +0,0 @@ -{ - "info": { - "_postman_id": "686c8ae3-4106-46cb-b479-5d833c80e93f", - "name": "Ai Vid Gen", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" - }, - "item": [ - { - "name": "{{base_url}}/projects/:projectId", - "id": "b3a36768-c57c-41af-a525-50063fd5e759", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "method": "PATCH", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"title\":\" huyasgdiujsagtyfcij\",\r\n \"status\":\"delete\",\r\n \"visibility\":\"private\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{base_url}}/projects/:projectId", - "host": [ - "{{base_url}}" - ], - "path": [ - "projects", - ":projectId" - ], - "variable": [ - { - "key": "projectId", - "value": "6943ffeaf0739e8ec0331c86", - "uuid": "0aa39b46-8347-4689-ab96-433780a82888" - } - ] - } - }, - "response": [] - }, - { - "name": "{{base_url}}/auth/refresh-token", - "id": "038c970e-2a09-48c3-a6ac-9516b300ff18", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "auth": { - "type": "noauth" - }, - "method": "POST", - "header": [ - { - "key": "X-Forwarded-For", - "value": "49.37.182.221", - "type": "text", - "uuid": "3b4f68c9-6d59-4d55-93d1-fcad469eae33" - } - ], - "body": { - "mode": "raw", - "raw": "", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{base_url}}/auth/refresh-token", - "host": [ - "{{base_url}}" - ], - "path": [ - "auth", - "refresh-token" - ] - } - }, - "response": [] - }, - { - "name": "{{base_url}}/projects/:projectId", - "id": "9686111c-4b6f-44fa-996c-a29438e26077", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "method": "PATCH", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"title\":\" huyasgdiujsagtyfcij\",\r\n \"status\":\"delete\",\r\n \"visibility\":\"private\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{base_url}}/projects/:projectId", - "host": [ - "{{base_url}}" - ], - "path": [ - "projects", - ":projectId" - ], - "variable": [ - { - "key": "projectId", - "value": "6943ffeaf0739e8ec0331c86", - "uuid": "0aa39b46-8347-4689-ab96-433780a82888" - } - ] - } - }, - "response": [] - }, - { - "name": "{{base_url}}/projects/:projectId", - "id": "05e443b9-60d3-40f8-8a1b-31fdf5a57767", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "method": "GET", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"bio\":\"Chuddu Mall\",\r\n \"links\":{\r\n \"website\":\"https://gmail.com\",\r\n \"facebook\": \"https://gmail.com\",\r\n \"instagram\":\"https://gitmail.com\"\r\n }\r\n}" - }, - "url": { - "raw": "{{base_url}}/projects/:projectId", - "host": [ - "{{base_url}}" - ], - "path": [ - "projects", - ":projectId" - ], - "variable": [ - { - "key": "projectId", - "value": "6943ffeaf0739e8ec0331c86", - "uuid": "64bcac29-bb8f-4d3b-b46c-ce58c93d989a" - } - ] - } - }, - "response": [] - }, - { - "name": "{{base_url}}/projects/:projectId", - "id": "2436b647-3a4a-4faa-8768-beb78e1da5a2", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "method": "DELETE", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"bio\":\"Chuddu Mall\",\r\n \"links\":{\r\n \"website\":\"https://gmail.com\",\r\n \"facebook\": \"https://gmail.com\",\r\n \"instagram\":\"https://gitmail.com\"\r\n }\r\n}" - }, - "url": { - "raw": "{{base_url}}/projects/:projectId", - "host": [ - "{{base_url}}" - ], - "path": [ - "projects", - ":projectId" - ], - "variable": [ - { - "key": "projectId", - "value": "69440d53032f4c583116b396", - "uuid": "81d17213-7105-428f-ba06-16d21b4c5ef7" - } - ] - } - }, - "response": [] - } - ] -} \ No newline at end of file diff --git a/postman/collections/car-care-new.postman_collection.json b/postman/collections/car-care-new.postman_collection.json deleted file mode 100644 index 5adadd7..0000000 --- a/postman/collections/car-care-new.postman_collection.json +++ /dev/null @@ -1,447 +0,0 @@ -{ - "info": { - "_postman_id": "dcf6a138-dd1d-497f-8d84-8e40279eab5c", - "name": "car-care-new", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" - }, - "item": [ - { - "name": "AWS Sign In", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "// Parse the JSON response", - "let response = pm.response.json();", - "", - "// Set the environment variable", - "pm.environment.set(\"access_token\", response.AuthenticationResult.AccessToken);", - "" - ], - "type": "text/javascript", - "id": "ac28718b-2500-452d-9dcd-81ecd0f163a8" - } - } - ], - "id": "3ad83c89-bcf8-4300-9deb-741f27a2c9b5", - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/x-amz-json-1.1", - "type": "text" - }, - { - "key": "X-Amz-Target", - "value": "AWSCognitoIdentityProviderService.InitiateAuth", - "type": "text" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"AuthFlow\": \"USER_PASSWORD_AUTH\",\n \"ClientId\": \"1uhm1plej95vc3sh4e13t6pjfg\",\n \"AuthParameters\": {\n \"USERNAME\": \"+971561256408\",\n \"PASSWORD\": \"StrongPassword123!\"\n }\n}\n", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "https://cognito-idp.me-central-1.amazonaws.com/me-central-1_UiGgOFjxy", - "protocol": "https", - "host": [ - "cognito-idp", - "me-central-1", - "amazonaws", - "com" - ], - "path": [ - "me-central-1_UiGgOFjxy" - ] - } - }, - "response": [] - }, - { - "name": "Get All Brands", - "id": "29f1d262-a768-4bb4-b6fd-afdf6cc34768", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/api/brands", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "api", - "brands" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "Get All Models for a Brand", - "id": "4f8f5c7d-6de5-4680-a890-768cc38fb7bd", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/api/carmodel/brands/4/models", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "api", - "carmodel", - "brands", - "4", - "models" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "Get All Variants for a model", - "id": "17c8d112-dc3c-4c3b-bf61-17e0e9d5f2b4", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/api/carvariant/all/car-model/1", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "api", - "carvariant", - "all", - "car-model", - "1" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "Get car Variant by car variant id", - "id": "76f917e4-bdda-4387-a227-f74a791b0c0b", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/api/carvariant/1", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "api", - "carvariant", - "1" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "Get All Region Specs", - "id": "815afaaf-551d-4898-a024-52a82e396a4b", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/api/regionspec", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "api", - "regionspec" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "Add User Car", - "id": "bbcaa5e7-ee46-48b9-9145-6a8dff20011f", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "{\n \"userId\": 1,\n \"brandId\": 4,\n \"brandName\": \"Audi\",\n \"modelId\": 1,\n \"modelName\": \"A3\",\n \"variantId\": 1,\n \"variantName\": \"Audi Q5 2.0 TFSI\",\n \"regionSpecId\": 1,\n \"regionName\": \"GCC\",\n \"makeYear\": 2024,\n \"makeMonth\": 1,\n \"chassisNumber\": \"AS/1122-2236\",\n \"plateNumber\": \"AUH29743\",\n \"carNickName\": \"Audi A3\",\n \"mileage\": 20000,\n \"mileageUnit\": \"MILES\",\n \"drivingConditionType\": \"EXTREME\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{car-care-host}}/user/cars", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "user", - "cars" - ] - } - }, - "response": [] - }, - { - "name": "Get User Car by Car Id", - "id": "dc59d5fb-7d26-4919-bf01-29efbe76a86c", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/user/cars/42", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "user", - "cars", - "42" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "update car", - "id": "b0d40778-a1f9-4f14-a846-fd489bfb72c2", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "PUT", - "header": [], - "body": { - "mode": "raw", - "raw": "{\n \"carId\": 1,\n \"chassisNumber\": \"AS/1122-2236\",\n \"plateNumber\": \"AUH297466\",\n \"carNickName\": \"Audi A3\",\n \"mileage\": 20000,\n \"mileageUnit\":\"MILES\",\n \"drivingConditionType\": \"EXTREME\"\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{car-care-host}}/user/cars", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "user", - "cars" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "Get User Cars", - "id": "7b0316f1-f0d8-4b7f-a067-eed83610a02c", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/user/cars", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "user", - "cars" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - }, - { - "name": "Get Service Schedules", - "id": "2124bc8c-bb99-4b4f-9b00-abecbf6dd2de", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{car-care-host}}/user/cars", - "host": [ - "{{car-care-host}}" - ], - "path": [ - "user", - "cars" - ], - "query": [ - { - "key": "", - "value": null, - "disabled": true - } - ] - } - }, - "response": [] - } - ] -} \ No newline at end of file diff --git a/postman/collections/natours.postman_collection.json b/postman/collections/natours.postman_collection.json deleted file mode 100644 index 9e73f2c..0000000 --- a/postman/collections/natours.postman_collection.json +++ /dev/null @@ -1,1072 +0,0 @@ -{ - "info": { - "_postman_id": "48a7c9d1-ff78-4257-a965-182a158c44b4", - "name": "natours", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" - }, - "item": [ - { - "name": "tours", - "item": [ - { - "name": "Get All Tours", - "id": "647080d1-d1a1-4356-b62b-4de9e8d25876", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [ - { - "key": "Authorization", - "value": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY3MTUwZDEwYTI3ZmNmYzE1YmVkNTY1YSIsImlhdCI6MTcyOTQzMjg0OSwiZXhwIjoxNzM3MjA4ODQ5fQ.JKWA2lz_z6d5z30MVIZJuztx4KQtU7Vh8fIG5r5hdqE", - "type": "text", - "disabled": true - } - ], - "body": { - "mode": "raw", - "raw": "", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/tours", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours" - ] - }, - "description": "### GET /api/v1/tours\n\nThis endpoint retrieves a list of tours. \n \n**Request** \nNo request body is required for this endpoint.\n\n**Request Body**\n\n- name (string, required): The name of the tour.\n \n- rating (string, required): The rating of the tour.\n \n- price (string, required): The price of the tour.\n \n\n**Response** \nThe response is a JSON object with the following schema:\n\n``` json\n{\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n },\n \"results\": {\n \"type\": \"integer\"\n },\n \"data\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"startLocation\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"_id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"duration\": {\n \"type\": \"integer\"\n },\n \"maxGroupSize\": {\n \"type\": \"integer\"\n },\n \"difficulty\": {\n \"type\": \"string\"\n },\n \"ratingsAverage\": {\n \"type\": \"number\"\n },\n \"ratingsQuantity\": {\n \"type\": \"integer\"\n },\n \"price\": {\n \"type\": \"integer\"\n },\n \"priceDiscount\": {\n \"type\": \"integer\"\n },\n \"imageCover\": {\n \"type\": \"string\"\n },\n \"images\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"createdAt\": {\n \"type\": \"string\"\n },\n \"startDates\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"secretTour\": {\n \"type\": \"boolean\"\n },\n \"guides\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"locations\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"slug\": {\n \"type\": \"string\"\n },\n \"durationWeeks\": {\n \"type\": \"integer\"\n },\n \"id\": {\n \"type\": \"string\"\n }\n }\n }\n }\n }\n}\n\n ```" - }, - "response": [] - }, - { - "name": "Get a Tour", - "id": "57d31b41-ff35-4c18-b2ad-090a45eb70ed", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "method": "GET", - "header": [], - "body": { - "mode": "raw", - "raw": "", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/tours/67253239fedc2a345921157a", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "67253239fedc2a345921157a" - ] - }, - "description": "### GET /api/v1/tours/67253239fedc2a345921157a\n\nThis endpoint retrieves details of a specific tour.\n\n**Request** \nNo request body is required for this endpoint.\n\n**Response** \nThe response will be a JSON object with the following schema:\n\n``` json\n{\n \"type\": \"object\",\n \"properties\": {\n \"status\": { \"type\": \"string\" },\n \"data\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": {\n \"type\": \"object\",\n \"properties\": {\n \"startLocation\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"type\": \"string\" },\n \"coordinates\": { \"type\": \"array\" }\n }\n },\n \"_id\": { \"type\": \"string\" },\n \"name\": { \"type\": \"string\" },\n \"duration\": { \"type\": \"number\" },\n \"maxGroupSize\": { \"type\": \"number\" },\n \"difficulty\": { \"type\": \"string\" },\n \"ratingsAverage\": { \"type\": \"number\" },\n \"ratingsQuantity\": { \"type\": \"number\" },\n \"price\": { \"type\": \"number\" },\n \"priceDiscount\": { \"type\": \"number\" },\n \"imageCover\": { \"type\": \"string\" },\n \"images\": { \"type\": \"array\" },\n \"createdAt\": { \"type\": \"string\" },\n \"startDates\": { \"type\": \"array\" },\n \"secretTour\": { \"type\": \"boolean\" },\n \"guides\": { \"type\": \"array\" },\n \"locations\": { \"type\": \"array\" },\n \"slug\": { \"type\": \"string\" },\n \"__v\": { \"type\": \"number\" },\n \"durationWeeks\": { \"type\": \"number\" },\n \"reviews\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"_id\": { \"type\": \"string\" },\n \"review\": { \"type\": \"string\" },\n \"rating\": { \"type\": \"number\" },\n \"tour\": { \"type\": \"string\" },\n \"user\": {\n \"type\": \"object\",\n \"properties\": {\n \"_id\": { \"type\": \"string\" },\n \"name\": { \"type\": \"string\" }\n }\n },\n \"createdAt\": { \"type\": \"string\" },\n \"__v\": { \"type\": \"number\" },\n \"id\": { \"type\": \"string\" }\n }\n }\n },\n \"id\": { \"type\": \"string\" }\n }\n }\n }\n }\n }\n}\n\n ```" - }, - "response": [] - }, - { - "name": "Get Tour Stats", - "id": "41dee70d-1bf0-43d0-818a-dd13cb11a76e", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "method": "GET", - "header": [], - "body": { - "mode": "raw", - "raw": "", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/tours/tour-stats", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "tour-stats" - ] - }, - "description": "### Get Tour Stats\n\nThis endpoint retrieves statistics for tours.\n\n#### Request Body\n\nThis is a GET request and does not require a request body.\n\n#### Response\n\n- **status** (string, required): The status of the response.\n \n- **data** (array, required): An array containing tour statistics.\n \n - **_id** (string, required): The ID of the tour.\n \n - **numTours** (integer, required): The number of tours.\n \n - **numRating** (integer, required): The number of ratings for the tour.\n \n - **avgRating** (integer, required): The average rating for the tour.\n \n - **avgPrice** (integer, required): The average price of the tour.\n \n - **minPrice** (integer, required): The minimum price of the tour.\n \n - **maxPrice** (integer, required): The maximum price of the tour.\n \n\n#### Example\n\n``` json\n{\n \"status\": \"\",\n \"data\": [\n {\n \"_id\": \"\",\n \"numTours\": 0,\n \"numRating\": 0,\n \"avgRating\": 0,\n \"avgPrice\": 0,\n \"minPrice\": 0,\n \"maxPrice\": 0\n }\n ]\n}\n\n ```" - }, - "response": [] - }, - { - "name": "Monthly Plan", - "id": "95285122-31a1-4015-a4d5-36f01b0be9c3", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/tours/monthly-plan/2021", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "monthly-plan", - "2021" - ] - }, - "description": "# Get Monthly Plan for Tours\n\nThis endpoint retrieves the monthly plan for tours for the year 2021.\n\n## Request\n\n- Method: GET\n \n- URL: {{URL}}/api/v1/tours/monthly-plan/2021\n \n\n## Response\n\nThe response for this request is a JSON object representing the monthly plan for tours in the year 2021. You can expect the following properties in the response:\n\n- `month`: (string) The month for which the plan is provided.\n \n- `numTours`: (number) The number of tours planned for the month.\n \n- `numReviews`: (number) The number of reviews received for the tours in the month.\n \n- `avgRating`: (number) The average rating for the tours in the month.\n \n\nExample response:\n\n``` json\n{\n \"month\": \"January\",\n \"numTours\": 10,\n \"numReviews\": 56,\n \"avgRating\": 4.5\n}\n\n ```" - }, - "response": [] - }, - { - "name": "Create Tour", - "id": "ead32a97-6003-48b4-bee9-11ffe69de6f0", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"name\": \"Test Tour tesla 1121\",\r\n \"duration\": 5,\r\n \"maxGroupSize\": 25,\r\n \"difficulty\": \"easy\",\r\n \"price\": 397,\r\n \"priceDiscount\": 300,\r\n \"imageCover\": \"tour-1-cover.jpg\"\r\n }", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/tours", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours" - ] - }, - "description": "### Create a New Tour\n\nThis endpoint is used to create a new tour.\n\n#### Request Body\n\n- name (string): The name of the tour.\n \n- duration (number): The duration of the tour in days.\n \n- maxGroupSize (number): The maximum group size for the tour.\n \n- difficulty (string): The difficulty level of the tour.\n \n- price (number): The price of the tour.\n \n- priceDiscount (number): The discount price of the tour.\n \n- imageCover (string): The cover image of the tour.\n \n\n#### Response\n\nThe response will be in JSON format with the following schema:\n\n``` json\n{\n \"status\": \"\",\n \"data\": {\n \"data\": {\n \"name\": \"\",\n \"duration\": 0,\n \"maxGroupSize\": 0,\n \"difficulty\": \"\",\n \"ratingsAverage\": 0,\n \"ratingsQuantity\": 0,\n \"price\": 0,\n \"priceDiscount\": 0,\n \"imageCover\": \"\",\n \"images\": [],\n \"createdAt\": \"\",\n \"startDates\": [],\n \"secretTour\": true,\n \"startLocation\": {\n \"type\": \"\",\n \"coordinates\": []\n },\n \"guides\": [],\n \"_id\": \"\",\n \"locations\": [],\n \"slug\": \"\",\n \"__v\": 0,\n \"durationWeeks\": 0,\n \"id\": \"\"\n }\n }\n}\n\n ```" - }, - "response": [] - }, - { - "name": "Delete Tour", - "id": "6dee8a10-7328-488c-88ae-3adbef7d6acb", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [], - "body": { - "mode": "raw", - "raw": "", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/tours/671f73da3b34e3fe4a132e12", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "671f73da3b34e3fe4a132e12" - ] - }, - "description": "This endpoint sends an HTTP DELETE request to the specified URL to delete a specific tour with the given ID. The request does not contain a request body.\n\nThe response to this request will not include a response body, but will indicate the success or failure of the deletion operation through the HTTP status code and any relevant headers." - }, - "response": [] - }, - { - "name": "Update Tour", - "id": "a21eb7a3-646e-4da8-a074-121a06ef0943", - "request": { - "method": "PATCH", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"name\": \"TEST For the factory update \",\r\n \"difficulty\": \"easy\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/tours/671ffc31db87a4fee8927187", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "671ffc31db87a4fee8927187" - ] - }, - "description": "This endpoint makes an HTTP PATCH request to update a specific tour identified by the provided ID. The request body should contain the updated tour details such as name and difficulty.\n\n### Response\n\nThe response of this request is a JSON schema representing the updated tour object." - }, - "response": [] - }, - { - "name": "Tour Within Radius", - "id": "b2a53f1a-a3d2-4c11-bc7c-a3e799717e11", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/tours/tour-within/200/center/34.111745,-118.113491/unit/mi", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "tour-within", - "200", - "center", - "34.111745,-118.113491", - "unit", - "mi" - ] - }, - "description": "This endpoint retrieves tour data within a specified distance from a geographical center point. The request should include the distance in miles, latitude, and longitude of the center point. The response will be in JSON format and will contain the schema for the tour data." - }, - "response": [] - }, - { - "name": "Distance of All tours", - "id": "d564445a-4504-4c39-ade9-b8a58a6ae71f", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/tours/distances/34.111745,-118.113491/unit/km", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "distances", - "34.111745,-118.113491", - "unit", - "km" - ] - }, - "description": "This endpoint retrieves the distances of tours from a specific location in kilometers. The response of this request is a JSON schema representing the distances of tours in kilometers." - }, - "response": [] - } - ], - "id": "ec719748-0041-432e-8a89-613d2f6b8f9b", - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "id": "d9697309-a6d5-4cf3-a5ed-2e3dc00993d6", - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "id": "10f34a2d-8a6e-490a-a287-43ded9b0d98f", - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - } - ] - }, - { - "name": "Tour/Reviews", - "item": [ - { - "name": "Create Review", - "id": "6f58d174-5ffe-47ef-8e61-201a84ae5b4f", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"rating\": 3,\r\n \"review\":\"Bhakk Bekar Nikla Salla Bekar Test\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/tours/67253239fedc2a345921157a/reviews", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "67253239fedc2a345921157a", - "reviews" - ] - } - }, - "response": [] - }, - { - "name": "Get All Reviews", - "id": "ab923947-9e97-4675-8382-7e1a3795cc3c", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/tours/5c88fa8cf4afda39709c2955/reviews", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "tours", - "5c88fa8cf4afda39709c2955", - "reviews" - ] - } - }, - "response": [] - } - ], - "id": "11e450c1-1f21-46ae-9a6e-c6e34e9abaab" - }, - { - "name": "reviews", - "item": [ - { - "name": "Post review", - "id": "df30e873-9767-492c-8db6-57530909df03", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"review\":\"lallalallalalalallalalalala\",\r\n \"rating\": 4,\r\n \"tour\": \"67253239fedc2a345921157a\",\r\n \"user\" : \"67154d2dc39c57af2e25645e\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/reviews", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "reviews" - ] - } - }, - "response": [] - }, - { - "name": "Get All Reviews", - "id": "1930f56e-6275-4f43-bff8-654d18a6e606", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/reviews/", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "reviews", - "" - ] - } - }, - "response": [] - }, - { - "name": "Delete Review", - "id": "14d21587-111a-4766-b5a2-c2997e8f95ee", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/reviews/6725360605d436ee1e7cf1d9", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "reviews", - "6725360605d436ee1e7cf1d9" - ] - } - }, - "response": [] - }, - { - "name": "Update Review", - "id": "39a3c133-6390-47ac-85ad-2256c9826ed7", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "PATCH", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"review\":\"Fool \",\r\n \"rating\":1\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/reviews/6725360605d436ee1e7cf1d9", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "reviews", - "6725360605d436ee1e7cf1d9" - ] - } - }, - "response": [] - } - ], - "id": "c46f0ceb-bb34-4038-bbff-29e643e0113f" - }, - { - "name": "users", - "item": [ - { - "name": "Get All USers", - "id": "1ebc0a6b-f5e5-47ef-a312-8b03c351a14f", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/users", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users" - ] - } - }, - "response": [] - }, - { - "name": "Update Current User", - "id": "88fd75a6-6bbc-448c-9337-e4cb90e35876", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "PATCH", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"email\": \"dono@momo.co\"\r\n ,\"name\":\"

Blah Blah Blah
\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/users/updateMe", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "updateMe" - ] - } - }, - "response": [] - }, - { - "name": "Delete Current User", - "id": "30584c8e-48b5-4208-85c4-a4e1883e38d8", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "DELETE", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/users/deleteMe", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "deleteMe" - ] - } - }, - "response": [] - }, - { - "name": "Delete User", - "id": "e2a08665-8046-4d44-b4a9-94100a8a175d", - "request": { - "method": "GET", - "header": [] - }, - "response": [] - }, - { - "name": "Get Current User", - "id": "909e219e-c7fd-46ae-b99c-ad7c0e349910", - "protocolProfileBehavior": { - "disableBodyPruning": true - }, - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "body": { - "mode": "raw", - "raw": "", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/users/me", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "me" - ] - } - }, - "response": [] - } - ], - "id": "bd1d9ee5-68b6-4829-ac50-71e85f138c02", - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "id": "bea72fed-1d27-4763-bab8-b4ae3c5315c2", - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "id": "2be820cd-6a7c-4984-bad6-164ed4215467", - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - } - ] - }, - { - "name": "Authentication", - "item": [ - { - "name": "login", - "event": [ - { - "listen": "test", - "script": { - "id": "e2cb5a69-60e4-4804-bf14-3c741bb857da", - "exec": [ - "pm.environment.set(\"jwt\", pm.response.json().token);" - ], - "type": "text/javascript", - "packages": {} - } - } - ], - "id": "b8f72b32-9d14-4a8e-b0f5-ac2493af4db0", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"email\":\"test@tetsing.son\",\r\n \"password\": \"Azeem1234\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/users/login", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "login" - ] - } - }, - "response": [] - }, - { - "name": "Sign Up", - "event": [ - { - "listen": "test", - "script": { - "id": "cb5242ec-a7f7-4c2a-807a-30784e220ddf", - "exec": [ - "pm.environment.set(\"jwt\", pm.response.json().token);" - ], - "type": "text/javascript", - "packages": {} - } - } - ], - "id": "a7d6c03d-282a-42b0-b97e-1c1d34c46881", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"name\":\"Test 2 Name\",\r\n \"email\": \"test@Tetsing.don\",\r\n \"password\":\"test12test\",\r\n \"passwordConfirm\":\"test12test\",\r\n \"passwordChangedAt\": \"2024-01-01\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/users/signup", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "signup" - ] - } - }, - "response": [] - }, - { - "name": "Forgot Password", - "id": "6be9669d-4dea-4dc4-876f-36d78b4506b9", - "request": { - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"email\":\"test@tetsing.von\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/users/forgotPassword", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "forgotPassword" - ] - } - }, - "response": [] - }, - { - "name": "Reset Password", - "event": [ - { - "listen": "test", - "script": { - "id": "6d06a8b2-8145-41ce-aa58-c4144f591e0f", - "exec": [ - "pm.environment.set(\"jwt\", pm.response.json().token);" - ], - "type": "text/javascript", - "packages": {} - } - } - ], - "id": "8a8dc136-0afb-4595-bea7-4c459f20a129", - "request": { - "method": "PATCH", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"password\":\"myluckisfucked101\",\r\n \"passwordConfirm\":\"myluckisfucked101\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/users/resetPassword/fcf9fe1f0dd01a3f9a6929e4492d04ded615cb7858c24dc1f18e3e390f199767", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "resetPassword", - "fcf9fe1f0dd01a3f9a6929e4492d04ded615cb7858c24dc1f18e3e390f199767" - ] - } - }, - "response": [] - }, - { - "name": "Update Password", - "event": [ - { - "listen": "test", - "script": { - "id": "33549756-4d86-4630-85da-29f8542ab181", - "exec": [ - "pm.environment.set(\"jwt\", pm.response.json().token);\r", - "" - ], - "type": "text/javascript", - "packages": {} - } - } - ], - "id": "8f36d52b-2ec3-48bb-891f-0119dcacb3f8", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "PATCH", - "header": [], - "body": { - "mode": "raw", - "raw": "{\r\n \"passwordCurrent\": \"KingKong10111\",\r\n \"passwordUpdate\": \"KingKong101111\",\r\n \"passwordConfirm\":\"KingKong101111\"\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "{{URL}}/api/v1/users/updatePassword", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "users", - "updatePassword" - ] - } - }, - "response": [] - } - ], - "id": "f34a6161-f02e-4e17-8abb-21cee7cfd3a2" - }, - { - "name": "Bookings", - "item": [ - { - "name": "Create Booking Session Stripe", - "id": "a05e41b5-957e-4736-928b-da371a706810", - "request": { - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "method": "GET", - "header": [], - "url": { - "raw": "{{URL}}/api/v1/bookings/checkout-session/5c88fa8cf4afda39709c2961", - "host": [ - "{{URL}}" - ], - "path": [ - "api", - "v1", - "bookings", - "checkout-session", - "5c88fa8cf4afda39709c2961" - ] - } - }, - "response": [] - }, - { - "name": "Get All The Meals", - "id": "baff3a2d-5a5e-4379-b1e3-2245f2cf2942", - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json", - "type": "text", - "disabled": true - } - ], - "body": { - "mode": "raw", - "raw": "{\r\n \"model\": \"ai/deepseek-rl-distill-llama\",\r\n \"messages\": [\r\n {\r\n \"role\": \"system\",\r\n \"content\": \"You are a Meal Plan Generator AI. Always respond ONLY in strict JSON format. Do not add any explanations, comments, or Markdown. Only return valid JSON.\"\r\n },\r\n {\r\n \"role\": \"user\",\r\n \"content\": \"Create a 1-month vegetarian meal plan for weight loss. Include weekly plans with meals (breakfast, lunch, dinner, snacks) and structure the response in JSON.\"\r\n },\r\n {\r\n \"role\": \"user\",\r\n \"content\": \"Example Input: Generate a 1-month meal plan for weight loss with the following preferences.\",\r\n \"metadata\": {\r\n \"meal_plan_duration\": \"1 Month\",\r\n \"goal\": \"Weight Loss - 5 kg\",\r\n \"preferences\": {\r\n \"diet_type\": \"Vegetarian\",\r\n \"high_protein\": true,\r\n \"low_sugar\": true,\r\n \"dairy_free\": true,\r\n \"location\": \"Delhi India\",\r\n \"budget\": \"Low to Medium\"\r\n }\r\n }\r\n },\r\n {\r\n \"role\": \"asiistant\",\r\n \"content\": \"Example Output : Please use english based on the location as english is different in every country\",\r\n \"metadata\": {\r\n \"weekly_plan\": [\r\n {\r\n \"week\": 1,\r\n \"days\": [\r\n {\r\n \"day\": \"Monday\",\r\n \"meals\": {\r\n \"breakfast\": \"Quinoa porridge with almond milk and chia seeds\",\r\n \"lunch\": \"Grilled tofu salad with mixed greens, chickpeas, and olive oil dressing\",\r\n \"dinner\": \"Stir-fried vegetables with tempeh and brown rice\",\r\n \"snacks\": [\r\n \"Handful of almonds\",\r\n \"Carrot and cucumber sticks with hummus\"\r\n ]\r\n }\r\n },\r\n {\r\n \"day\": \"Tuesday\",\r\n \"meals\": {\r\n \"breakfast\": \"Oats smoothie bowl with peanut butter and flaxseeds\",\r\n \"lunch\": \"Lentil soup with whole-grain toast\",\r\n \"dinner\": \"Vegetable quinoa with steamed broccoli\",\r\n \"snacks\": [\r\n \"Roasted chickpeas\",\r\n \"Apple slices with almond butter\"\r\n ]\r\n }\r\n }\r\n // ... Continue for remaining days of the week\r\n ]\r\n },\r\n {\r\n \"week\": 2,\r\n \"days\": [\r\n // Another week plan...\r\n ]\r\n }\r\n // ... Continue up to week 4\r\n ]\r\n }\r\n }\r\n ],\r\n \"stream\": false,\r\n \"response_format\": {\r\n \"type\": \"json_object\"\r\n }\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, - "url": { - "raw": "http://localhost:8000/api/chat", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "8000", - "path": [ - "api", - "chat" - ] - } - }, - "response": [] - } - ], - "id": "eb592ee7-94a0-4699-a564-680455f406da", - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{jwt}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "id": "faf2fb7d-54b4-43e5-a7b5-9376cb8f2b37", - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "id": "6a195d30-6dc9-4826-bfb2-b2c6f9bf5ac8", - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - } - ] - } - ] -} \ No newline at end of file diff --git a/postman/globals/workspace.postman_globals.json b/postman/globals/workspace.postman_globals.json deleted file mode 100644 index 391e574..0000000 --- a/postman/globals/workspace.postman_globals.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "id": "9434ce11-52c8-495e-9fea-5287073598ed", - "name": "Globals", - "values": [], - "_postman_variable_scope": "globals", - "_postman_exported_at": "2025-12-20T13:21:58.356Z" -} \ No newline at end of file diff --git a/src/config/corsConfig.ts b/src/config/corsConfig.ts index 01b159c..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,7 @@ 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 diff --git a/src/constants/authConsts.ts b/src/constants/authConsts.ts index d492f6f..15b196c 100644 --- a/src/constants/authConsts.ts +++ b/src/constants/authConsts.ts @@ -1,15 +1,7 @@ -// constants/accountStatus.ts -export const ACCOUNT_STATUSES = [ - "active", - "inactive", - "suspend", - "deactive", - "banned", - "delete", -] as const; +// constants/accountStatus.ts +export { ACCOUNT_STATUSES, type AccountStatus } from './userConts.js'; export const RESET_EXP_MIN = Number( process.env.PASSWORD_RESET_EXPIRES_MIN || 10 ); -export type AccountStatus = (typeof ACCOUNT_STATUSES)[number]; diff --git a/src/constants/globalConts.ts b/src/constants/globalConts.ts new file mode 100644 index 0000000..2be986f --- /dev/null +++ b/src/constants/globalConts.ts @@ -0,0 +1,6 @@ +export const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS + ? process.env.ALLOWED_ORIGINS.split(',') + : [ + process.env.DEV_CLIENT_URL || 'http://localhost:3000', + 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/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/userConts.ts b/src/constants/userConts.ts new file mode 100644 index 0000000..c27f24c --- /dev/null +++ b/src/constants/userConts.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]; \ No newline at end of file diff --git a/src/libs/ai/clients/openAI.ts b/src/libs/ai/clients/openAI.ts new file mode 100644 index 0000000..cb90de1 --- /dev/null +++ b/src/libs/ai/clients/openAI.ts @@ -0,0 +1,41 @@ +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: "system", + content: ` +You are a strict JSON generator. + +Rules: +- Output ONLY valid JSON +- No markdown +- No backticks +- No explanations +- No extra text +` + }, + { + role: "user", + content: prompt + } + ], + }), + } + ); + + 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/storyGenerationFormat.ts b/src/libs/ai/constants/storyGenerationFormat.ts new file mode 100644 index 0000000..e76659c --- /dev/null +++ b/src/libs/ai/constants/storyGenerationFormat.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 +`; \ No newline at end of file diff --git a/src/libs/ai/prompts/generateStoryPrompt.ts b/src/libs/ai/prompts/generateStoryPrompt.ts new file mode 100644 index 0000000..6932cb8 --- /dev/null +++ b/src/libs/ai/prompts/generateStoryPrompt.ts @@ -0,0 +1,76 @@ +import { ContextProfile } from "@models/ContextProfile.js"; +import { GLOBAL_SAFETY_RULES } from "../constants/globalSafetyRules.js"; +import { STORY_GENERATION_FORMAT } from "../constants/storyGenerationFormat.js"; +import { buildStoryContextSection } from "./utils/buildStoryContextSection.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 = buildStoryContextSection(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..9534d3c --- /dev/null +++ b/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts @@ -0,0 +1,105 @@ +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/storyGenerationFormat.js"; +import { buildStoryContextSection } from "./utils/buildStoryContextSection.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 = buildStoryContextSection(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/utils/buildStoryContextSection.ts b/src/libs/ai/prompts/utils/buildStoryContextSection.ts new file mode 100644 index 0000000..8d28393 --- /dev/null +++ b/src/libs/ai/prompts/utils/buildStoryContextSection.ts @@ -0,0 +1,79 @@ +import { ContextProfile } from "@models/ContextProfile.js"; + +export function buildStoryContextSection( + contextProfile?: ContextProfile | null +): string | null { + if (!contextProfile) return null; + + const lines: string[] = []; + + lines.push(` +STORY CONTEXT (BINDING — DO NOT EXPAND OR INTERPRET) +`.trim()); + + // Core narrative identity + lines.push(`Genre: ${contextProfile.genre}`); + lines.push(`Mood: ${contextProfile.mood}`); + lines.push(`Style: ${contextProfile.style}`); + lines.push(`Narrative Scope: ${contextProfile.narrativeScope}`); + + // Environment (cinematic grounding) + if (contextProfile.environment) { + lines.push( + `Environment: ${contextProfile.environment.type} (${contextProfile.environment.cameraMotion})` + ); + + if (contextProfile.environment.description) { + lines.push( + `Environment Notes: ${contextProfile.environment.description}` + ); + } + } + + // World rules (hard constraints) + if (contextProfile.worldRules) { + lines.push(` +WORLD RULES (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 (DO NOT ADD, REMOVE, OR RENAME) +${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) +${contextProfile.forbiddenElements + .map((f) => `- ${f.label} (${f.severity})`) + .join("\n")}`.trim()); + } + + // Narration profile (STYLE ONLY — NOT NUMBERS) + lines.push(` +NARRATION STYLE (DO NOT EXPOSE NUMBERS) +Tone: ${contextProfile.narrationProfile.tone} +Emotion Bias: ${contextProfile.narrationProfile.emotionBias} +Intensity Curve: ${contextProfile.narrationProfile.intensityCurve} +Pause Bias: ${contextProfile.narrationProfile.pauseBias} +Sentence Length Bias: ${contextProfile.narrationProfile.sentenceLengthBias} +Clause Density: ${contextProfile.narrationProfile.clauseDensity} +`.trim()); + + return lines.join("\n\n"); +} diff --git a/postman/environments/natours b/src/libs/ai/utils/costEstimator.ts similarity index 100% rename from postman/environments/natours rename to src/libs/ai/utils/costEstimator.ts diff --git a/src/modules/scenes/scenes.routes.ts b/src/libs/ai/utils/tokenCounter.ts similarity index 100% rename from src/modules/scenes/scenes.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 cbff4c7..25f403c 100644 --- a/src/middleware/auth/requireAuth.ts +++ b/src/middleware/auth/requireAuth.ts @@ -1,9 +1,8 @@ // 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 { UnauthenticatedError } from "@middleware/error/index.js"; +import jwt from "jsonwebtoken"; +import { UnauthenticatedError } from "@middleware/error/index.js"; +import { AccountStatus } from "@constants/userConts.js"; export const authMiddleware = async ( req: Request, @@ -22,42 +21,16 @@ export const authMiddleware = 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("Authentication required"); } - - // find user with this session - const user = await UserModel.findOne({ - _id: decoded.userId, - }); - - if (!user) { - throw new UnauthenticatedError("Authentication required"); - } - - const session = await SessionModel.findOne({ - sessionId: decoded.sessionId, - userId: decoded.userId, - valid: true, - }); - - if (!session || session.revokedAt) { - throw new UnauthenticatedError("Authentication required"); - } - - // ✅ 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/error/appError.ts b/src/middleware/error/appError.ts index 9fecc94..52b12ad 100644 --- a/src/middleware/error/appError.ts +++ b/src/middleware/error/appError.ts @@ -1,6 +1,10 @@ export class AppError extends Error { statusCode: number; code: string; + actions?: { + reason: string; + nextStep: string; + }; isOperational: boolean; details?: any; stackTrace?: string; @@ -9,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; @@ -32,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/globalErrorHandler.ts b/src/middleware/error/globalErrorHandler.ts index df41806..f58e5e4 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -24,8 +24,7 @@ const errorHandler = ( }); return res.status(err.statusCode).json(err.serialize()); - } - + } return res.status(500).json({ status: "error", message: "Internal Server Error", diff --git a/src/modules/story/story.routes.ts b/src/middleware/requireActiveAccountFresh.ts similarity index 100% rename from src/modules/story/story.routes.ts rename to src/middleware/requireActiveAccountFresh.ts diff --git a/src/middleware/security/accountStatusMiddleware.ts b/src/middleware/security/accountStatusMiddleware.ts deleted file mode 100644 index d7e8d0f..0000000 --- a/src/middleware/security/accountStatusMiddleware.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { Request, Response, NextFunction } from "express"; -import type { AuthenticatedRequest } from "types/RequestTypes.js"; -import { ForbiddenError } from "@middleware/error/index.js"; - -export function requireActiveAccount( - req: Request, - _res: Response, - next: NextFunction -) { - const status = (req as unknown as AuthenticatedRequest).user.accountStatus; - if (status !== "active") { - throw new ForbiddenError(`Account is ${status}. Reactivation required.`); - } - next(); -} - -export function blockBannedAccounts( - req: Request, - _res: Response, - next: NextFunction -) { - const status = (req as unknown as AuthenticatedRequest).user.accountStatus; - if (status === "banned") { - throw new ForbiddenError("This account has been permanently banned."); - } - - next(); -} - -export function allowOnlyInactiveAccounts( - req: Request, - _res: Response, - next: NextFunction -) { - const status = (req as unknown as AuthenticatedRequest).user.accountStatus; - - if (status === "active") { - throw new ForbiddenError("Account is already active."); - } - 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 index b5a7c23..d6c7921 100644 --- a/src/middleware/security/requireCsrf.ts +++ b/src/middleware/security/requireCsrf.ts @@ -1,35 +1,44 @@ -import type { Request, Response, NextFunction } from "express"; -import crypto from "crypto"; -import { BadRequestError } from "@middleware/error/index.js"; -import { SessionModel } from "@models/Session.js"; -import { AuthenticatedRequest } from "types/RequestTypes.js"; -import { compareHashTokens, hashToken } from "@utils/tokens.js"; +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 csrfCookie = req.cookies["csrf-token"]; - const csrfToken = req.headers["x-csrf-token"]; - if (!csrfToken || !csrfCookie) { - throw new BadRequestError( - "Invalid CSRF token" - ); - } +) => { + const unsafeMethods = ["POST", "PUT", "PATCH", "DELETE"]; +if (!unsafeMethods.includes(req.method)) { + return next(); +} +const origin = req.headers.origin; +if (!origin && !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({ - csrfTokenHash: hashToken(csrfCookie), + sessionId: req.sessionId, + valid: true, + revokedAt: null, }).select("+csrfTokenHash"); if (!session) { - throw new BadRequestError("Invalid CSRF token"); + throw new UnauthorizedError(); } - const hashCsrfToken = hashToken(csrfToken as string); - const isValid = compareHashTokens(session.csrfTokenHash, hashCsrfToken); + + const isValid = verifyToken(csrfTokenValue,session.csrfTokenHash); if (!isValid) { - throw new BadRequestError("Invalid CSRF token"); + throw new UnauthorizedError(); } - next(); + next() }; diff --git a/src/middleware/security/roles.ts b/src/middleware/security/roles.ts deleted file mode 100644 index e3baf8c..0000000 --- a/src/middleware/security/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/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/ContextProfile.ts b/src/models/ContextProfile.ts index 338c82f..feab780 100644 --- a/src/models/ContextProfile.ts +++ b/src/models/ContextProfile.ts @@ -1,42 +1,166 @@ import { Schema, model, Document, Types } from "mongoose"; -export interface VideoDefaults { - fps?: number; - quality?: string; +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 interface AudioDefaults { - voiceId?: string; // provider-specific voice identifier - gender?: "male" | "female" | "neutral"; - language?: string; // en-US, hi-IN, etc. - accent?: string; // optional locale/accent - tone?: "neutral" | "calm" | "dramatic" | "eerie"; - pacing?: "slow" | "medium" | "fast"; - emotionBias?: "flat" | "expressive" | "subtle"; +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; - name: string; // e.g. "Dark Horror Universe" - description?: string; // human-readable intent - genre?: string; // horror, sci-fi, drama - tone?: string; // dark, light, serious - mood?: string; // eerie, hopeful, tense - style?: string; // cinematic, poetic, minimal - worldRules?: string; // invariants of the universe + + projectId?: Types.ObjectId; + scope: ContextScope; + isDefaultForProject: boolean; + + name: string; + description?: string; + active: boolean; + + genre: GenreType; + mood: MoodType; + style: StyleType; + narrativeScope: NarrativeScope; + + environment: EnvironmentProfile; + + worldRules?: string; + narrativeConstraints?: string; + characters?: { name: string; description?: string; }[]; - narrativeConstraints?: string; // POV, tense, length rules - forbiddenElements?: string[]; // things AI must avoid - audioDefaults?: AudioDefaults; - videoConfigDefaults?: VideoDefaults; + forbiddenElements?: ForbiddenElement[]; - active: boolean; // active for project usage - version: number; // increments on edit + narrationProfile: NarrationProfile; // 🔒 SYSTEM-DERIVED + lastUsedAt?: Date; createdAt: Date; updatedAt: Date; } @@ -50,6 +174,24 @@ const contextProfileSchema = new Schema( index: true, }, + projectId: { + type: Schema.Types.ObjectId, + ref: "Project", + index: true, + }, + + scope: { + type: String, + enum: Object.values(ContextScope), + default: ContextScope.PROJECT, + required: true, + }, + + isDefaultForProject: { + type: Boolean, + default: false, + }, + name: { type: String, required: true, @@ -58,82 +200,134 @@ const contextProfileSchema = new Schema( description: { type: String, - maxlength: 1000, - trim: true, + maxlength: 600, + }, + + active: { + type: Boolean, + default: true, + }, + + 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, }, - genre: String, - tone: String, - mood: String, - style: String, + 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: 5000, + maxlength: 1000, + }, + + narrativeConstraints: { + type: String, + maxlength: 1000, }, characters: [ { name: { type: String, required: true }, - description: { type: String }, + description: String, }, ], - narrativeConstraints: { - type: String, - maxlength: 3000, - }, + forbiddenElements: [ + { + label: String, + severity: { + type: String, + enum: ["hard", "soft"], + default: "hard", + }, + }, + ], - forbiddenElements: { - type: [String], - default: [], - }, + narrationProfile: { + wordsPerSecond: { type: Number, required: true }, + minWordTolerance: { type: Number, required: true }, + maxWordTolerance: { type: Number, required: true }, - audioDefaults: { - voiceId: String, - gender: { + pauseBias: { type: String, - enum: ["male", "female", "neutral"], + enum: ["none", "low", "medium", "high"], + required: true, }, - language: { + + sentenceLengthBias: { type: String, + enum: ["very-short", "short", "medium", "long"], + required: true, }, - accent: { + + clauseDensity: { type: String, + enum: ["sparse", "balanced", "dense"], + required: true, }, + tone: { type: String, - enum: ["neutral", "calm", "dramatic", "eerie"], - }, - pacing: { - type: String, - enum: ["slow", "medium", "fast"], + enum: Object.values(ToneType), + required: true, }, + emotionBias: { type: String, - enum: ["flat", "expressive", "subtle"], + enum: ["flat", "subtle", "expressive"], + required: true, }, - }, - - videoConfigDefaults: { - fps: Number, - quality: String, - }, - active: { - type: Boolean, - default: true, + intensityCurve: { + type: String, + enum: Object.values(IntensityCurve), + required: true, + }, }, - - version: { - type: Number, - default: 1, + 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 -); +); \ No newline at end of file diff --git a/src/models/ContextProfileHistory.ts b/src/models/ContextProfileHistory.ts index e5bc21f..96f1760 100644 --- a/src/models/ContextProfileHistory.ts +++ b/src/models/ContextProfileHistory.ts @@ -1,5 +1,4 @@ -import { Schema, model, Document, Types } from "mongoose"; -import { VideoDefaults, AudioDefaults } from "./ContextProfile.js"; +import { Schema, model, Document, Types } from "mongoose"; export interface ContextProfileHistory extends Document { contextProfileId: Types.ObjectId; @@ -18,9 +17,7 @@ export interface ContextProfileHistory extends Document { description?: string; }[]; narrativeConstraints?: string; - forbiddenElements?: string[]; - audioDefaults?: AudioDefaults; - videoConfigDefaults?: VideoDefaults; + forbiddenElements?: string[]; }; changeReason?: string; // optional user/system note @@ -71,33 +68,7 @@ const contextProfileHistorySchema = new Schema( forbiddenElements: { type: [String], default: [], - }, - audioDefaults: { - voiceId: String, - gender: { - type: String, - enum: ["male", "female", "neutral"], - }, - language: String, - accent: String, - tone: { - type: String, - enum: ["neutral", "calm", "dramatic", "eerie"], - }, - pacing: { - type: String, - enum: ["slow", "medium", "fast"], - }, - emotionBias: { - type: String, - enum: ["flat", "expressive", "subtle"], - }, - }, - - videoConfigDefaults: { - fps: Number, - quality: String, - }, + }, }, changeReason: { diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts index ec6d7f5..1e90f44 100644 --- a/src/models/FinalVideo.ts +++ b/src/models/FinalVideo.ts @@ -67,7 +67,7 @@ const finalVideoSchema = new Schema( type: Schema.Types.ObjectId, ref: "Project", required: true, - indexe: true, + index: true, }, storyId: { type: Schema.Types.ObjectId, diff --git a/src/models/Project.ts b/src/models/Project.ts index 2a7408c..3b1a1eb 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -4,10 +4,8 @@ export interface ProjectType extends Document { title: string; description: string; status: "active" | "draft" | "archive" | "delete"; - visibility: "public" | "private"; - contextProfileId?: Types.ObjectId; - activeStoryId?: Types.ObjectId; - activeStoryGeneratedAt?: Date; + visibility: "public" | "private"; + defaultContextProfileId?: Types.ObjectId; generationCounts: { storiesGenerated: number; scenesGenerated: number; @@ -47,10 +45,8 @@ const projectSchema = new Schema( type: String, enum: ["public", "private"], default: "private", - }, - contextProfileId: { type: Schema.Types.ObjectId, ref: "ContextProfile" }, - activeStoryId: { type: Schema.Types.ObjectId, ref: "Story" }, - activeStoryGeneratedAt: { type: Date }, + }, + defaultContextProfileId: { type: Schema.Types.ObjectId, ref: "ContextProfile" }, generationCounts: { storiesGenerated: { type: Number, default: 0 }, scenesGenerated: { type: Number, default: 0 }, diff --git a/src/models/Scene.ts b/src/models/Scene.ts index 23fc4e4..457ee13 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -1,17 +1,19 @@ import { Schema, model, Document, Types } from "mongoose"; -export interface SceneAssetHistoryEntry { - assetId: Types.ObjectId; - replacedAt: Date; -} +// export interface SceneAssetHistoryEntry { +// assetId: Types.ObjectId; +// replacedAt: Date; +// } -export interface SceneEditHistoryEntry { - title?: string; - description?: string; - imagePrompt?: string; - duration?: number; - editedAt: Date; -} +// export interface SceneEditHistoryEntry { +// title?: string; +// description?: string; +// imagePrompt?: string; +// duration?: number; +// editedAt: Date; +// } + +// Put all history tracking in SceneRevision model later export interface Scene extends Document { userId: Types.ObjectId; @@ -19,15 +21,11 @@ export interface Scene extends Document { order: number; title?: string; description: string; + authorType: "ai" | "user" imagePrompt: string; - lastGeneratedAt?: Date; + videoPrompt?: string; duration?: number; - generationSource: "ai" | "manual"; - activeAssetId?: Types.ObjectId; - assetHistory: SceneAssetHistoryEntry[]; // max 3 (enforced in service too) - editHistory: SceneEditHistoryEntry[]; // max 3 (enforced in service too) - contextProfileId?: Types.ObjectId; - contextProfileVersion?: number; + activeAssetId?: Types.ObjectId; createdAt: Date; updatedAt: Date; } @@ -63,73 +61,24 @@ const sceneSchema = new Schema( type: String, required: true, }, - +authorType: { + type: String, + enum: ["ai", "user"], + default: "ai", +}, imagePrompt: { type: String, required: true, - }, - lastGeneratedAt: { - type: Date, - }, + }, duration: { type: Number, }, - - generationSource: { - type: String, - enum: ["ai", "manual"], - default: "ai", - }, - + activeAssetId: { type: Schema.Types.ObjectId, ref: "SceneAsset", }, - - assetHistory: { - type: [ - { - assetId: { - type: Schema.Types.ObjectId, - ref: "SceneAsset", - required: true, - }, - replacedAt: { - type: Date, - default: Date.now, - }, - }, - ], - default: [], - validate: { - validator: (v: SceneAssetHistoryEntry[]) => v.length <= 3, - message: "Scene assetHistory cannot exceed 3 entries", - }, - }, - editHistory: { - type: [ - { - title: { type: String }, - description: { type: String }, - imagePrompt: { type: String }, - duration: { type: Number }, - editedAt: { type: Date, default: Date.now }, - }, - ], - default: [], - validate: { - validator: (v: SceneEditHistoryEntry[]) => v.length <= 3, - message: "Scene editHistory cannot exceed 3 entries", - }, - }, - contextProfileId: { - type: Schema.Types.ObjectId, - ref: "ContextProfile", - }, - - contextProfileVersion: { - type: Number, - }, + }, { timestamps: true } ); diff --git a/src/models/Session.ts b/src/models/Session.ts index eba3062..a2f663c 100644 --- a/src/models/Session.ts +++ b/src/models/Session.ts @@ -32,6 +32,7 @@ const sessionSchema = new Schema({ 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 }, @@ -42,7 +43,8 @@ const sessionSchema = new Schema({ sessionSchema.index( { lastUsedAt: 1 }, { expireAfterSeconds: 30 * 24 * 60 * 60 } -); +); +//TTL index: automatically remove revoked sessions after 7 days sessionSchema.index( { revokedAt: 1 }, { diff --git a/src/models/Story.ts b/src/models/Story.ts index 01d4dae..3e5ff22 100644 --- a/src/models/Story.ts +++ b/src/models/Story.ts @@ -1,62 +1,38 @@ -import { User } from '@models/User.js'; -import { Schema, model, Document, Types } from "mongoose"; + import { Schema, model, Document, Types } from "mongoose"; + import { type StoryIntent, type Platform, platform, storyIntent } from "@constants/storyConsts.js"; -export interface StoryHistoryEntry { - title?: string; - content?: string; - audioAssetId?: Types.ObjectId; - editedAt: Date; -} +// export interface StoryHistoryEntry { +// title?: string; +// description?: string; +// content?: string; +// timeLimit?: number; +// editedAt: Date; +// } + +//TODO: Put all history tracking in StoryRevision model later + export interface Story extends Document { userId: Types.ObjectId; projectId?: Types.ObjectId; title: string; - content: string; - lastGeneratedAt?: Date; - audioAssetId?: Types.ObjectId; // current narration audio - backgroundAudioAssetId?: Types.ObjectId; // current background audio - effectAudioAssetIds?: Types.ObjectId[]; // effect audios - finalVideoId?: Types.ObjectId; // current Final video output - status: "active" | "rejected" | "archived"; - selected: boolean; - generationSource: "ai" | "manual"; - contextProfileId?: Types.ObjectId; - contextProfileVersion?: number; - editHistory: StoryHistoryEntry[]; // max 3 (enforced in service too) - savedBy: Types.ObjectId[]; + description: string; + content: { + summary: string; + body: string; + keywords?: string[]; + tags?: string[]; + }; + authorType: "ai" | "user"; + status: "active" | "delete" | "archive" | "draft"; + timeLimit?: number; + contextProfileId?: Types.ObjectId; + intent: StoryIntent; + platform: Platform; createdAt: Date; updatedAt: Date; } -/** - * Represents a Story document in the Cinetegrate system. - * - * A Story is the core narrative unit that drives AI video generation. It encapsulates - * the creative content along with associated media assets and generation metadata. - * - * @property {ObjectId} userId - Reference to the User who owns this story. Required and indexed for efficient queries. - * @property {ObjectId} projectId - Optional reference to the parent Project. Allows stories to be organized within projects. - * @property {string} title - The story title. Max 200 characters, trimmed whitespace. - * @property {string} content - The main narrative content. This is the primary input for AI video generation. - * @property {Date} lastGeneratedAt - Timestamp of the most recent video generation from this story. - * @property {ObjectId} audioAssetId - Reference to the primary AudioAsset (narration/voiceover). - * @property {ObjectId} backgroundAudioAssetId - Reference to background music AudioAsset. - * @property {ObjectId[]} effectAudioAssetIds - Array of references to sound effect AudioAssets. - * @property {ObjectId} finalVideoId - Reference to the generated FinalVideo output. - * @property {string} status - Story lifecycle state. Values: "active" | "rejected" | "archived". Default: "active". - * @property {boolean} selected - Flag indicating if story is selected for current workflow. Default: false. - * @property {string} generationSource - Origin of story content. Values: "ai" | "manual". Default: "ai". - * @property {ObjectId} contextProfileId - Reference to the ContextProfile used for generation. Enables version tracking and safe regeneration. - * @property {number} contextProfileVersion - Version number of the ContextProfile at time of generation. Used to detect profile changes and trigger regeneration workflows. - * @property {StoryHistoryEntry[]} editHistory - Array of up to 3 previous edits, tracking title, content, audio changes, and edit timestamps. Validates maximum 3 entries. Default: []. - * - * @remarks - * - The contextProfileId and contextProfileVersion pair work together to support safe regeneration scenarios. - * When a ContextProfile is updated, stories using older versions can be identified and re-generated with current context. - * - editHistory provides audit trail and rollback capability while maintaining storage efficiency with a strict 3-entry limit. - * - Timestamps are automatically managed for createdAt and updatedAt via the schema timestamps option. - */ const storySchema = new Schema( { userId: { @@ -76,76 +52,66 @@ const storySchema = new Schema( maxlength: 200, required: true, }, - content: { + description: { type: String, + trim: true, + maxlength: 1000, required: true, }, - lastGeneratedAt: { - type: Date, - }, - audioAssetId: { - type: Schema.Types.ObjectId, - ref: "AudioAsset", - }, - backgroundAudioAssetId: { - type: Schema.Types.ObjectId, - ref: "AudioAsset", - }, - effectAudioAssetIds: [ - { - type: Schema.Types.ObjectId, - ref: "AudioAsset", + content: { + body: { + type: String, + default: "", + }, + summary: { + type: String, + default: "", + }, + keywords: { + type: [String], + default: [], + }, + tags: { + type: [String], + default: [], }, - ], - finalVideoId: { - type: Schema.Types.ObjectId, - ref: "FinalVideo", }, - status: { + authorType: { type: String, - enum: ["active", "rejected", "archived"], - default: "active", - }, - selected: { - type: Boolean, - default: false, + enum: ["ai", "user"], + default: "ai", }, - generationSource: { + status: { type: String, - enum: ["ai", "manual"], - default: "ai", + enum: ["active", "archive", "delete", "draft"], + default: "active", + }, + timeLimit: { + type: Number, }, contextProfileId: { type: Schema.Types.ObjectId, ref: "ContextProfile", - }, - contextProfileVersion: { - type: Number, - }, - editHistory: { - type: [ - { - title: { type: String }, - content: { type: String }, - audioAssetId: { - type: Schema.Types.ObjectId, - ref: "AudioAsset", - }, - editedAt: { type: Date, default: Date.now }, - }, + }, + intent: { + type: String, + enum: [ + ...storyIntent ], - default: [], - validate: { - validator: (v: StoryHistoryEntry[]) => v.length <= 3, - message: "Story editHistory cannot exceed 3 entries", - }, + required: true, + default: "short-form", + }, + platform: { + type: String, + enum: [...platform], + required: true, + default: "youtube", }, - savedBy:[{ - type: Schema.Types.ObjectId, - ref: "User" - }] }, { timestamps: true } ); -export const StoryModel = model("Story", storySchema); +storySchema.index({ userId: 1, createdAt: -1 }); +storySchema.index({ userId: 1, projectId: 1, createdAt: -1 }); + +export const StoryModel = model("Story", storySchema); \ No newline at end of file diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index ceeb95e..9123a90 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -1,4 +1,3 @@ -import { AccountStatus } from "constants/authConsts.js"; import type { CookieOptions } from "express"; import type { Request, Response } from "express"; import { @@ -18,8 +17,7 @@ import type { ForgetPasswordInput, VerifyEmailInput, VerifyUpdateEmailInput, -} from "@validation/auth.schema.js"; -import { AuthenticatedRequest, ValidatedRequest } from "types/RequestTypes.js"; +} from "@validation/auth.schema.js"; const CookieOptions: CookieOptions = { httpOnly: true, @@ -28,8 +26,12 @@ const CookieOptions: CookieOptions = { maxAge: 1 * 24 * 60 * 60 * 1000, }; +const CSRF_AGE = 15*24*60*1000; +const REFRESH_AGE = 15*24*60*1000; +const ACCESS_AGE = 30*60*1000; + export const registerController = async (req: Request, res: Response) => { - const body = (req as ValidatedRequest).validatedBody; + const body = req.validatedBody as RegisterInput; const userAgent: string = req.headers["user-agent"] || "unknown"; const ip = @@ -42,22 +44,23 @@ export const registerController = async (req: Request, res: Response) => { 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, { ...CookieOptions, - maxAge: 30 * 60 * 1000, + maxAge: ACCESS_AGE, }) .cookie("refresh-token", refreshToken, { ...CookieOptions, - maxAge: 7 * 24 * 60 * 60 * 1000, + maxAge: REFRESH_AGE, }) .cookie("csrf-token", csrfToken, { ...CookieOptions, httpOnly: false, - maxAge: 30 * 24 * 60 * 60 * 1000, + maxAge: CSRF_AGE, }) .json({ user: { @@ -71,7 +74,7 @@ export const registerController = async (req: Request, res: Response) => { }; export const loginController = async (req: Request, res: Response) => { - const body = (req as ValidatedRequest).validatedBody; + const body = req.validatedBody as LoginInput; const userAgent: string = req.headers["user-agent"] || "unknown"; const ip = req.headers["x-forwarded-for"] || @@ -82,22 +85,23 @@ export const loginController = async (req: Request, res: Response) => { const payload = { ...body, userAgent, ip }; const result = await loginUser(payload); - const { user, accessToken, refreshToken, csrfToken, accountStatus } = result; + const { user, tokens } = result; + const { accessToken, refreshToken, csrfToken } = tokens; return res .status(200) .cookie("access-token", accessToken, { ...CookieOptions, - maxAge: 30 * 60 * 1000, + maxAge: ACCESS_AGE, }) .cookie("refresh-token", refreshToken, { ...CookieOptions, - maxAge: 7 * 24 * 60 * 60 * 1000, + maxAge: REFRESH_AGE, }) .cookie("csrf-token", csrfToken, { ...CookieOptions, httpOnly: false, - maxAge: 30 * 24 * 60 * 60 * 1000, + maxAge: CSRF_AGE, }) .json({ user: { @@ -106,13 +110,13 @@ export const loginController = async (req: Request, res: Response) => { username: user.username, displayName: user.displayName, avatar: user.avatarUrl, - accountStatus: accountStatus, + accountStatus: user.accountStatus, }, }); }; export const forgotPasswordController = async (req: Request, res: Response) => { - const payload = (req as ValidatedRequest).validatedBody; + const payload = req.validatedBody as ForgetPasswordInput; await createPasswordResetRequest(payload.email); return res.status(200).json({ status: "success", @@ -122,9 +126,7 @@ export const forgotPasswordController = async (req: Request, res: Response) => { }; export const resetPasswordController = async (req: Request, res: Response) => { - const { token, password } = ( - req as ValidatedRequest<{ token: string; password: string }> - ).validatedBody; + const { token, password } = req.validatedBody as { token: string; password: string }; await resetPassword(token, password); return res.status(200).json({ status: "success", @@ -150,16 +152,16 @@ export const refreshTokenController = async (req: Request, res: Response) => { .status(200) .cookie("access-token", accessToken, { ...CookieOptions, - maxAge: 30 * 60 * 1000, + maxAge: ACCESS_AGE, }) .cookie("refresh-token", refreshToken, { ...CookieOptions, - maxAge: 7 * 24 * 60 * 60 * 1000, + maxAge: REFRESH_AGE, }) .cookie("csrf-token", csrfToken, { ...CookieOptions, httpOnly: false, - maxAge: 30 * 24 * 60 * 60 * 1000, + maxAge: CSRF_AGE, }) .json({ message: "Tokens refreshed" }); }; @@ -168,7 +170,7 @@ export const emailVerificationController = async ( req: Request, res: Response ) => { - const userId = (req as AuthenticatedRequest).user?._id; + const userId = req?.user!.id await sendEmailVerification(userId); return res.status(200).json({ @@ -177,8 +179,7 @@ export const emailVerificationController = async ( }; export const verifyEmailController = async (req: Request, res: Response) => { - const { verificationToken } = (req as ValidatedRequest) - .validatedBody; + const { verificationToken } = req.validatedBody as VerifyEmailInput; await verifyEmail(verificationToken); return res.status(200).json({ @@ -190,10 +191,8 @@ export const verifyEmailChangeController = async ( req: Request, res: Response ) => { - const { verificationToken, code } = ( - req as ValidatedRequest - ).validatedBody; - const currentSessionId = (req as AuthenticatedRequest).sessionId; + 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", diff --git a/src/modules/auth/auth.routes.ts b/src/modules/auth/auth.routes.ts index 64ebc18..a2ea854 100644 --- a/src/modules/auth/auth.routes.ts +++ b/src/modules/auth/auth.routes.ts @@ -21,8 +21,7 @@ import { 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"; -import { requireActiveAccount } from "@middleware/security/accountStatusMiddleware.js"; +import { csrfMiddleware } from "@middleware/security/requireCsrf.js"; const router = Router(); @@ -30,8 +29,7 @@ router.post( "/register", validateBody(registerSchema), asyncHandler(registerController) -); - +); router.post("/login", validateBody(loginSchema), asyncHandler(loginController)); router.post( "/forgot-password", @@ -45,31 +43,28 @@ router.post( asyncHandler(resetPasswordController) ); + router.post( - "/refresh-token", - csrfMiddleware, + "/refresh-session", asyncHandler(refreshTokenController) ); router.post( "/email/verification", - authMiddleware, - requireActiveAccount, + authMiddleware, asyncHandler(emailVerificationController) ); router.post( "/email/verify", - authMiddleware, - requireActiveAccount, + authMiddleware, validateBody(verifyEmailSchema), asyncHandler(verifyEmailController) ); router.post( "/email/verify-change", - authMiddleware, - requireActiveAccount, + authMiddleware, validateBody(verifyUpdateEmailSchema), asyncHandler(verifyEmailChangeController) ); @@ -81,4 +76,4 @@ router.post( asyncHandler(logoutController) ); -export default router; +export default router; \ No newline at end of file diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 54f4350..a32d22f 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -5,8 +5,7 @@ import mongoose, { Types } from "mongoose"; 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 { - compareHashTokens, +import { generateAccessToken, generateCsrfToken, generateRefreshToken, @@ -29,7 +28,10 @@ import { 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 sendVerificationEmail from "@utils/emails/sender/sendEmailVerificationLink.js"; +import ensureActiveAccount from "security/guards/ensureActiveAccount.js"; +import { getAccountBlockResponse } from "security/guards/getAccountBlockResponse.js"; +import { createUserSession } from "./utils/createUserSession.js"; type LoginInputWithMeta = LoginInput & { userAgent: string; @@ -37,19 +39,20 @@ type LoginInputWithMeta = LoginInput & { }; type SignOutput = { user: User; - accessToken: string; - refreshToken: string; - csrfToken: string; - accountStatus?: string; + tokens: { + accessToken: string; + refreshToken: string; + csrfToken: string; + }; }; type RegisterInputWithMeta = RegisterInput & { userAgent: string; ip: string | string[] | undefined; }; -interface RefreshTokenOutput { - accessToken: string; - refreshToken: string; - csrfToken: string; +interface RefreshTokenOutput { + accessToken: string; + refreshToken: string; + csrfToken: string; } export async function registerUser( @@ -65,10 +68,8 @@ export async function registerUser( } } // Metadata - const ipData: any = await getIpInfo(ip as string); - const userAgentInfo = parseUserAgent(userAgent); - - const passwordHash = await bcrypt.hash(password, 10); + + const passwordHash = await bcrypt.hash(password, 10); const session = await mongoose.startSession(); session.startTransaction(); @@ -88,30 +89,15 @@ export async function registerUser( ); const user: User = result[0]; - const sessionId: string = crypto.randomBytes(32).toString("hex"); - const accessToken = generateAccessToken(user._id, sessionId); - const refreshToken = generateRefreshToken(user._id, sessionId); - const csrfToken = generateCsrfToken(); + const { sessionPayload, tokens } = await createUserSession({ + user, + userAgent, + ip: (Array.isArray(ip) ? ip[0] : ip) || "", +}); 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[0], - lat: ipData.latitude, - lng: ipData.longitude, - isp: ipData.asnOrganisation, - refreshTokenHash: hashToken(refreshToken), - csrfTokenHash: hashToken(csrfToken), - createdAt: Date.now(), - lastUsedAt: Date.now(), + ...sessionPayload }, ], { session } @@ -119,7 +105,7 @@ export async function registerUser( await session.commitTransaction(); // enqueue welcome email sendWelcomeEmail(user.email, user.displayName, user.username); - return { user, accessToken, refreshToken, csrfToken }; + return { user, tokens }; } catch (err) { await session.abortTransaction(); const errorMessage = err instanceof Error ? err.message : String(err); @@ -132,7 +118,7 @@ export async function registerUser( export async function loginUser( input: LoginInputWithMeta -): Promise { +): Promise { const { email, password, userAgent, ip } = input; const user: User | null = await UserModel.findOne({ email }).select( @@ -141,53 +127,33 @@ export async function loginUser( 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 lastStatusChange = user.changeHistory - .filter((change) => change.field === "accountStatus") - .sort((a, b) => b.at.getTime() - a.at.getTime())[0]; - - if (user.accountStatus === "banned") { - throw new ForbiddenError("This account has been permanently banned."); - } - if (user.accountStatus === "deactive" || user.accountStatus === "suspend") { - if (lastStatusChange.via === "admin") { - throw new ForbiddenError( - `Account is ${user.accountStatus} by admin. Please contact support.` - ); - } - } - const ipData: any = await getIpInfo(ip as string); - const userAgentInfo = parseUserAgent(userAgent); - const sessionId: string = crypto.randomBytes(32).toString("hex"); - - const accessToken = generateAccessToken(user._id, sessionId); - const refreshToken = generateRefreshToken(user._id, sessionId); - const csrfToken = generateCsrfToken(); - await SessionModel.create({ - sessionId, - userId: user._id, + } + + + const { sessionPayload, tokens } = await createUserSession({ + user, userAgent, - device: userAgentInfo.device, - browser: userAgentInfo.browser, - os: userAgentInfo.os, - ip: ipData.ip, - city: ipData.cityName, - country: ipData.countryName, - timezone: ipData.timeZones[0], - lat: ipData.latitude, - lng: ipData.longitude, - isp: ipData.asnOrganization, - refreshTokenHash: hashToken(refreshToken), - csrfTokenHash: hashToken(csrfToken), - createdAt: Date.now(), - lastUsedAt: Date.now(), - }); + ip: (Array.isArray(ip) ? ip[0] : ip) || "", + }); + await SessionModel.create(sessionPayload); - return { user, accessToken, refreshToken, csrfToken }; + return { user, tokens }; } export async function refreshTokens( @@ -195,72 +161,102 @@ export async function refreshTokens( userAgent: string, ip: string | string[] | undefined ): Promise { - let decoded; + let decoded: { + userId: string; + sessionId: string; + role: "user" | "admin"; + }; + try { - decoded = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!) as { - userId: string; - sessionId: string; - }; - } catch (err) { + decoded = jwt.verify( + refreshToken, + process.env.REFRESH_TOKEN_SECRET! + ) as typeof decoded; + } catch { throw new UnauthenticatedError("Authentication failed"); - } + } const session = await SessionModel.findOne({ sessionId: decoded.sessionId, userId: decoded.userId, - }).select("+refreshTokenHash +valid +revokedAt"); - - const user: User | null = await UserModel.findOne({ - _id: decoded.userId, - }); + valid: true, + revokedAt: null, + }).select("+refreshTokenHash +csrfTokenHash +expiresIn"); - if ( - !decoded || - !user || - !session || - !session.valid || - session.revokedAt || - !session.refreshTokenHash - ) { + if (!session || !session.refreshTokenHash || !session.expiresIn) { throw new UnauthenticatedError("Authentication failed"); } - const refreshCookieHash = hashToken(refreshToken); - const isValidToken = compareHashTokens( - refreshCookieHash, + // hard session expiry (absolute TTL) + if (session.expiresIn.getTime() <= Date.now()) { + await SessionModel.updateOne( + { _id: session._id }, + { valid: false, revokedAt: new Date() } + ).exec(); + + throw new UnauthenticatedError("Authentication failed: Session expired"); + } + + // verify refresh token (CORRECT ORDER) + const isValidToken = verifyToken( + refreshToken, session.refreshTokenHash ); - if ( - !isValidToken || - // session.userAgent !== userAgent || - // session.country !== ipData.countryName || - user.accountStatus !== "active" - ) { + if (!isValidToken) { await SessionModel.updateOne( { _id: session._id }, { valid: false, revokedAt: new Date() } ).exec(); + throw new UnauthenticatedError( - "Authentication failed:Session Revoked due to malicious behaviour" + "Authentication failed: Session revoked" ); } - const accessToken = generateAccessToken(user._id, session.sessionId); - const newRefreshToken = generateRefreshToken(user._id, session.sessionId); - const csrfToken = generateCsrfToken(); - - - await SessionModel.updateOne( - { _id: session._id }, - { - lastUsedAt: new Date(), - refreshTokenHash: hashToken(newRefreshToken), - csrfTokenHash: hashToken(csrfToken), - } - ) - - return { accessToken, refreshToken: newRefreshToken, csrfToken }; + const user = await UserModel.findOne({ + _id: decoded.userId, + accountStatus: { $ne: "banned" }, + }); + + if (!user) { + throw new UnauthenticatedError("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, // race protection + }, + { + 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) { @@ -322,20 +318,16 @@ export async function resetPassword(rawToken: string, newPassword: string) { ) { throw new BadRequestError("Invalid or expired token"); } - - const removePasswordReset = async () => { - user.passwordReset = undefined; + + if (user.passwordReset.expiresAt.getTime() < Date.now()) { + user.passwordReset = undefined; await user.save(); throw new BadRequestError("Invalid or expired token"); - }; - - if (user.passwordReset.expiresAt.getTime() < Date.now()) { - removePasswordReset(); } const isValid = verifyToken(rawToken, user.passwordReset.tokenHash); if (!isValid) { - removePasswordReset(); + throw new BadRequestError("Invalid or expired token"); } const hashedPassword = await bcrypt.hash(newPassword, 10); @@ -392,7 +384,7 @@ export async function resetPassword(rawToken: string, newPassword: string) { } export async function sendEmailVerification( - userId: Types.ObjectId + userId: string ): Promise { const user: User | null = await UserModel.findById(userId).select( "+emailVerification +changeHistory" @@ -400,9 +392,14 @@ export async function sendEmailVerification( if (!user) { 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"); } + const token = generateVerificationToken(); const verifyEmailUrl = `${ @@ -447,6 +444,10 @@ export async function verifyEmail(verificationToken: string): Promise { 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.emailVerification || @@ -502,6 +503,10 @@ export async function verifyUpdateEmail( 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 || diff --git a/src/modules/auth/utils/createUserSession.ts b/src/modules/auth/utils/createUserSession.ts new file mode 100644 index 0000000..80af66c --- /dev/null +++ b/src/modules/auth/utils/createUserSession.ts @@ -0,0 +1,54 @@ +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 createUserSession({ + 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 + ); + + const sessionPayload = { + 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[0], + lat: ipData.latitude, + lng: ipData.longitude, + isp: ipData.asnOrganization, + refreshTokenHash: hashToken(refreshToken), + csrfTokenHash: hashToken(csrfToken), + expiresIn: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), + createdAt: Date.now(), + lastUsedAt: Date.now(), + }; + + return { + sessionPayload, + tokens: { accessToken, refreshToken, csrfToken }, + }; +} diff --git a/src/modules/contextProfile/contextProfile.controller.ts b/src/modules/contextProfile/contextProfile.controller.ts new file mode 100644 index 0000000..34e6cec --- /dev/null +++ b/src/modules/contextProfile/contextProfile.controller.ts @@ -0,0 +1,31 @@ +import { Request, Response } from "express"; +import { + getContextProfileService, + listContextProfilesService, +} from "./contextProfile.service.js"; +import { createContextProfileSchema } from "@validation/contextProfile.schema.js"; + + +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..0037281 --- /dev/null +++ b/src/modules/contextProfile/contextProfile.routes.ts @@ -0,0 +1,17 @@ +import { Router } from "express"; +import { + getContextProfileController, + listContextProfilesController, +} from "./contextProfile.controller.js"; + +const router = Router(); + +// Future question: Do we want users to create context profiles directly? +// router.post("/", createContextProfileController); +// router.post("/:contextId/clone", cloneContextProfileController); + +router.get("/:contextId", getContextProfileController); + +router.get("/", listContextProfilesController); + +export default router; \ No newline at end of file diff --git a/src/modules/contextProfile/contextProfile.service.ts b/src/modules/contextProfile/contextProfile.service.ts new file mode 100644 index 0000000..d78565f --- /dev/null +++ b/src/modules/contextProfile/contextProfile.service.ts @@ -0,0 +1,56 @@ +import mongoose from "mongoose"; +import { + ContextProfileModel, + ContextScope, + EnvironmentProfile, + GenreType, + MoodType, + NarrativeScope, + StyleType, +} from "@models/ContextProfile.js"; +import { ProjectModel } from "@models/Project.js"; +import { NARRATION_PROFILES } from "constants/narrationProfiles.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; +}; + + +export async function getContextProfileService( + userId: string, + contextId: string +) { + const context = await ContextProfileModel.findOne({ + _id: contextId, + userId, + }); + + if (!context) throw new Error("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 }); +} diff --git a/src/modules/project/project.controller.ts b/src/modules/project/project.controller.ts index 1e7099f..6f94c31 100644 --- a/src/modules/project/project.controller.ts +++ b/src/modules/project/project.controller.ts @@ -1,6 +1,7 @@ -import { Request, Response } from "express"; + import { Request, Response } from "express"; import { createProject, + createProjectContextProfile, deleteProjectById, getArchivedProjects, getDeletedProjects, @@ -19,14 +20,16 @@ import { CreateProjectInput, UpdateProjectInput, UpdateManyIdsInput, + CreateProjectContextInput, } from "@validation/project.schema.js"; -import { paginationResponse } from "@utils/paginationResponse.js"; -import { PaginatedRequest } from "types/RequestTypes.js"; +import { paginationResponse } from "@utils/paginationResponse.js"; export const getProjectsController = async (req: Request, res: Response) => { - const {pagination, sorting} = (req as PaginatedRequest); + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const userId = req.user!.id; const [projects, total] = await getProjects( - req.user?._id!, + userId, pagination, sorting ); @@ -43,9 +46,11 @@ export const getDeletedProjectsController = async ( req: Request, res: Response ) => { - const {pagination, sorting} = (req as PaginatedRequest); + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const userId = req.user!.id; const [projects, total] = await getDeletedProjects( - req.user?._id!, + userId, pagination, sorting ); @@ -61,9 +66,11 @@ export const getArchivedProjectsController = async ( req: Request, res: Response ) => { - const {pagination, sorting} = (req as PaginatedRequest); + const pagination = req?.pagination!; + const sorting = req?.sorting!; + const userId = req.user!.id; const [projects, total] = await getArchivedProjects( - req.user?._id!, + userId, pagination, sorting ); @@ -77,28 +84,37 @@ export const getArchivedProjectsController = async ( }; export const postProjectController = async (req: Request, res: Response) => { - const input = (req as unknown as { validatedBody?: CreateProjectInput }) - .validatedBody!; - const newProject = await createProject(req.user?._id!, input); + 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 project = await getProjectById(projectId, req.user?._id!); + 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 as unknown as { validatedBody?: UpdateProjectInput }) - .validatedBody!; + const updates = req.validatedBody as UpdateProjectInput + const userId = req.user!.id; const updatedProject = await updateProjectById( projectId, - req.user?._id!, + userId, updates ); return res.status(200).json(updatedProject); @@ -109,7 +125,8 @@ export const deleteProjectByIdController = async ( res: Response ) => { const projectId = req.params.projectId as Types.ObjectId | string; - const response = await deleteProjectById(projectId, req.user?._id!); + const userId = req.user!.id; + const response = await deleteProjectById(projectId, userId); return res.status(200).json(response); }; @@ -119,10 +136,10 @@ export const updateProjectStatusController = async ( ) => { const projectId = req.params.projectId as Types.ObjectId | string; const { status } = req.body; - console.log("Status:", status, "Project ID:", projectId); + const userId = req.user!.id; const updatedProject = await updateProjectStatus( projectId, - req.user?._id!, + userId, status ); return res.status(200).json(updatedProject); @@ -134,9 +151,10 @@ export const updateProjectVisibilityController = async ( ) => { const projectId = req.params.projectId as Types.ObjectId | string; const { visibility } = req.body; + const userId = req.user!.id; const updatedProject = await updateProjectVisibility( - projectId, - req.user?._id!, + userId, + projectId, visibility ); return res.status(200).json(updatedProject); @@ -147,7 +165,8 @@ export const restoreProjectByIdController = async ( res: Response ) => { const projectId = req.params.projectId as Types.ObjectId | string; - const restoredProject = await restoreProjectById(projectId, req.user?._id!); + const userId = req.user!.id; + const restoredProject = await restoreProjectById(projectId, userId); return res.status(200).json(restoredProject); }; @@ -156,9 +175,10 @@ export const unarchiveProjectByIdController = async ( res: Response ) => { const projectId = req.params.projectId as Types.ObjectId | string; + const userId = req.user!.id; const unarchivedProject = await unarchiveProjectById( projectId, - req.user?._id! + userId ); return res.status(200).json(unarchivedProject); }; @@ -167,12 +187,11 @@ export const restoreManyProjectsController = async ( req: Request, res: Response ) => { - const { projectIds } = ( - req as unknown as { validatedBody?: UpdateManyIdsInput } - ).validatedBody!; + const { projectIds } = req.validatedBody as UpdateManyIdsInput; + const userId = req.user!.id; const restoredProjects = await restoreManyProjectsByIds( projectIds, - req.user?._id! + userId ); return res.status(200).json(restoredProjects); @@ -182,12 +201,11 @@ export const unarchiveManyProjectsController = async ( req: Request, res: Response ) => { - const { projectIds } = ( - req as unknown as { validatedBody?: UpdateManyIdsInput } - ).validatedBody!; + const { projectIds } = req.validatedBody as UpdateManyIdsInput; + const userId = req.user!.id; const unarchivedProjects = await unarchiveManyProjectsByIds( projectIds, - req.user?._id! + userId ); return res.status(200).json(unarchivedProjects); diff --git a/src/modules/project/project.routes.ts b/src/modules/project/project.routes.ts index 94ede3c..5c13633 100644 --- a/src/modules/project/project.routes.ts +++ b/src/modules/project/project.routes.ts @@ -1,5 +1,6 @@ -import { Router } from "express"; + import { Router } from "express"; import { + createProjectContextProfileController, deleteProjectByIdController, getArchivedProjectsController, getDeletedProjectsController, @@ -17,6 +18,7 @@ import { import { asyncHandler } from "@utils/asyncHandler.js"; import { validateBody } from "@validation/validateBody.js"; import { + createProjectContextProfileSchema, createProjectSchema, projectIdParamSchema, updateManyIdsSchema, @@ -25,17 +27,18 @@ import { updateProjectVisibilitySchema, } from "@validation/project.schema.js"; import { validateParams } from "@validation/validateParams.js"; +import { paginationAndSortingMiddleware } from "@middleware/paginationAndSorting.js"; const router = Router(); -router.get("/", asyncHandler(getProjectsController)); +router.get("/", paginationAndSortingMiddleware, asyncHandler(getProjectsController)); router.post( "/", validateBody(createProjectSchema), asyncHandler(postProjectController) ); -router.get("/deleted", asyncHandler(getDeletedProjectsController)); -router.get("/archived", asyncHandler(getArchivedProjectsController)); +router.get("/deleted", paginationAndSortingMiddleware, asyncHandler(getDeletedProjectsController)); +router.get("/archived", paginationAndSortingMiddleware, asyncHandler(getArchivedProjectsController)); router.patch( "/restore", validateBody(updateManyIdsSchema), @@ -46,14 +49,18 @@ router.patch( validateBody(updateManyIdsSchema), asyncHandler(unarchiveManyProjectsController) ); - - - + +// 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), @@ -87,10 +94,5 @@ router.patch( validateParams(projectIdParamSchema), asyncHandler(unarchiveProjectByIdController) ); -// Routes which go from a single project -// router.use("/projects/:projectId", contextRouter); -// router.use("/projects/:projectId", storyRouter); -// router.use("/projects/:projectId", assetRouter); -// router.use("/projects/:projectId", videosRouter); // finally videos routes -export default router; +export default router; \ No newline at end of file diff --git a/src/modules/project/project.service.ts b/src/modules/project/project.service.ts index f4b7ce7..a1977a0 100644 --- a/src/modules/project/project.service.ts +++ b/src/modules/project/project.service.ts @@ -1,5 +1,6 @@ import { BadRequestError, + ForbiddenError, InternalServerError, NotFoundError, } from "@middleware/error/index.js"; @@ -12,13 +13,15 @@ import { sanitizeProjectResponse, sanitizeProjects, } from "@utils/sanitizeProjectResponse.js"; -import { Types } from "mongoose"; +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, @@ -117,6 +120,88 @@ export async function getProjectById( }); } +export async function createProjectContextProfile( + userId: string, + projectId: string, + payload: any +) { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + const project = await ProjectModel.findOne({ + _id: projectId, + userId, + }).session(session); + + if (!project) throw new Error("Project not found"); + + // 🚨 CRITICAL RULE + if (project.defaultContextProfileId) { + throw new ForbiddenError("Project already has a default context"); + } + let contextProfileId; + + 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 Error("Global context not found"); + } + + // 🔒 CLONE — NEVER ATTACH DIRECTLY + const cloned = new ContextProfileModel({ + ...globalContext.toObject(), + _id: undefined, + projectId, + parentContextId: globalContext._id, + scope: ContextScope.PROJECT, + isDefaultForProject: true, + lastUsedAt: new Date(), + }); + + await cloned.save({ session }); + contextProfileId = cloned._id; + } + + project.defaultContextProfileId = contextProfileId; + await project.save({ session }); + await session.commitTransaction(); + return project; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + session.endSession(); + } +} + export async function updateProjectById( projectId: Types.ObjectId | string, userId: Types.ObjectId | string, diff --git a/src/modules/scenes/scenes.private.routes.ts b/src/modules/scenes/scenes.private.routes.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/modules/story/story.controller.ts b/src/modules/story/story.controller.ts index e69de29..331c2bf 100644 --- a/src/modules/story/story.controller.ts +++ b/src/modules/story/story.controller.ts @@ -0,0 +1,238 @@ +import { paginationResponse } from "@utils/paginationResponse.js"; +import { Request, Response } from "express"; +import { + addStoryContextService, + archiveStory, + createStory, + deleteStory, + generateStory, + getProjectStories, + getStoryById, + getUserStories, + regenerateStory, + restoreStory, + setStoryContextService, + unarchiveStory, + updateStory, + writeContent, +} from "./story.service.js"; +import { + 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 getProjectStoriesController = async ( + req: Request, + res: Response +) => { + console.log("STORY ROUTER REGISTERED"); + + 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 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.id; + 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 payload = req.validatedBody; + const result = await addStoryContextService( + userId, + storyId, + payload + ); + res.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.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 deleteStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.storyId; + + const response = await deleteStory(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 rollbackStoryController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const storyId = req.params.id; + + // to be implemented +}; + +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, + }); +}; \ No newline at end of file diff --git a/src/modules/story/story.private.routes.ts b/src/modules/story/story.private.routes.ts new file mode 100644 index 0000000..4af352c --- /dev/null +++ b/src/modules/story/story.private.routes.ts @@ -0,0 +1,38 @@ +import { Router } from 'express'; +import { createStoryController, deleteStoryController, getProjectStoriesController, getStoryByIdController, getUserStoriesController, regenerateStoryController, restoreStoryController, rollbackStoryController, unarchiveStoryController, updateStoryController, archiveStoryStatusController, generateStoryController, writeContentController, setStoryContextController, addStoryContextController } from './story.controller.js'; +import { paginationAndSortingMiddleware } from '@middleware/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( + "/project/:projectId", + validateParams(projectIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getProjectStoriesController) +) +// 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',validateParams(storyIdParamSchema), asyncHandler(deleteStoryController)); + +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; \ No newline at end of file diff --git a/src/modules/story/story.service.ts b/src/modules/story/story.service.ts index e69de29..6797ccb 100644 --- a/src/modules/story/story.service.ts +++ b/src/modules/story/story.service.ts @@ -0,0 +1,435 @@ +import { platform } from '@constants/storyConsts.js'; +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 { + CreateStoryInput, + RegenerateStoryInput, +} 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 mongoose from "mongoose"; +import { Pagination, Sorting } from "types/Pagination.js"; + +export async function getUserStories( + userId: string, + pagination: Pagination, + sorting: Sorting +) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId }) 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 }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, projectId }) as Promise, + ]); + return [stories, total]; +} + +export async function createStory( + userId: string, + projectId: string, + payload: CreateStoryInput +) { + const story = await StoryModel.create({ + userId, + projectId, + title: payload.title, + description: payload.description, + timeLimit: payload.timeLimit, + platform: payload.platform, + intent: payload.intent, + status: "draft", + }); + return story; +} + +export async function getStoryById(userId: string, storyId: string) { + const story = await StoryModel.findOne({ _id: storyId, userId }); + if (!story) { + throw new NotFoundError("Story not found"); + } + return story; +} + +export async function addStoryContextService( + userId: string, + storyId: string, + payload: any +) { + const session = await mongoose.startSession(); + session.startTransaction(); + try { + const story = await StoryModel.findOne({ + _id: storyId, + userId, + }).session(session); + if (!story) throw new NotFoundError("Story not found"); + + const narrationProfile = + NARRATION_PROFILES[payload.data.genre as GenreType]; + const [newContext] = await ContextProfileModel.create( + [ + { + userId, + name: payload.data.name, + description: payload.data.description, + genre: payload.data.genre, + mood: payload.data.mood, + style: payload.data.style, + environment: payload.data.environment, + worldRules: payload.data.worldRules, + narrativeConstraints: payload.data.narrativeConstraints, + narrationProfile, + scope: ContextScope.GLOBAL, + isDefaultForProject: false, + lastUsedAt: new Date(), + }, + ], + { session } + ); + + story.contextProfileId = newContext._id; + await story.save({ session }); + + await session.commitTransaction(); + return { + story, + contextMeta: { + id: newContext._id.toString(), + scope: newContext.scope, + createdAt: newContext.createdAt, + }, + contextPayload: newContext, + }; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + session.endSession(); + } +} + +export async function setStoryContextService( + userId: string, + storyId: string, + payload: any +) { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + const story = await StoryModel.findOne({ + _id: storyId, + userId, + }).session(session); + + if (!story) throw new NotFoundError("Story not found"); + + const project = await ProjectModel.findById(story.projectId).session( + session + ); + if (!project) throw new NotFoundError("Project not found"); + + if (payload.mode === "use-project") { + if (!project.defaultContextProfileId) { + throw new NotFoundError("Project has no 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"); + } + + await session.commitTransaction(); + 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"); + } + + story.contextProfileId = globalContext._id; + await story.save({ session }); + + await session.commitTransaction(); + return { + story, + contextMeta: { + id: globalContext._id.toString(), + scope: globalContext.scope, + createdAt: globalContext.createdAt, + }, + }; + } + throw new Error("Invalid story context mode"); + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + session.endSession(); + } +} + +export async function writeContent( + userId: string, + storyId: string, + payload: { + content: string; + summary: string; + keywords?: string[]; + tags?: string[]; + } +) { + const story = 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 } + ); + if (!story) { + throw new NotFoundError("Story not found or not authorized"); + } + return story; +} + +export async function generateStory(userId: string, storyId: string) { + const story = await StoryModel.findOne({ _id: storyId, userId }); + if (!story) { + throw new NotFoundError("Story not found"); + } + const contextProfile = await ContextProfileModel.findById(story.contextProfileId); + + const prompt = generateStoryPrompt({ + title: story.title, + description: story.description, + intent:story.intent, + platform: story.platform, + timeLimit: story.timeLimit, + contextProfile: contextProfile, + }); + 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); + 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 } + ); + + console.log("AI RESPONSE RECEIVED IN SERVICE:", content); + + return updatedStory; +} + +export async function regenerateStory( + userId: string, + storyId: string, + extraPrompt: RegenerateStoryInput +) { + const story = await StoryModel.findOne({ _id: storyId, userId }); + if (!story) { + throw new NotFoundError("Story not found"); + } + if (!extraPrompt || !extraPrompt.prompt) { + throw new ConflictError("No regeneration prompt provided."); + } + + const contextProfile = await ContextProfileModel.findById(story.contextProfileId); + + 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, + }); + 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); + + 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, + } + ); + return updatedStory; +} + +export async function updateStory( + userId: string, + storyId: string, + payload: Partial +) { + const story = 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 + if (!story) { + throw new NotFoundError("Story not found or not authorized"); + } + return story; +} + +export async function deleteStory( + userId: string, + storyId: string +): Promise { + const story = await StoryModel.findOne({ _id: storyId, userId }); + if (!story) { + throw new NotFoundError("Story not found"); + } + if (story.status === "delete") { + throw new ConflictError("Story is already deleted"); + } + 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 StoryModel.findOneAndUpdate( + { _id: storyId, userId, status: "delete" }, + { $set: { isDeleted: false, status: "active" }, $unset: { deletedAt: "" } }, + { new: true, lean: true } + ); + if (!story) { + throw new NotFoundError("Story not found or not deleted"); + } + return story; +} + +export async function archiveStory(userId: string, storyId: string) { + const story = await StoryModel.findOneAndUpdate( + { _id: storyId, userId, status: "active" }, + { $set: { status: "archive" } }, + { new: true, lean: true } + ); + if (!story) { + throw new NotFoundError("Story not found or not active"); + } + return story; +} + +export async function unarchiveStory(userId: string, storyId: string) { + const story = await StoryModel.findOneAndUpdate( + { _id: storyId, userId, status: "archive" }, + { $set: { status: "active" } }, + { new: true, lean: true } + ); + if (!story) { + throw new NotFoundError("Story not found or not archived"); + } + return story; +} + +// To be implemented +export async function rollbackStory(userId: string, storyId: string) { + return; +} \ No newline at end of file diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index 70d2f87..af26d39 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -26,12 +26,10 @@ import { updatePassword, updatePrivacySettings, updateProfile, -} from "./user.service.js"; -import { AuthenticatedRequest, ValidatedRequest } from "../../types/index.js"; -import { ValidatedParamsRequest } from "types/RequestTypes.js"; +} from "./user.service.js"; export const getProfileController = async (req: Request, res: Response) => { - const userId = (req as AuthenticatedRequest).user._id; + const userId = req.user!.id; const user = await getProfile(userId); return res.status(200).json({ id: user._id, @@ -48,15 +46,15 @@ export const getProfileController = async (req: Request, res: Response) => { }; export const updateProfileController = async (req: Request, res: Response) => { - const userId = (req as AuthenticatedRequest).user._id; - const updateData = (req as ValidatedRequest).validatedBody; + 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 as AuthenticatedRequest).user._id; + const userId = req.user!.id; const avatarData = req.file; const updatedUser = await updateAvatar(userId, avatarData); return res.status(200).json(updatedUser); @@ -67,7 +65,7 @@ export const deleteAvatarController = async ( res: Response, next: NextFunction ) => { - const userId = (req as AuthenticatedRequest).user._id; + const userId = req.user!.id; await deleteAvatar(userId); return res.status(204).send({ message: "Avatar deleted successfully", @@ -75,26 +73,26 @@ export const deleteAvatarController = async ( }; export const getSettingsController = async (req: Request, res: Response) => { - const userId = (req as AuthenticatedRequest).user._id; + 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 as AuthenticatedRequest).user._id; + 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 as AuthenticatedRequest).user._id; - const sessionId = (req as AuthenticatedRequest).sessionId!; + 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 as AuthenticatedRequest).user._id; + const userId = req.user!.id; const billingInfo = await getBilling(userId); return res.status(200).json(billingInfo); }; @@ -103,9 +101,8 @@ export const updateNotificationsController = async ( req: Request, res: Response ) => { - const userId = (req as AuthenticatedRequest).user._id; - const notificationPrefs = (req as ValidatedRequest) - .validatedBody; + const userId = req.user!.id; + const notificationPrefs = req.validatedBody as UpdateNotificationsType; const updatedUser = await updateNotifications(userId, notificationPrefs); return res.status(200).json({ @@ -118,9 +115,8 @@ export const updatePrivacySettingsController = async ( req: Request, res: Response ) => { - const userId = (req as AuthenticatedRequest).user._id; - const privacyPrefs = (req as ValidatedRequest) - .validatedBody!; + 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, @@ -129,10 +125,8 @@ export const updatePrivacySettingsController = async ( }; export const updatePasswordController = async (req: Request, res: Response) => { - const userId = (req as AuthenticatedRequest).user._id; - const { currentPassword, newPassword } = ( - req as ValidatedRequest - ).validatedBody; + 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); @@ -142,8 +136,8 @@ export const updatePasswordController = async (req: Request, res: Response) => { }; export const updateEmailController = async (req: Request, res: Response) => { - const userId = (req as AuthenticatedRequest).user._id; - const { newEmail } = (req as ValidatedRequest).validatedBody; + const userId = req.user!.id; + const { newEmail } = req.validatedBody as UpdateEmailType; await updateEmail(userId, newEmail); return res.status(200).json({ @@ -152,10 +146,9 @@ export const updateEmailController = async (req: Request, res: Response) => { }; export const deleteSessionController = async (req: Request, res: Response) => { - const userId = (req as AuthenticatedRequest).user._id; - const { sessionId } = (req as ValidatedParamsRequest) - .validatedParams; - const currentSession = (req as AuthenticatedRequest).sessionId!; + const userId = req.user!.id; + const { sessionId } = req.validatedParams as DeleteSessionParamsType; + const currentSession = req.sessionId!; if (currentSession === sessionId) { return res .status(400) @@ -169,10 +162,9 @@ export const deleteAllSessionsController = async ( req: Request, res: Response ) => { - const { removeCurrent } = (req as ValidatedRequest) - .validatedBody; - const userId = (req as AuthenticatedRequest).user._id; - const currentSession = (req as AuthenticatedRequest).sessionId; + const { removeCurrent } = req.validatedBody as DeleteAllSessionsType; + const userId = req.user!.id; + const currentSession = req.sessionId!; await deleteAllSessions(userId, currentSession, removeCurrent); return res.status(204).json(); }; @@ -181,7 +173,7 @@ export const deactivateAccountController = async ( req: Request, res: Response ) => { - const userId = (req as AuthenticatedRequest).user._id; + const userId = req.user!.id; await deactivateAccount(userId); return res.status(200).json({ @@ -193,7 +185,7 @@ export const reactivateAccountController = async ( req: Request, res: Response ) => { - const userId = (req as AuthenticatedRequest).user._id; + const userId = req.user!.id; const updatedUser = await reactivateAccount(userId); return res.status(200).json({ user: updatedUser, @@ -202,7 +194,7 @@ export const reactivateAccountController = async ( }; export const deleteAccountController = async (req: Request, res: Response) => { - const userId = (req as AuthenticatedRequest).user._id; + 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 980f4ae..2a4232d 100644 --- a/src/modules/user/user.routes.ts +++ b/src/modules/user/user.routes.ts @@ -1,6 +1,5 @@ import { Router } from "express"; import { asyncHandler } from "@utils/asyncHandler.js"; -import { csrfMiddleware } from "@middleware/security/requireCsrf.js"; import { deleteAvatarController, getBillingController, @@ -18,6 +17,7 @@ import { deleteAllSessionsController, deleteAccountController, deactivateAccountController, + reactivateAccountController, } from "./user.controller.js"; import { deleteAllSessionsSchema, @@ -30,12 +30,12 @@ import { } from "@validation/user.schema.js"; import { validateBody } from "@validation/validateBody.js"; import { validateParams } from "@validation/validateParams.js"; -import { avatarUpload } from "@middleware/avatarUpload.js"; -import { requireActiveAccount } from "@middleware/security/accountStatusMiddleware.js"; +import { avatarUpload } from "@middleware/avatarUpload.js"; +import { requireActiveAccount } from "@middleware/security/requireActiveAccount.js"; const router = Router(); -router.patch("/account/reactivate", asyncHandler(deleteAccountController)); +router.patch("/account/reactivate", asyncHandler(reactivateAccountController)); router.use(requireActiveAccount); router.get("/profile", asyncHandler(getProfileController)); @@ -43,8 +43,7 @@ router.get("/settings", asyncHandler(getSettingsController)); router.get("/security", asyncHandler(getSecurityController)); router.get("/sessions", asyncHandler(getSessionsController)); router.get("/billing", asyncHandler(getBillingController)); - -router.use(csrfMiddleware); + router.patch( "/profile", validateBody(updateProfileSchema), @@ -91,5 +90,6 @@ router.delete( 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 17a4543..27c7c07 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -1,9 +1,8 @@ -import { AccountStatus } from "constants/authConsts.js"; + import bcrypt from "bcrypt"; import { BadRequestError, - ConflictError, - ForbiddenError, + ConflictError, InternalServerError, NotFoundError, UnauthenticatedError, @@ -16,13 +15,12 @@ import { UpdatePrivacySettingsType, } from "@validation/user.schema.js"; import mongoose, { Types } from "mongoose"; -import { generateVerificationToken, verifyToken } from "@utils/tokens.js"; -import transporter from "config/mail.js"; -import { verifyUpdatedEmailTemplate } from "../../utils/emails/templates/verifyUpdatedEmail.js"; -import sendUpdateEmailLink from "@utils/emails/sender/sendUpdateEmaiLink.js"; +import { generateVerificationToken, verifyToken } from "@utils/tokens.js"; +import sendUpdateEmailLink from "@utils/emails/sender/sendUpdateEmailLink.js"; import sendOldEmailVerificationForEmailUpdate from "@utils/emails/sender/sendOldEmailVerificationForEmailUpdate.js"; +import { generateAllCookieTokens } from "@utils/generateAllCookieTokens.js"; -export const getProfile = async (userId: Types.ObjectId): Promise => { +export const getProfile = async (userId: string): Promise => { const user = await UserModel.findById(userId) .select( "-passwordHash -emailVerificationToken -resetPasswordToken -createdAt -updatedAt" @@ -40,7 +38,7 @@ export const getProfile = async (userId: Types.ObjectId): Promise => { }; export const updateProfile = async ( - userId: Types.ObjectId, + userId: string, updateData: Partial ): Promise> => { const user = await UserModel.findByIdAndUpdate(userId, updateData, { @@ -55,7 +53,7 @@ export const updateProfile = async ( }; export const updateAvatar = async ( - userId: Types.ObjectId, + userId: string, avatarData: Express.Multer.File | undefined ): Promise> => { if (!avatarData) { @@ -79,7 +77,7 @@ export const updateAvatar = async ( return resUser; }; -export const deleteAvatar = async (userId: Types.ObjectId): Promise => { +export const deleteAvatar = async (userId: string): Promise => { const user = await UserModel.findById(userId); if (!user) { throw new NotFoundError("User not found"); @@ -105,7 +103,7 @@ export const deleteAvatar = async (userId: Types.ObjectId): Promise => { }; export const getSettings = async ( - userId: Types.ObjectId + userId: string ): Promise> => { const user = await UserModel.findById(userId).select( "emailNotifications privacySettings" @@ -118,7 +116,7 @@ export const getSettings = async ( }; export const getSecurity = async ( - userId: Types.ObjectId + userId: string ): Promise> => { const user = await UserModel.findById(userId).select( "email phoneNumber passwordHash emailVerified phoneVerified lastPasswordChangeAt twoFactorEnabled oauthProviders" @@ -131,7 +129,7 @@ export const getSecurity = async ( }; export const getSessions = async ( - userId: Types.ObjectId, + userId: string, sessioId: string ): Promise< Array<{ @@ -168,7 +166,7 @@ export const getSessions = async ( }; export const getBilling = async ( - userId: Types.ObjectId + userId: string ): Promise> => { const user = await UserModel.findById(userId).select("plan billingInfo"); if (!user) { @@ -179,7 +177,7 @@ export const getBilling = async ( }; export const updateNotifications = async ( - userId: Types.ObjectId, + userId: string, notificationPrefs: UpdateNotificationsType ): Promise> => { const update: Record = {}; @@ -210,7 +208,7 @@ export const updateNotifications = async ( }; export const updatePrivacySettings = async ( - userId: Types.ObjectId, + userId: string, privacyPrefs: UpdatePrivacySettingsType ): Promise> => { const update: Record = {}; @@ -241,7 +239,7 @@ export const updatePrivacySettings = async ( }; export const updatePassword = async ( - userId: Types.ObjectId, + userId: string, currentPassword: string, newPassword: string ): Promise => { @@ -273,7 +271,7 @@ export const updatePassword = async ( }; export const updateEmail = async ( - userId: Types.ObjectId, + userId: string, newEmail: string ): Promise => { const user = await UserModel.findById(userId); @@ -315,7 +313,7 @@ export const updateEmail = async ( }; export const deleteSession = async ( - userId: Types.ObjectId, + userId: string, sessionId: string ): Promise => { const session = await SessionModel.findOne({ @@ -337,7 +335,7 @@ export const deleteSession = async ( }; export const deleteAllSessions = async ( - userId: Types.ObjectId, + userId: string, currentSessionId: string, removeCurrent: boolean | undefined ): Promise => { @@ -353,7 +351,7 @@ export const deleteAllSessions = async ( return; }; -export const deleteAccount = async (userId: Types.ObjectId): Promise => { +export const deleteAccount = async (userId: string): Promise => { const session = await mongoose.startSession(); session.startTransaction(); try { @@ -393,12 +391,15 @@ export const deleteAccount = async (userId: Types.ObjectId): Promise => { }; export const reactivateAccount = async ( - userId: Types.ObjectId + userId: string ): Promise> => { const user = await UserModel.findById(userId).select("+changeHistory +role"); if (!user) { throw new NotFoundError("User not found"); } + 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, { @@ -427,11 +428,12 @@ export const reactivateAccount = async ( throw new NotFoundError("User not found"); } const resUser = returnUserData(updatedUser, "profile"); + return resUser; }; export const deactivateAccount = async ( - userId: Types.ObjectId + userId: string ): Promise> => { const user = await UserModel.findById(userId).select("+changeHistory +role"); if (!user) { diff --git a/src/routes/api.ts b/src/routes/api.ts index 2b6d875..1288e9f 100644 --- a/src/routes/api.ts +++ b/src/routes/api.ts @@ -3,19 +3,29 @@ 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 { paginationAndSortingMiddleware } from "@middleware/paginationAndSorting.js"; -import { blockBannedAccounts } from "@middleware/security/accountStatusMiddleware.js"; +import {default as storyRouter} from '@modules/story/story.private.routes.js' +import { default as contextProfileRouter } from "@modules/contextProfile/contextProfile.routes.js"; + +import { csrfMiddleware } from "@middleware/security/requireCsrf.js"; +import { requireActiveAccount } from "@middleware/security/requireActiveAccount.js"; const apiRouter = Router(); +// private routes apiRouter.use("/auth", authRouter); -apiRouter.use(authMiddleware, blockBannedAccounts); +apiRouter.use(authMiddleware, csrfMiddleware); apiRouter.use("/user", userRouter); +apiRouter.use(requireActiveAccount); apiRouter.use( - "/projects", - authMiddleware, - paginationAndSortingMiddleware, + "/projects", projectRouter ); +apiRouter.use( + "/stories", + storyRouter +) +apiRouter.use('/context-profiles', + contextProfileRouter +); -export default apiRouter; +export default apiRouter; \ No newline at end of file diff --git a/src/routes/index.ts b/src/routes/index.ts index 50932e2..4e1494b 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -16,7 +16,12 @@ AppRouter.use(helmet()); const corsOptions = getCorsConfig(); AppRouter.use(cors(corsOptions)); -AppRouter.use(cookieParser()); +AppRouter.use(cookieParser()); + +AppRouter.use((_req, res, next) => { + res.setHeader("X-Debug-Server", process.pid.toString()); + next(); +}); // Basic logger AppRouter.use(requestLogger); 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..49fa74d --- /dev/null +++ b/src/security/guards/getAccountBlockResponse.ts @@ -0,0 +1,6 @@ +import { AccountStatus } from "@constants/userConts.js"; +import { accountStatusResponses } from "../policies/accountStatusResponses.js"; + +export function getAccountBlockResponse(status: Partial) { + return accountStatusResponses(status) || null; +} diff --git a/src/security/policies/accountStatusResponses.ts b/src/security/policies/accountStatusResponses.ts new file mode 100644 index 0000000..ee500d3 --- /dev/null +++ b/src/security/policies/accountStatusResponses.ts @@ -0,0 +1,48 @@ +import { AccountStatus } from "@constants/userConts.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/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/RequestTypes.ts b/src/types/RequestTypes.ts deleted file mode 100644 index 9c322f4..0000000 --- a/src/types/RequestTypes.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { User } from "@models/User.js"; -import { Request } from "express"; -import { Pagination, Sorting } from "./Pagination.js"; - -export interface AuthenticatedRequest extends Request { - user: User; - sessionId: string; -} - -export interface ValidatedRequest extends Request { - validatedBody: T; -} - -export interface ValidatedParamsRequest extends Request { - validatedParams: T; -} - -export interface PaginatedRequest extends Request { - pagination: Pagination; - sorting: Sorting; -} \ No newline at end of file diff --git a/src/types/express.d.ts b/src/types/express.d.ts index ba85473..d306fc4 100644 --- a/src/types/express.d.ts +++ b/src/types/express.d.ts @@ -1,14 +1,23 @@ import { type User } from "@models/User.ts"; // whatever your user type is import type { Pagination, Sorting } from "@middleware/paginationAndSorting.js"; +import { type AccountStatus, Role } from "constants/userConts.ts"; + +type AuthenticatedUser = { + id: string; + role: Role; + accountStatus?: AccountStatus; +}; declare global { namespace Express { interface Request { - user?: User; - sessionId?: string; + 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 index 9ab68b4..e69de29 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1 +0,0 @@ -export type { AuthenticatedRequest, ValidatedRequest, ValidatedParamsRequest, PaginatedRequest } from "./RequestTypes.js"; diff --git a/src/utils/buildSessionMetadata.ts b/src/utils/buildSessionMetadata.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/utils/emails/sender/sendEmailVerificationLink.ts b/src/utils/emails/sender/sendEmailVerificationLink.ts index ebe5aca..4bbe2cb 100644 --- a/src/utils/emails/sender/sendEmailVerificationLink.ts +++ b/src/utils/emails/sender/sendEmailVerificationLink.ts @@ -1,4 +1,3 @@ -import { InternalServerError } from "@middleware/error/index.js"; import { User } from "@models/User.js"; import transporter from "config/mail.js"; import { emailVerificationTemplate } from "../templates/emailVerification.js"; diff --git a/src/utils/emails/sender/sendResetLink.ts b/src/utils/emails/sender/sendResetLink.ts index 0bb799e..768ad3b 100644 --- a/src/utils/emails/sender/sendResetLink.ts +++ b/src/utils/emails/sender/sendResetLink.ts @@ -1,4 +1,3 @@ -import { InternalServerError } from "@middleware/error/index.js"; import { User } from "@models/User.js"; import transporter from "config/mail.js"; import { RESET_EXP_MIN } from "constants/authConsts.js"; diff --git a/src/utils/emails/sender/sendUpdateEmaiLink.ts b/src/utils/emails/sender/sendUpdateEmailLink.ts similarity index 100% rename from src/utils/emails/sender/sendUpdateEmaiLink.ts rename to src/utils/emails/sender/sendUpdateEmailLink.ts diff --git a/src/utils/generateAllCookieTokens.ts b/src/utils/generateAllCookieTokens.ts new file mode 100644 index 0000000..ed21627 --- /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/userConts.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/safeParseJSON.ts b/src/utils/safeParseJSON.ts new file mode 100644 index 0000000..069a02c --- /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; \ No newline at end of file diff --git a/src/utils/sanitizeProjectResponse.ts b/src/utils/sanitizeProjectResponse.ts index a1e3bb0..f9a8466 100644 --- a/src/utils/sanitizeProjectResponse.ts +++ b/src/utils/sanitizeProjectResponse.ts @@ -27,9 +27,7 @@ const sanitizeProjectResponse = ({ description: project.description, visibility: project.visibility, status: project.status, - contextProfileId: project.contextProfileId, - activeStoryId: project.activeStoryId, - activeStoryGeneratedAt: project.activeStoryGeneratedAt, + contextProfileId: project.defaultContextProfileId, generationCounts: project.generationCounts, createdAt: project.createdAt, updatedAt: project.updatedAt, diff --git a/src/utils/tokens.ts b/src/utils/tokens.ts index 2a48203..3153d52 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 { Types } from "mongoose"; +import { UnauthenticatedError } from "@middleware/error/index.js"; +import { AccountStatus } from "@constants/userConts.js"; const ACCESS_TOKEN_EXPIRES_IN: SignOptions["expiresIn"] = process.env .ACCESS_TOKEN_EXPIRES_IN as SignOptions["expiresIn"]; @@ -28,7 +30,7 @@ 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; @@ -53,14 +55,15 @@ export function hashToken(rawToken: string) { export function generateSessionId() { return crypto.randomBytes(32).toString("hex"); } -export function generateAccessToken(userId: Types.ObjectId, 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: Types.ObjectId, - sessionId: string + sessionId: string, + reduceTime: boolean = false ) { return jwt.sign({ userId, sessionId }, REFRESH_TOKEN_SECRET, { expiresIn: REFRESH_TOKEN_EXPIRES_IN, 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/project.schema.ts b/src/validation/project.schema.ts index c2064f1..8a2dad2 100644 --- a/src/validation/project.schema.ts +++ b/src/validation/project.schema.ts @@ -1,3 +1,4 @@ +import { CameraMotion, EnvironmentType, GenreType, MoodType, NarrativeScope, StyleType } from "@models/ContextProfile.js"; import { z } from "zod"; export const createProjectSchema = z @@ -7,7 +8,7 @@ export const createProjectSchema = z .string() .min(5, "Description is required") .max(500, "Description is too long"), - status: z.enum(["active", "draft", "archive", "delete"]), + status: z.enum(["active", "draft"]), visibility: z.enum(["public", "private"]).optional(), }) .strict(); @@ -36,11 +37,6 @@ export const updateProjectStatusSchema = z status: z.enum(["active", "draft", "archive"]), }) .strict(); -export const projectIdParamSchema = z - .object({ - projectId: z.string().length(24, "Invalid project ID"), - }) - .strict(); export const updateManyIdsSchema = z .object({ @@ -58,5 +54,73 @@ export type UpdateProjectVisibilityInput = z.infer< export type UpdateProjectStatusInput = z.infer< typeof updateProjectStatusSchema >; +export const projectIdParamSchema = z + .object({ + projectId: z.string().length(24, "Invalid project ID"), + }) + .strict(); + + + const environmentSchema = z.object({ + type: z.nativeEnum(EnvironmentType), + cameraMotion: z.nativeEnum(CameraMotion), + description: z.string().max(300).optional(), +}); + +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.nativeEnum(GenreType), + mood: z.nativeEnum(MoodType), + style: z.nativeEnum(StyleType), + + narrativeScope: z + .nativeEnum(NarrativeScope) + .optional(), + + environment: environmentSchema, + + 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< + typeof createProjectContextProfileSchema +>; diff --git a/src/validation/story.schema.ts b/src/validation/story.schema.ts index e69de29..4f3d856 100644 --- a/src/validation/story.schema.ts +++ b/src/validation/story.schema.ts @@ -0,0 +1,88 @@ +import { maxTimeLimit, minTimeLimit, storyIntent } from "@constants/storyConsts.js"; +import { platform } from "node:process"; +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(), + }) + .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").optional(), + }) + .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({ + data: z.object({ + name: z.string().min(1).max(100), + description: z.string().max(600).optional(), + + genre: z.string(), + mood: z.string(), + style: z.string(), + + environment: z.object({ + type: z.string(), + cameraMotion: z.string(), + description: z.string().max(300).optional(), + }), + + worldRules: z.string().max(1000).optional(), + narrativeConstraints: z.string().max(1000).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; \ No newline at end of file diff --git a/src/validation/user.schema.ts b/src/validation/user.schema.ts index cb8aa79..7089c04 100644 --- a/src/validation/user.schema.ts +++ b/src/validation/user.schema.ts @@ -1,6 +1,5 @@ // src/validation/user.schema.ts -import { z } from "zod"; -import { ACCOUNT_STATUSES } from "constants/authConsts.js"; +import { z } from "zod"; /* ------------------------- Body Schemas diff --git a/tsconfig.json b/tsconfig.json index b4a6870..5da82b9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,6 +22,8 @@ "@models/*": ["models/*"], "@routes/*":["routes/*"], "@validation/*":["validation/*"], + "@libs/*": ["libs/*"], + "@constants/*": ["constants/*"] } }, "include": ["src"] From d40675ca74e81d3a8cb6ae3cc661b58a40857317 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Wed, 21 Jan 2026 02:00:08 +0530 Subject: [PATCH 10/14] Add scenes module and fix some Context, Auth, User, Project module things --- .gitignore | 8 + src/constants/authConsts.ts | 2 +- src/constants/globalConts.ts | 3 +- src/constants/sceneConsts.ts | 15 + src/constants/{userConts.ts => userConsts.ts} | 2 +- src/libs/ai/clients/openAI.ts | 17 +- .../ai/constants/sceneAssetsPromptConts.ts | 21 + src/libs/ai/constants/scenesPromptConts.ts | 171 +++ ...enerationFormat.ts => storyPromptConts.ts} | 2 +- src/libs/ai/prompts/batchScenesPrompt.ts | 147 +++ src/libs/ai/prompts/generateStoryPrompt.ts | 46 +- .../generateStoryRegenerationPrompt.ts | 64 +- src/libs/ai/prompts/singleScenePrompt.ts | 249 +++++ src/middleware/auth/requireAuth.ts | 2 +- src/middleware/error/globalErrorHandler.ts | 20 +- src/middleware/security/requireCsrf.ts | 54 +- src/models/Narration.ts | 0 src/models/Scene.ts | 46 +- src/modules/auth/auth.controller.ts | 22 +- src/modules/auth/auth.service.ts | 99 +- .../contextProfile.controller.ts | 14 +- .../contextProfile/contextProfile.service.ts | 47 +- src/modules/narration/narration.controller.ts | 0 src/modules/narration/narration.routes.ts | 0 src/modules/narration/narration.service.ts | 0 src/modules/project/project.controller.ts | 63 +- src/modules/scenes/scenes.controller.ts | 245 +++++ src/modules/scenes/scenes.private.routes.ts | 144 +++ src/modules/scenes/scenes.service.ts | 994 ++++++++++++++++++ src/modules/story/story.controller.ts | 20 +- src/modules/story/story.service.ts | 9 +- src/modules/user/user.controller.ts | 9 +- src/modules/user/user.service.ts | 28 +- src/routes/api.ts | 42 +- .../guards/getAccountBlockResponse.ts | 6 +- .../policies/accountStatusResponses.ts | 2 +- src/types/Context.ts | 25 + src/types/express.d.ts | 2 +- src/utils/generateAllCookieTokens.ts | 2 +- src/utils/safeParseJSON.ts | 8 +- src/utils/tokens.ts | 2 +- src/validation/scenes.schema.ts | 221 ++++ src/validation/story.schema.ts | 3 +- tsconfig.json | 4 +- 44 files changed, 2539 insertions(+), 341 deletions(-) create mode 100644 src/constants/sceneConsts.ts rename src/constants/{userConts.ts => userConsts.ts} (79%) create mode 100644 src/libs/ai/constants/sceneAssetsPromptConts.ts create mode 100644 src/libs/ai/constants/scenesPromptConts.ts rename src/libs/ai/constants/{storyGenerationFormat.ts => storyPromptConts.ts} (99%) create mode 100644 src/libs/ai/prompts/batchScenesPrompt.ts create mode 100644 src/libs/ai/prompts/singleScenePrompt.ts create mode 100644 src/models/Narration.ts create mode 100644 src/modules/narration/narration.controller.ts create mode 100644 src/modules/narration/narration.routes.ts create mode 100644 src/modules/narration/narration.service.ts create mode 100644 src/types/Context.ts diff --git a/.gitignore b/.gitignore index 3859b7d..52f36d9 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,11 @@ coverage/ # Local certificates *.pem *.key + +// IDE specific files +.postman/ +postman/ +.history + +.prettierrc + diff --git a/src/constants/authConsts.ts b/src/constants/authConsts.ts index 15b196c..c249c0b 100644 --- a/src/constants/authConsts.ts +++ b/src/constants/authConsts.ts @@ -1,5 +1,5 @@ // constants/accountStatus.ts -export { ACCOUNT_STATUSES, type AccountStatus } from './userConts.js'; +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 index 2be986f..e6fddb2 100644 --- a/src/constants/globalConts.ts +++ b/src/constants/globalConts.ts @@ -3,4 +3,5 @@ export const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS : [ process.env.DEV_CLIENT_URL || 'http://localhost:3000', process.env.PROD_CLIENT_URL || 'https://your-production-app.com', - ]; \ No newline at end of file + ]; + \ No newline at end of file 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/userConts.ts b/src/constants/userConsts.ts similarity index 79% rename from src/constants/userConts.ts rename to src/constants/userConsts.ts index c27f24c..5af4d45 100644 --- a/src/constants/userConts.ts +++ b/src/constants/userConsts.ts @@ -16,4 +16,4 @@ export const ACCOUNT_STATUSES = [ "delete", ] as const; -export type AccountStatus = (typeof ACCOUNT_STATUSES)[number]; \ No newline at end of file +export type AccountStatus = (typeof ACCOUNT_STATUSES)[number]; diff --git a/src/libs/ai/clients/openAI.ts b/src/libs/ai/clients/openAI.ts index cb90de1..8d0c2a7 100644 --- a/src/libs/ai/clients/openAI.ts +++ b/src/libs/ai/clients/openAI.ts @@ -1,3 +1,5 @@ +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"); @@ -6,6 +8,7 @@ export async function openRouterAI(prompt: string): Promise { "https://openrouter.ai/api/v1/chat/completions", { method: "POST", + // signal: AbortSignal.timeout(30000), // 30s timeout headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", @@ -25,17 +28,25 @@ Rules: - No backticks - No explanations - No extra text -` +`, }, { role: "user", - content: prompt - } + content: 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/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/storyGenerationFormat.ts b/src/libs/ai/constants/storyPromptConts.ts similarity index 99% rename from src/libs/ai/constants/storyGenerationFormat.ts rename to src/libs/ai/constants/storyPromptConts.ts index e76659c..88b4299 100644 --- a/src/libs/ai/constants/storyGenerationFormat.ts +++ b/src/libs/ai/constants/storyPromptConts.ts @@ -26,4 +26,4 @@ MANDATORY RULES: - Keywords must be search-friendly and descriptive - Word/time limits defined elsewhere MUST be respected - Violating this format is a failure -`; \ No newline at end of file +`; diff --git a/src/libs/ai/prompts/batchScenesPrompt.ts b/src/libs/ai/prompts/batchScenesPrompt.ts new file mode 100644 index 0000000..bd24e08 --- /dev/null +++ b/src/libs/ai/prompts/batchScenesPrompt.ts @@ -0,0 +1,147 @@ +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; +import { buildStoryContextSection } from './utils/buildStoryContextSection.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'; + +export type BatchSceneMode = 'generate' | 'regenerate'; + +type StoryContent = { + summary?: string; + body?: string; + keywords?: string[]; + tags?: string[]; +}; + +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 = buildStoryContextSection(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 index 6932cb8..2456428 100644 --- a/src/libs/ai/prompts/generateStoryPrompt.ts +++ b/src/libs/ai/prompts/generateStoryPrompt.ts @@ -1,9 +1,9 @@ -import { ContextProfile } from "@models/ContextProfile.js"; -import { GLOBAL_SAFETY_RULES } from "../constants/globalSafetyRules.js"; -import { STORY_GENERATION_FORMAT } from "../constants/storyGenerationFormat.js"; -import { buildStoryContextSection } from "./utils/buildStoryContextSection.js"; -import { calculateWordLimits } from "../constants/calculateWordLimits.js"; -import { Platform, StoryIntent } from "@constants/storyConsts.js"; +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; +import { STORY_GENERATION_FORMAT } from '../constants/storyPromptConts.js'; +import { buildStoryContextSection } from './utils/buildStoryContextSection.js'; +import { calculateWordLimits } from '../constants/calculateWordLimits.js'; +import { Platform, StoryIntent } from '@constants/storyConsts.js'; type GenerateStoryPromptInput = { title: string; @@ -19,31 +19,35 @@ export function generateStoryPrompt({ title, description, timeLimit, - contextProfile, + contextProfile, }: GenerateStoryPromptInput): string { const sections: string[] = []; /* 1. ROLE (STRICT) */ - sections.push(` + 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()); +`.trim() + ); /* 2. STORY BRIEF */ - sections.push(` + sections.push( + ` STORY BRIEF Title: "${title}" Description: "${description}" -`.trim()); +`.trim() + ); /* 3. HARD TIME / LENGTH CONSTRAINT */ if (timeLimit) { - const { targetWords, minWords, maxWords } = - calculateWordLimits(timeLimit, contextProfile?.narrationProfile); + const { targetWords, minWords, maxWords } = calculateWordLimits(timeLimit, contextProfile?.narrationProfile); - sections.push(` + sections.push( + ` HARD LENGTH CONSTRAINT (ABSOLUTE) - Target length: ${targetWords} words @@ -54,16 +58,16 @@ Rules: - The story MUST stay within this range - Being shorter or longer is a FAILURE - If necessary, compress or expand minimally to fit -`.trim()); -} - +`.trim() + ); + } /* 4. CONTEXT PROFILE (BINDING, NO EXPANSION) */ if (contextProfile) { const contextSection = buildStoryContextSection(contextProfile); -if (contextSection) { - sections.push(contextSection); -} + if (contextSection) { + sections.push(contextSection); + } } /* 5. GLOBAL SAFETY RULES (ABSOLUTE) */ @@ -72,5 +76,5 @@ if (contextSection) { /* 6. OUTPUT FORMAT (STRICT JSON) */ sections.push(STORY_GENERATION_FORMAT.trim()); - return sections.join("\n\n"); + return sections.join('\n\n'); } diff --git a/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts b/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts index 9534d3c..3b5256d 100644 --- a/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts +++ b/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts @@ -1,9 +1,9 @@ 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/storyGenerationFormat.js"; -import { buildStoryContextSection } from "./utils/buildStoryContextSection.js"; -import { calculateWordLimits } from "../constants/calculateWordLimits.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 { buildStoryContextSection } from './utils/buildStoryContextSection.js'; +import { calculateWordLimits } from '../constants/calculateWordLimits.js'; type RegenerateStoryPromptInput = { title: string; @@ -27,15 +27,18 @@ export function generateStoryRegenerationPrompt({ const sections: string[] = []; /* 1. ROLE (CONTROLLED CREATION) */ - sections.push(` + 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()); +`.trim() + ); /* 2. FIXED STORY ANCHORS (DO NOT CHANGE) */ - sections.push(` + sections.push( + ` STORY ANCHORS (REFERENCE ONLY — DO NOT CHANGE) Title: "${title}" @@ -43,10 +46,12 @@ Description: "${description}" Existing Summary (intent reference only): ${existingSummary} -`.trim()); +`.trim() + ); /* 3. REGENERATION TASK */ - sections.push(` + sections.push( + ` REGENERATION TASK (MANDATORY) You must regenerate the story based on the anchors above. @@ -58,21 +63,24 @@ Rules: - Do NOT add unnecessary exposition - Prefer concise, efficient storytelling - Brevity is a priority -`.trim()); +`.trim() + ); /* 4. USER REQUEST */ - sections.push(` + sections.push( + ` USER REQUESTED CHANGES (ONLY THESE) ${extraPrompt} -`.trim()); - +`.trim() + ); + /* 5. HARD TIME / LENGTH CONSTRAINT */ - if (timeLimit) { - const { targetWords, minWords, maxWords } = - calculateWordLimits(timeLimit, contextProfile?.narrationProfile); + if (timeLimit) { + const { targetWords, minWords, maxWords } = calculateWordLimits(timeLimit, contextProfile?.narrationProfile); - sections.push(` + sections.push( + ` HARD LENGTH CONSTRAINT (ABSOLUTE) - Target length: ${targetWords} words @@ -83,17 +91,17 @@ Rules: - The story MUST stay within this range - Being shorter or longer is a FAILURE - If necessary, compress or expand minimally to fit -`.trim()); -} - +`.trim() + ); + } /* 4. CONTEXT PROFILE (BINDING, NO EXPANSION) */ - if (contextProfile) { - const contextSection = buildStoryContextSection(contextProfile); - if (contextSection) { - sections.push(contextSection); - } - } + if (contextProfile) { + const contextSection = buildStoryContextSection(contextProfile); + if (contextSection) { + sections.push(contextSection); + } + } /* 7. GLOBAL SAFETY RULES (ABSOLUTE) */ sections.push(GLOBAL_SAFETY_RULES.trim()); @@ -101,5 +109,5 @@ Rules: /* 8. OUTPUT FORMAT (STRICT JSON) */ sections.push(STORY_GENERATION_FORMAT.trim()); - return sections.join("\n\n"); + 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..1467c7f --- /dev/null +++ b/src/libs/ai/prompts/singleScenePrompt.ts @@ -0,0 +1,249 @@ +import { ContextProfile } from '@models/ContextProfile.js'; +import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; +import { buildStoryContextSection } from './utils/buildStoryContextSection.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'; + +export type SingleSceneMode = 'generate' | 'variation' | 'regenerate'; + +type StoryContent = { + summary?: string; + keywords?: string[]; + tags?: string[]; +}; + +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 = buildStoryContextSection(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/middleware/auth/requireAuth.ts b/src/middleware/auth/requireAuth.ts index 25f403c..5739456 100644 --- a/src/middleware/auth/requireAuth.ts +++ b/src/middleware/auth/requireAuth.ts @@ -2,7 +2,7 @@ import type { Request, Response, NextFunction } from "express"; import jwt from "jsonwebtoken"; import { UnauthenticatedError } from "@middleware/error/index.js"; -import { AccountStatus } from "@constants/userConts.js"; +import { AccountStatus } from "@constants/userConsts.js"; export const authMiddleware = async ( req: Request, diff --git a/src/middleware/error/globalErrorHandler.ts b/src/middleware/error/globalErrorHandler.ts index f58e5e4..67cb619 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -1,20 +1,16 @@ // src/middleware/errorHandler.ts -import { NextFunction, Request, Response } from "express"; -import { AppError } from "./appError.js"; -import logger from "@utils/logger.js"; +import { NextFunction, Request, Response } from 'express'; +import { AppError } from './appError.js'; +import logger from '@utils/logger.js'; -const errorHandler = ( - err: unknown, - req: Request, - res: Response, - next: NextFunction -) => { +const errorHandler = (err: unknown, req: Request, res: Response, next: NextFunction) => { // If it's a known error (instance of AppError) if (err instanceof AppError) { logger.error({ message: err.message, details: err.details, stack: err.stack, + actions: err.actions, request: { method: req.method, url: req.originalUrl, @@ -24,10 +20,10 @@ const errorHandler = ( }); return res.status(err.statusCode).json(err.serialize()); - } + } return res.status(500).json({ - status: "error", - message: "Internal Server Error", + status: 'error', + message: 'Internal Server Error', }); }; diff --git a/src/middleware/security/requireCsrf.ts b/src/middleware/security/requireCsrf.ts index d6c7921..ab03939 100644 --- a/src/middleware/security/requireCsrf.ts +++ b/src/middleware/security/requireCsrf.ts @@ -1,44 +1,48 @@ -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 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 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 origin = req.headers.origin; -if (!origin && !ALLOWED_ORIGINS.includes(origin as string)) { - throw new UnauthorizedError("Invalid origin"); -} - - const csrfToken = req.headers["x-csrf-token"]; + 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, + sessionId: req.sessionId, valid: true, - revokedAt: null, - }).select("+csrfTokenHash"); - + revokedAt: null, + }).select("+csrfTokenHash"); + if (!session) { throw new UnauthorizedError(); } - - const isValid = verifyToken(csrfTokenValue,session.csrfTokenHash); - if (!isValid) { + + try { + verifyToken(csrfTokenValue, session.csrfTokenHash); + } catch { throw new UnauthorizedError(); } - next() + next(); }; diff --git a/src/models/Narration.ts b/src/models/Narration.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/models/Scene.ts b/src/models/Scene.ts index 457ee13..d4520b7 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -1,4 +1,4 @@ -import { Schema, model, Document, Types } from "mongoose"; +import { Schema, model, Document, Types } from 'mongoose'; // export interface SceneAssetHistoryEntry { // assetId: Types.ObjectId; @@ -21,11 +21,12 @@ export interface Scene extends Document { order: number; title?: string; description: string; - authorType: "ai" | "user" + authorType: 'ai' | 'user'; imagePrompt: string; - videoPrompt?: string; + videoPrompt: string; duration?: number; - activeAssetId?: Types.ObjectId; + activeAssetId?: Types.ObjectId; + deletedAt?: Date; createdAt: Date; updatedAt: Date; } @@ -34,14 +35,14 @@ const sceneSchema = new Schema( { userId: { type: Schema.Types.ObjectId, - ref: "User", + ref: 'User', required: true, index: true, }, storyId: { type: Schema.Types.ObjectId, - ref: "Story", + ref: 'Story', required: true, }, @@ -61,28 +62,37 @@ const sceneSchema = new Schema( type: String, required: true, }, -authorType: { + authorType: { type: String, - enum: ["ai", "user"], - default: "ai", -}, + 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", + deletedAt: { + type: Date, + default: undefined, + index: true, }, - }, { timestamps: true } ); -sceneSchema.index({ storyId: 1, order: 1 }, { unique: true }); +sceneSchema.index( + { storyId: 1, order: 1 }, + { + unique: true, + partialFilterExpression: { deletedAt: { $exists: false } }, + } +); -export const SceneModel = model("Scene", sceneSchema); +export const SceneModel = model('Scene', sceneSchema); diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index 9123a90..d37a399 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -17,7 +17,7 @@ import type { ForgetPasswordInput, VerifyEmailInput, VerifyUpdateEmailInput, -} from "@validation/auth.schema.js"; +} from "@validation/auth.schema.js"; const CookieOptions: CookieOptions = { httpOnly: true, @@ -26,12 +26,12 @@ const CookieOptions: CookieOptions = { maxAge: 1 * 24 * 60 * 60 * 1000, }; -const CSRF_AGE = 15*24*60*1000; -const REFRESH_AGE = 15*24*60*1000; -const ACCESS_AGE = 30*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.validatedBody as RegisterInput; + const body = req.validatedBody as RegisterInput; const userAgent: string = req.headers["user-agent"] || "unknown"; const ip = @@ -96,7 +96,7 @@ export const loginController = async (req: Request, res: Response) => { }) .cookie("refresh-token", refreshToken, { ...CookieOptions, - maxAge: REFRESH_AGE, + maxAge: REFRESH_AGE, }) .cookie("csrf-token", csrfToken, { ...CookieOptions, @@ -126,7 +126,10 @@ export const forgotPasswordController = async (req: Request, res: Response) => { }; export const resetPasswordController = async (req: Request, res: Response) => { - const { token, password } = req.validatedBody as { token: string; password: string }; + const { token, password } = req.validatedBody as { + token: string; + password: string; + }; await resetPassword(token, password); return res.status(200).json({ status: "success", @@ -170,7 +173,7 @@ export const emailVerificationController = async ( req: Request, res: Response ) => { - const userId = req?.user!.id + const userId = req?.user!.id; await sendEmailVerification(userId); return res.status(200).json({ @@ -191,7 +194,8 @@ export const verifyEmailChangeController = async ( req: Request, res: Response ) => { - const { verificationToken, code } = req.validatedBody as VerifyUpdateEmailInput; + const { verificationToken, code } = + req.validatedBody as VerifyUpdateEmailInput; const currentSessionId = req?.sessionId; await verifyUpdateEmail(verificationToken, code, currentSessionId); return res.status(200).json({ diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index a32d22f..3510724 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -5,7 +5,7 @@ import mongoose, { Types } from "mongoose"; 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 { +import { generateAccessToken, generateCsrfToken, generateRefreshToken, @@ -28,9 +28,9 @@ import { 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 sendVerificationEmail from "@utils/emails/sender/sendEmailVerificationLink.js"; +import ensureActiveAccount from "security/guards/ensureActiveAccount.js"; +import { getAccountBlockResponse } from "security/guards/getAccountBlockResponse.js"; import { createUserSession } from "./utils/createUserSession.js"; type LoginInputWithMeta = LoginInput & { @@ -43,16 +43,16 @@ type SignOutput = { accessToken: string; refreshToken: string; csrfToken: string; - }; + }; }; type RegisterInputWithMeta = RegisterInput & { userAgent: string; ip: string | string[] | undefined; }; -interface RefreshTokenOutput { - accessToken: string; - refreshToken: string; - csrfToken: string; +interface RefreshTokenOutput { + accessToken: string; + refreshToken: string; + csrfToken: string; } export async function registerUser( @@ -68,8 +68,8 @@ export async function registerUser( } } // Metadata - - const passwordHash = await bcrypt.hash(password, 10); + + const passwordHash = await bcrypt.hash(password, 10); const session = await mongoose.startSession(); session.startTransaction(); @@ -90,14 +90,14 @@ export async function registerUser( const user: User = result[0]; const { sessionPayload, tokens } = await createUserSession({ - user, - userAgent, - ip: (Array.isArray(ip) ? ip[0] : ip) || "", -}); + user, + userAgent, + ip: (Array.isArray(ip) ? ip[0] : ip) || "", + }); await SessionModel.create( [ { - ...sessionPayload + ...sessionPayload, }, ], { session } @@ -118,7 +118,7 @@ export async function registerUser( export async function loginUser( input: LoginInputWithMeta -): Promise { +): Promise { const { email, password, userAgent, ip } = input; const user: User | null = await UserModel.findOne({ email }).select( @@ -128,30 +128,29 @@ export async function loginUser( 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, - }) - } + 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 createUserSession({ user, userAgent, ip: (Array.isArray(ip) ? ip[0] : ip) || "", - }); - await SessionModel.create(sessionPayload); + }); + await SessionModel.create(sessionPayload); return { user, tokens }; } @@ -198,10 +197,7 @@ export async function refreshTokens( } // verify refresh token (CORRECT ORDER) - const isValidToken = verifyToken( - refreshToken, - session.refreshTokenHash - ); + const isValidToken = verifyToken(refreshToken, session.refreshTokenHash); if (!isValidToken) { await SessionModel.updateOne( @@ -209,9 +205,7 @@ export async function refreshTokens( { valid: false, revokedAt: new Date() } ).exec(); - throw new UnauthenticatedError( - "Authentication failed: Session revoked" - ); + throw new UnauthenticatedError("Authentication failed: Session revoked"); } const user = await UserModel.findOne({ @@ -231,10 +225,7 @@ export async function refreshTokens( user.accountStatus ); - const newRefreshToken = generateRefreshToken( - user._id, - session.sessionId - ); + const newRefreshToken = generateRefreshToken(user._id, session.sessionId); const newCsrfToken = generateCsrfToken(); @@ -318,16 +309,16 @@ export async function resetPassword(rawToken: string, newPassword: string) { ) { throw new BadRequestError("Invalid or expired token"); } - + if (user.passwordReset.expiresAt.getTime() < Date.now()) { - user.passwordReset = undefined; + user.passwordReset = undefined; await user.save(); throw new BadRequestError("Invalid or expired token"); } const isValid = verifyToken(rawToken, user.passwordReset.tokenHash); if (!isValid) { - throw new BadRequestError("Invalid or expired token"); + throw new BadRequestError("Invalid or expired token"); } const hashedPassword = await bcrypt.hash(newPassword, 10); @@ -383,23 +374,21 @@ export async function resetPassword(rawToken: string, newPassword: string) { } } -export async function sendEmailVerification( - userId: string -): Promise { +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"); } - const active = ensureActiveAccount(user); - if(!active) { + const active = ensureActiveAccount(user); + if (!active) { throw new ForbiddenError("Account is not active"); - } + } if (user.emailVerified) { throw new ConflictError("Email is already verified"); } - + const token = generateVerificationToken(); const verifyEmailUrl = `${ @@ -445,7 +434,7 @@ export async function verifyEmail(verificationToken: string): Promise { throw new BadRequestError("Invalid or expired verification token"); } const active = ensureActiveAccount(user); - if(!active) { + if (!active) { throw new ForbiddenError("Account is not active"); } @@ -504,7 +493,7 @@ export async function verifyUpdateEmail( throw new BadRequestError("Invalid or expired verification token"); } const active = ensureActiveAccount(user); - if(!active) { + if (!active) { throw new ForbiddenError("Account is not active"); } if ( diff --git a/src/modules/contextProfile/contextProfile.controller.ts b/src/modules/contextProfile/contextProfile.controller.ts index 34e6cec..792e0b6 100644 --- a/src/modules/contextProfile/contextProfile.controller.ts +++ b/src/modules/contextProfile/contextProfile.controller.ts @@ -1,15 +1,10 @@ import { Request, Response } from "express"; -import { +import { getContextProfileService, listContextProfilesService, } from "./contextProfile.service.js"; -import { createContextProfileSchema } from "@validation/contextProfile.schema.js"; - -export async function getContextProfileController( - req: Request, - res: Response -) { +export async function getContextProfileController(req: Request, res: Response) { const context = await getContextProfileService( req.user!.id, req.params.contextId @@ -22,10 +17,7 @@ export async function listContextProfilesController( req: Request, res: Response ) { - const contexts = await listContextProfilesService( - req.user!.id, - req.query - ); + const contexts = await listContextProfilesService(req.user!.id, req.query); res.json({ data: contexts }); } diff --git a/src/modules/contextProfile/contextProfile.service.ts b/src/modules/contextProfile/contextProfile.service.ts index d78565f..c74b64a 100644 --- a/src/modules/contextProfile/contextProfile.service.ts +++ b/src/modules/contextProfile/contextProfile.service.ts @@ -1,52 +1,17 @@ -import mongoose from "mongoose"; -import { - ContextProfileModel, - ContextScope, - EnvironmentProfile, - GenreType, - MoodType, - NarrativeScope, - StyleType, -} from "@models/ContextProfile.js"; -import { ProjectModel } from "@models/Project.js"; -import { NARRATION_PROFILES } from "constants/narrationProfiles.js"; +import { NotFoundError } from '@middleware/error/index.js'; +import { ContextProfileModel } 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; -}; - - -export async function getContextProfileService( - userId: string, - contextId: string -) { +export async function getContextProfileService(userId: string, contextId: string) { const context = await ContextProfileModel.findOne({ _id: contextId, userId, }); - if (!context) throw new Error("Context not found"); + if (!context) throw new NotFoundError('Context not found'); return context; } - -export async function listContextProfilesService( - userId: string, - query: any -) { + +export async function listContextProfilesService(userId: string, query: any) { const filter: any = { userId }; if (query.scope) filter.scope = query.scope; diff --git a/src/modules/narration/narration.controller.ts b/src/modules/narration/narration.controller.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/modules/narration/narration.routes.ts b/src/modules/narration/narration.routes.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/modules/narration/narration.service.ts b/src/modules/narration/narration.service.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/modules/project/project.controller.ts b/src/modules/project/project.controller.ts index 6f94c31..95ebb83 100644 --- a/src/modules/project/project.controller.ts +++ b/src/modules/project/project.controller.ts @@ -1,4 +1,4 @@ - import { Request, Response } from "express"; +import { Request, Response } from "express"; import { createProject, createProjectContextProfile, @@ -21,18 +21,14 @@ import { UpdateProjectInput, UpdateManyIdsInput, CreateProjectContextInput, -} from "@validation/project.schema.js"; -import { paginationResponse } from "@utils/paginationResponse.js"; +} from "@validation/project.schema.js"; +import { paginationResponse } from "@utils/paginationResponse.js"; export const getProjectsController = async (req: Request, res: Response) => { - const pagination = req?.pagination!; + const pagination = req?.pagination!; const sorting = req?.sorting!; - const userId = req.user!.id; - const [projects, total] = await getProjects( - userId, - pagination, - 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, @@ -66,9 +62,9 @@ export const getArchivedProjectsController = async ( req: Request, res: Response ) => { - const pagination = req?.pagination!; + const pagination = req?.pagination!; const sorting = req?.sorting!; - const userId = req.user!.id; + const userId = req.user!.id; const [projects, total] = await getArchivedProjects( userId, pagination, @@ -97,11 +93,18 @@ export const getProjectByIdController = async (req: Request, res: Response) => { return res.status(200).json(project); }; -export const createProjectContextProfileController = async (req: Request, res: Response) => { - const projectId = req.params.projectId ; +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); + const newProject = await createProjectContextProfile( + userId, + projectId, + payload + ); return res.status(201).json(newProject); }; @@ -110,13 +113,9 @@ export const updateProjectByIdController = async ( 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 - ); + const updates = req.validatedBody as UpdateProjectInput; + const userId = req.user!.id; + const updatedProject = await updateProjectById(projectId, userId, updates); return res.status(200).json(updatedProject); }; @@ -137,11 +136,7 @@ export const updateProjectStatusController = async ( 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 - ); + const updatedProject = await updateProjectStatus(projectId, userId, status); return res.status(200).json(updatedProject); }; @@ -150,11 +145,11 @@ export const updateProjectVisibilityController = async ( res: Response ) => { const projectId = req.params.projectId as Types.ObjectId | string; - const { visibility } = req.body; + const { visibility } = req.body; const userId = req.user!.id; const updatedProject = await updateProjectVisibility( + projectId, userId, - projectId, visibility ); return res.status(200).json(updatedProject); @@ -176,10 +171,7 @@ export const unarchiveProjectByIdController = async ( ) => { const projectId = req.params.projectId as Types.ObjectId | string; const userId = req.user!.id; - const unarchivedProject = await unarchiveProjectById( - projectId, - userId - ); + const unarchivedProject = await unarchiveProjectById(projectId, userId); return res.status(200).json(unarchivedProject); }; @@ -189,10 +181,7 @@ export const restoreManyProjectsController = async ( ) => { const { projectIds } = req.validatedBody as UpdateManyIdsInput; const userId = req.user!.id; - const restoredProjects = await restoreManyProjectsByIds( - projectIds, - userId - ); + const restoredProjects = await restoreManyProjectsByIds(projectIds, userId); return res.status(200).json(restoredProjects); }; diff --git a/src/modules/scenes/scenes.controller.ts b/src/modules/scenes/scenes.controller.ts index e69de29..e1d967b 100644 --- a/src/modules/scenes/scenes.controller.ts +++ b/src/modules/scenes/scenes.controller.ts @@ -0,0 +1,245 @@ +import { Request, Response } from 'express'; +import { + createScene, + getSceneById, + getAllScenesForStory, + updateScene, + softDeleteScene, + restoreScene, + bulkReorder, + generateSceneWithAI, + regenerateScene, + generateAllScenes, + regenerateAllScenes, + duplicateScene, + moveSceneByOne, + getSceneCount, + restoreAllDeletedScenes, + bulkRestoreScenes, + updateSceneDuration, + getAllDeletedScenes, +} 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 getAllDeltedScenesController = 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 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, + }); +}; + +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, + }); +}; + +// 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, + }); +}; + +// 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 { duration } = req.validatedBody as DurationInput; + const scene = await updateSceneDuration(userId, sceneId, duration); + res.status(200).json({ + message: 'Scene duration updated successfully', + data: scene, + }); +}; + +export const deleteSceneController = 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 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 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 index e69de29..4b5e559 100644 --- a/src/modules/scenes/scenes.private.routes.ts +++ b/src/modules/scenes/scenes.private.routes.ts @@ -0,0 +1,144 @@ +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, + getSceneByIdController, + createSceneController, + updateSceneController, + deleteSceneController, + restoreSceneController, + moveSceneController, + bulkReorderController, + bulkRestoreScenesController, + restoreAllDeletedScenesController, + generateScenesController, + regenerateScenesController, + generateSingleSceneController, + regenerateSceneController, + getSceneCountController, + getAllDeltedScenesController, + updateSceneDurationController, +} from './scenes.controller.js'; + +const router = Router(); + +// ALL SCENES ROUTES FOR A STORY + +router.get('/:storyId', validateParams(storyIdParamSchema), asyncHandler(getAllStoryScenesController)); + +router.get('/:storyId/deleted', validateParams(storyIdParamSchema), asyncHandler(getAllDeltedScenesController)); + +router.get('/:storyId/count', validateParams(storyIdParamSchema), asyncHandler(getSceneCountController)); + +router.post( + '/:storyId/generate', + validateParams(storyIdParamSchema), + validateBody(generateAllScenesSchema), + asyncHandler(generateScenesController) +); + +router.post( + '/:storyId/regenerate', + validateParams(storyIdParamSchema), + validateBody(regenerateSceneSchema), + asyncHandler(regenerateScenesController) +); + +// 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/restore-all', + validateParams(storyIdParamSchema), + asyncHandler(restoreAllDeletedScenesController) +); + +// SINGLE SCENE ROUTES + +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.delete( + '/:storyId/scene/:sceneId', + validateParams(sceneAndStoryParamSchema), + asyncHandler(deleteSceneController) +); + +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..f59c65e 100644 --- a/src/modules/scenes/scenes.service.ts +++ b/src/modules/scenes/scenes.service.ts @@ -0,0 +1,994 @@ +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 { getContextProfileService } from '@modules/contextProfile/contextProfile.service.js'; +import { batchScenesPrompt } from '@libs/ai/prompts/batchScenesPrompt.js'; + +// Helpers for -> Ownership and -> State validation +async function validateStoryOwnership( + userId: string, + storyId: string, + session?: ClientSession +): Promise { + const query = StoryModel.findOne({ + _id: storyId, + userId, + status: { $ne: 'delete' }, + }); + + if (session) query.session(session); + + const story = await query; + if (!story) { + throw new NotFoundError('Story not found or access denied'); + } + return story; +} + +async function validateSceneOwnership( + userId: string, + sceneId: string, + options?: { session?: ClientSession } +): Promise { + const query = SceneModel.findOne({ + _id: sceneId, + userId, + }); + if (options?.session) query.session(options.session); + + const scene = await query; + if (!scene) { + throw new NotFoundError('Scene not found or access denied'); + } + return scene; +} + +function assertSceneNotDeleted(scene: Scene): void { + if (scene.deletedAt) { + throw new ConflictError('Cannot perform operation on deleted scene'); + } +} + +function assertSceneIsDeleted(scene: Scene): void { + if (!scene.deletedAt) { + throw new ConflictError('Scene is not deleted'); + } +} + +// -> 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, + 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 { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + 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'); + } + + console.log(generatedScenesData); + + 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: { + deletedAt: new Date(), + 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[]; + + await session.commitTransaction(); + return scenes; + } catch (error) { + console.error('REAL ERROR:', error); + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function regenerateAllScenes( + userId: string, + storyId: string, + extraPrompt?: string +): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + 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'); + } + + console.log(regeneratedScenesData); + + if ( + !regeneratedScenesData || + !Array.isArray(regeneratedScenesData) || + regeneratedScenesData.length !== totalScenes + ) { + throw new InternalServerError('AI returned invalid scene structure'); + } + + // Soft-delete old scenes ONLY after AI is validated + const ops = existingScenes.map((doc, i) => ({ + updateOne: { + filter: { _id: doc._id }, + update: { + $set: { + deletedAt: new Date(), + 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[]; + + await session.commitTransaction(); + return scenes; + } catch (error) { + console.log(error); + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function restoreAllDeletedScenes(userId: string, storyId: string): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + try { + 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); + if (scenesToRestore.length === 0) { + throw new BadRequestError('No deleted scenes to restore'); + } + const bulkOps = scenesToRestore.map((scene, index) => ({ + updateOne: { + filter: { _id: scene._id }, + update: { $unset: { deletedAt: '' }, $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP } }, + }, + })); + await SceneModel.bulkWrite(bulkOps, { session }); + const restoredScenes = await SceneModel.find({ + storyId, + userId, + }) + .sort({ order: 1 }) + .lean() + .session(session); + await session.commitTransaction(); + return restoredScenes; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +// Bulk scene services +export async function bulkRestoreScenes( + userId: string, + storyId: string, + sceneIds: string[] +): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + 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); + + if (scenesToRestore.length === 0) { + throw new BadRequestError('No valid scenes to restore'); + } + const bulkOps = scenesToRestore.map((scene, index) => ({ + updateOne: { + filter: { _id: scene._id }, + update: { $unset: { deletedAt: '' }, $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP } }, + }, + })); + await SceneModel.bulkWrite(bulkOps, { session }); + + const restoredScenes = await SceneModel.find({ + _id: { $in: sceneIds }, + storyId, + userId, + }) + .sort({ order: 1 }) + .lean() + .session(session); + await session.commitTransaction(); + return restoredScenes; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function bulkReorder( + userId: string, + storyId: string, + newOrderArray: BulkReorderInput +): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + await validateStoryOwnership(userId, storyId, session); + + const sceneIds = newOrderArray.sceneIds; + + 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 uniqueIds = new Set(sceneIds); + if (uniqueIds.size !== sceneIds.length) { + throw new BadRequestError('Duplicate scene IDs in order array'); + } + + 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); + + await session.commitTransaction(); + return updatedScenes; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +// Single scene services +export async function getSceneById(userId: string, storyId: string, sceneId: string): Promise { + await validateStoryOwnership(userId, storyId); + + const scene = await SceneModel.findOne({ + _id: sceneId, + storyId, + userId, + }); + + if (!scene) { + throw new NotFoundError('Scene not found'); + } + + return scene; +} + +export async function createScene( + userId: string, + storyId: string, + payload: CreateSceneInput, + position?: number +): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + 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 } + ); + + await session.commitTransaction(); + return scene; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function generateSceneWithAI( + userId: string, + storyId: string, + input?: GenerateSceneInput +): Promise { + const position = input?.position; + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + const story = 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; + } + } + + // check if this affects total scenes duration limit with time limit + + 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 } + ); + + await session.commitTransaction(); + return scene; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function regenerateScene( + userId: string, + sceneId: string, + input?: RegenerateSceneInput +): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + 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 } }) + .lean() + .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'); + } + + await session.commitTransaction(); + return updatedScene; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +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, sceneId: string, duration: number): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneNotDeleted(scene); + // check if this update does not effect total scenes duration limit with story time limit + const updatedScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $set: { duration } }, + { new: true, runValidators: true } + ); + 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 }> { + const session = await mongoose.startSession(); + session.startTransaction(); + + try { + 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, + }; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +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() } }); + return true; +} + +export async function restoreScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + assertSceneIsDeleted(scene); + const maxOrderScene = await SceneModel.findOne({ + storyId: scene.storyId, + userId, + deletedAt: { $exists: false }, + }) + .sort({ order: -1 }) + .lean(); + const newOrder = maxOrderScene ? maxOrderScene.order + SCENE_ORDER_GAP : SCENE_ORDER_GAP; + const restoredScene = await SceneModel.findByIdAndUpdate( + sceneId, + { $unset: { deletedAt: '' }, $set: { order: newOrder } }, + { new: true, runValidators: true } + ); + if (!restoredScene) { + throw new NotFoundError('Scene not found'); + } + return restoredScene; +} + +// 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(); + } +} + +export async function purgeDeletedScenes(userId: string, storyId: string): Promise { + await validateStoryOwnership(userId, storyId); + return 0; +} diff --git a/src/modules/story/story.controller.ts b/src/modules/story/story.controller.ts index 331c2bf..6af3960 100644 --- a/src/modules/story/story.controller.ts +++ b/src/modules/story/story.controller.ts @@ -41,8 +41,7 @@ export const getUserStoriesController = async (req: Request, res: Response) => { export const getProjectStoriesController = async ( req: Request, res: Response -) => { - console.log("STORY ROUTER REGISTERED"); +) => { const userId = req.user!.id; const projectId = req.params.projectId; @@ -78,7 +77,7 @@ export const createStoryController = async (req: Request, res: Response) => { export const getStoryByIdController = async (req: Request, res: Response) => { const userId = req.user!.id; - const storyId = req.params.id; + const storyId = req.params.storyId; const story = await getStoryById(userId, storyId); return res.status(200).json({ story, @@ -205,13 +204,6 @@ export const restoreStoryController = async (req: Request, res: Response) => { }); }; -export const rollbackStoryController = async (req: Request, res: Response) => { - const userId = req.user!.id; - const storyId = req.params.id; - - // to be implemented -}; - export const archiveStoryStatusController = async ( req: Request, res: Response @@ -235,4 +227,12 @@ export const unarchiveStoryController = async (req: Request, res: Response) => { 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 }; \ No newline at end of file diff --git a/src/modules/story/story.service.ts b/src/modules/story/story.service.ts index 6797ccb..5051095 100644 --- a/src/modules/story/story.service.ts +++ b/src/modules/story/story.service.ts @@ -1,5 +1,4 @@ -import { platform } from '@constants/storyConsts.js'; -import { ConflictError, NotFoundError } from "@middleware/error/index.js"; + import { ConflictError, NotFoundError } from "@middleware/error/index.js"; import { ContextProfileModel, ContextScope, @@ -14,7 +13,7 @@ import { } 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 { generateStoryPrompt } from "@libs/ai/prompts/generateStoryPrompt.js"; import { generateStoryRegenerationPrompt } from "libs/ai/prompts/generateStoryRegenerationPrompt.js"; import mongoose from "mongoose"; import { Pagination, Sorting } from "types/Pagination.js"; @@ -290,9 +289,7 @@ export async function generateStory(userId: string, storyId: string) { }, }, { new: true, runValidators: true } - ); - - console.log("AI RESPONSE RECEIVED IN SERVICE:", content); + ); return updatedStory; } diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index af26d39..33e8b8e 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -26,7 +26,7 @@ import { updatePassword, updatePrivacySettings, updateProfile, -} from "./user.service.js"; +} from "./user.service.js"; export const getProfileController = async (req: Request, res: Response) => { const userId = req.user!.id; @@ -116,7 +116,7 @@ export const updatePrivacySettingsController = async ( res: Response ) => { const userId = req.user!.id; - const privacyPrefs = req.validatedBody as UpdatePrivacySettingsType ; + const privacyPrefs = req.validatedBody as UpdatePrivacySettingsType; const updatedUser = await updatePrivacySettings(userId, privacyPrefs); return res.status(200).json({ id: updatedUser._id, @@ -126,7 +126,8 @@ export const updatePrivacySettingsController = async ( export const updatePasswordController = async (req: Request, res: Response) => { const userId = req.user!.id; - const { currentPassword, newPassword } = req.validatedBody as UpdatePasswordType; + const { currentPassword, newPassword } = + req.validatedBody as UpdatePasswordType; // TODO : Ask user if wanted to remove all sessions except current await updatePassword(userId, currentPassword, newPassword); @@ -137,7 +138,7 @@ export const updatePasswordController = async (req: Request, res: Response) => { export const updateEmailController = async (req: Request, res: Response) => { const userId = req.user!.id; - const { newEmail } = req.validatedBody as UpdateEmailType; + const { newEmail } = req.validatedBody as UpdateEmailType; await updateEmail(userId, newEmail); return res.status(200).json({ diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 27c7c07..b6d6acb 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -1,8 +1,7 @@ - import bcrypt from "bcrypt"; import { BadRequestError, - ConflictError, + ConflictError, InternalServerError, NotFoundError, UnauthenticatedError, @@ -14,11 +13,10 @@ import { UpdateNotificationsType, UpdatePrivacySettingsType, } from "@validation/user.schema.js"; -import mongoose, { Types } from "mongoose"; -import { generateVerificationToken, verifyToken } from "@utils/tokens.js"; +import mongoose from "mongoose"; +import { generateVerificationToken } from "@utils/tokens.js"; import sendUpdateEmailLink from "@utils/emails/sender/sendUpdateEmailLink.js"; import sendOldEmailVerificationForEmailUpdate from "@utils/emails/sender/sendOldEmailVerificationForEmailUpdate.js"; -import { generateAllCookieTokens } from "@utils/generateAllCookieTokens.js"; export const getProfile = async (userId: string): Promise => { const user = await UserModel.findById(userId) @@ -102,9 +100,7 @@ export const deleteAvatar = async (userId: string): Promise => { return; }; -export const getSettings = async ( - userId: string -): Promise> => { +export const getSettings = async (userId: string): Promise> => { const user = await UserModel.findById(userId).select( "emailNotifications privacySettings" ); @@ -115,9 +111,7 @@ export const getSettings = async ( return resUser; }; -export const getSecurity = async ( - userId: string -): Promise> => { +export const getSecurity = async (userId: string): Promise> => { const user = await UserModel.findById(userId).select( "email phoneNumber passwordHash emailVerified phoneVerified lastPasswordChangeAt twoFactorEnabled oauthProviders" ); @@ -165,9 +159,7 @@ export const getSessions = async ( return resSessions; }; -export const getBilling = async ( - userId: string -): Promise> => { +export const getBilling = async (userId: string): Promise> => { const user = await UserModel.findById(userId).select("plan billingInfo"); if (!user) { throw new NotFoundError("User not found"); @@ -397,8 +389,10 @@ export const reactivateAccount = async ( if (!user) { throw new NotFoundError("User not found"); } - if(user.accountStatus !== "deactive" && user.accountStatus !== "delete"){ - throw new BadRequestError("Account is not deactivated or deleted other than that cannot be reactivated. Contact support."); + 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, @@ -428,7 +422,7 @@ export const reactivateAccount = async ( throw new NotFoundError("User not found"); } const resUser = returnUserData(updatedUser, "profile"); - + return resUser; }; diff --git a/src/routes/api.ts b/src/routes/api.ts index 1288e9f..d3d2af1 100644 --- a/src/routes/api.ts +++ b/src/routes/api.ts @@ -1,31 +1,25 @@ -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 { 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 { csrfMiddleware } from "@middleware/security/requireCsrf.js"; -import { requireActiveAccount } from "@middleware/security/requireActiveAccount.js"; +import { csrfMiddleware } from '@middleware/security/requireCsrf.js'; +import { requireActiveAccount } from '@middleware/security/requireActiveAccount.js'; const apiRouter = Router(); // private routes -apiRouter.use("/auth", authRouter); -apiRouter.use(authMiddleware, csrfMiddleware); -apiRouter.use("/user", userRouter); +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('/projects', projectRouter); +apiRouter.use('/stories', storyRouter); +apiRouter.use('/context-profiles', contextProfileRouter); +apiRouter.use('/scenes', scenesRouter); -export default apiRouter; \ No newline at end of file +export default apiRouter; diff --git a/src/security/guards/getAccountBlockResponse.ts b/src/security/guards/getAccountBlockResponse.ts index 49fa74d..ef97eec 100644 --- a/src/security/guards/getAccountBlockResponse.ts +++ b/src/security/guards/getAccountBlockResponse.ts @@ -1,6 +1,6 @@ -import { AccountStatus } from "@constants/userConts.js"; +import { AccountStatus } from "@constants/userConsts.js"; import { accountStatusResponses } from "../policies/accountStatusResponses.js"; -export function getAccountBlockResponse(status: Partial) { - return accountStatusResponses(status) || null; +export function getAccountBlockResponse(status: AccountStatus | null | undefined) { + return accountStatusResponses(status); } diff --git a/src/security/policies/accountStatusResponses.ts b/src/security/policies/accountStatusResponses.ts index ee500d3..7e8293a 100644 --- a/src/security/policies/accountStatusResponses.ts +++ b/src/security/policies/accountStatusResponses.ts @@ -1,4 +1,4 @@ -import { AccountStatus } from "@constants/userConts.js"; +import { AccountStatus } from "@constants/userConsts.js"; export type AccountBlockStatusResponse = { httpStatus: number; 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/express.d.ts b/src/types/express.d.ts index d306fc4..dc1dbb5 100644 --- a/src/types/express.d.ts +++ b/src/types/express.d.ts @@ -1,6 +1,6 @@ import { type User } from "@models/User.ts"; // whatever your user type is import type { Pagination, Sorting } from "@middleware/paginationAndSorting.js"; -import { type AccountStatus, Role } from "constants/userConts.ts"; +import { type AccountStatus, Role } from "@constants/userConsts.ts"; type AuthenticatedUser = { id: string; diff --git a/src/utils/generateAllCookieTokens.ts b/src/utils/generateAllCookieTokens.ts index ed21627..e39d39a 100644 --- a/src/utils/generateAllCookieTokens.ts +++ b/src/utils/generateAllCookieTokens.ts @@ -1,6 +1,6 @@ import { Types } from "mongoose"; import { generateAccessToken, generateCsrfToken, generateRefreshToken } from "./tokens.js"; -import { AccountStatus } from "@constants/userConts.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); diff --git a/src/utils/safeParseJSON.ts b/src/utils/safeParseJSON.ts index 069a02c..4c2bfc8 100644 --- a/src/utils/safeParseJSON.ts +++ b/src/utils/safeParseJSON.ts @@ -1,12 +1,12 @@ function safeParseJSON(text: string) { const cleaned = text .trim() - .replace(/^```json/i, "") - .replace(/^```/, "") - .replace(/```$/, "") + .replace(/^```json/i, '') + .replace(/^```/, '') + .replace(/```$/, '') .trim(); return JSON.parse(cleaned); } -export default safeParseJSON; \ No newline at end of file +export default safeParseJSON; diff --git a/src/utils/tokens.ts b/src/utils/tokens.ts index 3153d52..58516fb 100644 --- a/src/utils/tokens.ts +++ b/src/utils/tokens.ts @@ -2,7 +2,7 @@ import jwt, { type SignOptions } from "jsonwebtoken"; import crypto from "crypto"; import type { Types } from "mongoose"; import { UnauthenticatedError } from "@middleware/error/index.js"; -import { AccountStatus } from "@constants/userConts.js"; +import { AccountStatus } from "@constants/userConsts.js"; const ACCESS_TOKEN_EXPIRES_IN: SignOptions["expiresIn"] = process.env .ACCESS_TOKEN_EXPIRES_IN as SignOptions["expiresIn"]; 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 4f3d856..72f4f11 100644 --- a/src/validation/story.schema.ts +++ b/src/validation/story.schema.ts @@ -1,5 +1,4 @@ -import { maxTimeLimit, minTimeLimit, storyIntent } from "@constants/storyConsts.js"; -import { platform } from "node:process"; +import { maxTimeLimit, minTimeLimit,platform, storyIntent } from "@constants/storyConsts.js"; import {z} from "zod"; diff --git a/tsconfig.json b/tsconfig.json index 5da82b9..c47e4f2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,7 +5,7 @@ "moduleResolution": "NodeNext", "rootDir": "./src", - "outDir": "./dist", + "outDir": "src/dist", "strict": true, "esModuleInterop": true, @@ -26,5 +26,5 @@ "@constants/*": ["constants/*"] } }, - "include": ["src"] + "include": ["src", "dist"] } \ No newline at end of file From e09bc24ade955eeb4e1a336018f52ca1d9b8db10 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Sat, 31 Jan 2026 08:17:01 +0530 Subject: [PATCH 11/14] Checkpoint from VS Code for coding agent session --- .postman/config.json | 12 - package-lock.json | 49 ++ package.json | 2 + src/config/creditPricing.ts | 29 + src/constants/sceneAssetConsts.ts | 33 + src/db/withTransaction.ts | 29 + src/domain/assertions/assertAssetState.ts | 28 + src/domain/assertions/assertCharacterFits.ts | 31 + .../assertions/assertNarrationFitsTime.ts | 41 ++ src/domain/assertions/assertNarrationState.ts | 16 + src/domain/assertions/assertSceneState.ts | 44 ++ src/domain/assertions/assertStoryState.ts | 32 + .../policies/accountStatusResponses.ts | 0 src/domain/policies/isSameContextContract.ts | 21 + .../ai/constants/narrationPromptConsts.ts | 34 + src/libs/ai/policies/resolveModel.ts | 204 ++++++ src/libs/ai/prompts/batchScenesPrompt.ts | 60 +- src/libs/ai/prompts/generateStoryPrompt.ts | 9 +- .../generateStoryRegenerationPrompt.ts | 9 +- src/libs/ai/prompts/narrationPrompt.ts | 217 ++++++ src/libs/ai/prompts/singleScenePrompt.ts | 11 +- .../ai/prompts/utils/buildContextSection.ts | 107 +++ .../prompts/utils/buildStoryContextSection.ts | 79 -- src/middleware/avatarUpload.ts | 27 - src/middleware/error/globalErrorHandler.ts | 31 +- src/middleware/loggerMiddleware.ts | 42 +- src/middleware/multer.ts | 75 -- src/middleware/multer/avatarUpload.ts | 18 + .../multer/filenameLogic/multerImage.ts | 60 ++ .../multer/filenameLogic/multerJSON.ts | 63 ++ .../multer/filenameLogic/multerVideo.ts | 66 ++ src/middleware/multer/imageAssetUpload.ts | 18 + src/middleware/multer/narrationJSONUpload.ts | 19 + src/middleware/multer/videoAssetUpload.ts | 18 + .../{ => request}/paginationAndSorting.ts | 0 src/middleware/requireActiveAccountFresh.ts | 0 src/models/AudioAsset.ts | 75 +- src/models/CapabilityOverride.ts | 67 ++ src/models/ContextProfile.ts | 222 +++--- src/models/ContextProfileHistory.ts | 97 --- src/models/Credits.ts | 80 +++ src/models/Narration.ts | 159 +++++ src/models/Plan.ts | 81 +++ src/models/Project.ts | 4 +- src/models/Scene.ts | 35 +- src/models/SceneAssets.ts | 65 +- src/models/Session.ts | 14 +- src/models/Story.ts | 73 +- src/models/User.ts | 66 +- src/modules/auth/auth.service.ts | 420 +++++------ ...UserSession.ts => createSessionPayload.ts} | 21 +- src/modules/auth/utils/createUsername.ts | 25 + src/modules/credit/credit.service.ts | 62 ++ .../featurePermission.service.ts | 66 ++ .../utils/resolveEffectiveCapabilities.ts | 24 + src/modules/narration/narration.constants.ts | 3 + src/modules/narration/narration.controller.ts | 209 ++++++ src/modules/narration/narration.routes.ts | 115 +++ src/modules/narration/narration.service.ts | 674 ++++++++++++++++++ src/modules/project/project.controller.ts | 94 +-- src/modules/project/project.service.ts | 208 +++--- .../sceneAssets/sceneAssets.controller.ts | 294 ++++++++ .../sceneAssets/sceneAssets.private.routes.ts | 152 ++++ .../sceneAssets/sceneAssets.service.ts | 536 ++++++++++++++ src/modules/scenes/scenes.controller.ts | 118 ++- src/modules/scenes/scenes.private.routes.ts | 95 ++- src/modules/scenes/scenes.service.ts | 437 ++++++------ src/modules/story/story.controller.ts | 190 +++-- src/modules/story/story.private.routes.ts | 129 +++- src/modules/story/story.service.ts | 531 +++++++------- .../subscription/subscription.service.ts | 45 ++ src/modules/user/user.routes.ts | 2 +- src/modules/user/user.service.ts | 270 +++---- src/routes/api.ts | 4 + src/routes/index.ts | 38 +- .../guards/getAccountBlockResponse.ts | 4 +- src/types/index.ts | 18 + src/utils/arraysEqual.ts | 13 + src/utils/buildSessionMetadata.ts | 0 src/utils/createUsername.ts | 21 - src/utils/getCreditCost.ts | 9 + src/utils/getVideoDuration.ts | 20 + src/utils/hashSceneOrder.ts | 15 + src/utils/sanitizeProjectResponse.ts | 19 +- ...urnUserData.ts => sanitizeUserResponse.ts} | 29 +- src/validation/narration.schema.ts | 79 ++ src/validation/project.schema.ts | 99 ++- src/validation/sceneAssets.schema.ts | 140 ++++ src/validation/story.schema.ts | 136 ++-- src/validators/validateAssetOwnership.ts | 22 + src/validators/validateNarrationOwnership.ts | 22 + src/validators/validateSceneOwnership.ts | 43 ++ src/validators/validateStoryOwnership.ts | 26 + src/validators/validateUser.ts | 13 + 94 files changed, 6052 insertions(+), 2010 deletions(-) delete mode 100644 .postman/config.json create mode 100644 src/config/creditPricing.ts create mode 100644 src/constants/sceneAssetConsts.ts create mode 100644 src/db/withTransaction.ts create mode 100644 src/domain/assertions/assertAssetState.ts create mode 100644 src/domain/assertions/assertCharacterFits.ts create mode 100644 src/domain/assertions/assertNarrationFitsTime.ts create mode 100644 src/domain/assertions/assertNarrationState.ts create mode 100644 src/domain/assertions/assertSceneState.ts create mode 100644 src/domain/assertions/assertStoryState.ts rename src/{security => domain}/policies/accountStatusResponses.ts (100%) create mode 100644 src/domain/policies/isSameContextContract.ts create mode 100644 src/libs/ai/constants/narrationPromptConsts.ts create mode 100644 src/libs/ai/policies/resolveModel.ts create mode 100644 src/libs/ai/prompts/narrationPrompt.ts create mode 100644 src/libs/ai/prompts/utils/buildContextSection.ts delete mode 100644 src/libs/ai/prompts/utils/buildStoryContextSection.ts delete mode 100644 src/middleware/avatarUpload.ts delete mode 100644 src/middleware/multer.ts create mode 100644 src/middleware/multer/avatarUpload.ts create mode 100644 src/middleware/multer/filenameLogic/multerImage.ts create mode 100644 src/middleware/multer/filenameLogic/multerJSON.ts create mode 100644 src/middleware/multer/filenameLogic/multerVideo.ts create mode 100644 src/middleware/multer/imageAssetUpload.ts create mode 100644 src/middleware/multer/narrationJSONUpload.ts create mode 100644 src/middleware/multer/videoAssetUpload.ts rename src/middleware/{ => request}/paginationAndSorting.ts (100%) delete mode 100644 src/middleware/requireActiveAccountFresh.ts create mode 100644 src/models/CapabilityOverride.ts delete mode 100644 src/models/ContextProfileHistory.ts create mode 100644 src/models/Credits.ts create mode 100644 src/models/Plan.ts rename src/modules/auth/utils/{createUserSession.ts => createSessionPayload.ts} (65%) create mode 100644 src/modules/auth/utils/createUsername.ts create mode 100644 src/modules/credit/credit.service.ts create mode 100644 src/modules/featurePermission/featurePermission.service.ts create mode 100644 src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts create mode 100644 src/modules/narration/narration.constants.ts create mode 100644 src/modules/sceneAssets/sceneAssets.controller.ts create mode 100644 src/modules/sceneAssets/sceneAssets.private.routes.ts create mode 100644 src/modules/sceneAssets/sceneAssets.service.ts create mode 100644 src/modules/subscription/subscription.service.ts create mode 100644 src/utils/arraysEqual.ts delete mode 100644 src/utils/buildSessionMetadata.ts delete mode 100644 src/utils/createUsername.ts create mode 100644 src/utils/getCreditCost.ts create mode 100644 src/utils/getVideoDuration.ts create mode 100644 src/utils/hashSceneOrder.ts rename src/utils/{returnUserData.ts => sanitizeUserResponse.ts} (82%) create mode 100644 src/validation/narration.schema.ts create mode 100644 src/validation/sceneAssets.schema.ts create mode 100644 src/validators/validateAssetOwnership.ts create mode 100644 src/validators/validateNarrationOwnership.ts create mode 100644 src/validators/validateSceneOwnership.ts create mode 100644 src/validators/validateStoryOwnership.ts create mode 100644 src/validators/validateUser.ts diff --git a/.postman/config.json b/.postman/config.json deleted file mode 100644 index bffa66c..0000000 --- a/.postman/config.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "workspace": { - "id": "a89b5db0-53ef-4ccd-805d-30769d8cbd88" - }, - "entities": { - "collections": [], - "environments": [], - "specs": [], - "flows": [], - "globals": [] - } -} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 0efc437..b0a374e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,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", @@ -31,6 +32,7 @@ "@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", @@ -2776,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", @@ -2908,6 +2920,11 @@ "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", @@ -3513,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", @@ -3810,6 +3841,12 @@ ], "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", @@ -5128,6 +5165,18 @@ "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", diff --git a/package.json b/package.json index 4730a85..4d6b540 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,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", @@ -31,6 +32,7 @@ "@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", diff --git a/src/config/creditPricing.ts b/src/config/creditPricing.ts new file mode 100644 index 0000000..9bea64f --- /dev/null +++ b/src/config/creditPricing.ts @@ -0,0 +1,29 @@ +export type ActionType = 'IMAGE_GEN' | 'AUDIO_GEN' | 'STORY_GEN' | 'VIDEO_GEN'; + +export const CREDIT_PRICING: Record> = { + IMAGE_GEN: { + 1: 2, + 2: 6, + 3: 10, + 4: 15, + }, + + AUDIO_GEN: { + 1: 2, + 2: 5, + 3: 8, + 4: 12, + }, + + STORY_GEN: { + 1: 1, + 2: 3, + 3: 6, + }, + + VIDEO_GEN: { + 1: 10, + 2: 20, + 3: 35, + }, +}; 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/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/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/security/policies/accountStatusResponses.ts b/src/domain/policies/accountStatusResponses.ts similarity index 100% rename from src/security/policies/accountStatusResponses.ts rename to src/domain/policies/accountStatusResponses.ts 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/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/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 index bd24e08..4988914 100644 --- a/src/libs/ai/prompts/batchScenesPrompt.ts +++ b/src/libs/ai/prompts/batchScenesPrompt.ts @@ -1,22 +1,16 @@ import { ContextProfile } from '@models/ContextProfile.js'; import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; -import { buildStoryContextSection } from './utils/buildStoryContextSection.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, + MULTI_SCENE_STRUCTURE_FORMAT, } from '../constants/scenesPromptConts.js'; +import { StoryContent } from 'types/index.js'; export type BatchSceneMode = 'generate' | 'regenerate'; -type StoryContent = { - summary?: string; - body?: string; - keywords?: string[]; - tags?: string[]; -}; - type BuildBatchScenePromptInput = { mode: BatchSceneMode; storyTitle: string; @@ -49,41 +43,46 @@ export function batchScenesPrompt(input: BuildBatchScenePromptInput): string { const sections: string[] = []; // ROLE - sections.push(` + 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()); +`.trim() + ); // MODE FRAMING sections.push( - mode === 'generate' - ? MULTI_SCENE_GENERATION_PROMPT.trim() - : MULTI_SCENE_REGENERATION_PROMPT.trim() + mode === 'generate' ? MULTI_SCENE_GENERATION_PROMPT.trim() : MULTI_SCENE_REGENERATION_PROMPT.trim() ); // STORY CONTEXT - sections.push(` + sections.push( + ` STORY CONTEXT Title: "${storyTitle}" Summary: "${storyContent.summary}" Platform: ${platform} Intent: ${intent} -`.trim()); +`.trim() + ); // STYLE CONTEXT (optional but useful) if (storyContent.keywords?.length || storyContent.tags?.length) { - sections.push(` + sections.push( + ` STYLE HINTS Keywords: ${storyContent.keywords?.join(', ') || 'N/A'} Tags: ${storyContent.tags?.join(', ') || 'N/A'} -`.trim()); +`.trim() + ); } // FULL STORY BODY — only for continuity if (storyContent.body) { - sections.push(` + sections.push( + ` FULL STORY REFERENCE (FOR CONTINUITY ONLY) ${storyContent.body} @@ -94,11 +93,13 @@ Rules: - Do NOT summarize it - Do NOT restate it - Use it only to preserve continuity and logic -`.trim()); +`.trim() + ); } // SCENE COUNT CONSTRAINT - sections.push(` + sections.push( + ` SCENE COUNT CONSTRAINT You must output EXACTLY ${totalScenes} scenes. @@ -106,12 +107,14 @@ Do NOT add scenes. Do NOT remove scenes. Do NOT merge scenes. Do NOT skip scenes. -`.trim()); +`.trim() + ); // TIME BUDGET if (storyTimeLimit) { const perSceneTimeLimit = Math.floor(storyTimeLimit / totalScenes); - sections.push(` + sections.push( + ` TIME BUDGET Total story duration: ${storyTimeLimit} seconds @@ -120,21 +123,24 @@ Target per scene: ~${perSceneTimeLimit} seconds Rules: - Minor variation is allowed - Do NOT significantly overshoot or undershoot -`.trim()); +`.trim() + ); } // CONTEXT PROFILE if (contextProfile) { - const contextSection = buildStoryContextSection(contextProfile); + const contextSection = buildContextSection(contextProfile); if (contextSection) sections.push(contextSection); } // EXTRA PROMPT (mainly for regeneration tuning) if (extraPrompt) { - sections.push(` + sections.push( + ` ADDITIONAL CREATIVE DIRECTION ${extraPrompt} -`.trim()); +`.trim() + ); } // SAFETY diff --git a/src/libs/ai/prompts/generateStoryPrompt.ts b/src/libs/ai/prompts/generateStoryPrompt.ts index 2456428..3790392 100644 --- a/src/libs/ai/prompts/generateStoryPrompt.ts +++ b/src/libs/ai/prompts/generateStoryPrompt.ts @@ -1,7 +1,7 @@ import { ContextProfile } from '@models/ContextProfile.js'; import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; import { STORY_GENERATION_FORMAT } from '../constants/storyPromptConts.js'; -import { buildStoryContextSection } from './utils/buildStoryContextSection.js'; +import { buildContextSection } from './utils/buildContextSection.js'; import { calculateWordLimits } from '../constants/calculateWordLimits.js'; import { Platform, StoryIntent } from '@constants/storyConsts.js'; @@ -44,7 +44,10 @@ Description: "${description}" /* 3. HARD TIME / LENGTH CONSTRAINT */ if (timeLimit) { - const { targetWords, minWords, maxWords } = calculateWordLimits(timeLimit, contextProfile?.narrationProfile); + const { targetWords, minWords, maxWords } = calculateWordLimits( + timeLimit, + contextProfile?.narrationProfile + ); sections.push( ` @@ -64,7 +67,7 @@ Rules: /* 4. CONTEXT PROFILE (BINDING, NO EXPANSION) */ if (contextProfile) { - const contextSection = buildStoryContextSection(contextProfile); + const contextSection = buildContextSection(contextProfile); if (contextSection) { sections.push(contextSection); } diff --git a/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts b/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts index 3b5256d..261cd77 100644 --- a/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts +++ b/src/libs/ai/prompts/generateStoryRegenerationPrompt.ts @@ -2,7 +2,7 @@ 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 { buildStoryContextSection } from './utils/buildStoryContextSection.js'; +import { buildContextSection } from './utils/buildContextSection.js'; import { calculateWordLimits } from '../constants/calculateWordLimits.js'; type RegenerateStoryPromptInput = { @@ -77,7 +77,10 @@ ${extraPrompt} /* 5. HARD TIME / LENGTH CONSTRAINT */ if (timeLimit) { - const { targetWords, minWords, maxWords } = calculateWordLimits(timeLimit, contextProfile?.narrationProfile); + const { targetWords, minWords, maxWords } = calculateWordLimits( + timeLimit, + contextProfile?.narrationProfile + ); sections.push( ` @@ -97,7 +100,7 @@ Rules: /* 4. CONTEXT PROFILE (BINDING, NO EXPANSION) */ if (contextProfile) { - const contextSection = buildStoryContextSection(contextProfile); + const contextSection = buildContextSection(contextProfile); if (contextSection) { sections.push(contextSection); } 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 index 1467c7f..f022af1 100644 --- a/src/libs/ai/prompts/singleScenePrompt.ts +++ b/src/libs/ai/prompts/singleScenePrompt.ts @@ -1,6 +1,6 @@ import { ContextProfile } from '@models/ContextProfile.js'; import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js'; -import { buildStoryContextSection } from './utils/buildStoryContextSection.js'; +import { buildContextSection } from './utils/buildContextSection.js'; import { Platform, StoryIntent } from '@constants/storyConsts.js'; import { SINGLE_SCENE_GENERATION_PROMPT, @@ -9,15 +9,10 @@ import { 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 StoryContent = { - summary?: string; - keywords?: string[]; - tags?: string[]; -}; - type BuildSingleScenePromptInput = { mode: SingleSceneMode; @@ -229,7 +224,7 @@ Do not significantly overrun or underrun. } if (contextProfile) { - const contextSection = buildStoryContextSection(contextProfile); + const contextSection = buildContextSection(contextProfile); if (contextSection) sections.push(contextSection); } 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/libs/ai/prompts/utils/buildStoryContextSection.ts b/src/libs/ai/prompts/utils/buildStoryContextSection.ts deleted file mode 100644 index 8d28393..0000000 --- a/src/libs/ai/prompts/utils/buildStoryContextSection.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { ContextProfile } from "@models/ContextProfile.js"; - -export function buildStoryContextSection( - contextProfile?: ContextProfile | null -): string | null { - if (!contextProfile) return null; - - const lines: string[] = []; - - lines.push(` -STORY CONTEXT (BINDING — DO NOT EXPAND OR INTERPRET) -`.trim()); - - // Core narrative identity - lines.push(`Genre: ${contextProfile.genre}`); - lines.push(`Mood: ${contextProfile.mood}`); - lines.push(`Style: ${contextProfile.style}`); - lines.push(`Narrative Scope: ${contextProfile.narrativeScope}`); - - // Environment (cinematic grounding) - if (contextProfile.environment) { - lines.push( - `Environment: ${contextProfile.environment.type} (${contextProfile.environment.cameraMotion})` - ); - - if (contextProfile.environment.description) { - lines.push( - `Environment Notes: ${contextProfile.environment.description}` - ); - } - } - - // World rules (hard constraints) - if (contextProfile.worldRules) { - lines.push(` -WORLD RULES (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 (DO NOT ADD, REMOVE, OR RENAME) -${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) -${contextProfile.forbiddenElements - .map((f) => `- ${f.label} (${f.severity})`) - .join("\n")}`.trim()); - } - - // Narration profile (STYLE ONLY — NOT NUMBERS) - lines.push(` -NARRATION STYLE (DO NOT EXPOSE NUMBERS) -Tone: ${contextProfile.narrationProfile.tone} -Emotion Bias: ${contextProfile.narrationProfile.emotionBias} -Intensity Curve: ${contextProfile.narrationProfile.intensityCurve} -Pause Bias: ${contextProfile.narrationProfile.pauseBias} -Sentence Length Bias: ${contextProfile.narrationProfile.sentenceLengthBias} -Clause Density: ${contextProfile.narrationProfile.clauseDensity} -`.trim()); - - return lines.join("\n\n"); -} diff --git a/src/middleware/avatarUpload.ts b/src/middleware/avatarUpload.ts deleted file mode 100644 index 01e8ceb..0000000 --- a/src/middleware/avatarUpload.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Request, Response, NextFunction } from "express"; -import multer from "multer"; -import { upload } from "./multer.js"; -import { 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 Error("Multer error during file upload", { cause: err })); - } - return next(err); - }); -}; diff --git a/src/middleware/error/globalErrorHandler.ts b/src/middleware/error/globalErrorHandler.ts index 67cb619..f1898c1 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -1,26 +1,35 @@ -// src/middleware/errorHandler.ts import { NextFunction, Request, Response } from 'express'; import { AppError } from './appError.js'; import logger from '@utils/logger.js'; -const errorHandler = (err: unknown, req: Request, res: Response, next: NextFunction) => { - // If it's a known error (instance of AppError) +const errorHandler = (err: unknown, req: Request, res: Response, _next: NextFunction) => { + const requestId = res.locals.requestId; + if (err instanceof AppError) { logger.error({ + requestId, + name: err.name, message: err.message, + statusCode: err.statusCode, details: err.details, - stack: err.stack, - actions: err.actions, - request: { - method: req.method, - url: req.originalUrl, - headers: req.headers, - body: req.body, - }, + 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()); } + + logger.error({ + requestId, + name: 'UnhandledError', + message: 'Unhandled exception', + stack: err instanceof Error ? err.stack : undefined, + method: req.method, + path: req.originalUrl, + }); + return res.status(500).json({ status: 'error', message: 'Internal Server Error', diff --git a/src/middleware/loggerMiddleware.ts b/src/middleware/loggerMiddleware.ts index ce2441e..a030e3f 100644 --- a/src/middleware/loggerMiddleware.ts +++ b/src/middleware/loggerMiddleware.ts @@ -1,16 +1,16 @@ -import type { Request, Response, NextFunction } from "express"; -import { randomUUID } from "crypto"; -import logger from "@utils/logger.js"; +import type { Request, Response, NextFunction } from 'express'; +import { randomUUID } from 'crypto'; +import logger from '@utils/logger.js'; -const isDev = process.env.NODE_ENV !== "production"; +const isDev = process.env.NODE_ENV !== 'production'; /* ---------- DEV helpers (safe: dev only) ---------- */ const getStatusColor = (status: number): string => { - 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 + 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 }; /* ---------- Middleware ---------- */ @@ -19,10 +19,9 @@ export function requestLogger(req: Request, res: Response, next: NextFunction) { const start = process.hrtime.bigint(); const requestId = randomUUID(); - (req as any).requestId = requestId; - res.setHeader("X-Request-Id", requestId); + res.locals.requestId = requestId; + res.setHeader('X-Request-Id', requestId); - // DEV: log incoming request (optional, low noise) if (isDev) { logger.debug( { @@ -30,13 +29,12 @@ export function requestLogger(req: Request, res: Response, next: NextFunction) { method: req.method, path: req.originalUrl, }, - "Incoming request" + 'Incoming request' ); } - res.on("finish", () => { - const durationNs = process.hrtime.bigint() - start; - const durationMs = Number(durationNs) / 1_000_000; + res.on('finish', () => { + const durationMs = Number(process.hrtime.bigint() - start) / 1_000_000; const logData = { requestId, @@ -45,29 +43,25 @@ export function requestLogger(req: Request, res: Response, next: NextFunction) { statusCode: res.statusCode, durationMs: Number(durationMs.toFixed(2)), ip: req.ip, - userAgent: req.headers["user-agent"], + userAgent: req.headers['user-agent'], userId: (req as any).user?._id, }; - /* ---------- DEV: pretty output ---------- */ if (isDev) { const color = getStatusColor(res.statusCode); - - // still goes through pino-pretty (NOT console.log) logger.info( logData, - `${color}$ ${req.method} ${req.originalUrl} ${res.statusCode} ${logData.durationMs}ms\x1b[0m` + `${color}$ ${req.method} ${req.originalUrl} ${res.statusCode} ${logData.durationMs}ms\x1b[0m` ); return; } - /* ---------- PROD: structured only ---------- */ if (res.statusCode >= 500) { - logger.error(logData, "Request failed"); + logger.error(logData, 'Request failed'); } else if (res.statusCode >= 400) { - logger.warn(logData, "Request completed with client error"); + logger.warn(logData, 'Request completed with client error'); } else { - logger.info(logData, "Request completed"); + logger.info(logData, 'Request completed'); } }); diff --git a/src/middleware/multer.ts b/src/middleware/multer.ts deleted file mode 100644 index 4ee7fbd..0000000 --- a/src/middleware/multer.ts +++ /dev/null @@ -1,75 +0,0 @@ -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"; - 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/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/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/paginationAndSorting.ts b/src/middleware/request/paginationAndSorting.ts similarity index 100% rename from src/middleware/paginationAndSorting.ts rename to src/middleware/request/paginationAndSorting.ts diff --git a/src/middleware/requireActiveAccountFresh.ts b/src/middleware/requireActiveAccountFresh.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/models/AudioAsset.ts b/src/models/AudioAsset.ts index 21906c3..eb97800 100644 --- a/src/models/AudioAsset.ts +++ b/src/models/AudioAsset.ts @@ -1,19 +1,17 @@ -import { Schema, model, Document, Types } from "mongoose"; +import { Schema, model, Document, Types } from 'mongoose'; export interface AudioAsset extends Document { userId: Types.ObjectId; - type: "narration" | "background" | "effect"; + narrationId?: Types.ObjectId; + activeNarration: boolean; + type: 'narration' | 'background' | 'effect'; url: string; - prompt?: string; // for AI-generated audio - generationSource: "ai" | "upload"; + prompt?: string; + generationSource: 'ai' | 'user'; voiceId?: string; - language?: string; - accent?: string; - tone?: string; - pacing?: string; - duration?: number; // seconds - format?: string; // mp3, wav, etc. - saved: boolean; // saved to library or not + duration?: number; + version?: number; + deletedAt: Date; createdAt: Date; updatedAt: Date; } @@ -22,13 +20,20 @@ const audioAssetSchema = new Schema( { userId: { type: Schema.Types.ObjectId, - ref: "User", + ref: 'User', required: true, - index: true, + }, + narrationId: { + type: Schema.Types.ObjectId, + ref: 'StoryNarration', + }, + activeNarration: { + type: Boolean, + default: false, }, type: { type: String, - enum: ["narration", "background", "effect"], + enum: ['narration', 'background', 'effect'], required: true, }, url: { @@ -40,40 +45,36 @@ const audioAssetSchema = new Schema( }, generationSource: { type: String, - enum: ["ai", "upload"], - default: "ai", + enum: ['ai', 'user'], + default: 'ai', }, voiceId: { type: String, }, - language: { - type: String, - }, - accent: { - type: String, - }, - tone: { - type: String, - }, - pacing: { - type: String, - }, duration: { type: Number, }, - format: { - type: String, + version: { + type: Number, + required: true, + default: 1, + min: 1, }, - saved: { - type: Boolean, - default: false, - index: true, + deletedAt: { + type: Date, }, }, { timestamps: true } ); -export const AudioAssetModel = model( - "AudioAsset", - audioAssetSchema +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/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 index feab780..ef0d36b 100644 --- a/src/models/ContextProfile.ts +++ b/src/models/ContextProfile.ts @@ -1,108 +1,110 @@ -import { Schema, model, Document, Types } from "mongoose"; +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", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + INTIMATE = 'intimate', + LOCAL = 'local', + REGIONAL = 'regional', + EPIC = 'epic', } export enum ContextScope { - PROJECT = "project", - GLOBAL = "global", + PROJECT = 'project', + GLOBAL = 'global', } export interface EnvironmentProfile { @@ -116,18 +118,18 @@ export interface NarrationProfile { minWordTolerance: number; maxWordTolerance: number; - pauseBias: "none" | "low" | "medium" | "high"; - sentenceLengthBias: "very-short" | "short" | "medium" | "long"; - clauseDensity: "sparse" | "balanced" | "dense"; + pauseBias: 'none' | 'low' | 'medium' | 'high'; + sentenceLengthBias: 'very-short' | 'short' | 'medium' | 'long'; + clauseDensity: 'sparse' | 'balanced' | 'dense'; tone: ToneType; - emotionBias: "flat" | "subtle" | "expressive"; + emotionBias: 'flat' | 'subtle' | 'expressive'; intensityCurve: IntensityCurve; } export interface ForbiddenElement { label: string; - severity: "hard" | "soft"; + severity: 'hard' | 'soft'; } export interface ContextProfile extends Document { @@ -136,10 +138,11 @@ export interface ContextProfile extends Document { projectId?: Types.ObjectId; scope: ContextScope; isDefaultForProject: boolean; + parentContextId: Types.ObjectId; name: string; description?: string; - active: boolean; + language?: string; genre: GenreType; mood: MoodType; @@ -154,6 +157,9 @@ export interface ContextProfile extends Document { characters?: { name: string; description?: string; + imageUrl?: string; + features?: Record; + behaviors?: Record; }[]; forbiddenElements?: ForbiddenElement[]; @@ -169,15 +175,13 @@ const contextProfileSchema = new Schema( { userId: { type: Schema.Types.ObjectId, - ref: "User", + ref: 'User', required: true, - index: true, }, projectId: { type: Schema.Types.ObjectId, - ref: "Project", - index: true, + ref: 'Project', }, scope: { @@ -191,7 +195,11 @@ const contextProfileSchema = new Schema( type: Boolean, default: false, }, - + parentContextId: { + type: Schema.Types.ObjectId, + ref: 'ContextProfile', + required: true, + }, name: { type: String, required: true, @@ -202,12 +210,10 @@ const contextProfileSchema = new Schema( type: String, maxlength: 600, }, - - active: { - type: Boolean, - default: true, + language: { + type: String, + default: 'en', }, - genre: { type: String, enum: Object.values(GenreType), @@ -260,7 +266,10 @@ const contextProfileSchema = new Schema( characters: [ { name: { type: String, required: true }, - description: String, + imageUrl: { type: String }, + description: { type: String, maxlength: 500, required: true }, + features: { type: Schema.Types.Mixed }, + behaviors: { type: Schema.Types.Mixed }, }, ], @@ -269,8 +278,8 @@ const contextProfileSchema = new Schema( label: String, severity: { type: String, - enum: ["hard", "soft"], - default: "hard", + enum: ['hard', 'soft'], + default: 'hard', }, }, ], @@ -282,19 +291,19 @@ const contextProfileSchema = new Schema( pauseBias: { type: String, - enum: ["none", "low", "medium", "high"], + enum: ['none', 'low', 'medium', 'high'], required: true, }, sentenceLengthBias: { type: String, - enum: ["very-short", "short", "medium", "long"], + enum: ['very-short', 'short', 'medium', 'long'], required: true, }, clauseDensity: { type: String, - enum: ["sparse", "balanced", "dense"], + enum: ['sparse', 'balanced', 'dense'], required: true, }, @@ -306,7 +315,7 @@ const contextProfileSchema = new Schema( emotionBias: { type: String, - enum: ["flat", "subtle", "expressive"], + enum: ['flat', 'subtle', 'expressive'], required: true, }, @@ -324,10 +333,7 @@ const contextProfileSchema = new Schema( ); contextProfileSchema.index({ projectId: 1, isDefaultForProject: 1 }); -contextProfileSchema.index({ parentContextId: 1 }); -contextProfileSchema.index({ userId: 1, lastUsedAt: -1 }); +contextProfileSchema.index({ parentContextId: 1 }); +contextProfileSchema.index({ userId: 1, lastUsedAt: -1 }); -export const ContextProfileModel = model( - "ContextProfile", - contextProfileSchema -); \ No newline at end of file +export const ContextProfileModel = model('ContextProfile', contextProfileSchema); diff --git a/src/models/ContextProfileHistory.ts b/src/models/ContextProfileHistory.ts deleted file mode 100644 index 96f1760..0000000 --- a/src/models/ContextProfileHistory.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { Schema, model, Document, Types } from "mongoose"; - -export interface ContextProfileHistory extends Document { - contextProfileId: Types.ObjectId; - userId: Types.ObjectId; - version: number; // version being archived - snapshot: { - name: string; - description?: string; - genre?: string; - tone?: string; - mood?: string; - style?: string; - worldRules?: string; - characters?: { - name: string; - description?: string; - }[]; - narrativeConstraints?: string; - forbiddenElements?: string[]; - }; - - changeReason?: string; // optional user/system note - changedAt: Date; -} - -const contextProfileHistorySchema = new Schema( - { - contextProfileId: { - type: Schema.Types.ObjectId, - ref: "ContextProfile", - required: true, - index: true, - }, - - userId: { - type: Schema.Types.ObjectId, - ref: "User", - required: true, - index: true, - }, - - version: { - type: Number, - required: true, - }, - - snapshot: { - name: { type: String, required: true }, - description: { type: String }, - - genre: String, - tone: String, - mood: String, - style: String, - - worldRules: String, - - characters: [ - { - name: { type: String, required: true }, - description: { type: String }, - }, - ], - - narrativeConstraints: String, - - forbiddenElements: { - type: [String], - default: [], - }, - }, - - changeReason: { - type: String, - maxlength: 1000, - }, - - changedAt: { - type: Date, - default: Date.now, - index: true, - }, - }, - { timestamps: false } -); - -// Add compound index for efficient version history queries -contextProfileHistorySchema.index({ contextProfileId: 1, version: 1 }); - -// Optional: Add index for time-based queries -contextProfileHistorySchema.index({ contextProfileId: 1, changedAt: -1 }); - -export const ContextProfileHistoryModel = model( - "ContextProfileHistory", - contextProfileHistorySchema -); 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/Narration.ts b/src/models/Narration.ts index e69de29..0b6d549 100644 --- a/src/models/Narration.ts +++ 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 3b1a1eb..acc9583 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -5,7 +5,7 @@ export interface ProjectType extends Document { description: string; status: "active" | "draft" | "archive" | "delete"; visibility: "public" | "private"; - defaultContextProfileId?: Types.ObjectId; + defaultContextProfileId: Types.ObjectId; generationCounts: { storiesGenerated: number; scenesGenerated: number; @@ -46,7 +46,7 @@ const projectSchema = new Schema( enum: ["public", "private"], default: "private", }, - defaultContextProfileId: { type: Schema.Types.ObjectId, ref: "ContextProfile" }, + defaultContextProfileId: { type: Schema.Types.ObjectId, ref: "ContextProfile", required: true }, generationCounts: { storiesGenerated: { type: Number, default: 0 }, scenesGenerated: { type: Number, default: 0 }, diff --git a/src/models/Scene.ts b/src/models/Scene.ts index d4520b7..122a32e 100644 --- a/src/models/Scene.ts +++ b/src/models/Scene.ts @@ -1,31 +1,19 @@ import { Schema, model, Document, Types } from 'mongoose'; -// export interface SceneAssetHistoryEntry { -// assetId: Types.ObjectId; -// replacedAt: Date; -// } - -// export interface SceneEditHistoryEntry { -// title?: string; -// description?: string; -// imagePrompt?: string; -// duration?: number; -// editedAt: Date; -// } - -// Put all history tracking in SceneRevision model later - +//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; @@ -62,6 +50,11 @@ const sceneSchema = new Schema( type: String, required: true, }, + narrativeRole: { + type: String, + enum: ['intro', 'transition', 'climax', 'outro', 'standard'], + default: 'standard', + }, authorType: { type: String, enum: ['ai', 'user'], @@ -78,10 +71,18 @@ const sceneSchema = new Schema( duration: { type: Number, }, + activeAssetId: { + type: Schema.Types.ObjectId, + ref: 'SceneAsset', + }, + active: { + type: Boolean, + required: true, + default: true, + }, deletedAt: { type: Date, - default: undefined, - index: true, + default: undefined, }, }, { timestamps: true } diff --git a/src/models/SceneAssets.ts b/src/models/SceneAssets.ts index 590e042..86ed5f7 100644 --- a/src/models/SceneAssets.ts +++ b/src/models/SceneAssets.ts @@ -1,18 +1,20 @@ -import { Schema, model, Document, Types } from "mongoose"; +import { allFormats, type AssetFormat } from '@constants/sceneAssetConsts.js'; +import { Schema, model, Document, Types } from 'mongoose'; export interface SceneAsset extends Document { userId: Types.ObjectId; - projectId?: Types.ObjectId; - type: "image" | "video"; + sceneId: Types.ObjectId; + type: 'image' | 'video'; url: string; - visibility: "private" | "public"; + visibility: 'private' | 'public'; prompt?: string; - generationSource: "ai" | "upload"; - saved: boolean; - active: boolean; + generationSource: 'ai' | 'user'; + version: number; width?: number; height?: number; + format?: AssetFormat; duration?: number; + deletedAt?: Date; createdAt: Date; updatedAt: Date; } @@ -21,18 +23,19 @@ const sceneAssetSchema = new Schema( { userId: { type: Schema.Types.ObjectId, - ref: "User", + ref: 'User', required: true, index: true, }, - projectId: { + sceneId: { type: Schema.Types.ObjectId, - ref: "Project", + ref: 'Scene', + required: true, index: true, }, type: { type: String, - enum: ["image", "video"], + enum: ['image', 'video'], required: true, }, url: { @@ -41,35 +44,45 @@ const sceneAssetSchema = new Schema( }, visibility: { type: String, - enum: ["private", "public"], - default: "public", + enum: ['private', 'public'], + default: 'public', }, prompt: { type: String, }, generationSource: { type: String, - enum: ["ai", "upload"], - default: "ai", + enum: ['ai', 'user'], + default: 'ai', }, - saved: { - type: Boolean, - default: false, - index: true, + format: { + type: String, + enum: allFormats, }, - active: { - type: Boolean, - default: true, - index: true, + version: { + type: Number, + required: true, + default: 1, + min: 1, }, width: Number, height: Number, duration: Number, + + deletedAt: { + type: Date, + }, }, + { timestamps: true } ); -export const SceneAssetModel = model( - "SceneAsset", - sceneAssetSchema +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 a2f663c..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 }, @@ -39,12 +39,10 @@ const sessionSchema = new Schema({ 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 revoked sessions after 7 days +//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 }, { @@ -59,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 3e5ff22..8d3b573 100644 --- a/src/models/Story.ts +++ b/src/models/Story.ts @@ -1,16 +1,7 @@ - import { Schema, model, Document, Types } from "mongoose"; - import { type StoryIntent, type Platform, platform, storyIntent } from "@constants/storyConsts.js"; - -// export interface StoryHistoryEntry { -// title?: string; -// description?: string; -// content?: string; -// timeLimit?: number; -// editedAt: Date; -// } +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; @@ -22,11 +13,14 @@ export interface Story extends Document { body: string; keywords?: string[]; tags?: string[]; + authorType: 'ai' | 'user'; }; - authorType: "ai" | "user"; - status: "active" | "delete" | "archive" | "draft"; + + status: 'active' | 'delete' | 'archive' | 'draft'; + deletedAt: Date; + version: number; timeLimit?: number; - contextProfileId?: Types.ObjectId; + contextProfileId: Types.ObjectId; intent: StoryIntent; platform: Platform; createdAt: Date; @@ -37,13 +31,13 @@ const storySchema = new Schema( { userId: { type: Schema.Types.ObjectId, - ref: "User", + ref: 'User', required: true, index: true, }, projectId: { type: Schema.Types.ObjectId, - ref: "Project", + ref: 'Project', index: true, }, title: { @@ -61,11 +55,11 @@ const storySchema = new Schema( content: { body: { type: String, - default: "", + default: '', }, summary: { type: String, - default: "", + default: '', }, keywords: { type: [String], @@ -75,43 +69,52 @@ const storySchema = new Schema( type: [String], default: [], }, + authorType: { + type: String, + enum: ['ai', 'user'], + default: 'ai', + }, }, - authorType: { - type: String, - enum: ["ai", "user"], - default: "ai", - }, + status: { type: String, - enum: ["active", "archive", "delete", "draft"], - default: "active", - }, + 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", - }, + ref: 'ContextProfile', + required: true, + }, intent: { type: String, - enum: [ - ...storyIntent - ], + enum: [...storyIntent], required: true, - default: "short-form", + default: 'short-form', }, platform: { type: String, enum: [...platform], required: true, - default: "youtube", + default: 'youtube', }, }, { timestamps: true } ); storySchema.index({ userId: 1, createdAt: -1 }); -storySchema.index({ userId: 1, projectId: 1, createdAt: -1 }); +storySchema.index({ userId: 1, projectId: 1, createdAt: -1 }); -export const StoryModel = model("Story", storySchema); \ No newline at end of file +export const StoryModel = model('Story', storySchema); diff --git a/src/models/User.ts b/src/models/User.ts index cfc5442..6efcd1e 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -1,10 +1,5 @@ -import { ACCOUNT_STATUSES } from "constants/authConsts.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( { @@ -22,7 +17,7 @@ const UpdateEmailSchema = new Schema( code: { type: String }, expiresAt: { type: Date }, requestedAt: { type: Date }, - requestMethod: { type: String }, // "self" | "oauth" + requestMethod: { type: String, enum: ['self', 'system', 'admin'] }, }, { _id: false } ); @@ -32,13 +27,13 @@ const changeMetaSchema = new Schema( field: { type: String, required: true, - enum: ["email", "password", "accountStatus"], + 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 }, @@ -46,7 +41,7 @@ const changeMetaSchema = new Schema( via: { type: String, - enum: ["user", "admin", "system"], + enum: ['user', 'admin', 'system'], required: true, }, }, @@ -89,8 +84,8 @@ const privacyPrefsSchema = new Schema( { profileVisibility: { type: String, - enum: ["private", "public", "unlisted"], - default: "private", + enum: ['private', 'public', 'unlisted'], + default: 'private', }, showEmailOnProfile: { type: Boolean, @@ -211,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, @@ -274,7 +276,7 @@ const userSchema = new Schema( // Account Status - accountStatus: { type: String, enum: ACCOUNT_STATUSES, default: "active" }, + accountStatus: { type: String, enum: ACCOUNT_STATUSES, default: 'active' }, // Billing billingCustomerId: { type: String }, @@ -282,12 +284,12 @@ 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 }, + cancelAtPeriodEnd: { type: Boolean, default: false }, // Notification settings notificationPrefs: { type: notificationPrefsSchema, @@ -296,12 +298,12 @@ const userSchema = new Schema( inApp: true, marketingEmails: false, }), - }, + }, // Privacy prefs privacyPrefs: { type: privacyPrefsSchema, default: () => ({ - profileVisibility: "private", + profileVisibility: 'private', showEmailOnProfile: false, showLinksOnProfile: true, allowDiscoverability: true, @@ -326,15 +328,9 @@ const userSchema = new Schema( } ); -/** - * 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/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 3510724..8993271 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -1,10 +1,8 @@ -import jwt from "jsonwebtoken"; -import bcrypt from "bcrypt"; -import crypto from "crypto"; -import mongoose, { Types } from "mongoose"; -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 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, @@ -12,26 +10,25 @@ import { generateVerificationToken, hashToken, verifyToken, -} from "@utils/tokens.js"; -import type { LoginInput, RegisterInput } from "@validation/auth.schema.js"; -import { getIpInfo } from "@utils/getIpInfo.js"; -import { parseUserAgent } from "@utils/parseUserAgent.js"; -import { createUsername } from "@utils/createUsername.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, ForbiddenError, - InternalServerError, NotFoundError, UnauthenticatedError, -} 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 { createUserSession } from "./utils/createUserSession.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; @@ -55,44 +52,41 @@ interface RefreshTokenOutput { csrfToken: string; } -export async function registerUser( - input: RegisterInputWithMeta -): Promise { +export async function registerUser(input: RegisterInputWithMeta): Promise { const { email, password, displayName, username, userAgent, ip } = input; const existing = await UserModel.findOne({ $or: [{ email }, { username }] }); if (existing) { if (existing.username === username) { - throw new ConflictError("Username already taken"); + throw new ConflictError('Username already taken'); } else { - throw new ConflictError("Email already registered"); + throw new ConflictError('Email already registered'); } } // Metadata const passwordHash = await bcrypt.hash(password, 10); - const session = await mongoose.startSession(); - session.startTransaction(); - try { + return withTransaction(async (session) => { + const userName = username ? username : await createUsername(email, session); const result: User[] = await UserModel.create( [ { email, passwordHash, - username: username - ? username.toLowerCase() - : `${await createUsername(email)}`, - displayName: displayName ?? email.split("@")[0], + username: userName.toLowerCase(), + displayName: displayName ?? email.split('@')[0], }, ], { session } ); const user: User = result[0]; - const { sessionPayload, tokens } = await createUserSession({ + await assignFreePlan(user._id, session); + + const { sessionPayload, tokens } = await createSessionPayload({ user, userAgent, - ip: (Array.isArray(ip) ? ip[0] : ip) || "", + ip: (Array.isArray(ip) ? ip[0] : ip) || '', }); await SessionModel.create( [ @@ -102,57 +96,53 @@ export async function registerUser( ], { session } ); - await session.commitTransaction(); // enqueue welcome email sendWelcomeEmail(user.email, user.displayName, user.username); return { user, tokens }; - } catch (err) { - await session.abortTransaction(); - const errorMessage = err instanceof Error ? err.message : String(err); - console.error(err); - throw new InternalServerError("Failed to register user", errorMessage); - } finally { - session.endSession(); - } + }); } -export async function loginUser( - input: LoginInputWithMeta -): Promise { - const { email, password, userAgent, ip } = input; +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, - }); + 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.'); } - 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 passedTest = await bcrypt.compare(password, user.passwordHash); + if (!passedTest) { + throw new UnauthenticatedError('Email or Password does not match!'); + } - const { sessionPayload, tokens } = await createUserSession({ - user, - userAgent, - ip: (Array.isArray(ip) ? ip[0] : ip) || "", + const { sessionPayload, tokens } = await createSessionPayload({ + user, + userAgent, + ip: (Array.isArray(ip) ? ip[0] : ip) || '', + }); + await SessionModel.create( + [ + { + ...sessionPayload, + }, + ], + { session } + ); + return { user, tokens }; }); - await SessionModel.create(sessionPayload); - - return { user, tokens }; } export async function refreshTokens( @@ -163,16 +153,13 @@ export async function refreshTokens( let decoded: { userId: string; sessionId: string; - role: "user" | "admin"; + role: 'user' | 'admin'; }; try { - decoded = jwt.verify( - refreshToken, - process.env.REFRESH_TOKEN_SECRET! - ) as typeof decoded; + decoded = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!) as typeof decoded; } catch { - throw new UnauthenticatedError("Authentication failed"); + throw new UnauthenticatedError('Authentication failed'); } const session = await SessionModel.findOne({ @@ -180,50 +167,37 @@ export async function refreshTokens( userId: decoded.userId, valid: true, revokedAt: null, - }).select("+refreshTokenHash +csrfTokenHash +expiresIn"); + }).select('+refreshTokenHash +csrfTokenHash +expiresIn'); if (!session || !session.refreshTokenHash || !session.expiresIn) { - throw new UnauthenticatedError("Authentication failed"); + throw new UnauthenticatedError('Authentication failed'); } - // hard session expiry (absolute TTL) if (session.expiresIn.getTime() <= Date.now()) { - await SessionModel.updateOne( - { _id: session._id }, - { valid: false, revokedAt: new Date() } - ).exec(); + await SessionModel.updateOne({ _id: session._id }, { valid: false, revokedAt: new Date() }).exec(); - throw new UnauthenticatedError("Authentication failed: Session expired"); + throw new UnauthenticatedError('Authentication failed: Session expired'); } - // verify refresh token (CORRECT ORDER) const isValidToken = verifyToken(refreshToken, session.refreshTokenHash); if (!isValidToken) { - await SessionModel.updateOne( - { _id: session._id }, - { valid: false, revokedAt: new Date() } - ).exec(); + await SessionModel.updateOne({ _id: session._id }, { valid: false, revokedAt: new Date() }).exec(); - throw new UnauthenticatedError("Authentication failed: Session revoked"); + throw new UnauthenticatedError('Authentication failed: Session revoked'); } const user = await UserModel.findOne({ _id: decoded.userId, - accountStatus: { $ne: "banned" }, + accountStatus: { $ne: 'banned' }, }); if (!user) { - throw new UnauthenticatedError("Authentication failed"); + throw new UnauthenticatedError('Authentication failed'); } // rotate tokens - const newAccessToken = generateAccessToken( - user._id, - session.sessionId, - user.role, - user.accountStatus - ); + const newAccessToken = generateAccessToken(user._id, session.sessionId, user.role, user.accountStatus); const newRefreshToken = generateRefreshToken(user._id, session.sessionId); @@ -232,7 +206,7 @@ export async function refreshTokens( await SessionModel.updateOne( { _id: session._id, - refreshTokenHash: session.refreshTokenHash, // race protection + refreshTokenHash: session.refreshTokenHash, }, { refreshTokenHash: hashToken(newRefreshToken), @@ -254,8 +228,8 @@ export async function createPasswordResetRequest(email: string) { const normalized = email.trim().toLowerCase(); const user: User | null = await UserModel.findOne({ email: normalized, - }).select("+passwordReset +changeHistory +accountStatus"); - if (!user || user.accountStatus !== "active") { + }).select('+passwordReset +changeHistory +accountStatus'); + if (!user || user.accountStatus !== 'active') { generateVerificationToken(); setTimeout(() => {}, 500); return; @@ -271,13 +245,13 @@ export async function createPasswordResetRequest(email: string) { changeHistory: { $each: [ { - field: "password", + field: 'password', from: null, to: null, by: user._id, - reason: "User requested password reset", + reason: 'User requested password reset', at: new Date(), - via: "user", + via: 'user', }, ], $slice: -100, @@ -286,9 +260,7 @@ export async function createPasswordResetRequest(email: string) { } ); - 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)}`; @@ -298,36 +270,38 @@ export async function createPasswordResetRequest(email: string) { export async function resetPassword(rawToken: string, newPassword: string) { const hash = hashToken(rawToken); - const user: User | null = await UserModel.findOne({ - "passwordReset.tokenHash": hash, - }).select("+passwordReset +passwordHash +changeHistory +accountStatus"); - if ( - !user || - !user.passwordReset?.tokenHash || - !user.passwordReset.expiresAt || - user.accountStatus !== "active" - ) { - throw new BadRequestError("Invalid or expired token"); - } + 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(); - 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 isValid = verifyToken(rawToken, user.passwordReset.tokenHash); + if (!isValid) { + throw new BadRequestError('Invalid or expired token'); + } - const hashedPassword = await bcrypt.hash(newPassword, 10); + const hashedPassword = await bcrypt.hash(newPassword, 10); - const session = await mongoose.startSession(); - session.startTransaction(); - try { - await UserModel.findOneAndUpdate( - { _id: user._id, "passwordReset.tokenHash": hash }, + const updatedResult = await UserModel.findOneAndUpdate( + { _id: user._id, 'passwordReset.tokenHash': hash }, { $set: { passwordHash: hashedPassword, @@ -338,13 +312,13 @@ export async function resetPassword(rawToken: string, newPassword: string) { changeHistory: { $each: [ { - field: "password", + field: 'password', by: user._id, from: null, to: null, - reason: "User reset the password via password reset", + reason: 'User reset the password via password reset', at: new Date(), - via: "user", + via: 'user', }, ], $slice: -100, @@ -353,6 +327,9 @@ export async function resetPassword(rawToken: string, newPassword: string) { }, { session } ); + if (!updatedResult) { + throw new BadRequestError('Token already used or invalid'); + } await SessionModel.updateMany( { userId: user._id }, { @@ -361,39 +338,31 @@ export async function resetPassword(rawToken: string, newPassword: string) { }, { session } ); - await session.commitTransaction(); - // enqueue password changed email - sendPasswordUpdatedEmail(user); - return; - } 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(); + emailPayload = updatedResult; + }); + + //TODO: enqueue password changed email + if (emailPayload) { + sendPasswordUpdatedEmail(emailPayload); } } export async function sendEmailVerification(userId: string): Promise { - const user: User | null = await UserModel.findById(userId).select( - "+emailVerification +changeHistory" - ); + 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"); + 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 verifyEmailUrl = `${process.env.APP_URL}/verify-email?token=${encodeURIComponent(token.raw)}`; await UserModel.updateOne( { _id: user._id }, @@ -409,11 +378,11 @@ export async function sendEmailVerification(userId: string): Promise { changeHistory: { $each: [ { - field: "email", + field: 'email', by: user._id, - reason: "User requested email verification", + reason: 'User requested email verification', at: new Date(), - via: "user", + via: 'user', }, ], $slice: -100, @@ -428,14 +397,14 @@ export async function sendEmailVerification(userId: string): Promise { export async function verifyEmail(verificationToken: string): Promise { const hash = hashToken(verificationToken); const user: User | null = await UserModel.findOne({ - "emailVerification.tokenHash": hash, - }).select("+emailVerification +changeHistory"); + 'emailVerification.tokenHash': hash, + }).select('+emailVerification +changeHistory'); if (!user) { - throw new BadRequestError("Invalid or expired verification token"); + throw new BadRequestError('Invalid or expired verification token'); } const active = ensureActiveAccount(user); if (!active) { - throw new ForbiddenError("Account is not active"); + throw new ForbiddenError('Account is not active'); } if ( @@ -446,30 +415,27 @@ export async function verifyEmail(verificationToken: string): Promise { ) { user.emailVerification = undefined; await user.save(); - throw new BadRequestError("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 BadRequestError("Invalid or expired verification token"); + throw new BadRequestError('Invalid or expired verification token'); } await UserModel.findOneAndUpdate( - { _id: user._id, "emailVerification.tokenHash": hash }, + { _id: user._id, 'emailVerification.tokenHash': hash }, { $set: { emailVerified: true, emailVerification: undefined }, $push: { changeHistory: { $each: [ { - field: "email", - from: "unverified", - to: "verified", + field: 'email', + from: 'unverified', + to: 'verified', by: user._id, - reason: "User verified their email", + reason: 'User verified their email', at: new Date(), - via: "user", + via: 'user', }, ], $slice: -100, @@ -486,42 +452,40 @@ export async function verifyUpdateEmail( currentSessionId?: string ): Promise { const hash = hashToken(verificationToken); - const user: User | null = await UserModel.findOne({ - "pendingEmailChange.tokenHash": hash, - }).select("+pendingEmailChange +changeHistory"); - 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(); - 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"); - } - const session = await mongoose.startSession(); - session.startTransaction(); - try { + + 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 }, { @@ -534,13 +498,13 @@ export async function verifyUpdateEmail( changeHistory: { $each: [ { - field: "email", + field: 'email', from: user.email, to: user.pendingEmailChange.newEmail, by: user._id, - reason: "User verified email change", + reason: 'User verified email change', at: new Date(), - via: "user", + via: 'user', }, ], $slice: -100, @@ -558,19 +522,7 @@ export async function verifyUpdateEmail( }, { 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 - ); - } finally { - session.endSession(); - } - return; + }); } export async function logoutUser(refreshToken: string) { @@ -581,7 +533,7 @@ 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, @@ -589,7 +541,7 @@ export async function logoutUser(refreshToken: string) { valid: true, }); if (!session) { - throw new NotFoundError("Session not found"); + throw new NotFoundError('Session not found'); } session.revokedAt = new Date(); session.valid = false; diff --git a/src/modules/auth/utils/createUserSession.ts b/src/modules/auth/utils/createSessionPayload.ts similarity index 65% rename from src/modules/auth/utils/createUserSession.ts rename to src/modules/auth/utils/createSessionPayload.ts index 80af66c..829af06 100644 --- a/src/modules/auth/utils/createUserSession.ts +++ b/src/modules/auth/utils/createSessionPayload.ts @@ -1,11 +1,12 @@ -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"; +import { Session } 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 createUserSession({ +export async function createSessionPayload({ user, userAgent, ip, @@ -17,7 +18,7 @@ export async function createUserSession({ const ipData: any = await getIpInfo(ip); const userAgentInfo = parseUserAgent(userAgent); - const sessionId = crypto.randomBytes(32).toString("hex"); + const sessionId = crypto.randomBytes(32).toString('hex'); const { accessToken, refreshToken, csrfToken } = generateAllCookieTokens( user._id, @@ -43,8 +44,8 @@ export async function createUserSession({ refreshTokenHash: hashToken(refreshToken), csrfTokenHash: hashToken(csrfToken), expiresIn: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), - createdAt: Date.now(), - lastUsedAt: Date.now(), + createdAt: new Date(), + lastUsedAt: new Date(), }; return { 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/credit/credit.service.ts b/src/modules/credit/credit.service.ts new file mode 100644 index 0000000..2510842 --- /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: Types.ObjectId, + 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..b3ec371 --- /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 '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 '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 index e69de29..c5bbd83 100644 --- a/src/modules/narration/narration.controller.ts +++ 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 index e69de29..3ac4aa4 100644 --- a/src/modules/narration/narration.routes.ts +++ 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 index e69de29..2d2d82f 100644 --- a/src/modules/narration/narration.service.ts +++ 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 95ebb83..19da635 100644 --- a/src/modules/project/project.controller.ts +++ b/src/modules/project/project.controller.ts @@ -1,4 +1,4 @@ -import { Request, Response } from "express"; +import { Request, Response } from 'express'; import { createProject, createProjectContextProfile, @@ -14,15 +14,15 @@ import { updateProjectById, updateProjectStatus, updateProjectVisibility, -} from "./project.service.js"; -import { Types } from "mongoose"; +} from './project.service.js'; +import { Types } from 'mongoose'; import { CreateProjectInput, UpdateProjectInput, UpdateManyIdsInput, CreateProjectContextInput, -} from "@validation/project.schema.js"; -import { paginationResponse } from "@utils/paginationResponse.js"; +} from '@validation/project.schema.js'; +import { paginationResponse } from '@utils/paginationResponse.js'; export const getProjectsController = async (req: Request, res: Response) => { const pagination = req?.pagination!; @@ -38,18 +38,11 @@ export const getProjectsController = async (req: Request, res: Response) => { }); }; -export const getDeletedProjectsController = async ( - req: Request, - res: Response -) => { +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 [projects, total] = await getDeletedProjects(userId, pagination, sorting); const paginationRes = paginationResponse(pagination, total as number); return res.status(200).json({ items: projects, @@ -58,18 +51,11 @@ export const getDeletedProjectsController = async ( }, }); }; -export const getArchivedProjectsController = async ( - req: Request, - res: Response -) => { +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 [projects, total] = await getArchivedProjects(userId, pagination, sorting); const paginationRes = paginationResponse(pagination, total as number); return res.status(200).json({ items: projects, @@ -93,25 +79,15 @@ export const getProjectByIdController = async (req: Request, res: Response) => { return res.status(200).json(project); }; -export const createProjectContextProfileController = async ( - req: Request, - res: Response -) => { +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 - ); + const newProject = await createProjectContextProfile(userId, projectId, payload); return res.status(201).json(newProject); }; -export const updateProjectByIdController = async ( - req: Request, - res: Response -) => { +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; @@ -119,20 +95,14 @@ export const updateProjectByIdController = async ( return res.status(200).json(updatedProject); }; -export const deleteProjectByIdController = async ( - req: Request, - res: Response -) => { +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 updateProjectStatusController = async ( - req: Request, - res: Response -) => { +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; @@ -140,45 +110,29 @@ export const updateProjectStatusController = async ( return res.status(200).json(updatedProject); }; -export const updateProjectVisibilityController = async ( - req: Request, - res: Response -) => { +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 - ); + const updatedProject = await updateProjectVisibility(projectId, userId, visibility); return res.status(200).json(updatedProject); }; -export const restoreProjectByIdController = async ( - req: Request, - res: Response -) => { +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 -) => { +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); }; -export const restoreManyProjectsController = async ( - req: Request, - res: Response -) => { +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); @@ -186,16 +140,10 @@ export const restoreManyProjectsController = async ( return res.status(200).json(restoredProjects); }; -export const unarchiveManyProjectsController = async ( - req: Request, - res: Response -) => { +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 - ); + const unarchivedProjects = await unarchiveManyProjectsByIds(projectIds, userId); return res.status(200).json(unarchivedProjects); }; diff --git a/src/modules/project/project.service.ts b/src/modules/project/project.service.ts index a1977a0..126f613 100644 --- a/src/modules/project/project.service.ts +++ b/src/modules/project/project.service.ts @@ -1,39 +1,27 @@ import { - BadRequestError, - ForbiddenError, + BadRequestError, + ForbiddenError, InternalServerError, NotFoundError, -} from "@middleware/error/index.js"; -import type { - 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"; +} from '@middleware/error/index.js'; +import type { 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 -) { +export async function getProjects(userId: Types.ObjectId | string, pagination: Pagination, sorting: Sorting) { const filter = { userId, status: { $in: ACTIVE_STATUSES } }; const [projects, total] = await Promise.all([ ProjectModel.find(filter) .skip(pagination.skip) .limit(pagination.limit) - .sort({ [sorting.sortBy]: sorting.sortOrder}), + .sort({ [sorting.sortBy]: sorting.sortOrder }), ProjectModel.countDocuments(filter) as Promise, ]); if (!projects || projects.length === 0) { @@ -48,12 +36,12 @@ export async function getDeletedProjects( pagination: Pagination, sorting: Sorting ) { - const filter = { userId, status: "delete" }; + 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}), + .sort({ [sorting.sortBy]: sorting.sortOrder }), ProjectModel.countDocuments(filter) as Promise, ]); if (!projects || projects.length === 0) { @@ -68,12 +56,12 @@ export async function getArchivedProjects( pagination: Pagination, sorting: Sorting ) { - const filter = { userId, status: "archive" }; + 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}), + .sort({ [sorting.sortBy]: sorting.sortOrder }), ProjectModel.countDocuments(filter) as Promise, ]); if (!projects || projects.length === 0) { @@ -83,48 +71,38 @@ export async function getArchivedProjects( return [resProjects, total]; } -export async function createProject( - userId: Types.ObjectId | string, - projectInput: CreateProjectInput -) { +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", + visibility: projectInput.visibility || 'private', status: projectInput.status, }); if (!newProject) { - throw new InternalServerError("Failed to create project"); + throw new InternalServerError('Failed to create project'); } return sanitizeProjectResponse({ project: newProject, - type: "getProjectById", + type: 'getProjectById', }); } -export async function getProjectById( - projectId: Types.ObjectId | string, - userId: Types.ObjectId | string -) { +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"); + throw new NotFoundError('Project is not found'); } return sanitizeProjectResponse({ project: project, - type: "getProjectById", + type: 'getProjectById', }); } -export async function createProjectContextProfile( - userId: string, - projectId: string, - payload: any -) { +export async function createProjectContextProfile(userId: string, projectId: string, payload: any) { const session = await mongoose.startSession(); session.startTransaction(); @@ -134,16 +112,25 @@ export async function createProjectContextProfile( userId, }).session(session); - if (!project) throw new Error("Project not found"); + if (!project) throw new Error('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"); - } + throw new ForbiddenError('Project already has a default context'); + } let contextProfileId; - - if (payload.mode === "new") { - const narrationProfile = NARRATION_PROFILES[payload.data.genre as GenreType]; + + if (payload.mode === 'new') { + const narrationProfile = NARRATION_PROFILES[payload.data.genre as GenreType]; const [context] = await ContextProfileModel.create( [ { @@ -161,18 +148,18 @@ export async function createProjectContextProfile( }, ], { session } - ); + ); contextProfileId = context._id; } - - if (payload.mode === "use-global") { + + if (payload.mode === 'use-global') { const globalContext = await ContextProfileModel.findOne({ _id: payload.globalContextId, scope: ContextScope.GLOBAL, }).session(session); if (!globalContext) { - throw new Error("Global context not found"); + throw new NotFoundError('Global context not found'); } // 🔒 CLONE — NEVER ATTACH DIRECTLY @@ -180,8 +167,8 @@ export async function createProjectContextProfile( ...globalContext.toObject(), _id: undefined, projectId, - parentContextId: globalContext._id, scope: ContextScope.PROJECT, + parentContextId: globalContext._id, isDefaultForProject: true, lastUsedAt: new Date(), }); @@ -191,7 +178,7 @@ export async function createProjectContextProfile( } project.defaultContextProfileId = contextProfileId; - await project.save({ session }); + await project.save({ session }); await session.commitTransaction(); return project; } catch (err) { @@ -202,32 +189,34 @@ export async function createProjectContextProfile( } } +// TODO:createUpdatedContextProfile function + export async function updateProjectById( projectId: Types.ObjectId | string, userId: Types.ObjectId | string, updates: UpdateProjectInput ) { - const updateSet: Partial> = {}; + const updateSet: Partial> = {}; - if (typeof updates.title === "string") { + if (typeof updates.title === 'string') { const trimmedTitle = updates.title.trim(); if (trimmedTitle.length === 0) { - throw new BadRequestError("Title cannot be empty"); + throw new BadRequestError('Title cannot be empty'); } updateSet.title = trimmedTitle; } - if (typeof updates.description === "string") { + if (typeof updates.description === 'string') { const trimmedDescription = updates.description.trim(); if (trimmedDescription.length === 0) { - throw new BadRequestError("Description cannot be empty"); + 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"); - } + throw new BadRequestError('No valid fields provided for update'); + } const project = await ProjectModel.findOneAndUpdate( { @@ -239,101 +228,75 @@ export async function updateProjectById( { new: true, runValidators: true } ); if (!project) { - throw new NotFoundError("Project is not found"); + throw new NotFoundError('Project is not found'); } return sanitizeProjectResponse({ project: project, - type: "getProjectById", + 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 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 updateProjectVisibility( projectId: Types.ObjectId | string, userId: Types.ObjectId | string, - visibility: "public" | "private" + visibility: 'public' | 'private' ) { const project = await ProjectModel.findOneAndUpdate( { _id: projectId, userId, - status: { $eq: "active" }, + status: { $eq: 'active' }, }, { $set: { visibility } }, { new: true, runValidators: true } ); if (!project) { - throw new NotFoundError("Project is not found"); + throw new NotFoundError('Project is not found'); } return sanitizeProjectResponse({ project: project, - type: "getProjectById", + type: 'getProjectById', }); } -export async function updateProjectStatus ( +export async function updateProjectStatus( projectId: Types.ObjectId | string, userId: Types.ObjectId | string, - status: "active" | "archive" | "draft" + status: 'active' | 'archive' | 'draft' ) { - const result = await transitionProjectById( - projectId, - userId, - ["draft", "active", "archive"], - status - ); + const result = await transitionProjectById(projectId, userId, ['draft', 'active', 'archive'], status); return result; } -export async function restoreProjectById ( +export async function restoreProjectById( projectId: Types.ObjectId | string, userId: Types.ObjectId | string ) { - const result = await transitionProjectById( - projectId, - userId, - ["delete"], - "active" ) + const result = await transitionProjectById(projectId, userId, ['delete'], 'active'); return result; -}; +} -export async function unarchiveProjectById ( +export async function unarchiveProjectById( projectId: Types.ObjectId | string, userId: Types.ObjectId | string ) { - const result = await transitionProjectById( - projectId, - userId, - ["archive"], - "active" - ); + const result = await transitionProjectById(projectId, userId, ['archive'], 'active'); return result; } export const restoreManyProjectsByIds = async ( projectIds: (Types.ObjectId | string)[], userId: Types.ObjectId | string -) => { - const result = await transitionManyProjectsByIds( - projectIds, - userId, - "delete", - "active" - ); +) => { + const result = await transitionManyProjectsByIds(projectIds, userId, 'delete', 'active'); return result; }; @@ -341,14 +304,9 @@ export const unarchiveManyProjectsByIds = async ( projectIds: (Types.ObjectId | string)[], userId: Types.ObjectId | string ) => { - const result = await transitionManyProjectsByIds( - projectIds, - userId, - "archive", - "active" - ); + const result = await transitionManyProjectsByIds(projectIds, userId, 'archive', 'active'); return result; }; // Future Possible Functions: ArchiveManyProjectsByIds, DeleteManyProjectsByIds -// Remember to handle visibility changes when archiving or deleting projects \ No newline at end of file +// Remember to handle visibility changes when archiving or deleting projects diff --git a/src/modules/sceneAssets/sceneAssets.controller.ts b/src/modules/sceneAssets/sceneAssets.controller.ts new file mode 100644 index 0000000..b2341a5 --- /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.videoUrl, + }, + }); +}; + +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..60ef0df --- /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/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..ed9d775 --- /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: 'VIDEO_GEN', + grade: grade || 1, + }); + + // Deduct credits if applicable + if (grade && grade > 1) { + const creditsUsed = await getCreditCost('VIDEO_GEN', grade); + await consumeCredits(user._id, 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): Promise { + 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 e1d967b..772b6b8 100644 --- a/src/modules/scenes/scenes.controller.ts +++ b/src/modules/scenes/scenes.controller.ts @@ -5,19 +5,26 @@ import { getAllScenesForStory, updateScene, softDeleteScene, + permanentDeleteScene, restoreScene, bulkReorder, generateSceneWithAI, regenerateScene, generateAllScenes, regenerateAllScenes, - duplicateScene, moveSceneByOne, getSceneCount, + softdeleteAllScenes, restoreAllDeletedScenes, + permanentDeleteAllScenes, bulkRestoreScenes, + bulkSoftdeleteScenes, + bulkPermanentDeleteScenes, updateSceneDuration, getAllDeletedScenes, + reactivateScene, + getAllInactiveScenesForStory, + deactivateScene, } from './scenes.service.js'; import type { CreateSceneInput, @@ -44,7 +51,17 @@ export const getAllStoryScenesController = async (req: Request, res: Response) = }); }; -export const getAllDeltedScenesController = async (req: Request, res: Response) => { +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; @@ -56,6 +73,36 @@ export const getAllDeltedScenesController = async (req: Request, res: Response) }); }; +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; @@ -82,16 +129,6 @@ export const regenerateScenesController = async (req: Request, res: Response) => }); }; -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, - }); -}; - // BULK SCENES CONTROLLERS export const bulkReorderController = async (req: Request, res: Response) => { @@ -118,6 +155,28 @@ export const bulkRestoreScenesController = async (req: Request, res: Response) = }); }; +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) => { @@ -187,15 +246,16 @@ export const updateSceneController = async (req: Request, res: Response) => { 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, sceneId, duration); + const scene = await updateSceneDuration(userId, storyId, sceneId, duration); res.status(200).json({ message: 'Scene duration updated successfully', data: scene, }); }; -export const deleteSceneController = async (req: Request, res: Response) => { +export const softDeleteSceneController = async (req: Request, res: Response) => { const userId = req.user!.id; const sceneId = req.params.sceneId; @@ -207,6 +267,16 @@ export const deleteSceneController = async (req: Request, res: Response) => { }); }; +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; @@ -219,6 +289,26 @@ export const restoreSceneController = async (req: Request, res: Response) => { }); }; +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; diff --git a/src/modules/scenes/scenes.private.routes.ts b/src/modules/scenes/scenes.private.routes.ts index 4b5e559..5c2e119 100644 --- a/src/modules/scenes/scenes.private.routes.ts +++ b/src/modules/scenes/scenes.private.routes.ts @@ -19,22 +19,30 @@ import { import { getAllStoryScenesController, + getAllInactiveStoryScenesController, + getAllDeletedScenesController, getSceneByIdController, createSceneController, updateSceneController, - deleteSceneController, + softDeleteSceneController, + permanentDeleteAllScenesController, restoreSceneController, moveSceneController, bulkReorderController, bulkRestoreScenesController, + bulkSoftDeleteScenesController, + bulkPermanentDeleteScenesController, restoreAllDeletedScenesController, + softDeleteAllScenesController, + permanentDeleteSceneController, generateScenesController, regenerateScenesController, generateSingleSceneController, regenerateSceneController, getSceneCountController, - getAllDeltedScenesController, updateSceneDurationController, + deactivateSceneController, + reactivateSceneController, } from './scenes.controller.js'; const router = Router(); @@ -42,23 +50,36 @@ 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(getAllDeltedScenesController)); +router.get( + '/:storyId/deleted', + validateParams(storyIdParamSchema), + asyncHandler(getAllDeletedScenesController) +); router.get('/:storyId/count', validateParams(storyIdParamSchema), asyncHandler(getSceneCountController)); router.post( - '/:storyId/generate', + '/:storyId/scenes/restore-all', validateParams(storyIdParamSchema), - validateBody(generateAllScenesSchema), - asyncHandler(generateScenesController) + asyncHandler(restoreAllDeletedScenesController) ); -router.post( - '/:storyId/regenerate', +router.delete( + '/:storyId/scenes/soft', validateParams(storyIdParamSchema), - validateBody(regenerateSceneSchema), - asyncHandler(regenerateScenesController) + asyncHandler(softDeleteAllScenesController) +); + +router.delete( + '/:storyId/scenes/permanent', + validateParams(storyIdParamSchema), + asyncHandler(permanentDeleteAllScenesController) ); // BULK SCENES ROUTES @@ -78,14 +99,40 @@ router.post( ); router.post( - '/:storyId/scenes/restore-all', + '/:storyId/scenes/soft-delete-bulk', validateParams(storyIdParamSchema), - asyncHandler(restoreAllDeletedScenesController) + validateBody(bulkRestoreSchema), + asyncHandler(bulkSoftDeleteScenesController) +); + +router.post( + '/:storyId/scenes/permanent-delete-bulk', + validateParams(storyIdParamSchema), + validateBody(bulkRestoreSchema), + asyncHandler(bulkPermanentDeleteScenesController) ); // SINGLE SCENE ROUTES -router.get('/:storyId/scene/:sceneId', validateParams(sceneAndStoryParamSchema), asyncHandler(getSceneByIdController)); +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', @@ -115,10 +162,28 @@ router.patch( 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', + '/:storyId/scene/:sceneId/soft', + validateParams(sceneAndStoryParamSchema), + asyncHandler(softDeleteSceneController) +); + +router.delete( + '/:storyId/scene/:sceneId/permanent', validateParams(sceneAndStoryParamSchema), - asyncHandler(deleteSceneController) + asyncHandler(permanentDeleteSceneController) ); router.post( diff --git a/src/modules/scenes/scenes.service.ts b/src/modules/scenes/scenes.service.ts index f59c65e..5af28b0 100644 --- a/src/modules/scenes/scenes.service.ts +++ b/src/modules/scenes/scenes.service.ts @@ -20,59 +20,22 @@ import type { import { singleScenePrompt } from '@libs/ai/prompts/singleScenePrompt.js'; import { openRouterAI } from '@libs/ai/clients/openAI.js'; import { ContextProfileModel } from '@models/ContextProfile.js'; -import { getContextProfileService } from '@modules/contextProfile/contextProfile.service.js'; import { batchScenesPrompt } from '@libs/ai/prompts/batchScenesPrompt.js'; - -// Helpers for -> Ownership and -> State validation -async function validateStoryOwnership( - userId: string, - storyId: string, - session?: ClientSession -): Promise { - const query = StoryModel.findOne({ - _id: storyId, - userId, - status: { $ne: 'delete' }, - }); - - if (session) query.session(session); - - const story = await query; - if (!story) { - throw new NotFoundError('Story not found or access denied'); - } - return story; -} - -async function validateSceneOwnership( - userId: string, - sceneId: string, - options?: { session?: ClientSession } -): Promise { - const query = SceneModel.findOne({ - _id: sceneId, - userId, - }); - if (options?.session) query.session(options.session); - - const scene = await query; - if (!scene) { - throw new NotFoundError('Scene not found or access denied'); - } - return scene; -} - -function assertSceneNotDeleted(scene: Scene): void { - if (scene.deletedAt) { - throw new ConflictError('Cannot perform operation on deleted scene'); - } -} - -function assertSceneIsDeleted(scene: Scene): void { - if (!scene.deletedAt) { - throw new ConflictError('Scene is not deleted'); - } -} +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 { @@ -148,12 +111,24 @@ export async function getAllScenesForStory(userId: string, storyId: string): Pro 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({ @@ -165,10 +140,7 @@ export async function getAllDeletedScenes(userId: string, storyId: string): Prom } export async function generateAllScenes(userId: string, storyId: string, total: number): Promise { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { + return withTransaction(async (session) => { const story = await validateStoryOwnership(userId, storyId, session); const contextProfile = await ContextProfileModel.findOne({ @@ -205,8 +177,6 @@ export async function generateAllScenes(userId: string, storyId: string, total: throw new InternalServerError('AI generation failed'); } - console.log(generatedScenesData); - if (!generatedScenesData || !Array.isArray(generatedScenesData) || generatedScenesData.length !== total) { throw new InternalServerError('AI returned invalid scene structure'); } @@ -221,7 +191,7 @@ export async function generateAllScenes(userId: string, storyId: string, total: filter: { _id: doc._id }, update: { $set: { - deletedAt: new Date(), + active: false, order: -(Date.now() * 1000 + i), }, }, @@ -247,15 +217,8 @@ export async function generateAllScenes(userId: string, storyId: string, total: ordered: true, })) as Scene[]; - await session.commitTransaction(); return scenes; - } catch (error) { - console.error('REAL ERROR:', error); - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); } export async function regenerateAllScenes( @@ -263,10 +226,7 @@ export async function regenerateAllScenes( storyId: string, extraPrompt?: string ): Promise { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { + return withTransaction(async (session) => { const story = await validateStoryOwnership(userId, storyId, session); const existingScenes = await SceneModel.find({ @@ -319,8 +279,6 @@ export async function regenerateAllScenes( throw new InternalServerError('AI regeneration failed'); } - console.log(regeneratedScenesData); - if ( !regeneratedScenesData || !Array.isArray(regeneratedScenesData) || @@ -329,13 +287,12 @@ export async function regenerateAllScenes( throw new InternalServerError('AI returned invalid scene structure'); } - // Soft-delete old scenes ONLY after AI is validated const ops = existingScenes.map((doc, i) => ({ updateOne: { filter: { _id: doc._id }, update: { $set: { - deletedAt: new Date(), + active: false, order: -(Date.now() * 1000 + i), }, }, @@ -361,21 +318,12 @@ export async function regenerateAllScenes( ordered: true, })) as Scene[]; - await session.commitTransaction(); return scenes; - } catch (error) { - console.log(error); - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); } export async function restoreAllDeletedScenes(userId: string, storyId: string): Promise { - const session = await mongoose.startSession(); - session.startTransaction(); - try { + return withTransaction(async (session) => { await validateStoryOwnership(userId, storyId, session); const activeScenes = await SceneModel.find({ storyId, userId, deletedAt: { $exists: false } }) .sort({ order: -1 }) @@ -387,13 +335,16 @@ export async function restoreAllDeletedScenes(userId: string, storyId: string): userId, deletedAt: { $exists: true }, }).session(session); - if (scenesToRestore.length === 0) { - throw new BadRequestError('No deleted scenes to restore'); - } + + assertHasDeletedScenes(scenesToRestore); + const bulkOps = scenesToRestore.map((scene, index) => ({ updateOne: { filter: { _id: scene._id }, - update: { $unset: { deletedAt: '' }, $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP } }, + update: { + $unset: { deletedAt: '' }, + $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP, active: true }, + }, }, })); await SceneModel.bulkWrite(bulkOps, { session }); @@ -404,14 +355,37 @@ export async function restoreAllDeletedScenes(userId: string, storyId: string): .sort({ order: 1 }) .lean() .session(session); - await session.commitTransaction(); return restoredScenes; - } catch (error) { - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); +} + +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 @@ -420,10 +394,7 @@ export async function bulkRestoreScenes( storyId: string, sceneIds: string[] ): Promise { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { + return withTransaction(async (session) => { await validateStoryOwnership(userId, storyId, session); const activeScenes = await SceneModel.find({ storyId, userId, deletedAt: { $exists: false } }) .sort({ order: -1 }) @@ -437,13 +408,14 @@ export async function bulkRestoreScenes( deletedAt: { $exists: true }, }).session(session); - if (scenesToRestore.length === 0) { - throw new BadRequestError('No valid scenes to restore'); - } + assertHasDeletedScenes(scenesToRestore); const bulkOps = scenesToRestore.map((scene, index) => ({ updateOne: { filter: { _id: scene._id }, - update: { $unset: { deletedAt: '' }, $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP } }, + update: { + $unset: { deletedAt: '' }, + $set: { order: lastOrder + (index + 1) * SCENE_ORDER_GAP, active: true }, + }, }, })); await SceneModel.bulkWrite(bulkOps, { session }); @@ -456,14 +428,45 @@ export async function bulkRestoreScenes( .sort({ order: 1 }) .lean() .session(session); - await session.commitTransaction(); return restoredScenes; - } catch (error) { - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); +} + +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( @@ -471,14 +474,17 @@ export async function bulkReorder( storyId: string, newOrderArray: BulkReorderInput ): Promise { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { + 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, @@ -490,11 +496,6 @@ export async function bulkReorder( throw new BadRequestError('Invalid scene IDs or scenes not in this story'); } - const uniqueIds = new Set(sceneIds); - if (uniqueIds.size !== sceneIds.length) { - throw new BadRequestError('Duplicate scene IDs in order array'); - } - const tempOps = sceneIds.map((sceneId, index) => ({ updateOne: { filter: { _id: sceneId, storyId, userId }, @@ -522,29 +523,15 @@ export async function bulkReorder( .lean() .session(session); - await session.commitTransaction(); return updatedScenes; - } catch (error) { - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); } // Single scene services export async function getSceneById(userId: string, storyId: string, sceneId: string): Promise { await validateStoryOwnership(userId, storyId); - const scene = await SceneModel.findOne({ - _id: sceneId, - storyId, - userId, - }); - - if (!scene) { - throw new NotFoundError('Scene not found'); - } + const scene = await validateStorySceneOwnership(userId, sceneId, storyId); return scene; } @@ -555,10 +542,7 @@ export async function createScene( payload: CreateSceneInput, position?: number ): Promise { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { + return withTransaction(async (session) => { await validateStoryOwnership(userId, storyId, session); let orderValue: number; @@ -594,14 +578,8 @@ export async function createScene( { session } ); - await session.commitTransaction(); return scene; - } catch (error) { - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); } export async function generateSceneWithAI( @@ -610,12 +588,11 @@ export async function generateSceneWithAI( input?: GenerateSceneInput ): Promise { const position = input?.position; - const session = await mongoose.startSession(); - session.startTransaction(); - - try { + 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); @@ -630,8 +607,6 @@ export async function generateSceneWithAI( } } - // check if this affects total scenes duration limit with time limit - const scenes = await SceneModel.find({ storyId, userId, deletedAt: { $exists: false } }) .lean() .session(session); @@ -697,14 +672,8 @@ export async function generateSceneWithAI( { session } ); - await session.commitTransaction(); return scene; - } catch (error) { - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); } export async function regenerateScene( @@ -712,11 +681,8 @@ export async function regenerateScene( sceneId: string, input?: RegenerateSceneInput ): Promise { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { - const scene = await validateSceneOwnership(userId, sceneId, { session }); + return withTransaction(async (session) => { + const scene = await validateSceneOwnership(userId, sceneId, session); assertSceneNotDeleted(scene); const story = await StoryModel.findById(scene.storyId).session(session); @@ -728,9 +694,11 @@ export async function regenerateScene( session ); - const scenes = await SceneModel.find({ storyId: scene.storyId, userId, deletedAt: { $exists: false } }) - .lean() - .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) @@ -799,14 +767,8 @@ export async function regenerateScene( throw new NotFoundError('Failed to regenerate scene'); } - await session.commitTransaction(); return updatedScene; - } catch (error) { - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); - } + }); } export async function updateScene( @@ -840,19 +802,42 @@ export async function updateScene( return updatedScene; } -export async function updateSceneDuration(userId: string, sceneId: string, duration: number): Promise { - const scene = await validateSceneOwnership(userId, sceneId); - assertSceneNotDeleted(scene); - // check if this update does not effect total scenes duration limit with story time limit - const updatedScene = await SceneModel.findByIdAndUpdate( - sceneId, - { $set: { duration } }, - { 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( @@ -860,11 +845,8 @@ export async function moveSceneByOne( sceneId: string, direction: 'prev' | 'next' ): Promise<{ moved: Scene; swappedWith: Scene }> { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { - const scene = await validateSceneOwnership(userId, sceneId, { session }); + return withTransaction(async (session) => { + const scene = await validateSceneOwnership(userId, sceneId, session); assertSceneNotDeleted(scene); const operator = direction === 'prev' ? '$lt' : '$gt'; @@ -912,36 +894,59 @@ export async function moveSceneByOne( moved: updatedScene, swappedWith: updatedNeighbor, }; - } catch (error) { - await session.abortTransaction(); - throw error; - } finally { - session.endSession(); + }); +} + +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() } }); + 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 maxOrderScene = await SceneModel.findOne({ - storyId: scene.storyId, - userId, - deletedAt: { $exists: false }, - }) - .sort({ order: -1 }) - .lean(); - const newOrder = maxOrderScene ? maxOrderScene.order + SCENE_ORDER_GAP : SCENE_ORDER_GAP; + + const newOrder = await getNextOrderValue(scene.storyId.toString()); const restoredScene = await SceneModel.findByIdAndUpdate( sceneId, - { $unset: { deletedAt: '' }, $set: { order: newOrder } }, + { $unset: { deletedAt: '' }, $set: { order: newOrder, active: true } }, { new: true, runValidators: true } ); if (!restoredScene) { @@ -950,13 +955,20 @@ export async function restoreScene(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 }); + const scene = await validateSceneOwnership(userId, sceneId, session); assertSceneNotDeleted(scene); const newOrder = await getNextOrderValue(scene.storyId.toString(), session); @@ -987,8 +999,3 @@ export async function duplicateScene(userId: string, sceneId: string): Promise { - await validateStoryOwnership(userId, storyId); - return 0; -} diff --git a/src/modules/story/story.controller.ts b/src/modules/story/story.controller.ts index 6af3960..1f32e7d 100644 --- a/src/modules/story/story.controller.ts +++ b/src/modules/story/story.controller.ts @@ -1,11 +1,16 @@ -import { paginationResponse } from "@utils/paginationResponse.js"; -import { Request, Response } from "express"; +import { paginationResponse } from '@utils/paginationResponse.js'; +import { Request, Response } from 'express'; import { addStoryContextService, archiveStory, createStory, - deleteStory, - generateStory, + softdeleteStory, + permanentDeleteStory, + getProjectArchivedStories, + getProjectDeletedStories, + getUserArchivedStories, + getUserDeletedStories, + generateStory, getProjectStories, getStoryById, getUserStories, @@ -15,14 +20,15 @@ import { unarchiveStory, updateStory, writeContent, -} from "./story.service.js"; +} from './story.service.js'; import { + AddStoryContextInput, CreateStoryInput, RegenerateStoryInput, SetStoryContextInput, UpdateStoryInput, WriteContentInput, -} from "@validation/story.schema.js"; +} from '@validation/story.schema.js'; export const getUserStoriesController = async (req: Request, res: Response) => { const userId = req.user!.id; @@ -38,21 +44,70 @@ export const getUserStoriesController = async (req: Request, res: Response) => { }); }; -export const getProjectStoriesController = async ( - req: Request, - res: Response -) => { +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 getProjectStories( - userId, - projectId, - pagination, - 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, @@ -65,12 +120,12 @@ export const getProjectStoriesController = async ( 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 payload = req.validatedBody as CreateStoryInput; const story = await createStory(userId, projectId, payload); return res.status(201).json({ - message: "Story created successfully", + message: 'Story created successfully', story, }); }; @@ -84,40 +139,25 @@ export const getStoryByIdController = async (req: Request, res: Response) => { }); }; -export const addStoryContextController = async ( - req: Request, - res: Response -) => { +export const addStoryContextController = async (req: Request, res: Response) => { const userId = req.user!.id; const storyId = req.params.storyId; - const payload = req.validatedBody; - const result = await addStoryContextService( - userId, - storyId, - payload - ); - res.json({ - message: "Story context profile added", + 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 -) { +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.json({ - message: "Story context updated", + + const result = await setStoryContextService(userId, req.params.storyId, payload); + + res.status(200).json({ + message: 'Story context updated', data: result, }); } @@ -129,29 +169,23 @@ export const writeContentController = async (req: Request, res: Response) => { const story = await writeContent(userId, storyId, payload); return res.status(200).json({ - message: "Content added successfully", + message: 'Content added successfully', data: story, }); }; -export const generateStoryController = async ( - req: Request, - res: Response -) => { +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", + message: 'Story generated successfully', data: response, }); }; - -export const regenerateStoryController = async ( - req: Request, - res: 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; @@ -159,8 +193,8 @@ export const regenerateStoryController = async ( const story = await regenerateStory(userId, storyId, extraPrompt); return res.status(200).json({ - message: "Story regeneration initiated", - data: story, + message: 'Story regeneration initiated', + data: story, }); }; @@ -172,23 +206,39 @@ export const updateStoryController = async (req: Request, res: Response) => { const story = await updateStory(userId, storyId, payload); return res.status(200).json({ - message: "Story updated successfully", + message: 'Story updated successfully', story, }); }; -export const deleteStoryController = async (req: Request, res: Response) => { +export const softdeleteStoryController = async (req: Request, res: Response) => { const userId = req.user!.id; const storyId = req.params.storyId; - const response = await deleteStory(userId, storyId); + const response = await softdeleteStory(userId, storyId); if (!response) { return res.status(409).json({ - message: "Story could not be deleted" + message: 'Story could not be deleted', }); } return res.status(200).json({ - message: "Story deleted successfully", + 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 }, }); }; @@ -199,21 +249,18 @@ export const restoreStoryController = async (req: Request, res: Response) => { const story = await restoreStory(userId, storyId); return res.status(200).json({ - message: "Story restored successfully", + message: 'Story restored successfully', data: story, }); }; -export const archiveStoryStatusController = async ( - req: Request, - res: Response -) => { +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", + message: 'Story archived successfully', story: response, }); }; @@ -224,15 +271,14 @@ export const unarchiveStoryController = async (req: Request, res: Response) => { const response = await unarchiveStory(userId, storyId); return res.status(200).json({ - message: "Story unarchived successfully", + 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 -}; \ No newline at end of file +}; diff --git a/src/modules/story/story.private.routes.ts b/src/modules/story/story.private.routes.ts index 4af352c..b56d784 100644 --- a/src/modules/story/story.private.routes.ts +++ b/src/modules/story/story.private.routes.ts @@ -1,38 +1,123 @@ -import { Router } from 'express'; -import { createStoryController, deleteStoryController, getProjectStoriesController, getStoryByIdController, getUserStoriesController, regenerateStoryController, restoreStoryController, rollbackStoryController, unarchiveStoryController, updateStoryController, archiveStoryStatusController, generateStoryController, writeContentController, setStoryContextController, addStoryContextController } from './story.controller.js'; +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/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'; +import { + addStoryContextSchema, + createStorySchema, + regenerateStorySchema, + setStoryContextSchema, + storyIdParamSchema, + updateStorySchema, + writeContentSchema, +} from '@validation/story.schema.js'; -const router = Router(); - -router.get("/", paginationAndSortingMiddleware, asyncHandler(getUserStoriesController)); +const router = Router(); + +router.get('/', paginationAndSortingMiddleware, asyncHandler(getUserStoriesController)); +router.get('/deleted', paginationAndSortingMiddleware, asyncHandler(getUserDeletedStoriesController)); +router.get('/archived', paginationAndSortingMiddleware, asyncHandler(getUserArchivedStoriesController)); router.get( - "/project/:projectId", + '/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.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/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.patch('/:storyId',validateParams(storyIdParamSchema), validateBody(updateStorySchema), asyncHandler(updateStoryController)); -router.delete('/:storyId',validateParams(storyIdParamSchema), asyncHandler(deleteStoryController)); +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 +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; \ No newline at end of file +export default router; diff --git a/src/modules/story/story.service.ts b/src/modules/story/story.service.ts index 5051095..e3a40b2 100644 --- a/src/modules/story/story.service.ts +++ b/src/modules/story/story.service.ts @@ -1,60 +1,117 @@ - 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 { 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, -} 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 mongoose from "mongoose"; -import { Pagination, Sorting } from "types/Pagination.js"; - -export async function getUserStories( + 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'; + +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 }) + StoryModel.find({ userId, projectId, status: { $in: ['active', 'draft'] } }) .skip(pagination.skip) .limit(pagination.limit) .sort({ [sorting.sortBy]: sorting.sortOrder }), - StoryModel.countDocuments({ userId }) as Promise, + StoryModel.countDocuments({ userId, projectId, status: { $in: ['active', 'draft'] } }) as Promise, ]); - return [stories, total]; } -export async function getProjectStories( +export async function getProjectDeletedStories( userId: string, projectId: string, pagination: Pagination, sorting: Sorting ) { const [stories, total] = await Promise.all([ - StoryModel.find({ userId, projectId }) + StoryModel.find({ userId, projectId, status: 'delete' }) .skip(pagination.skip) .limit(pagination.limit) .sort({ [sorting.sortBy]: sorting.sortOrder }), - StoryModel.countDocuments({ userId, projectId }) as Promise, + StoryModel.countDocuments({ userId, projectId, status: 'delete' }) as Promise, ]); return [stories, total]; } -export async function createStory( +export async function getProjectArchivedStories( userId: string, projectId: string, - payload: CreateStoryInput + 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 story = await StoryModel.create({ userId, projectId, @@ -63,49 +120,58 @@ export async function createStory( timeLimit: payload.timeLimit, platform: payload.platform, intent: payload.intent, - status: "draft", + status: payload.status, }); return story; } export async function getStoryById(userId: string, storyId: string) { - const story = await StoryModel.findOne({ _id: storyId, userId }); - if (!story) { - throw new NotFoundError("Story not found"); - } + const story = await validateStoryOwnership(userId, storyId); return story; } export async function addStoryContextService( userId: string, storyId: string, - payload: any + context: AddStoryContextInput['context'] ) { - const session = await mongoose.startSession(); - session.startTransaction(); - try { - const story = await StoryModel.findOne({ - _id: storyId, - userId, - }).session(session); - if (!story) throw new NotFoundError("Story not found"); - - const narrationProfile = - NARRATION_PROFILES[payload.data.genre as GenreType]; + 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, - name: payload.data.name, - description: payload.data.description, - genre: payload.data.genre, - mood: payload.data.mood, - style: payload.data.style, - environment: payload.data.environment, - worldRules: payload.data.worldRules, - narrativeConstraints: payload.data.narrativeConstraints, + 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.GLOBAL, + scope: ContextScope.PROJECT, isDefaultForProject: false, lastUsedAt: new Date(), }, @@ -116,7 +182,6 @@ export async function addStoryContextService( story.contextProfileId = newContext._id; await story.save({ session }); - await session.commitTransaction(); return { story, contextMeta: { @@ -126,51 +191,36 @@ export async function addStoryContextService( }, contextPayload: newContext, }; - } catch (err) { - await session.abortTransaction(); - throw err; - } finally { - session.endSession(); - } + }); } -export async function setStoryContextService( - userId: string, - storyId: string, - payload: any -) { - const session = await mongoose.startSession(); - session.startTransaction(); - - try { - const story = await StoryModel.findOne({ - _id: storyId, - userId, - }).session(session); +export async function setStoryContextService(userId: string, storyId: string, payload: SetStoryContextInput) { + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + assertStoryIsActive(story); - if (!story) throw new NotFoundError("Story not found"); - - const project = await ProjectModel.findById(story.projectId).session( - session - ); - if (!project) throw new NotFoundError("Project not found"); + 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 (payload.mode === 'use-project') { if (!project.defaultContextProfileId) { - throw new NotFoundError("Project has no default context"); + 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); + const context = await ContextProfileModel.findById(project.defaultContextProfileId).session(session); if (!context) { - throw new NotFoundError("Context profile not found"); + throw new NotFoundError('Context profile not found'); } - await session.commitTransaction(); return { story, contextMeta: { @@ -181,7 +231,7 @@ export async function setStoryContextService( }; } - if (payload.mode === "use-global") { + if (payload.mode === 'use-global') { const globalContext = await ContextProfileModel.findOne({ _id: payload.globalContextId, scope: ContextScope.GLOBAL, @@ -189,13 +239,16 @@ export async function setStoryContextService( }).session(session); if (!globalContext) { - throw new NotFoundError("Global context not found"); + 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 }); - await session.commitTransaction(); return { story, contextMeta: { @@ -205,13 +258,8 @@ export async function setStoryContextService( }, }; } - throw new Error("Invalid story context mode"); - } catch (err) { - await session.abortTransaction(); - throw err; - } finally { - session.endSession(); - } + throw new ConflictError('Invalid story context mode'); + }); } export async function writeContent( @@ -224,7 +272,9 @@ export async function writeContent( tags?: string[]; } ) { - const story = await StoryModel.findOneAndUpdate( + const story = await validateStoryOwnership(userId, storyId); + assertStoryIsActive(story); + const updatedStory = await StoryModel.findOneAndUpdate( { _id: storyId, userId }, { $set: { @@ -234,199 +284,184 @@ export async function writeContent( keywords: payload.keywords!, tags: payload.tags!, }, - authorType: "user", - status: "active", + authorType: 'user', + status: 'active', }, }, { new: true } ); - if (!story) { - throw new NotFoundError("Story not found or not authorized"); - } - return story; + return updatedStory; } export async function generateStory(userId: string, storyId: string) { - const story = await StoryModel.findOne({ _id: storyId, userId }); - if (!story) { - throw new NotFoundError("Story not found"); - } - const contextProfile = await ContextProfileModel.findById(story.contextProfileId); - - const prompt = generateStoryPrompt({ - title: story.title, - description: story.description, - intent:story.intent, - platform: story.platform, - timeLimit: story.timeLimit, - contextProfile: contextProfile, - }); - 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); - 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", + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + const contextProfile = await ContextProfileModel.findById(story.contextProfileId).session(session); + + const prompt = generateStoryPrompt({ + title: story.title, + description: story.description, + intent: story.intent, + platform: story.platform, + timeLimit: story.timeLimit, + contextProfile: contextProfile, + }); + + // put this AI generation service in a different location which also have quality level understanding and control + 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); + // Consume credits to be implemented here + + // TODO: Consume credits to be implemented here + // await consumeCredits(userId, 'story_generation', session); + 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 } - ); - - return updatedStory; + { new: true, runValidators: true, session } + ); + return updatedStory; + }); } -export async function regenerateStory( - userId: string, - storyId: string, - extraPrompt: RegenerateStoryInput -) { - const story = await StoryModel.findOne({ _id: storyId, userId }); - if (!story) { - throw new NotFoundError("Story not found"); - } - if (!extraPrompt || !extraPrompt.prompt) { - throw new ConflictError("No regeneration prompt provided."); - } - - const contextProfile = await ContextProfileModel.findById(story.contextProfileId); - - 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, - }); - 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); +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 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, + 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, + }); + let response; + try { + response = await openRouterAI(prompt); + } catch (err) { + throw new ConflictError('AI regeneration failed, please try again.'); } - ); - return updatedStory; + const rawcontent = response.choices[0].message?.content || ''; + if (!rawcontent) { + throw new ConflictError('AI regeneration returned empty content, please try again.'); + } + const content = safeParseJSON(rawcontent); + + 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 -) { - const story = await StoryModel.findOneAndUpdate( +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 - if (!story) { - throw new NotFoundError("Story not found or not authorized"); - } - return story; + + return updatedStory; } -export async function deleteStory( - userId: string, - storyId: string -): Promise { - const story = await StoryModel.findOne({ _id: storyId, userId }); - if (!story) { - throw new NotFoundError("Story not found"); - } - if (story.status === "delete") { - throw new ConflictError("Story is already deleted"); - } +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" } } + { _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 StoryModel.findOneAndUpdate( - { _id: storyId, userId, status: "delete" }, - { $set: { isDeleted: false, status: "active" }, $unset: { deletedAt: "" } }, + 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 } ); - if (!story) { - throw new NotFoundError("Story not found or not deleted"); - } - return story; + 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 StoryModel.findOneAndUpdate( - { _id: storyId, userId, status: "active" }, - { $set: { status: "archive" } }, + 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 } ); - if (!story) { - throw new NotFoundError("Story not found or not active"); - } - return story; + return updatedStory; } export async function unarchiveStory(userId: string, storyId: string) { - const story = await StoryModel.findOneAndUpdate( - { _id: storyId, userId, status: "archive" }, - { $set: { status: "active" } }, + 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 } ); - if (!story) { - throw new NotFoundError("Story not found or not archived"); - } - return story; + return updatedStory; } -// To be implemented +// To be implemented in future export async function rollbackStory(userId: string, storyId: string) { return; -} \ No newline at end of file +} 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.routes.ts b/src/modules/user/user.routes.ts index 2a4232d..2823bf3 100644 --- a/src/modules/user/user.routes.ts +++ b/src/modules/user/user.routes.ts @@ -30,7 +30,7 @@ import { } from "@validation/user.schema.js"; import { validateBody } from "@validation/validateBody.js"; import { validateParams } from "@validation/validateParams.js"; -import { avatarUpload } from "@middleware/avatarUpload.js"; +import { avatarUpload } from "@middleware/multer/avatarUpload.js"; import { requireActiveAccount } from "@middleware/security/requireActiveAccount.js"; const router = Router(); diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index b6d6acb..e58b81e 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -1,52 +1,41 @@ -import bcrypt from "bcrypt"; +import bcrypt from 'bcrypt'; import { BadRequestError, ConflictError, InternalServerError, NotFoundError, UnauthenticatedError, -} from "@middleware/error/index.js"; -import { SessionModel } from "@models/Session.js"; -import { type User, UserModel } from "@models/User.js"; -import { returnUserData } from "@utils/returnUserData.js"; -import { - UpdateNotificationsType, - UpdatePrivacySettingsType, -} from "@validation/user.schema.js"; -import mongoose from "mongoose"; -import { generateVerificationToken } from "@utils/tokens.js"; -import sendUpdateEmailLink from "@utils/emails/sender/sendUpdateEmailLink.js"; -import sendOldEmailVerificationForEmailUpdate from "@utils/emails/sender/sendOldEmailVerificationForEmailUpdate.js"; +} 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" - ) + .select('-passwordHash -emailVerificationToken -resetPasswordToken -createdAt -updatedAt') .catch((err) => { - throw new InternalServerError( - "Could not fetch user profile", - err.message - ); + throw new InternalServerError('Could not fetch user profile', err.message); }); if (!user) { - throw new NotFoundError("User not found"); + throw new NotFoundError('User not found'); } return user; }; -export const updateProfile = async ( - userId: string, - 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 NotFoundError("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(user, "profile"); + const resUser = sanitizeUserResponse(user, 'profile'); return resUser; }; @@ -55,7 +44,7 @@ export const updateAvatar = async ( avatarData: Express.Multer.File | undefined ): Promise> => { if (!avatarData) { - throw new BadRequestError("Avatar file not found"); + throw new BadRequestError('Avatar file not found'); } const { filename, path } = avatarData; @@ -63,62 +52,52 @@ export const updateAvatar = async ( // For now, we will just use the filename as is const avatarUrl = `${path}/${filename}`; - const user = await UserModel.findByIdAndUpdate( - userId, - { avatarUrl: avatarUrl }, - { new: true } - ); + const user = await UserModel.findByIdAndUpdate(userId, { avatarUrl: avatarUrl }, { new: true }); if (!user) { - throw new NotFoundError("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: string): Promise => { const user = await UserModel.findById(userId); if (!user) { - throw new NotFoundError("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. */ - const oldAvatarUrl = user.avatarUrl; if (!oldAvatarUrl) { return; } - //TODO Add logic to delete the avatar file from storage if necessary - await UserModel.findByIdAndUpdate( - userId, - { $unset: { avatarUrl: "" } }, - { new: true } - ); + await UserModel.findByIdAndUpdate(userId, { $unset: { avatarUrl: '' } }, { new: true }); return; }; export const getSettings = async (userId: string): Promise> => { - const user = await UserModel.findById(userId).select( - "emailNotifications privacySettings" - ); + 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: 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 NotFoundError("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; }; @@ -143,14 +122,9 @@ export const getSessions = async ( 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, @@ -160,11 +134,11 @@ export const getSessions = async ( }; export const getBilling = async (userId: string): Promise> => { - const user = await UserModel.findById(userId).select("plan billingInfo"); + const user = await UserModel.findById(userId).select('plan billingInfo'); if (!user) { - throw new NotFoundError("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; }; @@ -175,27 +149,22 @@ export const updateNotifications = async ( const update: Record = {}; if (notificationPrefs.emailNotifications !== undefined) { - update["notificationPrefs.emailOnJobComplete"] = - notificationPrefs.emailNotifications; + update['notificationPrefs.emailOnJobComplete'] = notificationPrefs.emailNotifications; } if (notificationPrefs.pushNotifications !== undefined) { - update["notificationPrefs.inApp"] = notificationPrefs.pushNotifications; + update['notificationPrefs.inApp'] = notificationPrefs.pushNotifications; } if (notificationPrefs.newsletter !== undefined) { - update["notificationPrefs.marketingEmails"] = notificationPrefs.newsletter; + update['notificationPrefs.marketingEmails'] = notificationPrefs.newsletter; } - const user = await UserModel.findByIdAndUpdate( - userId, - { $set: update }, - { new: true } - ); + const user = await UserModel.findByIdAndUpdate(userId, { $set: update }, { new: true }); if (!user) { - throw new NotFoundError("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; }; @@ -205,28 +174,23 @@ export const updatePrivacySettings = async ( ): Promise> => { const update: Record = {}; if (privacyPrefs.profileVisibility !== undefined) { - update["privacyPrefs.profileVisibility"] = privacyPrefs.profileVisibility; + update['privacyPrefs.profileVisibility'] = privacyPrefs.profileVisibility; } if (privacyPrefs.showEmailOnProfile !== undefined) { - update["privacyPrefs.showEmailOnProfile"] = privacyPrefs.showEmailOnProfile; + update['privacyPrefs.showEmailOnProfile'] = privacyPrefs.showEmailOnProfile; } if (privacyPrefs.showLinksOnProfile !== undefined) { - update["privacyPrefs.showLinksOnProfile"] = privacyPrefs.showLinksOnProfile; + update['privacyPrefs.showLinksOnProfile'] = privacyPrefs.showLinksOnProfile; } if (privacyPrefs.allowDiscoverability !== undefined) { - update["privacyPrefs.allowDiscoverability"] = - privacyPrefs.allowDiscoverability; + update['privacyPrefs.allowDiscoverability'] = privacyPrefs.allowDiscoverability; } - const user = await UserModel.findByIdAndUpdate( - userId, - { $set: update }, - { new: true } - ); + const user = await UserModel.findByIdAndUpdate(userId, { $set: update }, { new: true }); if (!user) { - throw new NotFoundError("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; }; @@ -235,47 +199,42 @@ export const updatePassword = async ( currentPassword: string, newPassword: string ): Promise => { - const user = await UserModel.findById(userId).select( - "+passwordHash +changeHistory" - ); + const user = await UserModel.findById(userId).select('+passwordHash +changeHistory'); if (!user) { - throw new NotFoundError("User not found"); + throw new NotFoundError('User not found'); } const isMatch = await bcrypt.compare(currentPassword, user.passwordHash); if (!isMatch) { - throw new UnauthenticatedError("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", + field: 'password', by: user._id, - from: "", - to: "", - reason: "User initiated password change", + from: '', + to: '', + reason: 'User initiated password change', at: new Date(), - via: "user", + via: 'user', }); await user.save(); return; }; -export const updateEmail = async ( - userId: string, - 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) @@ -283,9 +242,7 @@ export const updateEmail = async ( .slice(0, 6); const codeHash = await bcrypt.hash(code, 10); - const updateEmailUrl = `${ - process.env.APP_URL - }/verify-email-change?token=${encodeURIComponent(token.raw)}`; + const updateEmailUrl = `${process.env.APP_URL}/verify-email-change?token=${encodeURIComponent(token.raw)}`; user.pendingEmailChange = { newEmail: newEmail, @@ -293,31 +250,28 @@ export const updateEmail = async ( tokenHash: token.hash, 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); + 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: string, - 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 NotFoundError("Session not found"); + throw new NotFoundError('Session not found'); } if (session.revokedAt) { - throw new BadRequestError("Session already revoked"); + throw new BadRequestError('Session already revoked'); } session.revokedAt = new Date(); @@ -338,31 +292,29 @@ export const deleteAllSessions = async ( await SessionModel.updateMany(filter, { revokedAt: new Date(), valid: false }) .exec() .catch((err) => { - throw new InternalServerError("Could not revoke sessions", err.message); + throw new InternalServerError('Could not revoke sessions', err.message); }); return; }; export const deleteAccount = async (userId: string): Promise => { - const session = await mongoose.startSession(); - session.startTransaction(); - try { + return withTransaction(async (session) => { await UserModel.findByIdAndUpdate( userId, { deletedAt: new Date(), - accountStatus: "delete", + accountStatus: 'delete', $push: { changeHistory: { $each: [ { - field: "accountStatus", - from: "active", - to: "delete", + field: 'accountStatus', + from: 'active', + to: 'delete', by: userId, - reason: "User deleted account", + reason: 'User deleted account', at: new Date(), - via: "user", + via: 'user', }, ], $slice: -100, @@ -372,42 +324,33 @@ export const deleteAccount = async (userId: string): Promise => { { session } ); await SessionModel.deleteMany({ userId }, { session }); - await session.commitTransaction(); - } catch (err) { - await session.abortTransaction(); - throw new InternalServerError("Could not delete account", String(err)); - } finally { - session.endSession(); - } - return; + }); }; -export const reactivateAccount = async ( - userId: string -): Promise> => { - const user = await UserModel.findById(userId).select("+changeHistory +role"); +export const reactivateAccount = async (userId: string): Promise> => { + const user = await UserModel.findById(userId).select('+changeHistory +role'); if (!user) { - throw new NotFoundError("User not found"); + throw new NotFoundError('User not found'); } - if (user.accountStatus !== "deactive" && user.accountStatus !== "delete") { + if (user.accountStatus !== 'deactive' && user.accountStatus !== 'delete') { throw new BadRequestError( - "Account is not deactivated or deleted other than that cannot be reactivated. Contact support." + 'Account is not deactivated or deleted other than that cannot be reactivated. Contact support.' ); } const updatedUser = await UserModel.findByIdAndUpdate( userId, { - accountStatus: "active", + accountStatus: 'active', deletedAt: null, $push: { changeHistory: { $each: [ { - field: "accountStatus", + field: 'accountStatus', from: user.accountStatus, - to: "active", + to: 'active', by: user._id, - reason: "Account reactivated", + reason: 'Account reactivated', at: new Date(), via: user.role, }, @@ -419,37 +362,32 @@ export const reactivateAccount = async ( { new: true } ); if (!updatedUser) { - throw new NotFoundError("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(updatedUser, "profile"); + const resUser = sanitizeUserResponse(updatedUser, 'profile'); return resUser; }; -export const deactivateAccount = async ( - userId: string -): Promise> => { - const user = await UserModel.findById(userId).select("+changeHistory +role"); - if (!user) { - throw new NotFoundError("User not found"); - } - - const session = await mongoose.startSession(); - session.startTransaction(); - try { +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'); + } const updatedUser = await UserModel.findByIdAndUpdate( userId, { - accountStatus: "deactive", + accountStatus: 'deactive', $push: { changeHistory: { $each: [ { - field: "accountStatus", + field: 'accountStatus', from: user.accountStatus, - to: "deactive", + to: 'deactive', by: user._id, - reason: "Account status updated", + reason: 'Account status updated', at: new Date(), via: user.role, }, @@ -466,16 +404,10 @@ export const deactivateAccount = async ( }, { session } ); - await session.commitTransaction(); if (!updatedUser) { - throw new NotFoundError("User not found"); + throw new NotFoundError('User not found'); } - const resUser = returnUserData(updatedUser, "profile"); + const resUser = sanitizeUserResponse(updatedUser, 'profile'); return resUser; - } catch (err) { - await session.abortTransaction(); - throw new InternalServerError("Could not update account", String(err)); - } finally { - session.endSession(); - } + }); }; diff --git a/src/routes/api.ts b/src/routes/api.ts index d3d2af1..0096905 100644 --- a/src/routes/api.ts +++ b/src/routes/api.ts @@ -6,6 +6,8 @@ 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'; @@ -21,5 +23,7 @@ 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 4e1494b..3b66256 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,37 +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 { 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"; +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()); -AppRouter.use(cookieParser()); +AppRouter.use(requestLogger); AppRouter.use((_req, res, next) => { - res.setHeader("X-Debug-Server", process.pid.toString()); + res.setHeader('X-Debug-Server', process.pid.toString()); next(); -}); - -// Basic logger -AppRouter.use(requestLogger); +}); // 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/getAccountBlockResponse.ts b/src/security/guards/getAccountBlockResponse.ts index ef97eec..01fd448 100644 --- a/src/security/guards/getAccountBlockResponse.ts +++ b/src/security/guards/getAccountBlockResponse.ts @@ -1,5 +1,5 @@ -import { AccountStatus } from "@constants/userConsts.js"; -import { accountStatusResponses } from "../policies/accountStatusResponses.js"; +import { AccountStatus } from '@constants/userConsts.js'; +import { accountStatusResponses } from '../../policies/accountStatusResponses.js'; export function getAccountBlockResponse(status: AccountStatus | null | undefined) { return accountStatusResponses(status); diff --git a/src/types/index.ts b/src/types/index.ts index e69de29..c27e895 100644 --- a/src/types/index.ts +++ 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/buildSessionMetadata.ts b/src/utils/buildSessionMetadata.ts deleted file mode 100644 index e69de29..0000000 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/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/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/sanitizeProjectResponse.ts b/src/utils/sanitizeProjectResponse.ts index f9a8466..623c05a 100644 --- a/src/utils/sanitizeProjectResponse.ts +++ b/src/utils/sanitizeProjectResponse.ts @@ -1,16 +1,13 @@ -import { Project } from "@models/Project.js"; +import { Project } from '@models/Project.js'; interface ProjectResponse { project: Project; - type: "getProjects" | "getProjectById"; + type: 'getProjects' | 'getProjectById'; } -const sanitizeProjectResponse = ({ - project, - type = "getProjectById", -}: ProjectResponse) => { +const sanitizeProjectResponse = ({ project, type = 'getProjectById' }: ProjectResponse) => { switch (type) { - case "getProjects": + case 'getProjects': return { _id: project._id, title: project.title, @@ -20,14 +17,14 @@ const sanitizeProjectResponse = ({ createdAt: project.createdAt, updatedAt: project.updatedAt, }; - case "getProjectById": + case 'getProjectById': return { _id: project._id, title: project.title, description: project.description, visibility: project.visibility, status: project.status, - contextProfileId: project.defaultContextProfileId, + contextProfileId: project.defaultContextProfileId, generationCounts: project.generationCounts, createdAt: project.createdAt, updatedAt: project.updatedAt, @@ -38,9 +35,7 @@ const sanitizeProjectResponse = ({ }; const sanitizeProjects = (projects: Project[]) => { - return projects.map((project) => - sanitizeProjectResponse({ project, type: "getProjects" }) - ); + 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 82% rename from src/utils/returnUserData.ts rename to src/utils/sanitizeUserResponse.ts index f8769bc..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,13 +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, @@ -32,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, @@ -51,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, @@ -64,7 +59,7 @@ export const returnUserData = (user: User, type: UserReturnType) => { usage: user.usage, }; - case "account": + case 'account': return { _id: user._id, email: user.email, 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 8a2dad2..115e678 100644 --- a/src/validation/project.schema.ts +++ b/src/validation/project.schema.ts @@ -1,88 +1,76 @@ -import { CameraMotion, EnvironmentType, GenreType, MoodType, NarrativeScope, StyleType } from "@models/ContextProfile.js"; -import { z } from "zod"; +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(), + 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(), + 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" - ); + .refine((data) => Object.keys(data).length > 0, 'At least one field must be provided'); export const updateProjectVisibilitySchema = z .object({ - visibility: z.enum(["public", "private"]), + visibility: z.enum(['public', 'private']), }) .strict(); export const updateProjectStatusSchema = z .object({ - status: z.enum(["active", "draft", "archive"]), + 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"), + .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< - typeof updateProjectVisibilitySchema ->; -export type UpdateProjectStatusInput = z.infer< - typeof updateProjectStatusSchema ->; +export type UpdateProjectVisibilityInput = z.infer; +export type UpdateProjectStatusInput = z.infer; export const projectIdParamSchema = z .object({ - projectId: z.string().length(24, "Invalid project ID"), + projectId: z.string().length(24, 'Invalid project ID'), }) .strict(); - - const environmentSchema = z.object({ - type: z.nativeEnum(EnvironmentType), - cameraMotion: z.nativeEnum(CameraMotion), - description: z.string().max(300).optional(), -}); - const newProjectContextSchema = z.object({ - mode: z.literal("new"), + mode: z.literal('new'), data: z.object({ 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), + genre: z.enum(GenreType), + mood: z.enum(MoodType), + style: z.enum(StyleType), - narrativeScope: z - .nativeEnum(NarrativeScope) - .optional(), + narrativeScope: z.enum(NarrativeScope).optional(), - environment: environmentSchema, + 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(), @@ -101,26 +89,23 @@ const newProjectContextSchema = z.object({ .array( z.object({ label: z.string().min(1), - severity: z.enum(["hard", "soft"]).optional(), + severity: z.enum(['hard', 'soft']).optional(), }) ) .optional(), }), }); - + const useGlobalProjectContextSchema = z.object({ - mode: z.literal("use-global"), + mode: z.literal('use-global'), globalContextId: z.string().min(1), }); - -export const createProjectContextProfileSchema = - z.discriminatedUnion("mode", [ - newProjectContextSchema, - useGlobalProjectContextSchema, - ]); + +export const createProjectContextProfileSchema = z.discriminatedUnion('mode', [ + newProjectContextSchema, + useGlobalProjectContextSchema, +]); export type ProjectIdParam = z.infer; export type UpdateManyIdsInput = z.infer; -export type CreateProjectContextInput = z.infer< - typeof createProjectContextProfileSchema ->; +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/story.schema.ts b/src/validation/story.schema.ts index 72f4f11..69c90f8 100644 --- a/src/validation/story.schema.ts +++ b/src/validation/story.schema.ts @@ -1,87 +1,125 @@ -import { maxTimeLimit, minTimeLimit,platform, storyIntent } from "@constants/storyConsts.js"; -import {z} from "zod"; - +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`), + .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 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 +export const regenerateStorySchema = z .object({ - prompt: z.string().max(200, "Prompt is too long").optional(), + prompt: z.string().max(200, 'Prompt is too long'), }) .strict(); - export const updateStorySchema = z +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(), + 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(); + .object({ + storyId: z.string().length(24, 'Invalid story ID'), + }) + .strict(); -export const setStoryContextSchema = z.discriminatedUnion("mode", [ - z.object({ - mode: z.literal("use-project"), - }).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(), + z + .object({ + mode: z.literal('use-global'), + globalContextId: z.string().min(1), + }) + .strict(), ]); -export const addStoryContextSchema = z.object({ - data: z.object({ +export const addStoryContextSchema = z + .object({ + context: z.object({ name: z.string().min(1).max(100), description: z.string().max(600).optional(), - genre: z.string(), - mood: z.string(), - style: z.string(), + genre: z.enum(GenreType), + mood: z.enum(MoodType), + style: z.enum(StyleType), + narrativeScope: z.enum(NarrativeScope).optional(), environment: z.object({ - type: z.string(), - cameraMotion: z.string(), + 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(), + 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(); + }) + .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; \ No newline at end of file +export type SetStoryContextInput = z.infer; +export type AddStoryContextInput = 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/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; +} From 7d4382f5736f517d5a6b977f794b2a0fbc2ac39d Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Fri, 6 Mar 2026 07:20:29 +0530 Subject: [PATCH 12/14] Updated All Modules and Added Docker Files --- .dockerignore | 9 +- .gitignore | 2 + Dockerfile | 13 +- Dockerfile.dev | 11 + docker-compose.dev.yml | 21 + docker-compose.prod.yml | 17 + src/config/creditPricing.ts | 52 +- src/constants/audioAssetConsts.ts | 30 + src/constants/globalConts.ts | 2 +- src/constants/videoConfigConsts.ts | 154 +++++ .../assertions/assertAudioAssetState.ts | 44 ++ src/libs/ai/clients/openAI.ts | 54 +- src/middleware/error/globalErrorHandler.ts | 4 +- src/middleware/error/index.ts | 32 +- src/middleware/multer/audioAssetUpload.ts | 18 + .../multer/filenameLogic/multerAudio.ts | 74 ++ .../request/paginationAndSorting.ts | 31 +- src/middleware/security/requireCsrf.ts | 31 +- src/models/ContextProfile.ts | 5 +- src/models/FinalVideo.ts | 84 +-- src/models/Project.ts | 25 +- src/models/VideoConfig.ts | 488 +++++++++++++ src/modules/audio/audio.constants.ts | 28 + src/modules/audio/audio.controller.ts | 292 ++++++++ src/modules/audio/audio.routes.ts | 175 +++++ src/modules/audio/audio.service.ts | 611 +++++++++++++++++ src/modules/auth/auth.controller.ts | 116 ++-- src/modules/auth/auth.routes.ts | 63 +- src/modules/auth/auth.service.ts | 15 +- .../auth/utils/createSessionPayload.ts | 26 +- .../contextProfile.controller.ts | 9 + .../contextProfile/contextProfile.routes.ts | 13 +- .../contextProfile/contextProfile.service.ts | 85 ++- src/modules/credit/credit.service.ts | 2 +- src/modules/project/project.controller.ts | 136 +++- src/modules/project/project.routes.ts | 97 +-- src/modules/project/project.service.ts | 241 ++++++- src/modules/project/rules/projectStatus.ts | 29 +- .../utils/transitionManyProjectsByIds.ts | 38 +- .../project/utils/transitionProjectById.ts | 6 +- .../sceneAssets/sceneAssets.private.routes.ts | 2 +- src/modules/story/story.private.routes.ts | 2 +- src/modules/story/story.service.ts | 28 +- src/modules/user/user.controller.ts | 2 +- src/modules/videoConfig/index.ts | 3 + .../videoConfig/videoConfig.controller.ts | 379 +++++++++++ src/modules/videoConfig/videoConfig.routes.ts | 107 +++ .../videoConfig/videoConfig.service.ts | 639 ++++++++++++++++++ .../guards/getAccountBlockResponse.ts | 2 +- src/types/express.d.ts | 12 +- src/utils/getIpInfo.ts | 10 +- src/utils/paginationResponse.ts | 5 +- src/utils/sanitizeProjectResponse.ts | 1 + src/validation/audio.schema.ts | 125 ++++ src/validation/auth.schema.ts | 45 +- src/validation/user.schema.ts | 11 +- src/validation/videoConfig.schema.ts | 263 +++++++ src/validators/validateAudioAssetOwnership.ts | 22 + .../validateVideoConfigOwnership.ts | 48 ++ tsconfig.json | 5 +- 60 files changed, 4393 insertions(+), 501 deletions(-) create mode 100644 Dockerfile.dev create mode 100644 docker-compose.dev.yml create mode 100644 docker-compose.prod.yml create mode 100644 src/constants/audioAssetConsts.ts create mode 100644 src/constants/videoConfigConsts.ts create mode 100644 src/domain/assertions/assertAudioAssetState.ts create mode 100644 src/middleware/multer/audioAssetUpload.ts create mode 100644 src/middleware/multer/filenameLogic/multerAudio.ts create mode 100644 src/models/VideoConfig.ts create mode 100644 src/modules/audio/audio.constants.ts create mode 100644 src/modules/audio/audio.controller.ts create mode 100644 src/modules/audio/audio.routes.ts create mode 100644 src/modules/audio/audio.service.ts create mode 100644 src/modules/videoConfig/index.ts create mode 100644 src/modules/videoConfig/videoConfig.controller.ts create mode 100644 src/modules/videoConfig/videoConfig.routes.ts create mode 100644 src/modules/videoConfig/videoConfig.service.ts create mode 100644 src/validation/audio.schema.ts create mode 100644 src/validation/videoConfig.schema.ts create mode 100644 src/validators/validateAudioAssetOwnership.ts create mode 100644 src/validators/validateVideoConfigOwnership.ts 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/.gitignore b/.gitignore index 52f36d9..432a6c3 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,8 @@ Design # Node modules node_modules/ +postman + # Temporary files npm-temp/ temp/ diff --git a/Dockerfile b/Dockerfile index f955eb8..53f5b4b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,13 +2,14 @@ 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 ci --only=production + +COPY . . + +RUN npm run build + 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/src/config/creditPricing.ts b/src/config/creditPricing.ts index 9bea64f..a03d068 100644 --- a/src/config/creditPricing.ts +++ b/src/config/creditPricing.ts @@ -1,11 +1,28 @@ -export type ActionType = 'IMAGE_GEN' | 'AUDIO_GEN' | 'STORY_GEN' | 'VIDEO_GEN'; +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> = { - IMAGE_GEN: { + 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: { @@ -13,17 +30,44 @@ export const CREDIT_PRICING: Record> = { 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, }, - VIDEO_GEN: { - 1: 10, + IMG_TO_VIDEO_GEN: { 2: 20, 3: 35, + 4: 50, + 5: 75, }, }; 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/globalConts.ts b/src/constants/globalConts.ts index e6fddb2..3558001 100644 --- a/src/constants/globalConts.ts +++ b/src/constants/globalConts.ts @@ -1,7 +1,7 @@ export const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : [ - process.env.DEV_CLIENT_URL || 'http://localhost:3000', + 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/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/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/libs/ai/clients/openAI.ts b/src/libs/ai/clients/openAI.ts index 8d0c2a7..df9749c 100644 --- a/src/libs/ai/clients/openAI.ts +++ b/src/libs/ai/clients/openAI.ts @@ -1,25 +1,22 @@ -import { InternalServerError } from "@middleware/error/index.js"; +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"); + if (!API_KEY) throw new Error('Missing OpenRouter API key'); - const response = await fetch( - "https://openrouter.ai/api/v1/chat/completions", - { - method: "POST", - // signal: AbortSignal.timeout(30000), // 30s timeout - headers: { - Authorization: `Bearer ${API_KEY}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - model: "google/gemma-3-27b-it:free", - temperature: 0.7, - messages: [ - { - role: "system", - content: ` + 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: @@ -28,23 +25,18 @@ Rules: - No backticks - No explanations - No extra text + +User request: +${prompt} `, - }, - { - role: "user", - content: prompt, - }, - ], - }), - } - ); + }, + ], + }), + }); if (!response.ok) { const errorText = await response.text(); - throw new InternalServerError( - "AI API error ", - `(${response.status}): ${errorText}` - ); + throw new InternalServerError('AI API error ', `(${response.status}): ${errorText}`); } const data = await response.json(); diff --git a/src/middleware/error/globalErrorHandler.ts b/src/middleware/error/globalErrorHandler.ts index f1898c1..d0519c7 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -21,13 +21,15 @@ const errorHandler = (err: unknown, req: Request, res: Response, _next: NextFunc return res.status(err.statusCode).json(err.serialize()); } + console.log(err); logger.error({ requestId, name: 'UnhandledError', message: 'Unhandled exception', - stack: err instanceof Error ? err.stack : undefined, + 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({ diff --git a/src/middleware/error/index.ts b/src/middleware/error/index.ts index d45f113..d290125 100644 --- a/src/middleware/error/index.ts +++ b/src/middleware/error/index.ts @@ -1,100 +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) { + 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/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/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/request/paginationAndSorting.ts b/src/middleware/request/paginationAndSorting.ts index 23e2926..23eb833 100644 --- a/src/middleware/request/paginationAndSorting.ts +++ b/src/middleware/request/paginationAndSorting.ts @@ -1,25 +1,21 @@ -import { Request, Response, NextFunction } from "express"; -import { BadRequestError } from "./error/index.js"; -import type { Pagination, Sorting } from "types/Pagination.js"; +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 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"); + throw new BadRequestError('Page must be greater than 0'); } if (limit < 1 || limit > MAX_LIMIT) { @@ -34,16 +30,15 @@ export function paginationAndSortingMiddleware( // ---------- Sorting ---------- const sortBy = - typeof req.query.sortBy === "string" && - ALLOWED_SORT_FIELDS.includes(req.query.sortBy) + typeof req.query.sortBy === 'string' && ALLOWED_SORT_FIELDS.includes(req.query.sortBy) ? req.query.sortBy - : "createdAt"; + : 'createdAt'; - const sortOrder = req.query.sortOrder === "asc" ? 1 : -1; // default desc + const sortOrder = req.query.sortOrder === 'asc' ? 1 : -1; // default desc const sorting: Sorting = { - sortBy, - sortOrder + sortBy, + sortOrder, }; req.pagination = pagination; diff --git a/src/middleware/security/requireCsrf.ts b/src/middleware/security/requireCsrf.ts index ab03939..a1dc2f7 100644 --- a/src/middleware/security/requireCsrf.ts +++ b/src/middleware/security/requireCsrf.ts @@ -1,28 +1,21 @@ -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"; +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"]; +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 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"]; + const csrfToken = req.headers['x-csrf-token']; if (!csrfToken) { throw new UnauthorizedError(); } @@ -32,7 +25,7 @@ export const csrfMiddleware = async ( sessionId: req.sessionId, valid: true, revokedAt: null, - }).select("+csrfTokenHash"); + }).select('+csrfTokenHash'); if (!session) { throw new UnauthorizedError(); diff --git a/src/models/ContextProfile.ts b/src/models/ContextProfile.ts index ef0d36b..7584cce 100644 --- a/src/models/ContextProfile.ts +++ b/src/models/ContextProfile.ts @@ -138,7 +138,7 @@ export interface ContextProfile extends Document { projectId?: Types.ObjectId; scope: ContextScope; isDefaultForProject: boolean; - parentContextId: Types.ObjectId; + parentContextId?: Types.ObjectId; name: string; description?: string; @@ -198,7 +198,6 @@ const contextProfileSchema = new Schema( parentContextId: { type: Schema.Types.ObjectId, ref: 'ContextProfile', - required: true, }, name: { type: String, @@ -267,7 +266,7 @@ const contextProfileSchema = new Schema( { name: { type: String, required: true }, imageUrl: { type: String }, - description: { type: String, maxlength: 500, required: true }, + description: { type: String, maxlength: 500 }, features: { type: Schema.Types.Mixed }, behaviors: { type: Schema.Types.Mixed }, }, diff --git a/src/models/FinalVideo.ts b/src/models/FinalVideo.ts index 1e90f44..cb94bcb 100644 --- a/src/models/FinalVideo.ts +++ b/src/models/FinalVideo.ts @@ -1,77 +1,37 @@ -import { Schema, model, Document, Types } from "mongoose"; - -interface RenderConfig { - fps?: number; - resolution?: "480p" | "720p" | "1080p" | "1440p"; - bitrate?: number; - codec?: string; // h264, h265 ; -} +import { Schema, model, Document, Types } from 'mongoose'; export interface FinalVideo extends Document { userId: Types.ObjectId; projectId: Types.ObjectId; storyId: Types.ObjectId; - videoUrl?: string; // final rendered file + videoUrl?: string; lastError?: { message: string; code?: number; count?: number }; backgroundAudioAssetId?: Types.ObjectId; narrationAudioAssetId?: Types.ObjectId; - sceneAssetIds: Types.ObjectId[]; // resolved visuals in order + sceneAssetIds: Types.ObjectId[]; duration?: number; - renderConfig?: RenderConfig; - status: "rendering" | "completed" | "failed"; + videoConfigId: Types.ObjectId; + status: 'rendering' | 'completed' | 'failed'; createdAt: Date; updatedAt: Date; } -/** - * Represents a FinalVideo document in the Cinetegrate system. - * - * A FinalVideo is the rendered output of the AI video generation process. It contains - * the final video file, associated audio assets, scene compositions, and rendering configuration. - * - * @property {ObjectId} userId - Reference to the User who owns this video. Required and indexed for efficient queries. - * @property {ObjectId} projectId - Reference to the parent Project. Required and indexed for efficient queries. - * @property {ObjectId} storyId - Reference to the source Story. Required and indexed for efficient queries. - * @property {string} videoUrl - URL to the final rendered video file. - * @property {Object} lastError - Error information from failed rendering attempts. Contains message, code, and count of consecutive failures. - * @property {string} lastError.message - Error message describing the failure. - * @property {number} lastError.code - Error code for programmatic handling. - * @property {number} lastError.count - Count of consecutive failures. - * @property {ObjectId} backgroundAudioAssetId - Reference to the background music AudioAsset. - * @property {ObjectId} narrationAudioAssetId - Reference to the narration/voiceover AudioAsset. - * @property {ObjectId[]} sceneAssetIds - Ordered array of SceneAsset references representing visual compositions. Required. - * @property {number} duration - Total duration of the final video in seconds. - * @property {Object} renderConfig - Configuration parameters for video rendering. - * @property {number} renderConfig.fps - Frames per second for output video. - * @property {string} renderConfig.resolution - Output resolution. Values: "480p" | "720p" | "1080p" | "1440p". - * @property {number} renderConfig.bitrate - Bitrate in kbps for encoding. - * @property {string} renderConfig.codec - Video codec used. Values: "h264" | "h265". - * @property {string} status - Rendering lifecycle state. Values: "rendering" | "completed" | "failed". Default: "rendering". Indexed for efficient status queries. - * @property {Date} createdAt - Timestamp of document creation. Automatically managed. - * @property {Date} updatedAt - Timestamp of last document update. Automatically managed. - * - * @remarks - * - The sceneAssetIds array maintains scene order critical to final video composition. - * - lastError tracking enables robust retry logic and failure diagnostics. - * - renderConfig provides comprehensive control over output quality and format. - */ - const finalVideoSchema = new Schema( { userId: { type: Schema.Types.ObjectId, - ref: "User", + ref: 'User', required: true, }, projectId: { type: Schema.Types.ObjectId, - ref: "Project", + ref: 'Project', required: true, index: true, }, storyId: { type: Schema.Types.ObjectId, - ref: "Story", + ref: 'Story', required: true, index: true, }, @@ -87,30 +47,25 @@ const finalVideoSchema = new Schema( }, backgroundAudioAssetId: { type: Schema.Types.ObjectId, - ref: "AudioAsset", + ref: 'AudioAsset', }, narrationAudioAssetId: { type: Schema.Types.ObjectId, - ref: "AudioAsset", + ref: 'AudioAsset', }, sceneAssetIds: { - type: [{ type: Schema.Types.ObjectId, ref: "SceneAsset" }], + type: [{ type: Schema.Types.ObjectId, ref: 'SceneAsset' }], required: true, }, - duration: Number, - renderConfig: { - fps: Number, - resolution: { - type: String, - enum: ["480p", "720p", "1080p", "1440p"], - }, - bitrate: Number, - codec: String, + videoConfigId: { + type: Schema.Types.ObjectId, + ref: 'VideoConfig', // Reference to VideoConfig model + required: true, }, status: { type: String, - enum: ["rendering", "completed", "failed"], - default: "rendering", + enum: ['rendering', 'completed', 'failed'], + default: 'rendering', index: true, }, }, @@ -119,7 +74,4 @@ const finalVideoSchema = new Schema( finalVideoSchema.index({ userId: 1, status: 1 }); -export const FinalVideoModel = model( - "FinalVideo", - finalVideoSchema -); +export const FinalVideoModel = model('FinalVideo', finalVideoSchema); diff --git a/src/models/Project.ts b/src/models/Project.ts index acc9583..a8ed179 100644 --- a/src/models/Project.ts +++ b/src/models/Project.ts @@ -1,11 +1,12 @@ -import { Schema, model, Document, Types, HydratedDocument } from "mongoose"; +import { Schema, model, Document, Types, HydratedDocument } from 'mongoose'; export interface ProjectType extends Document { userId: Types.ObjectId; title: string; description: string; - status: "active" | "draft" | "archive" | "delete"; - visibility: "public" | "private"; - defaultContextProfileId: Types.ObjectId; + thumbnail?: string; + status: 'active' | 'draft' | 'archive' | 'delete'; + visibility: 'public' | 'private'; + defaultContextProfileId?: Types.ObjectId; generationCounts: { storiesGenerated: number; scenesGenerated: number; @@ -33,20 +34,20 @@ const projectSchema = new Schema( }, userId: { type: Schema.Types.ObjectId, - ref: "User", + ref: 'User', required: true, }, status: { type: String, - enum: ["active", "draft", "archive", "delete"], - default: "active", + enum: ['active', 'draft', 'archive', 'delete'], + default: 'active', }, visibility: { type: String, - enum: ["public", "private"], - default: "private", - }, - defaultContextProfileId: { type: Schema.Types.ObjectId, ref: "ContextProfile", required: true }, + enum: ['public', 'private'], + default: 'private', + }, + defaultContextProfileId: { type: Schema.Types.ObjectId, ref: 'ContextProfile' }, generationCounts: { storiesGenerated: { type: Number, default: 0 }, scenesGenerated: { type: Number, default: 0 }, @@ -62,4 +63,4 @@ projectSchema.index({ userId: 1, status: 1, createdAt: -1 }); export type Project = HydratedDocument; -export const ProjectModel = model("Project", projectSchema); +export const ProjectModel = model('Project', projectSchema); 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 d37a399..41434f1 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -1,5 +1,6 @@ -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, sendEmailVerification, @@ -10,19 +11,19 @@ import { resetPassword, verifyEmail, verifyUpdateEmail, -} from "./auth.service.js"; +} from './auth.service.js'; import type { RegisterInput, LoginInput, ForgetPasswordInput, VerifyEmailInput, VerifyUpdateEmailInput, -} from "@validation/auth.schema.js"; +} 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, }; @@ -33,12 +34,8 @@ const ACCESS_AGE = 30 * 60 * 1000; export const registerController = async (req: Request, res: Response) => { 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 }; @@ -49,15 +46,15 @@ export const registerController = async (req: Request, res: Response) => { return res .status(200) - .cookie("access-token", accessToken, { + .cookie('access-token', accessToken, { ...CookieOptions, maxAge: ACCESS_AGE, }) - .cookie("refresh-token", refreshToken, { + .cookie('refresh-token', refreshToken, { ...CookieOptions, maxAge: REFRESH_AGE, }) - .cookie("csrf-token", csrfToken, { + .cookie('csrf-token', csrfToken, { ...CookieOptions, httpOnly: false, maxAge: CSRF_AGE, @@ -75,12 +72,8 @@ export const registerController = async (req: Request, res: Response) => { export const loginController = async (req: Request, res: Response) => { const body = req.validatedBody as LoginInput; - 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.socket.remoteAddress || req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip; const payload = { ...body, userAgent, ip }; @@ -90,27 +83,30 @@ export const loginController = async (req: Request, res: Response) => { return res .status(200) - .cookie("access-token", accessToken, { + .cookie('access-token', accessToken, { ...CookieOptions, maxAge: ACCESS_AGE, }) - .cookie("refresh-token", refreshToken, { + .cookie('refresh-token', refreshToken, { ...CookieOptions, maxAge: REFRESH_AGE, }) - .cookie("csrf-token", csrfToken, { + .cookie('csrf-token', csrfToken, { ...CookieOptions, httpOnly: false, maxAge: CSRF_AGE, }) .json({ - user: { - id: user._id, - email: user.email, - username: user.username, - displayName: user.displayName, - avatar: user.avatarUrl, - accountStatus: user.accountStatus, + status: 'success', + data: { + user: { + id: user._id, + email: user.email, + username: user.username, + displayName: user.displayName, + avatar: user.avatarUrl, + accountStatus: user.accountStatus, + }, }, }); }; @@ -119,9 +115,8 @@ export const forgotPasswordController = async (req: Request, res: Response) => { 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.', }); }; @@ -132,52 +127,45 @@ export const resetPasswordController = async (req: Request, res: Response) => { }; 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 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 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, userAgent, ip); const { accessToken, refreshToken, csrfToken } = result; return res .status(200) - .cookie("access-token", accessToken, { + .cookie('access-token', accessToken, { ...CookieOptions, maxAge: ACCESS_AGE, }) - .cookie("refresh-token", refreshToken, { + .cookie('refresh-token', refreshToken, { ...CookieOptions, maxAge: REFRESH_AGE, }) - .cookie("csrf-token", csrfToken, { + .cookie('csrf-token', csrfToken, { ...CookieOptions, httpOnly: false, maxAge: CSRF_AGE, }) - .json({ message: "Tokens refreshed" }); + .json({ message: 'Tokens refreshed' }); }; -export const emailVerificationController = async ( - req: Request, - res: Response -) => { +export const emailVerificationController = async (req: Request, res: Response) => { const userId = req?.user!.id; await sendEmailVerification(userId); return res.status(200).json({ - message: "Verification email sent successfully", + message: 'Verification email sent successfully', }); }; @@ -186,32 +174,28 @@ export const verifyEmailController = async (req: Request, res: Response) => { 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, code } = - req.validatedBody as VerifyUpdateEmailInput; +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 a2ea854..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,7 +9,7 @@ import { emailVerificationController, verifyEmailController, verifyEmailChangeController, -} from "./auth.controller.js"; +} from './auth.controller.js'; import { forgotPasswordSchema, loginSchema, @@ -17,63 +17,38 @@ import { resetPasswordSchema, verifyEmailSchema, 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"; +} 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(); -router.post( - "/register", - validateBody(registerSchema), - asyncHandler(registerController) -); -router.post("/login", validateBody(loginSchema), asyncHandler(loginController)); -router.post( - "/forgot-password", - validateBody(forgotPasswordSchema), - asyncHandler(forgotPasswordController) -); +router.post('/register', validateBody(registerSchema), asyncHandler(registerController)); +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-session", - asyncHandler(refreshTokenController) -); +router.post('/email/verification', authMiddleware, asyncHandler(emailVerificationController)); router.post( - "/email/verification", - authMiddleware, - asyncHandler(emailVerificationController) -); - -router.post( - "/email/verify", - authMiddleware, + '/email/verify', + authMiddleware, validateBody(verifyEmailSchema), asyncHandler(verifyEmailController) ); router.post( - "/email/verify-change", - authMiddleware, + '/email/verify-change', + authMiddleware, validateBody(verifyUpdateEmailSchema), asyncHandler(verifyEmailChangeController) ); -router.post( - "/logout", - authMiddleware, - csrfMiddleware, - asyncHandler(logoutController) -); +router.post('/logout', authMiddleware, csrfMiddleware, asyncHandler(logoutController)); -export default router; \ No newline at end of file +export default router; diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 8993271..d5261c7 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -53,7 +53,7 @@ interface RefreshTokenOutput { } export async function registerUser(input: RegisterInputWithMeta): Promise { - const { email, password, displayName, username, userAgent, ip } = input; + const { email, password, name, username, userAgent, ip } = input; const existing = await UserModel.findOne({ $or: [{ email }, { username }] }); if (existing) { if (existing.username === username) { @@ -74,7 +74,7 @@ export async function registerUser(input: RegisterInputWithMeta): Promise = { 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[0], - lat: ipData.latitude, - lng: ipData.longitude, - isp: ipData.asnOrganization, refreshTokenHash: hashToken(refreshToken), csrfTokenHash: hashToken(csrfToken), expiresIn: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), @@ -48,6 +39,19 @@ export async function createSessionPayload({ 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/contextProfile/contextProfile.controller.ts b/src/modules/contextProfile/contextProfile.controller.ts index 792e0b6..d7a030d 100644 --- a/src/modules/contextProfile/contextProfile.controller.ts +++ b/src/modules/contextProfile/contextProfile.controller.ts @@ -1,8 +1,17 @@ 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( diff --git a/src/modules/contextProfile/contextProfile.routes.ts b/src/modules/contextProfile/contextProfile.routes.ts index 0037281..0471ee5 100644 --- a/src/modules/contextProfile/contextProfile.routes.ts +++ b/src/modules/contextProfile/contextProfile.routes.ts @@ -1,17 +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(); -// Future question: Do we want users to create context profiles directly? -// router.post("/", createContextProfileController); +router.post("/", validateBody(createContextProfileSchema), asyncHandler(createContextProfileController)); // router.post("/:contextId/clone", cloneContextProfileController); -router.get("/:contextId", getContextProfileController); +router.get("/:contextId", asyncHandler(getContextProfileController)); -router.get("/", listContextProfilesController); +router.get("/", asyncHandler(listContextProfilesController)); -export default router; \ No newline at end of file +export default router; diff --git a/src/modules/contextProfile/contextProfile.service.ts b/src/modules/contextProfile/contextProfile.service.ts index c74b64a..82bac98 100644 --- a/src/modules/contextProfile/contextProfile.service.ts +++ b/src/modules/contextProfile/contextProfile.service.ts @@ -1,5 +1,9 @@ -import { NotFoundError } from '@middleware/error/index.js'; -import { ContextProfileModel } from '@models/ContextProfile.js'; +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({ @@ -19,3 +23,80 @@ export async function listContextProfilesService(userId: string, query: any) { 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 index 2510842..9cd4f4a 100644 --- a/src/modules/credit/credit.service.ts +++ b/src/modules/credit/credit.service.ts @@ -17,7 +17,7 @@ export async function getAvailableCredits(userId: Types.ObjectId): Promise { diff --git a/src/modules/project/project.controller.ts b/src/modules/project/project.controller.ts index 19da635..eb4a006 100644 --- a/src/modules/project/project.controller.ts +++ b/src/modules/project/project.controller.ts @@ -1,12 +1,20 @@ import { Request, Response } from 'express'; import { + archiveAllProjects, + archiveManyProjectsByIds, createProject, createProjectContextProfile, + deleteAllProjects, + deleteManyProjectsByIds, deleteProjectById, getArchivedProjects, getDeletedProjects, getProjectById, getProjects, + permanentDeleteAllProjects, + permanentDeleteManyProjects, + permanentDeleteProjectById, + restoreAllProjects, restoreManyProjectsByIds, restoreProjectById, unarchiveManyProjectsByIds, @@ -14,6 +22,8 @@ import { updateProjectById, updateProjectStatus, updateProjectVisibility, + unarchiveAllProjects, + getDraftProjects, } from './project.service.js'; import { Types } from 'mongoose'; import { @@ -38,6 +48,23 @@ export const getProjectsController = async (req: Request, res: Response) => { }); }; +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!; @@ -65,6 +92,90 @@ export const getArchivedProjectsController = async (req: Request, res: Response) }); }; +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; @@ -102,6 +213,15 @@ export const deleteProjectByIdController = async (req: Request, res: Response) = 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; @@ -131,19 +251,3 @@ export const unarchiveProjectByIdController = async (req: Request, res: Response const unarchivedProject = await unarchiveProjectById(projectId, userId); return res.status(200).json(unarchivedProject); }; - -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 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); -}; diff --git a/src/modules/project/project.routes.ts b/src/modules/project/project.routes.ts index 5c13633..5ea1f98 100644 --- a/src/modules/project/project.routes.ts +++ b/src/modules/project/project.routes.ts @@ -1,22 +1,32 @@ - import { Router } from "express"; +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"; +} from './project.controller.js'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { validateBody } from '@validation/validateBody.js'; import { createProjectContextProfileSchema, createProjectSchema, @@ -25,74 +35,85 @@ import { updateProjectSchema, updateProjectStatusSchema, updateProjectVisibilitySchema, -} from "@validation/project.schema.js"; -import { validateParams } from "@validation/validateParams.js"; -import { paginationAndSortingMiddleware } from "@middleware/paginationAndSorting.js"; +} 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("/deleted", paginationAndSortingMiddleware, asyncHandler(getDeletedProjectsController)); -router.get("/archived", paginationAndSortingMiddleware, asyncHandler(getArchivedProjectsController)); -router.patch( - "/restore", - validateBody(updateManyIdsSchema), - asyncHandler(restoreManyProjectsController) +router.get('/', paginationAndSortingMiddleware, asyncHandler(getProjectsController)); +router.post('/', validateBody(createProjectSchema), asyncHandler(postProjectController)); +router.get( + '/draft', + paginationAndSortingMiddleware, + asyncHandler(getDraftProjectsController) ); -router.patch( - "/unarchive", +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(unarchiveManyProjectsController) + asyncHandler(permanentDeleteManyProjectsController) ); - + // Project ID specific routes -router.get( - "/:projectId", - validateParams(projectIdParamSchema), - asyncHandler(getProjectByIdController) -); +router.get('/:projectId', validateParams(projectIdParamSchema), asyncHandler(getProjectByIdController)); router.post( - "/:projectId/context-profile", + '/:projectId/context-profile', validateParams(projectIdParamSchema), validateBody(createProjectContextProfileSchema), - asyncHandler(createProjectContextProfileController)); + asyncHandler(createProjectContextProfileController) +); router.patch( - "/:projectId", + '/:projectId', validateParams(projectIdParamSchema), validateBody(updateProjectSchema), asyncHandler(updateProjectByIdController) ); +router.delete('/:projectId', validateParams(projectIdParamSchema), asyncHandler(deleteProjectByIdController)); router.delete( - "/:projectId", + '/:projectId/permanent', validateParams(projectIdParamSchema), - asyncHandler(deleteProjectByIdController) + asyncHandler(permanentDeleteProjectByIdController) ); router.patch( - "/:projectId/status", + '/:projectId/status', validateParams(projectIdParamSchema), validateBody(updateProjectStatusSchema), asyncHandler(updateProjectStatusController) ); router.patch( - "/:projectId/visibility", + '/:projectId/visibility', validateParams(projectIdParamSchema), validateBody(updateProjectVisibilitySchema), asyncHandler(updateProjectVisibilityController) ); router.patch( - "/:projectId/restore", + '/:projectId/restore', validateParams(projectIdParamSchema), asyncHandler(restoreProjectByIdController) ); router.patch( - "/:projectId/unarchive", + '/:projectId/unarchive', validateParams(projectIdParamSchema), asyncHandler(unarchiveProjectByIdController) ); -export default router; \ No newline at end of file +export default router; diff --git a/src/modules/project/project.service.ts b/src/modules/project/project.service.ts index 126f613..4516d08 100644 --- a/src/modules/project/project.service.ts +++ b/src/modules/project/project.service.ts @@ -4,7 +4,11 @@ import { InternalServerError, NotFoundError, } from '@middleware/error/index.js'; -import type { CreateProjectInput, UpdateProjectInput } from '@validation/project.schema.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'; @@ -16,7 +20,7 @@ import { ContextProfileModel, ContextScope, GenreType } from '@models/ContextPro import { NARRATION_PROFILES } from 'constants/narrationProfiles.js'; export async function getProjects(userId: Types.ObjectId | string, pagination: Pagination, sorting: Sorting) { - const filter = { userId, status: { $in: ACTIVE_STATUSES } }; + const filter = { userId, status: { $eq: 'active' } }; const [projects, total] = await Promise.all([ ProjectModel.find(filter) .skip(pagination.skip) @@ -31,6 +35,32 @@ export async function getProjects(userId: Types.ObjectId | string, pagination: P 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, @@ -71,13 +101,152 @@ export async function getArchivedProjects( 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', - status: projectInput.status, + // A project stays draft until a default context profile is attached. + status: 'draft', }); if (!newProject) { throw new InternalServerError('Failed to create project'); @@ -102,7 +271,11 @@ export async function getProjectById(projectId: Types.ObjectId | string, userId: }); } -export async function createProjectContextProfile(userId: string, projectId: string, payload: any) { +export async function createProjectContextProfile( + userId: string, + projectId: string, + payload: CreateProjectContextInput +) { const session = await mongoose.startSession(); session.startTransaction(); @@ -112,7 +285,7 @@ export async function createProjectContextProfile(userId: string, projectId: str userId, }).session(session); - if (!project) throw new Error('Project not found'); + if (!project) throw new NotFoundError('Project not found'); const existingContext = await ContextProfileModel.findOne({ projectId: project._id, @@ -127,7 +300,7 @@ export async function createProjectContextProfile(userId: string, projectId: str if (project.defaultContextProfileId) { throw new ForbiddenError('Project already has a default context'); } - let contextProfileId; + let contextProfileId: Types.ObjectId | undefined; if (payload.mode === 'new') { const narrationProfile = NARRATION_PROFILES[payload.data.genre as GenreType]; @@ -177,10 +350,20 @@ export async function createProjectContextProfile(userId: string, projectId: str 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 project; + return sanitizeProjectResponse({ + project, + type: 'getProjectById', + }); } catch (err) { await session.abortTransaction(); throw err; @@ -244,6 +427,34 @@ export async function deleteProjectById(projectId: Types.ObjectId | string, user }; } +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, @@ -292,21 +503,5 @@ export async function unarchiveProjectById( return result; } -export const restoreManyProjectsByIds = async ( - projectIds: (Types.ObjectId | string)[], - userId: Types.ObjectId | string -) => { - const result = await transitionManyProjectsByIds(projectIds, userId, 'delete', 'active'); - return result; -}; - -export const unarchiveManyProjectsByIds = async ( - projectIds: (Types.ObjectId | string)[], - userId: Types.ObjectId | string -) => { - const result = await transitionManyProjectsByIds(projectIds, 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 index 891c566..5c6c4aa 100644 --- a/src/modules/project/rules/projectStatus.ts +++ b/src/modules/project/rules/projectStatus.ts @@ -1,30 +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 = Exclude< - ProjectStatus, - "draft" ->; +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" + from: 'draft' | 'active' | 'archive' | 'delete', + to: 'draft' | 'active' | 'archive' | 'delete' ) { const allowed = { - draft: ["active", "delete"], - active: ["archive", "delete"], - archive: ["active", "delete"], - delete: ["active"], + 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 index 3b649c2..93e6530 100644 --- a/src/modules/project/utils/transitionManyProjectsByIds.ts +++ b/src/modules/project/utils/transitionManyProjectsByIds.ts @@ -1,32 +1,27 @@ -import { ProjectModel } from "@models/Project.js"; -import { Types } from "mongoose"; -import { TransitionableManyProjectStatus } from "../rules/projectStatus.js"; - +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, - fromStatus: TransitionableManyProjectStatus, - toStatus: TransitionableManyProjectStatus + fromStatuses: TransitionableManyProjectStatus, + toStatus: ProjectStatus ) => { - const normalizedIds = projectIds.map(id => ({ + 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 validObjectIds = normalizedIds.filter((i) => i.isValid).map((i) => i.objectId!); const projects = await ProjectModel.find({ _id: { $in: validObjectIds }, userId, - }).select("_id status"); + }).select('_id status'); - const projectMap = new Map( - projects.map(p => [p._id.toString(), p.status]) - ); + const projectMap = new Map(projects.map((p) => [p._id.toString(), p.status])); const results: { id: string; message: string }[] = []; const idsToUpdate: Types.ObjectId[] = []; @@ -35,34 +30,31 @@ export const transitionManyProjectsByIds = async ( const idStr = String(item.raw); if (!item.isValid) { - results.push({ id: idStr, message: "Invalid project ID" }); + 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" }); + results.push({ id: idStr, message: 'Project not found or not accessible' }); continue; } - if (status !== fromStatus) { + if (!fromStatuses.includes(status)) { results.push({ id: idStr, - message: `Project not in ${fromStatus} state`, + message: `Project not in allowed state (${fromStatuses.join(', ')})`, }); continue; } idsToUpdate.push(item.objectId!); - results.push({ id: idStr, message: "Updated successfully" }); + results.push({ id: idStr, message: 'Updated successfully' }); } if (idsToUpdate.length > 0) { - await ProjectModel.updateMany( - { _id: { $in: idsToUpdate } }, - { $set: { status: toStatus } } - ); + 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 index 2a59a2d..c59cdb8 100644 --- a/src/modules/project/utils/transitionProjectById.ts +++ b/src/modules/project/utils/transitionProjectById.ts @@ -1,4 +1,4 @@ -import { ConflictError, NotFoundError } from "@middleware/error/index.js"; +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"; @@ -32,6 +32,10 @@ export async function transitionProjectById( ); } + 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") { diff --git a/src/modules/sceneAssets/sceneAssets.private.routes.ts b/src/modules/sceneAssets/sceneAssets.private.routes.ts index 60ef0df..28d0857 100644 --- a/src/modules/sceneAssets/sceneAssets.private.routes.ts +++ b/src/modules/sceneAssets/sceneAssets.private.routes.ts @@ -38,7 +38,7 @@ import { import multer from 'multer'; import { videoAssetUpload } from '@middleware/multer/videoAssetUpload.js'; import { imageAssetUpload } from '@middleware/multer/imageAssetUpload.js'; -import { paginationAndSortingMiddleware } from '@middleware/paginationAndSorting.js'; +import { paginationAndSortingMiddleware } from '@middleware/request/paginationAndSorting.js'; const router = Router(); diff --git a/src/modules/story/story.private.routes.ts b/src/modules/story/story.private.routes.ts index b56d784..e1c429b 100644 --- a/src/modules/story/story.private.routes.ts +++ b/src/modules/story/story.private.routes.ts @@ -20,7 +20,7 @@ import { setStoryContextController, addStoryContextController, } from './story.controller.js'; -import { paginationAndSortingMiddleware } from '@middleware/paginationAndSorting.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'; diff --git a/src/modules/story/story.service.ts b/src/modules/story/story.service.ts index e3a40b2..fd72b0d 100644 --- a/src/modules/story/story.service.ts +++ b/src/modules/story/story.service.ts @@ -22,6 +22,7 @@ import { 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([ @@ -112,9 +113,18 @@ export async function getProjectArchivedStories( //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, @@ -297,7 +307,8 @@ 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, @@ -307,11 +318,11 @@ export async function generateStory(userId: string, storyId: string) { contextProfile: contextProfile, }); - // put this AI generation service in a different location which also have quality level understanding and control + await consumeCredits(userId, 10, session); let response; try { response = await openRouterAI(prompt); - } catch (err) { + } catch (err) { throw new ConflictError('AI generation failed, please try again.'); } const rawcontent = response.choices[0].message?.content || ''; @@ -319,10 +330,10 @@ export async function generateStory(userId: string, storyId: string) { throw new ConflictError('AI generation returned empty content, please try again.'); } const content = safeParseJSON(rawcontent); - // Consume credits to be implemented here + if (!content.story || !content.summary) { + throw new ConflictError('Error parsing AI generated content, please try again.'); + } - // TODO: Consume credits to be implemented here - // await consumeCredits(userId, 'story_generation', session); const updatedStory = await StoryModel.findOneAndUpdate( { _id: storyId, userId }, { @@ -362,6 +373,7 @@ export async function regenerateStory(userId: string, storyId: string, extraProm extraPrompt: extraPrompt.prompt, contextProfile: contextProfile, }); + await consumeCredits(userId, 5, session); let response; try { response = await openRouterAI(prompt); @@ -373,7 +385,9 @@ export async function regenerateStory(userId: string, storyId: string, extraProm 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 }, { diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index 33e8b8e..23fd8d7 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -38,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, diff --git a/src/modules/videoConfig/index.ts b/src/modules/videoConfig/index.ts new file mode 100644 index 0000000..99ea9cf --- /dev/null +++ b/src/modules/videoConfig/index.ts @@ -0,0 +1,3 @@ +export { default as videoConfigRoutes } from './videoConfig.routes'; +export { default as videoConfigController } from './videoConfig.controller'; +export { default as videoConfigService } from './videoConfig.service'; 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/security/guards/getAccountBlockResponse.ts b/src/security/guards/getAccountBlockResponse.ts index 01fd448..e630312 100644 --- a/src/security/guards/getAccountBlockResponse.ts +++ b/src/security/guards/getAccountBlockResponse.ts @@ -1,5 +1,5 @@ import { AccountStatus } from '@constants/userConsts.js'; -import { accountStatusResponses } from '../../policies/accountStatusResponses.js'; +import { accountStatusResponses } from '@domain/policies/accountStatusResponses.js'; export function getAccountBlockResponse(status: AccountStatus | null | undefined) { return accountStatusResponses(status); diff --git a/src/types/express.d.ts b/src/types/express.d.ts index dc1dbb5..d2b67e1 100644 --- a/src/types/express.d.ts +++ b/src/types/express.d.ts @@ -1,10 +1,10 @@ -import { type User } from "@models/User.ts"; // whatever your user type is -import type { Pagination, Sorting } from "@middleware/paginationAndSorting.js"; -import { type AccountStatus, Role } from "@constants/userConsts.ts"; +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; + role: Role; accountStatus?: AccountStatus; }; @@ -12,12 +12,12 @@ declare global { namespace Express { interface Request { user?: AuthenticatedUser; - sessionId?: string; + sessionId?: string; pagination?: Pagination; sorting?: Sorting; validatedBody?: unknown; validatedParams?: unknown; - accountStatus?: string; + accountStatus?: string; } } } diff --git a/src/utils/getIpInfo.ts b/src/utils/getIpInfo.ts index ca40b68..3003f3c 100644 --- a/src/utils/getIpInfo.ts +++ b/src/utils/getIpInfo.ts @@ -1,4 +1,4 @@ -import { fetch } from "undici"; +import { fetch } from 'undici'; interface IpInfo { ipVersion: number; @@ -26,11 +26,9 @@ export async function getIpInfo(ip: string) { try { const res = await fetch(`https://free.freeipapi.com/api/json/${ip}`); const data = (await res.json()) as IpInfo; - if (!data || !data.cityName || !data.countryName) { - return { city: "Unknown", country: "Unknown" }; - } - return data; + 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/paginationResponse.ts b/src/utils/paginationResponse.ts index 88518d9..73aa1a8 100644 --- a/src/utils/paginationResponse.ts +++ b/src/utils/paginationResponse.ts @@ -1,11 +1,10 @@ - -import { Pagination } from "types/Pagination.js"; +import { Pagination } from 'types/Pagination.js'; export function paginationResponse(pagination: Pagination, totalItems: number) { return { page: pagination.page, limit: pagination.limit, - totalItems: totalItems, + total: totalItems || 0, totalPages: Math.ceil(totalItems / pagination.limit), hasNext: pagination.page * pagination.limit < totalItems, hasPrev: pagination.page > 1, diff --git a/src/utils/sanitizeProjectResponse.ts b/src/utils/sanitizeProjectResponse.ts index 623c05a..a4870f6 100644 --- a/src/utils/sanitizeProjectResponse.ts +++ b/src/utils/sanitizeProjectResponse.ts @@ -24,6 +24,7 @@ const sanitizeProjectResponse = ({ project, type = 'getProjectById' }: ProjectRe description: project.description, visibility: project.visibility, status: project.status, + defaultContextProfileId: project.defaultContextProfileId, contextProfileId: project.defaultContextProfileId, generationCounts: project.generationCounts, createdAt: project.createdAt, 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 1cb2960..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,22 +27,17 @@ 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, "Display name is required") - .max(80, "Display name is too long"), + 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', }); } }) @@ -54,7 +46,7 @@ const registerSchema = z const loginSchema = z .object({ email: z.email(), - password: z.string().min(1, "Password is required"), + password: z.string().min(1, 'Password is required'), }) .strict(); @@ -67,20 +59,17 @@ const forgotPasswordSchema = z 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', }); } }) @@ -95,7 +84,7 @@ const verifyEmailSchema = z const verifyUpdateEmailSchema = z .object({ verificationToken: z.string().min(10), - code: z.string().length(6, { message: "Code must be 6 characters long" }), + code: z.string().length(6, { message: 'Code must be 6 characters long' }), }) .strict(); diff --git a/src/validation/user.schema.ts b/src/validation/user.schema.ts index 7089c04..671dee8 100644 --- a/src/validation/user.schema.ts +++ b/src/validation/user.schema.ts @@ -90,11 +90,7 @@ export const deleteSessionParamsSchema = z sessionId: z.string().min(1), }) .strict(); - -/* ------------------------- - Types - -------------------------*/ - + export type UpdateAvatarType = z.infer; export type UpdateProfileType = z.infer; export type UpdateNotificationsType = z.infer; @@ -105,7 +101,4 @@ export type UpdatePasswordType = z.infer; export type UpdateEmailType = z.infer; export type DeleteAllSessionsType = z.infer; export type DeleteSessionParamsType = z.infer; - -/* ------------------------- - Middleware helpers - -------------------------*/ + \ No newline at end of file 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/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/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 c47e4f2..b4cbacc 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,8 +22,11 @@ "@models/*": ["models/*"], "@routes/*":["routes/*"], "@validation/*":["validation/*"], + "@validators/*": ["validators/*"], "@libs/*": ["libs/*"], - "@constants/*": ["constants/*"] + "@constants/*": ["constants/*"], + "@security/*": ["security/*"], + "@domain/*": ["domain/*"], } }, "include": ["src", "dist"] From f52d45d10615c87406931fddd5bdea9a2dcbaf9d Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Fri, 6 Mar 2026 07:45:47 +0530 Subject: [PATCH 13/14] Fast Removed Errors for trying EC2 --- .../featurePermission/featurePermission.service.ts | 4 ++-- src/modules/sceneAssets/sceneAssets.controller.ts | 2 +- src/modules/sceneAssets/sceneAssets.service.ts | 8 ++++---- src/modules/videoConfig/index.ts | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/modules/featurePermission/featurePermission.service.ts b/src/modules/featurePermission/featurePermission.service.ts index b3ec371..e55349c 100644 --- a/src/modules/featurePermission/featurePermission.service.ts +++ b/src/modules/featurePermission/featurePermission.service.ts @@ -33,7 +33,7 @@ export async function assertFeaturePermission({ userId, action, grade }: Permiss const caps = resolveEffectiveCapabilities(plan.capabilities, overrides); switch (action) { - case 'IMAGE_GEN': + case 'TXT_TO_IMAGE_GEN': if (!caps.image || grade > caps.image.maxTier) { throw new ForbiddenError('Image generation grade not allowed'); } @@ -51,7 +51,7 @@ export async function assertFeaturePermission({ userId, action, grade }: Permiss } return; - case 'VIDEO_GEN': + case 'TXT_TO_VIDEO_GEN': if (!caps.video || !caps.video.enabled) { throw new ForbiddenError('Video generation not allowed'); } diff --git a/src/modules/sceneAssets/sceneAssets.controller.ts b/src/modules/sceneAssets/sceneAssets.controller.ts index b2341a5..0f395d8 100644 --- a/src/modules/sceneAssets/sceneAssets.controller.ts +++ b/src/modules/sceneAssets/sceneAssets.controller.ts @@ -188,7 +188,7 @@ export const generateVideoAssetController = async (req: Request, res: Response) message: 'Video asset generated successfully', data: { sceneId, - filename: response.videoUrl, + filename: response.url, }, }); }; diff --git a/src/modules/sceneAssets/sceneAssets.service.ts b/src/modules/sceneAssets/sceneAssets.service.ts index ed9d775..cb12143 100644 --- a/src/modules/sceneAssets/sceneAssets.service.ts +++ b/src/modules/sceneAssets/sceneAssets.service.ts @@ -338,14 +338,14 @@ export async function generateVideoAsset( // wait and check plan permissions await assertFeaturePermission({ userId: user._id, - action: 'VIDEO_GEN', + action: 'TXT_TO_VIDEO_GEN', grade: grade || 1, }); // Deduct credits if applicable if (grade && grade > 1) { - const creditsUsed = await getCreditCost('VIDEO_GEN', grade); - await consumeCredits(user._id, creditsUsed, session); + const creditsUsed = await getCreditCost('TXT_TO_VIDEO_GEN', grade); + await consumeCredits(userId, creditsUsed, session); } // Placeholder logic for video generation @@ -369,7 +369,7 @@ export async function generateVideoAsset( } } -export async function generateImageAsset(userId: string, sceneId: string): Promise { +export async function generateImageAsset(userId: string, sceneId: string) { const scene = await validateSceneOwnership(userId, sceneId); // Placeholder logic for image generation } diff --git a/src/modules/videoConfig/index.ts b/src/modules/videoConfig/index.ts index 99ea9cf..0cffd74 100644 --- a/src/modules/videoConfig/index.ts +++ b/src/modules/videoConfig/index.ts @@ -1,3 +1,3 @@ -export { default as videoConfigRoutes } from './videoConfig.routes'; -export { default as videoConfigController } from './videoConfig.controller'; -export { default as videoConfigService } from './videoConfig.service'; +// export { default as videoConfigRoutes } from './videoConfig.routes.js'; +// export { default as videoConfigController } from './videoConfig.controller.js'; +// export { default as videoConfigService } from './videoConfig.service.js'; From 481be9bf8ccc5602c9d8113207b574b1231ada93 Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Fri, 6 Mar 2026 08:43:37 +0530 Subject: [PATCH 14/14] setup deploy pipeline --- .github/workflows/deploy.yml | 49 ++++++++++++++++++++++++++++++++++++ Dockerfile | 15 +++++++++-- 2 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/deploy.yml 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/Dockerfile b/Dockerfile index 53f5b4b..9f17ba7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,26 @@ -FROM node:20-alpine +FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ -RUN npm ci --only=production +RUN npm install COPY . . RUN npm run build + +FROM node:20-alpine + +WORKDIR /app + +COPY package*.json ./ + +RUN npm install --omit=dev + +COPY --from=builder /app/dist ./dist + EXPOSE 4000 CMD ["node", "dist/server.js"] \ No newline at end of file