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/.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/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/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..a03d068 --- /dev/null +++ b/src/config/creditPricing.ts @@ -0,0 +1,73 @@ +export type ActionType = + | 'TXT_TO_IMAGE_GEN' + | 'IMG_TO_IMAGE_GEN' + | 'AUDIO_GEN' + | 'STORY_GEN' + | 'TXT_TO_VIDEO_GEN' + | 'IMG_TO_VIDEO_GEN' + | 'SCENE_GEN' + | 'NARRATION_GEN'; + +export const CREDIT_PRICING: Record> = { + TXT_TO_IMAGE_GEN: { + 1: 2, + 2: 6, + 3: 10, + 4: 15, + 5: 25, + }, + + IMG_TO_IMAGE_GEN: { + 1: 2, + 2: 6, + 3: 10, + 4: 15, + 5: 25, + }, + + AUDIO_GEN: { + 1: 2, + 2: 5, + 3: 8, + 4: 12, + 5: 20, + }, + + STORY_GEN: { + 1: 1, + 2: 3, + 3: 6, + 4: 10, + 5: 15, + }, + + SCENE_GEN: { + 1: 1, + 2: 2, + 3: 4, + 4: 6, + 5: 10, + 10: 60, + }, + NARRATION_GEN: { + 1: 1, + 2: 3, + 3: 5, + 4: 8, + 5: 12, + }, + + TXT_TO_VIDEO_GEN: { + 2: 20, + 3: 35, + 4: 50, + 5: 75, + }, + + IMG_TO_VIDEO_GEN: { + 2: 20, + 3: 35, + 4: 50, + 5: 75, + }, +}; diff --git a/src/constants/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/sceneAssetConsts.ts b/src/constants/sceneAssetConsts.ts new file mode 100644 index 0000000..cb953d2 --- /dev/null +++ b/src/constants/sceneAssetConsts.ts @@ -0,0 +1,33 @@ +// Scene Asset validation constants +export const MAX_ASSET_PROMPT_LENGTH = 2000; +export const MAX_ASSET_URL_LENGTH = 2048; +export const MAX_ASSETS_PER_SCENE = 50; + +// Asset types +export const assetTypes = ['image', 'video'] as const; +export type AssetType = (typeof assetTypes)[number]; + +// Visibility types +export const visibilityTypes = ['private', 'public'] as const; +export type VisibilityType = (typeof visibilityTypes)[number]; + +// Generation sources +export const generationSources = ['ai', 'user'] as const; +export type GenerationSource = (typeof generationSources)[number]; + +// Supported formats +export const videoFormats = ['mp4', 'mov', 'mkv', 'mpg', 'webm', 'avi', 'ogg', 'mpeg', 'm4v', 'flv', 'wmv', '3gp'] as const; +export const imageFormats = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp', 'svg', 'ico', 'heic', 'raw'] as const; +export const allFormats = [...videoFormats, ...imageFormats] as const; + +export type VideoFormat = (typeof videoFormats)[number]; +export type ImageFormat = (typeof imageFormats)[number]; +export type AssetFormat = (typeof allFormats)[number]; + +// Dimension constraints +export const MIN_DIMENSION = 1; +export const MAX_DIMENSION = 8192; + +// Duration constraints (for video assets) +export const MIN_ASSET_DURATION = 0.1; +export const MAX_ASSET_DURATION = 3600; // 1 hour max diff --git a/src/constants/videoConfigConsts.ts b/src/constants/videoConfigConsts.ts new file mode 100644 index 0000000..04a5445 --- /dev/null +++ b/src/constants/videoConfigConsts.ts @@ -0,0 +1,154 @@ +export const MIN_VIDEO_DURATION = 1; +export const MAX_VIDEO_DURATION = 60 * 60 * 1000; +export const DEFAULT_SCENE_DURATION = 5; + +export const MAX_NARRATION_START_OFFSET = 60; +export const MAX_NARRATION_END_OFFSET = 60; + +export const MIN_VOLUME = 0; +export const MAX_VOLUME = 100; +export const DEFAULT_NARRATION_VOLUME = 100; +export const DEFAULT_SOUND_EFFECT_VOLUME = 70; +export const DEFAULT_BACKGROUND_AUDIO_VOLUME = 30; + +export const MIN_SOUND_EFFECT_USE_PERCENTAGE = 1; +export const MAX_SOUND_EFFECT_USE_PERCENTAGE = 100; +export const DEFAULT_SOUND_EFFECT_USE_PERCENTAGE = 90; +export const MAX_SOUND_EFFECTS_PER_CONFIG = 50; + +export const MAX_VIDEO_EFFECTS_PER_CONFIG = 100; +export const MIN_EFFECT_INTENSITY = 0; +export const MAX_EFFECT_INTENSITY = 100; +export const DEFAULT_EFFECT_INTENSITY = 50; + +export const MIN_FADE_DURATION = 0; +export const MAX_FADE_DURATION = 10; +export const DEFAULT_FADE_IN_DURATION = 0.5; +export const DEFAULT_FADE_OUT_DURATION = 0.5; + +export const MIN_TRANSITION_DURATION = 0; +export const MAX_TRANSITION_DURATION = 5; +export const DEFAULT_TRANSITION_DURATION = 0.5; + +export const MIN_CAPTION_FONT_SIZE = 8; +export const MAX_CAPTION_FONT_SIZE = 120; +export const DEFAULT_CAPTION_FONT_SIZE = 24; +export const MAX_CAPTION_OFFSET = 500; + +export const RESOLUTION_PRESETS = { + '480p': { width: 854, height: 480 }, + '720p': { width: 1280, height: 720 }, + '1080p': { width: 1920, height: 1080 }, + '1440p': { width: 2560, height: 1440 }, + '4k': { width: 3840, height: 2160 }, +} as const; + +export const ASPECT_RATIO_VALUES = { + '16:9': 16 / 9, + '9:16': 9 / 16, + '1:1': 1, + '4:3': 4 / 3, + '21:9': 21 / 9, +} as const; + +export const SUPPORTED_FRAME_RATES = [24, 30, 60] as const; +export const SUPPORTED_FORMATS = ['mp4', 'webm', 'mov'] as const; +export const SUPPORTED_QUALITY_LEVELS = ['low', 'medium', 'high', 'ultra'] as const; + +export const QUALITY_BITRATE_MAP = { + low: 2500, + medium: 5000, + high: 10000, + ultra: 20000, +} as const; + +export const VIDEO_EFFECT_TYPES = [ + 'blur', + 'zoom', + 'pan', + 'fade', + 'overlay', + 'color_filter', + 'vignette', + 'shake', + 'glitch', + 'slow_motion', + 'speed_up', + 'ken_burns', + 'picture_in_picture', + 'split_screen', + 'custom', +] as const; + +export const TRANSITION_TYPES = [ + 'none', + 'fade', + 'dissolve', + 'wipe_left', + 'wipe_right', + 'wipe_up', + 'wipe_down', + 'slide_left', + 'slide_right', + 'zoom_in', + 'zoom_out', + 'blur', +] as const; + +export const VERTICAL_POSITIONS = ['top', 'middle', 'bottom'] as const; +export const HORIZONTAL_POSITIONS = ['left', 'center', 'right'] as const; + +export const CAPTION_ANIMATION_TYPES = ['none', 'fade', 'slide', 'typewriter', 'bounce'] as const; + +export const EASING_FUNCTIONS = ['linear', 'ease-in', 'ease-out', 'ease-in-out', 'bounce'] as const; + +export const FONT_WEIGHTS = ['normal', 'bold', 'light'] as const; + +export const DEFAULT_FONTS = [ + 'Arial', + 'Helvetica', + 'Times New Roman', + 'Georgia', + 'Verdana', + 'Roboto', + 'Open Sans', + 'Lato', + 'Montserrat', + 'Poppins', +] as const; + +export const MIN_WATERMARK_OPACITY = 0; +export const MAX_WATERMARK_OPACITY = 100; +export const DEFAULT_WATERMARK_OPACITY = 70; +export const MIN_WATERMARK_SIZE = 1; +export const MAX_WATERMARK_SIZE = 100; +export const DEFAULT_WATERMARK_SIZE = 10; +export const MAX_WATERMARK_TEXT_LENGTH = 100; + +export const ANCHOR_POINTS = [ + 'top-left', + 'top-center', + 'top-right', + 'center-left', + 'center', + 'center-right', + 'bottom-left', + 'bottom-center', + 'bottom-right', +] as const; + +export const VIDEO_CONFIG_ERROR_MESSAGES = { + NOT_FOUND: 'Video configuration not found', + UNAUTHORIZED: 'You are not authorized to access this video configuration', + INVALID_STORY: 'Invalid story reference', + INVALID_PROJECT: 'Invalid project reference', + INVALID_NARRATION: 'Invalid narration reference', + INVALID_SCENE_ORDER: 'Invalid scene order configuration', + INVALID_TIMING: 'Invalid timing configuration', + INVALID_SOUND_EFFECT: 'Invalid sound effect configuration', + INVALID_VIDEO_EFFECT: 'Invalid video effect configuration', + DURATION_EXCEEDED: 'Video duration exceeds maximum allowed', + TOO_MANY_SOUND_EFFECTS: `Maximum ${MAX_SOUND_EFFECTS_PER_CONFIG} sound effects allowed`, + TOO_MANY_VIDEO_EFFECTS: `Maximum ${MAX_VIDEO_EFFECTS_PER_CONFIG} video effects allowed`, + NOT_READY: 'Video configuration is not ready for rendering', +} as const; diff --git a/src/db/withTransaction.ts b/src/db/withTransaction.ts new file mode 100644 index 0000000..820eb79 --- /dev/null +++ b/src/db/withTransaction.ts @@ -0,0 +1,29 @@ +import mongoose, { ClientSession } from 'mongoose'; + +type TransactionCallback = (session: ClientSession) => Promise; + +/** + * Executes the given callback inside a MongoDB transaction. + * - Always commits on success + * - Always aborts on error + * - Always ends the session + * + * No retries. No swallowing errors. No side effects here. + */ +export async function withTransaction(callback: TransactionCallback): Promise { + const session = await mongoose.startSession(); + + try { + session.startTransaction(); + + const result = await callback(session); + + await session.commitTransaction(); + return result; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} diff --git a/src/domain/assertions/assertAssetState.ts b/src/domain/assertions/assertAssetState.ts new file mode 100644 index 0000000..88c256b --- /dev/null +++ b/src/domain/assertions/assertAssetState.ts @@ -0,0 +1,28 @@ +import { ConflictError } from '@middleware/error/index.js'; +import { SceneAsset } from '@models/SceneAssets.js'; + +function assertAssetNotDeleted(asset: SceneAsset): void { + if (asset.deletedAt) { + throw new ConflictError('Cannot perform operation on deleted asset'); + } +} + +function assertAssetIsDeleted(asset: SceneAsset): void { + if (!asset.deletedAt) { + throw new ConflictError('Asset is not deleted'); + } +} + +function assertHasDeletedAssets(assets: SceneAsset[]): void { + if (assets.length === 0) { + throw new ConflictError('No deleted assets exists'); + } +} + +function assertHasNonDeletedAssets(assets: SceneAsset[]): void { + if (assets.length === 0) { + throw new ConflictError('No assets to delete'); + } +} + +export { assertAssetNotDeleted, assertAssetIsDeleted, assertHasDeletedAssets, assertHasNonDeletedAssets }; diff --git a/src/domain/assertions/assertAudioAssetState.ts b/src/domain/assertions/assertAudioAssetState.ts new file mode 100644 index 0000000..5e9360a --- /dev/null +++ b/src/domain/assertions/assertAudioAssetState.ts @@ -0,0 +1,44 @@ +import { BadRequestError, ConflictError } from '@middleware/error/index.js'; +import { AudioAsset } from '@models/AudioAsset.js'; + +export function assertAudioAssetNotDeleted(audioAsset: AudioAsset): void { + if (audioAsset.deletedAt) { + throw new ConflictError('Audio asset is already deleted'); + } +} + +export function assertAudioAssetIsDeleted(audioAsset: AudioAsset): void { + if (!audioAsset.deletedAt) { + throw new ConflictError('Audio asset is not deleted'); + } +} + +export function assertAudioAssetIsActive(audioAsset: AudioAsset): void { + if (!audioAsset.activeNarration) { + throw new BadRequestError('Audio asset is not the active narration'); + } +} + +export function assertAudioAssetNotActive(audioAsset: AudioAsset): void { + if (audioAsset.activeNarration) { + throw new BadRequestError('Cannot perform this operation on the active audio asset. Please set another audio asset as active first.'); + } +} + +export function assertHasDeletedAudioAssets(audioAssets: AudioAsset[]): void { + if (!audioAssets.length) { + throw new BadRequestError('No deleted audio assets found to restore'); + } +} + +export function assertHasNonDeletedAudioAssets(audioAssets: AudioAsset[]): void { + if (!audioAssets.length) { + throw new BadRequestError('No audio assets found to delete'); + } +} + +export function assertAudioAssetTypeIsNarration(audioAsset: AudioAsset): void { + if (audioAsset.type !== 'narration') { + throw new BadRequestError('This operation is only allowed for narration type audio assets'); + } +} diff --git a/src/domain/assertions/assertCharacterFits.ts b/src/domain/assertions/assertCharacterFits.ts new file mode 100644 index 0000000..50a0670 --- /dev/null +++ b/src/domain/assertions/assertCharacterFits.ts @@ -0,0 +1,31 @@ +import { BadRequestError } from '@middleware/error/index.js'; +import { ContextProfile } from '@models/ContextProfile.js'; +import { NarrationSegment } from '@models/Narration.js'; + +export function assertCharacterFits(segments: NarrationSegment[], context: ContextProfile): void { + const hasContextCharacters = Array.isArray(context.characters) && context.characters.length > 0; + + const allowedNames = hasContextCharacters + ? new Set(context.characters!.map((c) => c.name.toLowerCase().trim())) + : null; + + for (const seg of segments) { + if (seg.character === undefined || seg.character === null) { + continue; + } + + if (typeof seg.character !== 'string' || seg.character.trim() === '') { + throw new BadRequestError('Invalid character reference in narration segment'); + } + + if (!hasContextCharacters) { + throw new BadRequestError('This story has no characters defined, but narration references a character'); + } + + const normalized = seg.character.toLowerCase().trim(); + + if (!allowedNames!.has(normalized)) { + throw new BadRequestError(`Character "${seg.character}" is not part of the story context`); + } + } +} diff --git a/src/domain/assertions/assertNarrationFitsTime.ts b/src/domain/assertions/assertNarrationFitsTime.ts new file mode 100644 index 0000000..9e64dff --- /dev/null +++ b/src/domain/assertions/assertNarrationFitsTime.ts @@ -0,0 +1,41 @@ +import { BadRequestError } from '@middleware/error/index.js'; + +export interface NarrationProfile { + wordsPerSecond: number; + minWordTolerance: number; + maxWordTolerance: number; +} + +export interface NarrationTimingInput { + durationSeconds: number; + narrationText: string; + profile: NarrationProfile; +} + +function countWords(text: string): number { + return text.trim().split(/\s+/).filter(Boolean).length; +} + +export function assertNarrationFitsTime({ + durationSeconds, + narrationText, + profile, +}: NarrationTimingInput): void { + const wordCount = countWords(narrationText); + + const baseWords = durationSeconds * profile.wordsPerSecond; + + const minWords = Math.floor(baseWords + profile.minWordTolerance); + const maxWords = Math.ceil(baseWords + profile.maxWordTolerance); + + if (wordCount < minWords || wordCount > maxWords) { + throw new BadRequestError( + `Narration text does not fit time window. + Duration: ${durationSeconds}s + Allowed words: ${minWords}-${maxWords} + Provided: ${wordCount} + Segment text: \`${narrationText}\` + ` + ); + } +} diff --git a/src/domain/assertions/assertNarrationState.ts b/src/domain/assertions/assertNarrationState.ts new file mode 100644 index 0000000..a030176 --- /dev/null +++ b/src/domain/assertions/assertNarrationState.ts @@ -0,0 +1,16 @@ +import { ConflictError } from '@middleware/error/index.js'; +import { StoryNarration } from '@models/Narration.js'; + +function assertNarrationNotDeleted(narration: StoryNarration): void { + if (narration.deletedAt) { + throw new ConflictError('Cannot perform operation on deleted narration'); + } +} + +function assertNarrationIsDeleted(narration: StoryNarration): void { + if (!narration.deletedAt) { + throw new ConflictError('Narration is not deleted'); + } +} + +export { assertNarrationNotDeleted, assertNarrationIsDeleted }; diff --git a/src/domain/assertions/assertSceneState.ts b/src/domain/assertions/assertSceneState.ts new file mode 100644 index 0000000..3355be0 --- /dev/null +++ b/src/domain/assertions/assertSceneState.ts @@ -0,0 +1,44 @@ +import { Scene } from '@models/Scene.js'; +import { ConflictError } from '@middleware/error/index.js'; + +export function assertSceneNotDeleted(scene: Scene): void { + if (scene.deletedAt) { + throw new ConflictError('Cannot perform operation on deleted scene'); + } +} + +export function assertSceneIsDeleted(scene: Scene): void { + if (!scene.deletedAt) { + throw new ConflictError('Scene is not deleted'); + } +} + +export function assertSceneIsActive(scene: Scene): void { + if (scene.deletedAt || scene.active === false) { + throw new ConflictError('Scene is not active'); + } +} + +export function assertSceneIsInactive(scene: Scene): void { + if (scene.active === true && !scene.deletedAt) { + throw new ConflictError('Scene is not inactive'); + } +} + +export function assertHasDeletedScenes(scenes: Scene[]): void { + if (scenes.length === 0) { + throw new ConflictError('No deleted scenes found'); + } +} + +export function assertHasNonDeletedScenes(scenes: Scene[]): void { + if (scenes.length === 0) { + throw new ConflictError('No non-deleted scenes found'); + } +} + +export function assertHasActiveScenes(scenes: Scene[]): void { + if (scenes.length === 0) { + throw new ConflictError('No active scenes found'); + } +} diff --git a/src/domain/assertions/assertStoryState.ts b/src/domain/assertions/assertStoryState.ts new file mode 100644 index 0000000..0d4fd0e --- /dev/null +++ b/src/domain/assertions/assertStoryState.ts @@ -0,0 +1,32 @@ +import { ConflictError } from '@middleware/error/index.js'; +import { Story } from '@models/Story.js'; + +export function assertStoryNotDeleted(story: Story): void { + if (story.status === 'delete' || story.deletedAt) { + throw new ConflictError('Cannot operate on deleted story'); + } +} + +export function assertStoryIsDeleted(story: Story): void { + if (story.status !== 'delete' || !story.deletedAt) { + throw new ConflictError('Story is not deleted'); + } +} + +export function assertStoryIsActive(story: Story): void { + if (story.status !== 'active' || story.deletedAt) { + throw new ConflictError('Story is not active'); + } +} + +export function assertStoryIsArchived(story: Story): void { + if (story.status !== 'archive') { + throw new ConflictError('Story is not archived'); + } +} + +export function assertStoryNotArchived(story: Story): void { + if (story.status === 'archive') { + throw new ConflictError('Story is archived'); + } +} diff --git a/src/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/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/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..d0519c7 100644 --- a/src/middleware/error/globalErrorHandler.ts +++ b/src/middleware/error/globalErrorHandler.ts @@ -1,26 +1,37 @@ -// 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()); } + + console.log(err); + logger.error({ + requestId, + name: 'UnhandledError', + message: 'Unhandled exception', + stack: process.env.NODE_ENV !== 'production' ? (err as Error).stack : undefined, + method: req.method, + path: req.originalUrl, + userId: (req as any).user?._id, + }); + return res.status(500).json({ status: 'error', message: 'Internal Server Error', 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/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/audioAssetUpload.ts b/src/middleware/multer/audioAssetUpload.ts new file mode 100644 index 0000000..26afdf0 --- /dev/null +++ b/src/middleware/multer/audioAssetUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerAudio.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const audioAssetUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('audioFile')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Audio file size exceeds the 100MB limit', err)); + } + return next(new BadRequestError('Multer error during audio upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/multer/avatarUpload.ts b/src/middleware/multer/avatarUpload.ts new file mode 100644 index 0000000..77f2995 --- /dev/null +++ b/src/middleware/multer/avatarUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerImage.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const avatarUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('avatar')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Avatar file size exceeds the 2MB limit', err)); + } + return next(new BadRequestError('Multer error during file upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/multer/filenameLogic/multerAudio.ts b/src/middleware/multer/filenameLogic/multerAudio.ts new file mode 100644 index 0000000..745dcee --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerAudio.ts @@ -0,0 +1,74 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/audio'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.mp3', '.wav', '.ogg', '.aac', '.m4a', '.flac', '.wma', '.opus']; +const allowedMimetypes = [ + 'audio/mpeg', + 'audio/mp3', + 'audio/wav', + 'audio/wave', + 'audio/x-wav', + 'audio/ogg', + 'audio/aac', + 'audio/mp4', + 'audio/x-m4a', + 'audio/flac', + 'audio/x-flac', + 'audio/x-ms-wma', + 'audio/opus', +]; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only audio files (mp3, wav, ogg, aac, m4a, flac, wma, opus) are allowed')); + return; + } + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only audio files (mp3, wav, ogg, aac, m4a, flac, wma, opus) are allowed')); + return; + } + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only audio files (mp3, wav, ogg, aac, m4a, flac, wma, opus) are allowed')); + return; + } + cb(null, true); +}; + +const upload = multer({ + storage, + fileFilter, + limits: { fileSize: 10 * 1024 * 1024 }, // 10 MB limit +}); + +export { upload }; diff --git a/src/middleware/multer/filenameLogic/multerImage.ts b/src/middleware/multer/filenameLogic/multerImage.ts new file mode 100644 index 0000000..738f67c --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerImage.ts @@ -0,0 +1,60 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/images'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']; +const allowedMimetypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only image files (jpg, jpeg, png, gif, webp) are allowed')); + return; + } + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only image files (jpg, jpeg, png, gif, webp) are allowed')); + return; + } + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only image files (jpg, jpeg, png, gif, webp) are allowed')); + return; + } + cb(null, true); +}; + +const upload = multer({ + storage, + fileFilter, + limits: { fileSize: 2 * 1024 * 1024 }, +}); + +export { upload }; diff --git a/src/middleware/multer/filenameLogic/multerJSON.ts b/src/middleware/multer/filenameLogic/multerJSON.ts new file mode 100644 index 0000000..901ba5e --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerJSON.ts @@ -0,0 +1,63 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/json'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.json']; +const allowedMimetypes = ['application/json']; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only JSON files are allowed')); + return; + } + + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only JSON files are allowed')); + return; + } + + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only JSON files are allowed')); + return; + } + + cb(null, true); +}; + +const uploadJSON = multer({ + storage, + fileFilter, + limits: { fileSize: 2 * 1024 * 1024 }, // 2MB max limit +}); + +export { uploadJSON }; diff --git a/src/middleware/multer/filenameLogic/multerVideo.ts b/src/middleware/multer/filenameLogic/multerVideo.ts new file mode 100644 index 0000000..e1a0a0a --- /dev/null +++ b/src/middleware/multer/filenameLogic/multerVideo.ts @@ -0,0 +1,66 @@ +import { Request } from 'express'; +import fs from 'fs'; +import multer from 'multer'; +import { BadRequestError } from '../../error/index.js'; + +const storage = multer.diskStorage({ + destination: function ( + _req: Request, + _file: Express.Multer.File, + cb: (error: Error | null, destination: string) => void + ) { + const uploadPath = './temp/uploads/videos'; + fs.mkdir(uploadPath, { recursive: true }, (err) => { + if (err) { + cb(err, uploadPath); + } else { + cb(null, uploadPath); + } + }); + }, + filename: function ( + _req: Request, + file: Express.Multer.File, + cb: (error: Error | null, filename: string) => void + ) { + const lastDotIndex = file.originalname.lastIndexOf('.'); + const fileExtension = lastDotIndex >= 0 ? file.originalname.substring(lastDotIndex).toLowerCase() : ''; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); + }, +}); + +const allowedExtensions = ['.mp4', '.mov', '.avi', '.mkv', '.webm']; +const allowedMimetypes = [ + 'video/mp4', + 'video/quicktime', + 'video/x-msvideo', + 'video/x-matroska', + 'video/webm', +]; + +const fileFilter: multer.Options['fileFilter'] = (_req, file, cb) => { + if (!allowedMimetypes.includes(file.mimetype)) { + cb(new BadRequestError('Only video files (mp4, mov, avi, mkv, webm) are allowed')); + return; + } + const lastDotIndex = file.originalname.lastIndexOf('.'); + if (lastDotIndex < 0) { + cb(new BadRequestError('Only video files (mp4, mov, avi, mkv, webm) are allowed')); + return; + } + const fileExtension = file.originalname.substring(lastDotIndex).toLowerCase(); + if (!allowedExtensions.includes(fileExtension)) { + cb(new BadRequestError('Only video files (mp4, mov, avi, mkv, webm) are allowed')); + return; + } + cb(null, true); +}; + +const upload = multer({ + storage, + fileFilter, + limits: { fileSize: 20 * 1024 * 1024 }, +}); + +export { upload }; diff --git a/src/middleware/multer/imageAssetUpload.ts b/src/middleware/multer/imageAssetUpload.ts new file mode 100644 index 0000000..1ada5ce --- /dev/null +++ b/src/middleware/multer/imageAssetUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerImage.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const imageAssetUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('sceneImage')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Avatar file size exceeds the 2MB limit', err)); + } + return next(new BadRequestError('Multer error during file upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/multer/narrationJSONUpload.ts b/src/middleware/multer/narrationJSONUpload.ts new file mode 100644 index 0000000..ae94776 --- /dev/null +++ b/src/middleware/multer/narrationJSONUpload.ts @@ -0,0 +1,19 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { uploadJSON } from './filenameLogic/multerJSON.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const narrationJSONUpload = (req: Request, res: Response, next: NextFunction) => { + uploadJSON.single('narrationFile')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('JSON file size exceeds the 2MB limit', err)); + } + return next(new BadRequestError('Multer error during JSON upload', { cause: err })); + } + + return next(err); + }); +}; diff --git a/src/middleware/multer/videoAssetUpload.ts b/src/middleware/multer/videoAssetUpload.ts new file mode 100644 index 0000000..764d56b --- /dev/null +++ b/src/middleware/multer/videoAssetUpload.ts @@ -0,0 +1,18 @@ +import { Request, Response, NextFunction } from 'express'; +import multer from 'multer'; +import { upload } from './filenameLogic/multerVideo.js'; +import { BadRequestError, PayloadTooLargeError } from '../error/index.js'; + +export const videoAssetUpload = (req: Request, res: Response, next: NextFunction) => { + upload.single('sceneVideo')(req, res, (err) => { + if (!err) return next(); + + if (err instanceof multer.MulterError) { + if (err.code === 'LIMIT_FILE_SIZE') { + return next(new PayloadTooLargeError('Video file size exceeds the 50MB limit', err)); + } + return next(new BadRequestError('Multer error during video upload', { cause: err })); + } + return next(err); + }); +}; diff --git a/src/middleware/paginationAndSorting.ts b/src/middleware/paginationAndSorting.ts deleted file mode 100644 index 23e2926..0000000 --- a/src/middleware/paginationAndSorting.ts +++ /dev/null @@ -1,53 +0,0 @@ -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/request/paginationAndSorting.ts b/src/middleware/request/paginationAndSorting.ts new file mode 100644 index 0000000..23eb833 --- /dev/null +++ b/src/middleware/request/paginationAndSorting.ts @@ -0,0 +1,48 @@ +import { Request, Response, NextFunction } from 'express'; +import { BadRequestError } from '../error/index.js'; +import type { Pagination, Sorting } from 'types/Pagination.js'; + +const DEFAULT_PAGE = 1; +const DEFAULT_LIMIT = 10; +const MAX_LIMIT = 50; + +// Whitelist sortable fields (CRITICAL) +const ALLOWED_SORT_FIELDS = ['createdAt', 'updatedAt', 'title', 'status', 'name', 'lastUsedAt']; + +export function paginationAndSortingMiddleware(req: Request, _res: Response, next: NextFunction) { + // ---------- Pagination ---------- + const page = Number(req.query.page) || DEFAULT_PAGE; + const limit = Number(req.query.limit) || DEFAULT_LIMIT; + + if (page < 1) { + throw new BadRequestError('Page must be greater than 0'); + } + + if (limit < 1 || limit > MAX_LIMIT) { + throw new BadRequestError(`Limit must be between 1 and ${MAX_LIMIT}`); + } + + const pagination: Pagination = { + page, + limit, + skip: (page - 1) * limit, + }; + + // ---------- Sorting ---------- + const sortBy = + typeof req.query.sortBy === 'string' && ALLOWED_SORT_FIELDS.includes(req.query.sortBy) + ? req.query.sortBy + : 'createdAt'; + + const sortOrder = req.query.sortOrder === 'asc' ? 1 : -1; // default desc + + const sorting: Sorting = { + sortBy, + sortOrder, + }; + + req.pagination = pagination; + req.sorting = sorting; + + next(); +} diff --git a/src/middleware/requireActiveAccountFresh.ts b/src/middleware/requireActiveAccountFresh.ts deleted file mode 100644 index e69de29..0000000 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/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..7584cce 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,10 @@ const contextProfileSchema = new Schema( type: Boolean, default: false, }, - + parentContextId: { + type: Schema.Types.ObjectId, + ref: 'ContextProfile', + }, name: { type: String, required: true, @@ -202,12 +209,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 +265,10 @@ const contextProfileSchema = new Schema( characters: [ { name: { type: String, required: true }, - description: String, + imageUrl: { type: String }, + description: { type: String, maxlength: 500 }, + features: { type: Schema.Types.Mixed }, + behaviors: { type: Schema.Types.Mixed }, }, ], @@ -269,8 +277,8 @@ const contextProfileSchema = new Schema( label: String, severity: { type: String, - enum: ["hard", "soft"], - default: "hard", + enum: ['hard', 'soft'], + default: 'hard', }, }, ], @@ -282,19 +290,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 +314,7 @@ const contextProfileSchema = new Schema( emotionBias: { type: String, - enum: ["flat", "subtle", "expressive"], + enum: ['flat', 'subtle', 'expressive'], required: true, }, @@ -324,10 +332,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/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/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..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" }, + 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/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/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 3510724..d5261c7 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 { - const { email, password, displayName, username, userAgent, ip } = input; +export async function registerUser(input: RegisterInputWithMeta): Promise { + const { email, password, name, username, userAgent, ip } = input; const existing = await UserModel.findOne({ $or: [{ email }, { username }] }); if (existing) { 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: name ?? 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,52 @@ 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 +152,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('No refresh token, Authentication failed'); } const session = await SessionModel.findOne({ @@ -180,50 +166,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('No refresh token, 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('No refresh token, Authentication failed'); } - // 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('No refresh token, Authentication failed'); } const user = await UserModel.findOne({ _id: decoded.userId, - accountStatus: { $ne: "banned" }, + accountStatus: { $ne: 'banned' }, }); if (!user) { - throw new UnauthenticatedError("Authentication failed"); + throw new UnauthenticatedError('No refresh token, 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 +205,7 @@ export async function refreshTokens( await SessionModel.updateOne( { _id: session._id, - refreshTokenHash: session.refreshTokenHash, // race protection + refreshTokenHash: session.refreshTokenHash, }, { refreshTokenHash: hashToken(newRefreshToken), @@ -254,8 +227,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 +244,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 +259,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 +269,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 +311,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 +326,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 +337,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 +377,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 +396,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 +414,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 +451,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 +497,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 +521,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 +532,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 +540,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/createSessionPayload.ts b/src/modules/auth/utils/createSessionPayload.ts new file mode 100644 index 0000000..03da6aa --- /dev/null +++ b/src/modules/auth/utils/createSessionPayload.ts @@ -0,0 +1,59 @@ +import { SessionData } from '../../../models/Session.js'; +import { generateAllCookieTokens } from '@utils/generateAllCookieTokens.js'; +import { getIpInfo } from '@utils/getIpInfo.js'; +import { parseUserAgent } from '@utils/parseUserAgent.js'; +import { hashToken } from '@utils/tokens.js'; +import crypto from 'crypto'; +import { User } from '@models/User.js'; + +export async function createSessionPayload({ + user, + userAgent, + ip, +}: { + user: User; + userAgent: string; + ip: string; +}) { + const ipData: any = await getIpInfo(ip); + const userAgentInfo = parseUserAgent(userAgent); + const sessionId = crypto.randomBytes(32).toString('hex'); + const { accessToken, refreshToken, csrfToken } = generateAllCookieTokens( + user._id, + sessionId, + user.role, + user.accountStatus + ); + + let sessionPayload: Partial = { + sessionId, + userId: user._id, + userAgent, + device: userAgentInfo.device, + browser: userAgentInfo.browser, + os: userAgentInfo.os, + refreshTokenHash: hashToken(refreshToken), + csrfTokenHash: hashToken(csrfToken), + expiresIn: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), + createdAt: new Date(), + lastUsedAt: new Date(), + }; + + if (ipData.success) { + sessionPayload = { + ...sessionPayload, + ip: ipData.ip, + city: ipData.cityName, + country: ipData.countryName, + timezone: ipData.timeZones[0] || 'unknown', + lat: ipData.latitude, + lng: ipData.longitude, + isp: ipData.asnOrganization, + }; + } + + return { + sessionPayload, + tokens: { accessToken, refreshToken, csrfToken }, + }; +} diff --git a/src/modules/auth/utils/createUserSession.ts b/src/modules/auth/utils/createUserSession.ts deleted file mode 100644 index 80af66c..0000000 --- a/src/modules/auth/utils/createUserSession.ts +++ /dev/null @@ -1,54 +0,0 @@ -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/auth/utils/createUsername.ts b/src/modules/auth/utils/createUsername.ts new file mode 100644 index 0000000..e90eb33 --- /dev/null +++ b/src/modules/auth/utils/createUsername.ts @@ -0,0 +1,25 @@ +import crypto from 'crypto'; +import { UserModel } from '@models/User.js'; +import { ClientSession } from 'mongoose'; + +export const createUsername = async (email: string, session: ClientSession): Promise => { + const base = email + .split('@')[0] + .toLowerCase() + .replace(/[^a-z0-9]/g, ''); + + // Fallback if base becomes empty + const root = base || 'user'; + + // Retry up to 10 times before failing + for (let i = 0; i < 10; i++) { + const suffix = crypto.randomBytes(3).toString('hex'); // 6 hex chars + const username = `${root}${suffix}`; + + const exists = await UserModel.exists({ username }).session(session); + if (!exists) return username; + } + + // If all 10 attempts failed (extremely rare), use a timestamp fallback + return `${root}${Date.now().toString(36)}`; +}; diff --git a/src/modules/contextProfile/contextProfile.controller.ts b/src/modules/contextProfile/contextProfile.controller.ts 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 new file mode 100644 index 0000000..9cd4f4a --- /dev/null +++ b/src/modules/credit/credit.service.ts @@ -0,0 +1,62 @@ +import mongoose, { Types } from 'mongoose'; +import { CreditsModel } from '@models/Credits.js'; +import { ForbiddenError, InternalServerError } from '@middleware/error/index.js'; + +export async function getAvailableCredits(userId: Types.ObjectId): Promise { + const rows = await CreditsModel.find({ + userId, + isExpired: false, + $or: [{ validTill: null }, { validTill: { $gt: new Date() } }], + }); + + let total = 0; + for (const row of rows) { + total += Math.max(0, row.creditsGranted - row.creditsUsed); + } + return total; +} + +export async function consumeCredits( + userId: string, + amount: number, + session: mongoose.ClientSession +): Promise { + if (amount <= 0) return; + + try { + const creditEntries = await CreditsModel.find( + { + userId, + isExpired: false, + $or: [{ validTill: null }, { validTill: { $gt: new Date() } }], + }, + null, + { session } + ).sort({ validTill: 1, createdAt: 1 }); + + let creditsToConsume = amount; + + for (const entry of creditEntries) { + if (creditsToConsume === 0) break; + + const available = entry.creditsGranted - entry.creditsUsed; + if (available <= 0) continue; + + const usedNow = Math.min(available, creditsToConsume); + + entry.creditsUsed += usedNow; + creditsToConsume -= usedNow; + + await entry.save({ session }); + } + + // 3. If not enough credits → rollback + if (creditsToConsume > 0) { + throw new ForbiddenError('Insufficient credits'); + } + } catch (err) { + throw err instanceof ForbiddenError + ? err + : new InternalServerError('Credit consumption failed', String(err)); + } +} diff --git a/src/modules/featurePermission/featurePermission.service.ts b/src/modules/featurePermission/featurePermission.service.ts new file mode 100644 index 0000000..e55349c --- /dev/null +++ b/src/modules/featurePermission/featurePermission.service.ts @@ -0,0 +1,66 @@ +import { Types } from 'mongoose'; +import { UserModel } from '@models/User.js'; +import { PlanModel } from '@models/Plan.js'; +import { UserCapabilityOverrideModel } from '@models/CapabilityOverride.js'; +import { ForbiddenError, InternalServerError } from '@middleware/error/index.js'; +import { ActionType } from 'config/creditPricing.js'; +import { resolveEffectiveCapabilities } from '@modules/featurePermission/utils/resolveEffectiveCapabilities.js'; + +type PermissionInput = { + userId: Types.ObjectId; + action: ActionType; + grade: number; +}; + +export async function assertFeaturePermission({ userId, action, grade }: PermissionInput): Promise { + const user = await UserModel.findById(userId).lean(); + if (!user || !user.currentPlan) { + throw new InternalServerError('User or plan not found'); + } + + const plan = await PlanModel.findById(user.currentPlan).lean(); + if (!plan || !plan.isActive || !plan.capabilities) { + throw new ForbiddenError('Plan is inactive or invalid'); + } + + const now = new Date(); + const overrides = await UserCapabilityOverrideModel.find({ + userId, + validFrom: { $lte: now }, + validTill: { $gt: now }, + }).lean(); + + const caps = resolveEffectiveCapabilities(plan.capabilities, overrides); + + switch (action) { + case 'TXT_TO_IMAGE_GEN': + if (!caps.image || grade > caps.image.maxTier) { + throw new ForbiddenError('Image generation grade not allowed'); + } + return; + + case 'AUDIO_GEN': + if (!caps.audio || grade > caps.audio.maxTier) { + throw new ForbiddenError('Audio generation grade not allowed'); + } + return; + + case 'STORY_GEN': + if (!caps.story || grade > caps.story.maxTier) { + throw new ForbiddenError('Story generation grade not allowed'); + } + return; + + case 'TXT_TO_VIDEO_GEN': + if (!caps.video || !caps.video.enabled) { + throw new ForbiddenError('Video generation not allowed'); + } + if (grade > caps.video.maxSeconds) { + throw new ForbiddenError('Video request exceeds plan limit'); + } + return; + + default: + throw new InternalServerError(`Unknown action: ${action}`); + } +} diff --git a/src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts b/src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts new file mode 100644 index 0000000..ba10bd4 --- /dev/null +++ b/src/modules/featurePermission/utils/resolveEffectiveCapabilities.ts @@ -0,0 +1,24 @@ +import { CapabilityOverrideData } from '@models/CapabilityOverride.js'; + +export function resolveEffectiveCapabilities(planCaps: any, overrides: CapabilityOverrideData[]) { + const effective = structuredClone(planCaps); + + for (const o of overrides) { + const feature = o.feature as keyof typeof effective; + const key = o.capabilityKey; + + if (!effective[feature]) continue; + + const baseValue = effective[feature][key]; + + if (typeof baseValue === 'number' && typeof o.value === 'number') { + effective[feature][key] = Math.max(baseValue, o.value); + } + + if (typeof baseValue === 'boolean' && typeof o.value === 'boolean') { + effective[feature][key] = baseValue || o.value; + } + } + + return effective; +} diff --git a/src/modules/narration/narration.constants.ts b/src/modules/narration/narration.constants.ts new file mode 100644 index 0000000..935221f --- /dev/null +++ b/src/modules/narration/narration.constants.ts @@ -0,0 +1,3 @@ +export const DEFAULT_WORDS_PER_SECOND = 2.5; +export const MAX_NARRATION_LENGTH = 20000; +export const NARRATION_VERSION_GAP = 1; \ No newline at end of file diff --git a/src/modules/narration/narration.controller.ts b/src/modules/narration/narration.controller.ts 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..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 { Request, Response } from 'express'; import { + archiveAllProjects, + archiveManyProjectsByIds, createProject, createProjectContextProfile, + deleteAllProjects, + deleteManyProjectsByIds, deleteProjectById, getArchivedProjects, getDeletedProjects, getProjectById, getProjects, + permanentDeleteAllProjects, + permanentDeleteManyProjects, + permanentDeleteProjectById, + restoreAllProjects, restoreManyProjectsByIds, restoreProjectById, unarchiveManyProjectsByIds, @@ -14,15 +22,17 @@ import { updateProjectById, updateProjectStatus, updateProjectVisibility, -} from "./project.service.js"; -import { Types } from "mongoose"; + unarchiveAllProjects, + getDraftProjects, +} from './project.service.js'; +import { Types } from 'mongoose'; import { CreateProjectInput, UpdateProjectInput, UpdateManyIdsInput, CreateProjectContextInput, -} from "@validation/project.schema.js"; -import { paginationResponse } from "@utils/paginationResponse.js"; +} 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 +48,28 @@ export const getProjectsController = async (req: Request, res: Response) => { }); }; -export const getDeletedProjectsController = 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!; 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 +78,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, @@ -79,6 +92,90 @@ export const getArchivedProjectsController = async ( }); }; +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; @@ -93,25 +190,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 +206,23 @@ 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 permanentDeleteProjectByIdController = async (req: Request, res: Response) => { + const projectId = req.params.projectId as Types.ObjectId | string; + const userId = req.user!.id; + + const result = await permanentDeleteProjectById(projectId, userId); + + return res.status(200).json(result); +}; + +export const updateProjectStatusController = async (req: Request, res: Response) => { const projectId = req.params.projectId as Types.ObjectId | string; const { status } = req.body; const userId = req.user!.id; @@ -140,62 +230,24 @@ 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 -) => { - 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 a1977a0..4516d08 100644 --- a/src/modules/project/project.service.ts +++ b/src/modules/project/project.service.ts @@ -1,44 +1,62 @@ import { - BadRequestError, - ForbiddenError, + BadRequestError, + ForbiddenError, InternalServerError, NotFoundError, -} from "@middleware/error/index.js"; +} from '@middleware/error/index.js'; import type { + CreateProjectContextInput, CreateProjectInput, UpdateProjectInput, -} from "@validation/project.schema.js"; -import { ProjectModel, ProjectType } from "@models/Project.js"; -import { - sanitizeProjectResponse, - sanitizeProjects, -} from "@utils/sanitizeProjectResponse.js"; -import mongoose, { Types } from "mongoose"; -import { Pagination, Sorting } from "../../types/Pagination.js"; -import { - ACTIVE_STATUSES, -} from "./rules/projectStatus.js"; -import { transitionManyProjectsByIds } from "./utils/transitionManyProjectsByIds.js"; -import { transitionProjectById } from "./utils/transitionProjectById.js"; -import { ContextProfileModel, ContextScope, GenreType } from "@models/ContextProfile.js"; -import { NARRATION_PROFILES } from "constants/narrationProfiles.js"; - -export async function getProjects( +} from '@validation/project.schema.js'; +import { ProjectModel, ProjectType } from '@models/Project.js'; +import { sanitizeProjectResponse, sanitizeProjects } from '@utils/sanitizeProjectResponse.js'; +import mongoose, { Types } from 'mongoose'; +import { Pagination, Sorting } from '../../types/Pagination.js'; +import { ACTIVE_STATUSES } from './rules/projectStatus.js'; +import { transitionManyProjectsByIds } from './utils/transitionManyProjectsByIds.js'; +import { transitionProjectById } from './utils/transitionProjectById.js'; +import { ContextProfileModel, ContextScope, GenreType } from '@models/ContextProfile.js'; +import { NARRATION_PROFILES } from 'constants/narrationProfiles.js'; + +export async function getProjects(userId: Types.ObjectId | string, pagination: Pagination, sorting: Sorting) { + const filter = { userId, status: { $eq: 'active' } }; + const [projects, total] = await Promise.all([ + ProjectModel.find(filter) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + ProjectModel.countDocuments(filter) as Promise, + ]); + if (!projects || projects.length === 0) { + return [[], total]; + } + const resProjects = sanitizeProjects(projects); + return [resProjects, total]; +} + +export async function getDraftProjects( userId: Types.ObjectId | string, pagination: Pagination, sorting: Sorting -) { - const filter = { userId, status: { $in: ACTIVE_STATUSES } }; +) { + 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) as Promise, + .sort({ [sorting.sortBy]: sorting.sortOrder }), + ProjectModel.countDocuments(filter), ]); + if (!projects || projects.length === 0) { return [[], total]; } + const resProjects = sanitizeProjects(projects); return [resProjects, total]; } @@ -48,12 +66,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 +86,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,47 +101,180 @@ export async function getArchivedProjects( return [resProjects, total]; } -export async function createProject( - userId: Types.ObjectId | string, - projectInput: CreateProjectInput +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, + visibility: projectInput.visibility || 'private', + // A project stays draft until a default context profile is attached. + status: 'draft', }); if (!newProject) { - throw new InternalServerError("Failed to create project"); + 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 + payload: CreateProjectContextInput ) { const session = await mongoose.startSession(); session.startTransaction(); @@ -134,16 +285,25 @@ export async function createProjectContextProfile( 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, + isDefaultForProject: true, + }).session(session); + + if (existingContext) { + throw new ForbiddenError('Project already has a default context'); + } // 🚨 CRITICAL RULE if (project.defaultContextProfileId) { - throw new ForbiddenError("Project already has a default context"); - } - let contextProfileId; - - if (payload.mode === "new") { - const narrationProfile = NARRATION_PROFILES[payload.data.genre as GenreType]; + throw new ForbiddenError('Project already has a default context'); + } + let contextProfileId: Types.ObjectId | undefined; + + if (payload.mode === 'new') { + const narrationProfile = NARRATION_PROFILES[payload.data.genre as GenreType]; const [context] = await ContextProfileModel.create( [ { @@ -161,18 +321,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 +340,8 @@ export async function createProjectContextProfile( ...globalContext.toObject(), _id: undefined, projectId, - parentContextId: globalContext._id, scope: ContextScope.PROJECT, + parentContextId: globalContext._id, isDefaultForProject: true, lastUsedAt: new Date(), }); @@ -190,10 +350,20 @@ export async function createProjectContextProfile( contextProfileId = cloned._id; } + if (!contextProfileId) { + throw new BadRequestError('Invalid context creation mode'); + } + project.defaultContextProfileId = contextProfileId; - await project.save({ session }); + 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; @@ -202,32 +372,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,116 +411,97 @@ 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( +export async function deleteProjectById(projectId: Types.ObjectId | string, userId: Types.ObjectId | string) { + await transitionProjectById(projectId, userId, ['draft', 'active', 'archive'], 'delete'); + return { + status: 'success', + message: 'Project deleted successfully', + }; +} + +export async function permanentDeleteProjectById( projectId: Types.ObjectId | string, userId: Types.ObjectId | string ) { - await transitionProjectById( - projectId, + const project = await ProjectModel.findOne({ + _id: projectId, userId, - ["draft", "active", "archive"], - "delete" - ); - return { - status: "success", - message: "Project deleted successfully", -} } - + }).select('_id status'); + + if (!project) { + throw new NotFoundError('Project not found'); + } + + if (project.status !== 'delete') { + throw new ForbiddenError('Project must be deleted before permanent removal'); + } + + await ProjectModel.deleteOne({ + _id: project._id, + userId, + }); + + return { + status: 'success', + message: 'Project permanently deleted', + }; +} + export async function updateProjectVisibility( projectId: Types.ObjectId | string, userId: Types.ObjectId | string, - visibility: "public" | "private" + 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" - ); - 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 +// 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.controller.ts b/src/modules/sceneAssets/sceneAssets.controller.ts new file mode 100644 index 0000000..0f395d8 --- /dev/null +++ b/src/modules/sceneAssets/sceneAssets.controller.ts @@ -0,0 +1,294 @@ +import { Request, Response } from 'express'; +import { + getAllAssetsForScene, + getAllDeletedAssets, + getAssetById, + getAssetCount, + getActiveAssetForScene, + setActiveAsset, + restoreAsset, + bulkRestoreAssets, + restoreAllDeletedAssets, + uploadVideoAsset, + uploadImageAsset, + softDeleteAllAssetsForScene, + permanentDeleteAllAssetsForScene, + softBulkDeleteAssets, + permanentBulkDeleteAssets, + softDeleteAsset, + permanentDeleteAsset, + forceDeleteActiveAsset, + generateVideoAsset, +} from './sceneAssets.service.js'; +import type { + BulkDeleteAssetsInput, + BulkRestoreAssetsInput, + SetActiveAssetInput, +} from '@validation/sceneAssets.schema.js'; +import { paginationResponse } from '@utils/paginationResponse.js'; + +// All Op controllers +export const getAllAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const pagination = req?.pagination; + const sorting = req?.sorting; + + const [assets, total] = await getAllAssetsForScene(userId, sceneId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + res.status(200).json({ + message: 'Assets retrieved successfully', + data: assets, + pagination: paginationRes, + }); +}; + +export const getAllDeletedAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const pagination = req?.pagination; + const sorting = req?.sorting; + + const [assets, total] = await getAllDeletedAssets(userId, sceneId, pagination, sorting); + + const paginationRes = paginationResponse(pagination, total as number); + + res.status(200).json({ + message: 'Deleted assets retrieved successfully', + data: assets, + pagination: paginationRes, + }); +}; + +export const restoreAllDeletedAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const result = await restoreAllDeletedAssets(userId, sceneId); + + res.status(200).json({ + message: 'All deleted assets restored successfully', + restoredCount: result.restoredCount, + }); +}; + +export const softDeleteAllAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const result = await softDeleteAllAssetsForScene(userId, sceneId); + + res.status(200).json({ + message: 'All assets safe deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const permanentDeleteAllAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const result = await permanentDeleteAllAssetsForScene(userId, sceneId); + res.status(200).json({ + message: 'All assets deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const getAssetCountController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const count = await getAssetCount(userId, sceneId); + + res.status(200).json({ + message: 'Asset count retrieved successfully', + count, + }); +}; + +// Bulk Op controllers +export const softBulkDeleteAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetIds } = req.validatedBody as BulkDeleteAssetsInput; + + const result = await softBulkDeleteAssets(userId, sceneId, assetIds); + + res.status(200).json({ + message: 'Assets safe deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const permanentBulkDeleteAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetIds } = req.validatedBody as BulkDeleteAssetsInput; + + const result = await permanentBulkDeleteAssets(userId, sceneId, assetIds); + + res.status(200).json({ + message: 'Assets safe deleted successfully', + deletedCount: result.deletedCount, + }); +}; + +export const bulkRestoreAssetsController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetIds } = req.validatedBody as BulkRestoreAssetsInput; + + const result = await bulkRestoreAssets(userId, sceneId, assetIds); + + res.status(200).json({ + message: 'Assets restored successfully', + data: result, + }); +}; + +// Single Op controllers +export const getAssetByIdController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + const asset = await getAssetById(userId, assetId); + + res.status(200).json({ + message: 'Asset retrieved successfully', + data: asset, + }); +}; + +export const getActiveAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + + const asset = await getActiveAssetForScene(userId, sceneId); + + if (!asset) { + return res.status(200).json({ + message: 'No active asset found for this scene', + data: null, + }); + } + + res.status(200).json({ + message: 'Active asset retrieved successfully', + data: asset, + }); +}; + +export const generateVideoAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const response = await generateVideoAsset(userId, sceneId); + res.status(201).json({ + message: 'Video asset generated successfully', + data: { + sceneId, + filename: response.url, + }, + }); +}; + +export const generateImageAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; +}; + +export const uploadVideoAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const file = req.file; + if (!file) { + return res.status(400).json({ message: 'No video file uploaded' }); + } + + const response = await uploadVideoAsset(userId, sceneId, file); + + res.status(201).json({ + message: 'Video asset uploaded successfully', + data: { + sceneId, + filename: response.videoUrl, + }, + }); +}; + +export const uploadImageAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const file = req.file; + if (!file) { + return res.status(400).json({ message: 'No image file uploaded' }); + } + + const response = await uploadImageAsset(userId, sceneId, file); + + res.status(201).json({ + message: 'Image asset uploaded successfully', + data: { + sceneId, + filename: file.originalname, + }, + }); +}; + +export const setActiveAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { sceneId } = req.params; + const { assetId } = req.validatedBody as SetActiveAssetInput; + + const asset = await setActiveAsset(userId, sceneId, assetId); + + res.status(200).json({ + message: 'Active asset set successfully', + data: asset, + }); +}; + +export const softDeleteAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + const asset = await softDeleteAsset(userId, assetId); + res.status(200).json({ + message: 'Asset safe deleted successfully', + data: asset, + }); +}; + +export const permanentDeleteAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + const asset = await permanentDeleteAsset(userId, assetId); + res.status(200).json({ + message: 'Asset deleted successfully', + data: asset, + }); +}; + +export const forceDeleteActiveAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + await forceDeleteActiveAsset(userId, assetId); + res.status(200).json({ + message: 'Asset deleted successfully', + data: true, + }); +}; + +export const restoreAssetController = async (req: Request, res: Response) => { + const userId = req.user!.id; + const { assetId } = req.params; + + const asset = await restoreAsset(userId, assetId); + + res.status(200).json({ + message: 'Asset restored successfully', + data: asset, + }); +}; diff --git a/src/modules/sceneAssets/sceneAssets.private.routes.ts b/src/modules/sceneAssets/sceneAssets.private.routes.ts new file mode 100644 index 0000000..28d0857 --- /dev/null +++ b/src/modules/sceneAssets/sceneAssets.private.routes.ts @@ -0,0 +1,152 @@ +import { Router } from 'express'; +import { asyncHandler } from '@utils/asyncHandler.js'; +import { validateParams } from '@validation/validateParams.js'; +import { validateBody } from '@validation/validateBody.js'; + +import { + sceneIdParamSchema, + sceneAssetIdParamSchema, + sceneAssetAndSceneParamSchema, + // bulkDeleteAssetsSchema, + bulkRestoreAssetsSchema, + setActiveAssetSchema, + bulkDeleteAssetsSchema, +} from '@validation/sceneAssets.schema.js'; + +import { + getAllAssetsController, + getAllDeletedAssetsController, + getAssetByIdController, + getAssetCountController, + getActiveAssetController, + setActiveAssetController, + uploadVideoAssetController, + uploadImageAssetController, + softDeleteAssetController, + softBulkDeleteAssetsController, + softDeleteAllAssetsController, + permanentDeleteAssetController, + permanentBulkDeleteAssetsController, + permanentDeleteAllAssetsController, + forceDeleteActiveAssetController, + restoreAssetController, + bulkRestoreAssetsController, + restoreAllDeletedAssetsController, + generateVideoAssetController, + generateImageAssetController, +} from './sceneAssets.controller.js'; +import multer from 'multer'; +import { videoAssetUpload } from '@middleware/multer/videoAssetUpload.js'; +import { imageAssetUpload } from '@middleware/multer/imageAssetUpload.js'; +import { paginationAndSortingMiddleware } from '@middleware/request/paginationAndSorting.js'; + +const router = Router(); + +// All Op routes +router.get( + '/:sceneId', + validateParams(sceneIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllAssetsController) +); +router.get( + '/:sceneId/deleted', + validateParams(sceneIdParamSchema), + paginationAndSortingMiddleware, + asyncHandler(getAllDeletedAssetsController) +); +router.get('/:sceneId/count', validateParams(sceneIdParamSchema), asyncHandler(getAssetCountController)); + +router.delete('/:sceneId/', validateParams(sceneIdParamSchema), asyncHandler(softDeleteAllAssetsController)); + +router.delete( + '/:sceneId/permanent', + validateParams(sceneIdParamSchema), + asyncHandler(permanentDeleteAllAssetsController) +); + +router.post( + '/:sceneId/restore', + validateParams(sceneIdParamSchema), + asyncHandler(restoreAllDeletedAssetsController) +); + +// Bulk Op routes +router.post( + '/:sceneId/soft-bulk-delete', + validateParams(sceneIdParamSchema), + validateBody(bulkDeleteAssetsSchema), + asyncHandler(softBulkDeleteAssetsController) +); + +router.post( + '/:sceneId/permanent-bulk-delete', + validateParams(sceneIdParamSchema), + validateBody(bulkDeleteAssetsSchema), + asyncHandler(permanentDeleteAllAssetsController) +); + +router.post( + '/:sceneId/bulk-restore', + validateParams(sceneIdParamSchema), + validateBody(bulkRestoreAssetsSchema), + asyncHandler(bulkRestoreAssetsController) +); + +// Single Op routes +router.get('/:assetId', validateParams(sceneAssetIdParamSchema), asyncHandler(getAssetByIdController)); + +router.get('/:sceneId/active', validateParams(sceneIdParamSchema), asyncHandler(getActiveAssetController)); + +router.post( + '/:sceneId/generate/video', + validateParams(sceneIdParamSchema), + asyncHandler(generateVideoAssetController) +); + +router.post( + '/:sceneId/generate/image', + validateParams(sceneIdParamSchema), + asyncHandler(generateImageAssetController) +); + +router.post( + '/:sceneId/upload-video', + validateParams(sceneIdParamSchema), + videoAssetUpload, + asyncHandler(uploadVideoAssetController) +); + +router.post( + '/:sceneId/upload-image', + validateParams(sceneIdParamSchema), + imageAssetUpload, + asyncHandler(uploadImageAssetController) +); + +router.patch( + '/:sceneId/:assetId/set-active', + validateParams(sceneAssetAndSceneParamSchema), + validateBody(setActiveAssetSchema), + asyncHandler(setActiveAssetController) +); + +router.delete('/:assetId', validateParams(sceneAssetIdParamSchema), asyncHandler(softDeleteAssetController)); +router.delete( + '/:assetId/permanent', + validateParams(sceneAssetIdParamSchema), + asyncHandler(permanentDeleteAssetController) +); +router.delete( + '/:assetId/force', + validateParams(sceneAssetIdParamSchema), + asyncHandler(forceDeleteActiveAssetController) +); + +router.patch( + '/:sceneId/:assetId/restore', + validateParams(sceneAssetAndSceneParamSchema), + asyncHandler(restoreAssetController) +); + +export default router; diff --git a/src/modules/sceneAssets/sceneAssets.service.ts b/src/modules/sceneAssets/sceneAssets.service.ts new file mode 100644 index 0000000..cb12143 --- /dev/null +++ b/src/modules/sceneAssets/sceneAssets.service.ts @@ -0,0 +1,536 @@ +import fs from 'fs/promises'; +import { SceneAssetModel, SceneAsset } from '@models/SceneAssets.js'; +import { SceneModel } from '@models/Scene.js'; +import { NotFoundError, BadRequestError, ConflictError } from '@middleware/error/index.js'; +import mongoose, { ClientSession } from 'mongoose'; +import type { Pagination, Sorting } from 'types/Pagination.js'; +import { getVideoDuration } from '@utils/getVideoDuration.js'; +import { assertFeaturePermission } from '@modules/featurePermission/featurePermission.service.js'; +import { getCreditCost } from '@utils/getCreditCost.js'; +import { consumeCredits } from '@modules/credit/credit.service.js'; +import { validateSceneOwnership } from 'validators/validateSceneOwnership.js'; +import { validateAssetOwnership } from 'validators/validateAssetOwnership.js'; +import { validateUser } from 'validators/validateUser.js'; +import { + assertAssetIsDeleted, + assertAssetNotDeleted, + assertHasDeletedAssets, + assertHasNonDeletedAssets, +} from 'domain/assertions/assertAssetState.js'; +import { withTransaction } from '@db/withTransaction.js'; + +// Get the next version number for an asset in a scene +async function getNextVersionNumber(sceneId: string, session?: ClientSession): Promise { + const query = SceneAssetModel.findOne({ sceneId }).sort({ version: -1 }).select('version'); + + if (session) query.session(session); + + const lastAsset = await query; + return lastAsset ? lastAsset.version + 1 : 1; +} + +// All Op services +export async function getAllAssetsForScene( + userId: string, + sceneId: string, + pagination: Pagination, + sorting: Sorting +): Promise<[SceneAsset[], number]> { + const { page, limit, skip } = pagination; + const { sortBy, sortOrder } = sorting; + const [assets, total] = await Promise.all([ + SceneAssetModel.find({ + sceneId, + userId, + deletedAt: { $exists: false }, + }) + .sort(sortBy ? { [sortBy]: sortOrder } : { createdAt: -1 }) + .skip(skip) + .limit(limit), + SceneAssetModel.countDocuments({ + sceneId, + userId, + deletedAt: { $exists: false }, + }), + ]); + return [assets, total]; +} + +export async function getAllDeletedAssets( + userId: string, + sceneId: string, + pagination: Pagination, + sorting: Sorting +): Promise<[SceneAsset[], number]> { + const { page, limit, skip } = pagination; + const { sortBy, sortOrder } = sorting; + const [assets, total] = await Promise.all([ + SceneAssetModel.find({ + sceneId, + userId, + deletedAt: { $exists: true }, + }) + .sort(sortBy ? { [sortBy]: sortOrder } : { createdAt: -1 }) + .skip(skip) + .limit(limit), + SceneAssetModel.countDocuments({ + sceneId, + userId, + deletedAt: { $exists: true }, + }), + ]); + return [assets, total]; +} + +export async function restoreAllDeletedAssets( + userId: string, + sceneId: string +): Promise<{ restoredCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assetsToRestore = await SceneAssetModel.find({ + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + assertHasDeletedAssets(assetsToRestore); + + const bulkOps = assetsToRestore.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $unset: { deletedAt: 1 } }, + }, + })); + const result = await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { restoredCount: result.modifiedCount }; + }); +} + +export async function softDeleteAllAssetsForScene( + userId: string, + sceneId: string +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assetsToDelete = await SceneAssetModel.find({ + userId, + sceneId, + deletedAt: { $exists: false }, + }).session(session); + + assertHasNonDeletedAssets(assetsToDelete); + + const scenes = await SceneModel.find({ + activeAssetId: { $in: assetsToDelete.map((a) => a._id) }, + }).session(session); + if (scenes.length > 0) { + throw new BadRequestError( + `Cannot delete an active asset. Please unset it as active from ${scenes.map((s) => s._id).join(', ')} before deletion or Force delete instead.` + ); + } + + const bulkOps = assetsToDelete.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $set: { deletedAt: new Date() } }, + }, + })); + + const result = await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: result.modifiedCount }; + }); +} + +export async function permanentDeleteAllAssetsForScene( + userId: string, + sceneId: string +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assetsToDelete = await SceneAssetModel.find({ + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + + assertHasDeletedAssets(assetsToDelete); + + const bulkOps = assetsToDelete.map((asset) => ({ + deleteOne: { filter: { _id: asset._id } }, + })); + + const result = await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: result.deletedCount || 0 }; + }); +} + +export async function getAssetCount(userId: string, sceneId: string): Promise { + await validateSceneOwnership(userId, sceneId); + + const count = await SceneAssetModel.countDocuments({ + sceneId, + userId, + deletedAt: { $exists: false }, + }); + + return count; +} + +// Bulk Op services +export async function softBulkDeleteAssets( + userId: string, + sceneId: string, + assetIds: string[] +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + sceneId, + deletedAt: { $exists: false }, + }).session(session); + + if (assets.length !== assetIds.length) { + throw new BadRequestError('Some assets were not found or already deleted'); + } + + const scenes = await SceneModel.find({ + activeAssetId: { $in: assetIds }, + }).session(session); + if (scenes.length > 0) { + throw new BadRequestError( + `Cannot delete an active asset. Please unset it as active from ${scenes.map((s) => s._id).join(', ')} before deletion or Force delete instead.` + ); + } + + const bulkOps = assets.map((asset) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { $set: { deletedAt: new Date() } }, + }, + })); + + await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: assets.length }; + }); +} + +export async function permanentBulkDeleteAssets( + userId: string, + sceneId: string, + assetIds: string[] +): Promise<{ deletedCount: number }> { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + + if (assets.length !== assetIds.length) { + throw new BadRequestError('Some assets were not found'); + } + + const bulkOps = assets.map((asset) => ({ + deleteOne: { filter: { _id: asset._id } }, + })); + + await SceneAssetModel.bulkWrite(bulkOps, { session }); + + return { deletedCount: assets.length }; + }); +} + +export async function bulkRestoreAssets( + userId: string, + sceneId: string, + assetIds: string[] +): Promise { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + + const assets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + sceneId, + deletedAt: { $exists: true }, + }).session(session); + + if (assets.length !== assetIds.length) { + throw new BadRequestError('Some assets were not found or not deleted'); + } + + const bulkOps = assets.map((asset, index) => ({ + updateOne: { + filter: { _id: asset._id }, + update: { + $unset: { deletedAt: 1 }, + }, + }, + })); + await SceneAssetModel.bulkWrite(bulkOps, { session }); + + const restoredAssets = await SceneAssetModel.find({ + _id: { $in: assetIds }, + userId, + }) + .sort({ order: 1 }) + .lean() + .session(session); + await session.commitTransaction(); + return restoredAssets; + }); +} + +// Single Op services +export async function getAssetById(userId: string, assetId: string): Promise { + const asset = await validateAssetOwnership(userId, assetId); + return asset; +} + +export async function getActiveAssetForScene(userId: string, sceneId: string): Promise { + const scene = await validateSceneOwnership(userId, sceneId); + + if (!scene.activeAssetId) { + return null; + } + + const asset = await SceneAssetModel.findOne({ + _id: scene.activeAssetId, + userId, + deletedAt: { $exists: false }, + }); + + if (!asset) { + throw new ConflictError('The Asset does not exists'); + } + + return asset; +} + +export async function generateVideoAsset( + userId: string, + sceneId: string, + grade?: number +): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + try { + const scene = await validateSceneOwnership(userId, sceneId, session); + const user = await validateUser(userId, session); + + if (user.planEndsAt && user.planEndsAt <= new Date()) { + throw new BadRequestError('Plan has expired. Please renew to generate new assets.'); + } + + // wait and check plan permissions + await assertFeaturePermission({ + userId: user._id, + action: 'TXT_TO_VIDEO_GEN', + grade: grade || 1, + }); + + // Deduct credits if applicable + if (grade && grade > 1) { + const creditsUsed = await getCreditCost('TXT_TO_VIDEO_GEN', grade); + await consumeCredits(userId, creditsUsed, session); + } + + // Placeholder logic for video generation + const generatedVideoUrl = `/generated/videos/${sceneId}-${Date.now()}.mp4`; + const asset = new SceneAssetModel({ + userId, + sceneId, + type: 'video', + url: generatedVideoUrl, + visibility: 'public', + generationSource: 'ai', + version: await getNextVersionNumber(sceneId), + }); + await asset.save(); + return asset; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function generateImageAsset(userId: string, sceneId: string) { + const scene = await validateSceneOwnership(userId, sceneId); + // Placeholder logic for image generation +} + +export async function uploadVideoAsset( + userId: string, + sceneId: string, + file: Express.Multer.File +): Promise<{ asset: SceneAsset; videoUrl: string }> { + const scene = await validateSceneOwnership(userId, sceneId); + let duration: number; + + try { + duration = await getVideoDuration(file.path); + } catch { + await fs.unlink(file.path); + throw new BadRequestError('Invalid or corrupted video file'); + } + + console.log('Video duration:', duration, 'Scene duration:', scene.duration); + console.log('Difference:', Math.abs(duration - (scene.duration || 0))); + + if (scene.duration !== undefined && Math.abs(duration - scene.duration) > 0.25) { + await fs.unlink(file.path); + throw new BadRequestError('Video duration does not match existing scene duration and cannot be uploaded'); + } + // TODO: Add video to cloud storage here and get the URL + const videoUrl = `/uploads/videos/${file.filename}`; + const asset = new SceneAssetModel({ + userId, + sceneId, + type: 'video', + url: videoUrl, + visibility: 'public', + format: file.mimetype.split('/')[1] || undefined, + version: await getNextVersionNumber(sceneId), + duration, + }); + await asset.save(); + + await fs.unlink(file.path); + + return { asset, videoUrl }; +} + +export async function uploadImageAsset( + userId: string, + sceneId: string, + file: Express.Multer.File +): Promise { + await validateSceneOwnership(userId, sceneId); + //TODO: Add Image to cloud storage and get URL + const imageUrl = `/uploads/images/${file.filename}`; + const asset = new SceneAssetModel({ + userId, + sceneId, + type: 'image', + url: imageUrl, + visibility: 'public', + format: file.mimetype.split('/')[1] || undefined, + version: await getNextVersionNumber(sceneId), + }); + await asset.save(); + + await fs.unlink(file.path); + + return asset; +} + +export async function setActiveAsset(userId: string, sceneId: string, assetId: string): Promise { + return withTransaction(async (session) => { + await validateSceneOwnership(userId, sceneId, session); + const asset = await validateAssetOwnership(userId, assetId, session); + assertAssetNotDeleted(asset); + + await SceneModel.findByIdAndUpdate(sceneId, { activeAssetId: assetId }, { session }); + + return asset; + }); +} + +export async function softDeleteAsset(userId: string, assetId: string): Promise { + return withTransaction(async (session) => { + const asset = await validateAssetOwnership(userId, assetId, session); + assertAssetNotDeleted(asset); + + const activeAssetScenes = await SceneModel.find({ + activeAssetId: assetId, + }).session(session); + + if (activeAssetScenes.length > 0) { + throw new BadRequestError( + `Cannot delete an active asset. Please unset it as active from ${activeAssetScenes.map((scene) => scene._id).join(', ')} before deletion.` + ); + } + + await SceneAssetModel.findByIdAndUpdate(assetId, { deletedAt: new Date() }, { new: true, session }); + + await session.commitTransaction(); + return; + }); +} + +export async function forceDeleteActiveAsset(userId: string, assetId: string): Promise { + const asset = await validateAssetOwnership(userId, assetId); + const scene = await validateSceneOwnership(userId, asset.sceneId.toString()); + assertAssetNotDeleted(asset); + + if (scene.activeAssetId && scene.activeAssetId.equals(asset._id)) { + await SceneModel.findByIdAndUpdate( + asset.sceneId, + { + $unset: { activeAssetId: 1 }, + }, + { runValidators: true } + ); + } + await SceneAssetModel.findByIdAndUpdate(assetId, { deletedAt: new Date() }, { new: true }); + return; +} + +export async function permanentDeleteAsset(userId: string, assetId: string): Promise { + const session = await mongoose.startSession(); + session.startTransaction(); + try { + const asset = await validateAssetOwnership(userId, assetId, session); + assertAssetNotDeleted(asset); + const activeAssetScenes = await SceneModel.find({ + activeAssetId: assetId, + }).session(session); + for (const scene of activeAssetScenes) { + await SceneModel.findByIdAndUpdate(scene._id, { $unset: { activeAssetId: 1 } }, { session }); + } + const deletedAsset = await SceneAssetModel.findByIdAndUpdate( + assetId, + { deletedAt: new Date() }, + { new: true, session } + ); + await session.commitTransaction(); + return deletedAsset!; + } catch (error) { + await session.abortTransaction(); + throw error; + } finally { + session.endSession(); + } +} + +export async function restoreAsset(userId: string, assetId: string): Promise { + const asset = await validateAssetOwnership(userId, assetId); + assertAssetIsDeleted(asset); + + const restoredAsset = await SceneAssetModel.findByIdAndUpdate( + assetId, + { $unset: { deletedAt: 1 } }, + { new: true } + ); + + if (!restoredAsset) { + throw new NotFoundError('Asset not found'); + } + + return restoredAsset; +} diff --git a/src/modules/scenes/scenes.controller.ts b/src/modules/scenes/scenes.controller.ts index 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..e1c429b 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 { paginationAndSortingMiddleware } from '@middleware/paginationAndSorting.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/request/paginationAndSorting.js'; import { asyncHandler } from '@utils/asyncHandler.js'; import { projectIdParamSchema } from '@validation/project.schema.js'; import { validateParams } from '@validation/validateParams.js'; import { validateBody } from '@validation/validateBody.js'; -import { addStoryContextSchema, createStorySchema, regenerateStorySchema, setStoryContextSchema, storyIdParamSchema, updateStorySchema, writeContentSchema } from '@validation/story.schema.js'; +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..fd72b0d 100644 --- a/src/modules/story/story.service.ts +++ b/src/modules/story/story.service.ts @@ -1,111 +1,187 @@ - 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'; +import { consumeCredits } from '@modules/credit/credit.service.js'; + +export async function getUserStories(userId: string, pagination: Pagination, sorting: Sorting) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, status: { $in: ['active', 'draft'] } }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, status: { $in: ['active', 'draft'] } }) as Promise, + ]); + + return [stories, total]; +} + +export async function getUserDeletedStories(userId: string, pagination: Pagination, sorting: Sorting) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, status: 'delete' }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, status: 'delete' }) as Promise, + ]); + + return [stories, total]; +} + +export async function getUserArchivedStories(userId: string, pagination: Pagination, sorting: Sorting) { + const [stories, total] = await Promise.all([ + StoryModel.find({ userId, status: 'archive' }) + .skip(pagination.skip) + .limit(pagination.limit) + .sort({ [sorting.sortBy]: sorting.sortOrder }), + StoryModel.countDocuments({ userId, status: 'archive' }) as Promise, + ]); + + return [stories, total]; +} + +export async function getProjectStories( userId: string, + projectId: string, pagination: Pagination, sorting: Sorting ) { const [stories, total] = await Promise.all([ - StoryModel.find({ userId }) + 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 project = await ProjectModel.findOne({ _id: projectId, userId }); + if (!project) { + throw new NotFoundError('Project not found'); + } + if (!project.defaultContextProfileId) { + throw new ConflictError('Project does not have a default context profile set'); + } + const story = await StoryModel.create({ userId, projectId, + contextProfileId: project.defaultContextProfileId, title: payload.title, description: payload.description, timeLimit: payload.timeLimit, platform: payload.platform, intent: payload.intent, - status: "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 +192,6 @@ export async function addStoryContextService( story.contextProfileId = newContext._id; await story.save({ session }); - await session.commitTransaction(); return { story, contextMeta: { @@ -126,51 +201,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 +241,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 +249,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 +268,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 +282,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 +294,188 @@ 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", - }, - }, - { new: true, runValidators: true } - ); + return withTransaction(async (session) => { + const story = await validateStoryOwnership(userId, storyId, session); + const contextProfile = await ContextProfileModel.findById(story.contextProfileId).session(session); + + console.log(userId) + const prompt = generateStoryPrompt({ + title: story.title, + description: story.description, + intent: story.intent, + platform: story.platform, + timeLimit: story.timeLimit, + contextProfile: contextProfile, + }); + + await consumeCredits(userId, 10, session); + let response; + try { + response = await openRouterAI(prompt); + } catch (err) { + throw new ConflictError('AI generation failed, please try again.'); + } + const rawcontent = response.choices[0].message?.content || ''; + if (!rawcontent) { + throw new ConflictError('AI generation returned empty content, please try again.'); + } + const content = safeParseJSON(rawcontent); + if (!content.story || !content.summary) { + throw new ConflictError('Error parsing AI generated content, please try again.'); + } - return updatedStory; + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId }, + { + $set: { + content: { + body: content.story, + summary: content.summary, + keywords: content.keywords || [], + tags: content.tags || [], + }, + authorType: 'ai', + status: 'active', + }, + }, + { new: true, runValidators: true, session } + ); + return updatedStory; + }); } -export async function regenerateStory( - userId: string, - storyId: string, - extraPrompt: RegenerateStoryInput -) { - 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, + }); + await consumeCredits(userId, 5, session); + 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); + if (!content.story || !content.summary) { + throw new ConflictError('Error parsing AI regenerated content, please try again.'); + } + const updatedStory = await StoryModel.findOneAndUpdate( + { _id: storyId, userId }, + { + $set: { + content: { + body: content.story, + summary: content.summary, + keywords: content.keywords || [], + tags: content.tags || [], + }, + authorType: 'ai', + }, + }, + { + new: true, + runValidators: true, + session, + } + ); + return updatedStory; + }); } -export async function updateStory( - userId: string, - storyId: string, - payload: Partial -) { - 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.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/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/modules/videoConfig/index.ts b/src/modules/videoConfig/index.ts new file mode 100644 index 0000000..0cffd74 --- /dev/null +++ b/src/modules/videoConfig/index.ts @@ -0,0 +1,3 @@ +// export { default as videoConfigRoutes } from './videoConfig.routes.js'; +// export { default as videoConfigController } from './videoConfig.controller.js'; +// export { default as videoConfigService } from './videoConfig.service.js'; diff --git a/src/modules/videoConfig/videoConfig.controller.ts b/src/modules/videoConfig/videoConfig.controller.ts new file mode 100644 index 0000000..8ad3190 --- /dev/null +++ b/src/modules/videoConfig/videoConfig.controller.ts @@ -0,0 +1,379 @@ +// import { Request, Response, NextFunction } from 'express'; +// import { Types } from 'mongoose'; +// import videoConfigService, { createVideoConfig } from './videoConfig.service.js'; +// import { asyncHandler } from '@utils/asyncHandler.js'; +// import { CreateVideoConfigType } from '@validation/videoConfig.schema.js'; + +// // ============ Create Video Config ============ + +// export const createVideoConfigController = async (req: Request, res: Response) => { +// const userId = req.user?.id; +// const requestInput = req.validatedBody as CreateVideoConfigType + +// const videoConfig = await createVideoConfig({ +// userId, +// ...requestInput + +// }); + +// res.status(201).json({ +// success: true, +// message: 'Video configuration created successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Get Video Config By ID ============ + +// export const getVideoConfigById = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const populate = req.query.populate ? (req.query.populate as string).split(',') : undefined; + +// const videoConfig = await videoConfigService.getVideoConfigById(configId, userId, populate); + +// res.status(200).json({ +// success: true, +// data: videoConfig, +// }); +// }); + +// // ============ Get Video Configs ============ + +// export const getVideoConfigs = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); + +// const result = await videoConfigService.getVideoConfigs({ +// userId, +// storyId: req.query.storyId ? new Types.ObjectId(req.query.storyId as string) : undefined, +// projectId: req.query.projectId ? new Types.ObjectId(req.query.projectId as string) : undefined, +// isTemplate: req.query.isTemplate !== undefined ? req.query.isTemplate === 'true' : undefined, +// page: parseInt(req.query.page as string) || 1, +// limit: parseInt(req.query.limit as string) || 20, +// sortBy: req.query.sortBy as string, +// sortOrder: req.query.sortOrder as 'asc' | 'desc', +// }); + +// res.status(200).json({ +// success: true, +// data: result.data, +// pagination: result.pagination, +// }); +// }); + +// // ============ Update Video Config ============ + +// export const updateVideoConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// // Transform ObjectId strings if present +// const updates = { ...req.body }; +// if (updates.sceneOrder) { +// updates.sceneOrder = updates.sceneOrder.map((id: string) => new Types.ObjectId(id)); +// } +// if (updates.narration?.narrationId) { +// updates.narration.narrationId = new Types.ObjectId(updates.narration.narrationId); +// } +// if (updates.narration?.audioAssetId) { +// updates.narration.audioAssetId = new Types.ObjectId(updates.narration.audioAssetId); +// } + +// const videoConfig = await videoConfigService.updateVideoConfig(configId, userId, updates); + +// res.status(200).json({ +// success: true, +// message: 'Video configuration updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Delete Video Config ============ + +// export const deleteVideoConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// await videoConfigService.deleteVideoConfig(configId, userId); + +// res.status(200).json({ +// success: true, +// message: 'Video configuration deleted successfully', +// }); +// }); + +// // ============ Update Narration Config ============ + +// export const updateNarrationConfig = asyncHandler( +// async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const narrationConfig = { +// ...req.body, +// narrationId: new Types.ObjectId(req.body.narrationId), +// audioAssetId: req.body.audioAssetId ? new Types.ObjectId(req.body.audioAssetId) : undefined, +// }; + +// const videoConfig = await videoConfigService.updateNarrationConfig(configId, userId, narrationConfig); + +// res.status(200).json({ +// success: true, +// message: 'Narration configuration updated successfully', +// data: videoConfig, +// }); +// } +// ); + +// // ============ Update Caption Config ============ + +// export const updateCaptionConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateCaptionConfig(configId, userId, req.body); + +// res.status(200).json({ +// success: true, +// message: 'Caption configuration updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Add Sound Effect ============ + +// export const addSoundEffect = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const soundEffect = { +// ...req.body, +// audioAssetId: new Types.ObjectId(req.body.audioAssetId), +// }; + +// const videoConfig = await videoConfigService.addSoundEffect(configId, userId, soundEffect); + +// res.status(201).json({ +// success: true, +// message: 'Sound effect added successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Sound Effect ============ + +// export const updateSoundEffect = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); +// const index = parseInt(req.params.index); + +// const soundEffect = { +// ...req.body.soundEffect, +// audioAssetId: new Types.ObjectId(req.body.soundEffect.audioAssetId), +// }; + +// const videoConfig = await videoConfigService.updateSoundEffect(configId, userId, index, soundEffect); + +// res.status(200).json({ +// success: true, +// message: 'Sound effect updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Remove Sound Effect ============ + +// export const removeSoundEffect = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); +// const index = parseInt(req.params.index); + +// const videoConfig = await videoConfigService.removeSoundEffect(configId, userId, index); + +// res.status(200).json({ +// success: true, +// message: 'Sound effect removed successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Scene Order ============ + +// export const updateSceneOrder = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const sceneOrder = req.body.sceneOrder.map((id: string) => new Types.ObjectId(id)); +// const sceneTiming = req.body.sceneTiming?.map((timing: { sceneId: string }) => ({ +// ...timing, +// sceneId: new Types.ObjectId(timing.sceneId), +// })); + +// const videoConfig = await videoConfigService.updateSceneOrder(configId, userId, sceneOrder, sceneTiming); + +// res.status(200).json({ +// success: true, +// message: 'Scene order updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Transitions ============ + +// export const updateTransitions = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateTransitions(configId, userId, req.body.transitions); + +// res.status(200).json({ +// success: true, +// message: 'Transitions updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Output Settings ============ + +// export const updateOutputSettings = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateOutputSettings(configId, userId, req.body); + +// res.status(200).json({ +// success: true, +// message: 'Output settings updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Update Background Audio ============ + +// export const updateBackgroundAudio = asyncHandler( +// async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const backgroundAudio = { +// ...req.body, +// audioAssetId: req.body.audioAssetId ? new Types.ObjectId(req.body.audioAssetId) : undefined, +// }; + +// const videoConfig = await videoConfigService.updateBackgroundAudio(configId, userId, backgroundAudio); + +// res.status(200).json({ +// success: true, +// message: 'Background audio updated successfully', +// data: videoConfig, +// }); +// } +// ); + +// // ============ Update Watermark ============ + +// export const updateWatermark = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.updateWatermark(configId, userId, req.body); + +// res.status(200).json({ +// success: true, +// message: 'Watermark updated successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Validate For Rendering ============ + +// export const validateForRendering = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const result = await videoConfigService.validateForRendering(configId, userId); + +// res.status(200).json({ +// success: true, +// data: result, +// }); +// }); + +// // ============ Clone Video Config ============ + +// export const cloneVideoConfig = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const configId = new Types.ObjectId(req.params.configId); + +// const videoConfig = await videoConfigService.cloneVideoConfig( +// configId, +// userId, +// req.body.name, +// req.body.description +// ); + +// res.status(201).json({ +// success: true, +// message: 'Video configuration cloned successfully', +// data: videoConfig, +// }); +// }); + +// // ============ Get Templates ============ + +// export const getTemplates = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); +// const page = parseInt(req.query.page as string) || 1; +// const limit = parseInt(req.query.limit as string) || 20; + +// const result = await videoConfigService.getTemplates(userId, page, limit); + +// res.status(200).json({ +// success: true, +// data: result.data, +// pagination: result.pagination, +// }); +// }); + +// // ============ Apply Template ============ + +// export const applyTemplate = asyncHandler(async (req: Request, res: Response, _next: NextFunction) => { +// const userId = new Types.ObjectId(req.user!._id); + +// const videoConfig = await videoConfigService.applyTemplate( +// new Types.ObjectId(req.body.templateId), +// userId, +// new Types.ObjectId(req.body.storyId), +// new Types.ObjectId(req.body.projectId), +// req.body.name +// ); + +// res.status(201).json({ +// success: true, +// message: 'Template applied successfully', +// data: videoConfig, +// }); +// }); + +// export default { +// createVideoConfig, +// getVideoConfigById, +// getVideoConfigs, +// updateVideoConfig, +// deleteVideoConfig, +// updateNarrationConfig, +// updateCaptionConfig, +// addSoundEffect, +// updateSoundEffect, +// removeSoundEffect, +// updateSceneOrder, +// updateTransitions, +// updateOutputSettings, +// updateBackgroundAudio, +// updateWatermark, +// validateForRendering, +// cloneVideoConfig, +// getTemplates, +// applyTemplate, +// }; diff --git a/src/modules/videoConfig/videoConfig.routes.ts b/src/modules/videoConfig/videoConfig.routes.ts new file mode 100644 index 0000000..25202cf --- /dev/null +++ b/src/modules/videoConfig/videoConfig.routes.ts @@ -0,0 +1,107 @@ +// import { Router } from 'express'; +// import { validateBody } from '@validation/validateBody.js'; +// import { +// createVideoConfigSchema, +// updateVideoConfigSchema, +// updateNarrationConfigSchema, +// updateCaptionsConfigSchema, +// addSoundEffectSchema, +// updateSoundEffectSchema, +// updateSceneOrderSchema, +// updateTransitionsSchema, +// updateOutputSettingsSchema, +// updateBackgroundAudioSchema, +// updateWatermarkSchema, +// cloneVideoConfigSchema, +// applyTemplateSchema, +// } from '@validation/videoConfig.schema.js'; +// import { +// createVideoConfig, +// getVideoConfigById, +// getVideoConfigs, +// updateVideoConfig, +// deleteVideoConfig, +// updateNarrationConfig, +// updateCaptionConfig, +// addSoundEffect, +// updateSoundEffect, +// removeSoundEffect, +// updateSceneOrder, +// updateTransitions, +// updateOutputSettings, +// updateBackgroundAudio, +// updateWatermark, +// validateForRendering, +// cloneVideoConfig, +// getTemplates, +// applyTemplate, +// } from './videoConfig.controller.js'; +// import { asyncHandler } from '@utils/asyncHandler.js'; + +// const router = Router(); + +// router.post('/', validateBody(createVideoConfigSchema), asyncHandler(createVideoConfig)); + +// router.get('/', asyncHandler(getVideoConfigs)); + +// router.get('/templates', asyncHandler(getTemplates)); + +// router.post('/apply-template', validateBody(applyTemplateSchema), asyncHandler(applyTemplate)); + +// router.get('/:configId', asyncHandler(getVideoConfigById)); + +// router.patch('/:configId', validateBody(updateVideoConfigSchema), asyncHandler(updateVideoConfig)); + +// router.delete('/:configId', asyncHandler(deleteVideoConfig)); + +// router.patch( +// '/:configId/narration', +// validateBody(updateNarrationConfigSchema), +// asyncHandler(updateNarrationConfig) +// ); + +// router.patch( +// '/:configId/captions', +// validateBody(updateCaptionsConfigSchema), +// asyncHandler(updateCaptionConfig) +// ); + +// router.post('/:configId/sound-effects', validateBody(addSoundEffectSchema), asyncHandler(addSoundEffect)); + +// router.patch( +// '/:configId/sound-effects/:index', +// validateBody(updateSoundEffectSchema), +// asyncHandler(updateSoundEffect) +// ); + +// router.delete('/:configId/sound-effects/:index', asyncHandler(removeSoundEffect)); + +// router.patch('/:configId/scene-order', validateBody(updateSceneOrderSchema), asyncHandler(updateSceneOrder)); + +// router.patch( +// '/:configId/transitions', +// validateBody(updateTransitionsSchema), +// asyncHandler(updateTransitions) +// ); + +// router.patch( +// '/:configId/output-settings', +// validateBody(updateOutputSettingsSchema), +// asyncHandler(updateOutputSettings) +// ); + +// router.patch( +// '/:configId/background-audio', +// validateBody(updateBackgroundAudioSchema), +// asyncHandler(updateBackgroundAudio) +// ); + +// // Validate configuration for rendering +// router.post('/:configId/validate', asyncHandler(validateForRendering)); + +// // ============ Clone Routes ============ + +// // Clone a video configuration +// router.post('/:configId/clone', validateBody(cloneVideoConfigSchema), asyncHandler(cloneVideoConfig)); + +// export default router; diff --git a/src/modules/videoConfig/videoConfig.service.ts b/src/modules/videoConfig/videoConfig.service.ts new file mode 100644 index 0000000..6d9b7e3 --- /dev/null +++ b/src/modules/videoConfig/videoConfig.service.ts @@ -0,0 +1,639 @@ +// import { Types, FilterQuery, SortOrder } from 'mongoose'; +// import VideoConfig, { +// IVideoConfig, +// ISoundEffectConfig, +// ISceneTimingConfig, +// ITransitionConfig, +// INarrationConfig, +// ICaptionConfig, +// IOutputSettings, +// IBackgroundAudioConfig, +// IWatermarkConfig, +// } from '@models/VideoConfig.js'; +// import { AppError } from '../../middleware/error/appError'; +// import { VIDEO_CONFIG_ERROR_MESSAGES, MAX_SOUND_EFFECTS_PER_CONFIG } from '../../constants/videoConfigConsts'; +// import { validateVideoConfigOwnership } from '../../validators/validateVideoConfigOwnership'; + +// // ============ Types ============ + +// interface CreateVideoConfigInput { +// userId: Types.ObjectId; +// storyId: Types.ObjectId; +// projectId: Types.ObjectId; +// name: string; +// description?: string; +// sceneOrder: Types.ObjectId[]; +// sceneTiming?: ISceneTimingConfig[]; +// narration: INarrationConfig; +// captions?: ICaptionConfig; +// soundEffects?: ISoundEffectConfig[]; +// transitions?: ITransitionConfig[]; +// backgroundAudio?: IBackgroundAudioConfig; +// watermark?: IWatermarkConfig; +// outputSettings?: IOutputSettings; +// isTemplate?: boolean; +// templateName?: string; +// } + +// interface UpdateVideoConfigInput { +// name?: string; +// description?: string; +// sceneOrder?: Types.ObjectId[]; +// sceneTiming?: ISceneTimingConfig[]; +// narration?: INarrationConfig; +// captions?: ICaptionConfig; +// soundEffects?: ISoundEffectConfig[]; +// transitions?: ITransitionConfig[]; +// backgroundAudio?: IBackgroundAudioConfig; +// watermark?: IWatermarkConfig; +// outputSettings?: IOutputSettings; +// isTemplate?: boolean; +// templateName?: string; +// } + +// interface GetVideoConfigsQuery { +// userId: Types.ObjectId; +// storyId?: Types.ObjectId; +// projectId?: Types.ObjectId; +// isTemplate?: boolean; +// page?: number; +// limit?: number; +// sortBy?: string; +// sortOrder?: 'asc' | 'desc'; +// } + +// interface PaginatedResult { +// data: T[]; +// pagination: { +// total: number; +// page: number; +// limit: number; +// totalPages: number; +// hasNextPage: boolean; +// hasPrevPage: boolean; +// }; +// } + +// // ============ Service Functions ============ + +// /** +// * Create a new video configuration +// */ +// export async function createVideoConfig(input: CreateVideoConfigInput): Promise { +// const { +// userId, +// storyId, +// projectId, +// name, +// description, +// sceneOrder, +// sceneTiming, +// narration, +// captions, +// soundEffects, +// transitions, +// backgroundAudio, +// watermark, +// outputSettings, +// isTemplate, +// templateName, +// } = input; + +// // Validate sound effects count +// if (soundEffects && soundEffects.length > MAX_SOUND_EFFECTS_PER_CONFIG) { +// throw new AppError(VIDEO_CONFIG_ERROR_MESSAGES.TOO_MANY_SOUND_EFFECTS, 400); +// } + +// // Generate scene timing if not provided +// let finalSceneTiming = sceneTiming; +// if (!finalSceneTiming || finalSceneTiming.length === 0) { +// finalSceneTiming = sceneOrder.map((sceneId, index) => ({ +// sceneId, +// order: index, +// startTime: index * 5, // Default 5 seconds per scene +// duration: 5, +// })); +// } + +// // Calculate total duration from scene timing +// const totalDuration = calculateTotalDuration(finalSceneTiming); + +// const videoConfig = new VideoConfig({ +// userId, +// storyId, +// projectId, +// name, +// description, +// sceneOrder, +// sceneTiming: finalSceneTiming, +// totalDuration, +// narration, +// captions: captions || {}, +// soundEffects: soundEffects || [], +// videoEffects: [], // Video effects are stored but not used yet +// transitions: transitions || generateDefaultTransitions(sceneOrder.length), +// backgroundAudio: backgroundAudio || {}, +// watermark: watermark || {}, +// outputSettings: outputSettings || {}, +// isTemplate: isTemplate || false, +// templateName, +// }); + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Get a video configuration by ID +// */ +// export async function getVideoConfigById( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// populate?: string[] +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId, { +// populate, +// }); +// return videoConfig; +// } + +// /** +// * Get all video configurations for a user with pagination +// */ +// export async function getVideoConfigs(query: GetVideoConfigsQuery): Promise> { +// const { +// userId, +// storyId, +// projectId, +// isTemplate, +// page = 1, +// limit = 20, +// sortBy = 'createdAt', +// sortOrder = 'desc', +// } = query; + +// // Build filter +// const filter: FilterQuery = { userId }; + +// if (storyId) filter.storyId = storyId; +// if (projectId) filter.projectId = projectId; +// if (isTemplate !== undefined) filter.isTemplate = isTemplate; + +// // Build sort +// const sort: Record = { +// [sortBy]: sortOrder === 'asc' ? 1 : -1, +// }; + +// // Calculate skip +// const skip = (page - 1) * limit; + +// // Execute query +// const [data, total] = await Promise.all([ +// VideoConfig.find(filter).sort(sort).skip(skip).limit(limit).lean(), +// VideoConfig.countDocuments(filter), +// ]); + +// const totalPages = Math.ceil(total / limit); + +// return { +// data: data as IVideoConfig[], +// pagination: { +// total, +// page, +// limit, +// totalPages, +// hasNextPage: page < totalPages, +// hasPrevPage: page > 1, +// }, +// }; +// } + +// /** +// * Update a video configuration +// */ +// export async function updateVideoConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// updates: UpdateVideoConfigInput +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// // Validate sound effects count if provided +// if (updates.soundEffects && updates.soundEffects.length > MAX_SOUND_EFFECTS_PER_CONFIG) { +// throw new AppError(VIDEO_CONFIG_ERROR_MESSAGES.TOO_MANY_SOUND_EFFECTS, 400); +// } + +// // Apply updates +// Object.assign(videoConfig, updates); + +// // Recalculate total duration if scene timing changed +// if (updates.sceneTiming) { +// videoConfig.totalDuration = calculateTotalDuration(updates.sceneTiming); +// } + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Delete a video configuration +// */ +// export async function deleteVideoConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string +// ): Promise { +// await validateVideoConfigOwnership(configId, userId); +// await VideoConfig.findByIdAndDelete(configId); +// } + +// /** +// * Update narration configuration +// */ +// export async function updateNarrationConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// narrationConfig: INarrationConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.narration = narrationConfig; + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update caption configuration +// */ +// export async function updateCaptionConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// captionConfig: ICaptionConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.captions = captionConfig; + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Add a sound effect to a video configuration +// */ +// export async function addSoundEffect( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// soundEffect: ISoundEffectConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// // Check max sound effects +// if (videoConfig.soundEffects.length >= MAX_SOUND_EFFECTS_PER_CONFIG) { +// throw new AppError(VIDEO_CONFIG_ERROR_MESSAGES.TOO_MANY_SOUND_EFFECTS, 400); +// } + +// // Validate start time is within video duration +// if (soundEffect.startTime > videoConfig.totalDuration) { +// throw new AppError( +// `Sound effect start time (${soundEffect.startTime}s) exceeds video duration (${videoConfig.totalDuration}s)`, +// 400 +// ); +// } + +// videoConfig.soundEffects.push(soundEffect); +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update a sound effect in a video configuration +// */ +// export async function updateSoundEffect( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// index: number, +// soundEffect: ISoundEffectConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// if (index < 0 || index >= videoConfig.soundEffects.length) { +// throw new AppError('Sound effect index out of range', 400); +// } + +// videoConfig.soundEffects[index] = soundEffect; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Remove a sound effect from a video configuration +// */ +// export async function removeSoundEffect( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// index: number +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// if (index < 0 || index >= videoConfig.soundEffects.length) { +// throw new AppError('Sound effect index out of range', 400); +// } + +// videoConfig.soundEffects.splice(index, 1); +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update scene order and timing +// */ +// export async function updateSceneOrder( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// sceneOrder: Types.ObjectId[], +// sceneTiming?: ISceneTimingConfig[] +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.sceneOrder = sceneOrder; + +// if (sceneTiming) { +// videoConfig.sceneTiming = sceneTiming; +// videoConfig.totalDuration = calculateTotalDuration(sceneTiming); +// } else { +// // Generate new timing based on new order +// videoConfig.sceneTiming = sceneOrder.map((sceneId, index) => ({ +// sceneId, +// order: index, +// startTime: index * 5, +// duration: 5, +// })); +// videoConfig.totalDuration = calculateTotalDuration(videoConfig.sceneTiming); +// } + +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update transitions +// */ +// export async function updateTransitions( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// transitions: ITransitionConfig[] +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.transitions = transitions; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update output settings +// */ +// export async function updateOutputSettings( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// outputSettings: IOutputSettings +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.outputSettings = outputSettings; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update background audio +// */ +// export async function updateBackgroundAudio( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// backgroundAudio: IBackgroundAudioConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.backgroundAudio = backgroundAudio; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Update watermark settings +// */ +// export async function updateWatermark( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// watermark: IWatermarkConfig +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// videoConfig.watermark = watermark; +// await videoConfig.save(); +// return videoConfig; +// } + +// /** +// * Validate a video configuration for rendering +// */ +// export async function validateForRendering( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string +// ): Promise<{ isValid: boolean; errors: string[] }> { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId, { +// populate: ['sceneOrder'], +// }); + +// const errors: string[] = []; + +// // Check scene order +// if (!videoConfig.sceneOrder || videoConfig.sceneOrder.length === 0) { +// errors.push('At least one scene is required'); +// } + +// // Check narration +// if (!videoConfig.narration?.narrationId) { +// errors.push('Narration is required'); +// } + +// // Check total duration +// if (videoConfig.totalDuration <= 0) { +// errors.push('Total duration must be greater than 0'); +// } + +// // Check sound effects timing +// for (let i = 0; i < videoConfig.soundEffects.length; i++) { +// const effect = videoConfig.soundEffects[i]; +// if (effect.enabled && effect.startTime > videoConfig.totalDuration) { +// errors.push(`Sound effect "${effect.name}" starts after video ends`); +// } +// } + +// // Check narration timing +// const narration = videoConfig.narration; +// if (narration.enabled) { +// const effectiveStart = narration.startOffset; +// const effectiveEnd = videoConfig.totalDuration - narration.endOffset; + +// if (effectiveStart >= effectiveEnd) { +// errors.push('Narration start offset and end offset overlap'); +// } +// } + +// const isValid = errors.length === 0; + +// return { isValid, errors }; +// } + +// /** +// * Clone a video configuration +// */ +// export async function cloneVideoConfig( +// configId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// newName: string, +// newDescription?: string +// ): Promise { +// const { videoConfig } = await validateVideoConfigOwnership(configId, userId); + +// const clonedConfig = new VideoConfig({ +// userId: videoConfig.userId, +// storyId: videoConfig.storyId, +// projectId: videoConfig.projectId, +// name: newName, +// description: newDescription || videoConfig.description, +// sceneOrder: [...videoConfig.sceneOrder], +// sceneTiming: videoConfig.sceneTiming.map((t) => ({ ...t })), +// totalDuration: videoConfig.totalDuration, +// narration: { ...videoConfig.narration }, +// captions: { ...videoConfig.captions }, +// soundEffects: videoConfig.soundEffects.map((s) => ({ ...s })), +// videoEffects: videoConfig.videoEffects.map((v) => ({ ...v })), +// transitions: videoConfig.transitions.map((t) => ({ ...t })), +// backgroundAudio: { ...videoConfig.backgroundAudio }, +// watermark: { ...videoConfig.watermark }, +// outputSettings: { ...videoConfig.outputSettings }, +// isTemplate: false, +// version: 1, +// }); + +// await clonedConfig.save(); +// return clonedConfig; +// } + +// /** +// * Get templates for a user +// */ +// export async function getTemplates( +// userId: Types.ObjectId | string, +// page = 1, +// limit = 20 +// ): Promise> { +// return getVideoConfigs({ +// userId: new Types.ObjectId(userId), +// isTemplate: true, +// page, +// limit, +// }); +// } + +// /** +// * Apply a template to create a new video configuration +// */ +// export async function applyTemplate( +// templateId: Types.ObjectId | string, +// userId: Types.ObjectId | string, +// storyId: Types.ObjectId | string, +// projectId: Types.ObjectId | string, +// name: string +// ): Promise { +// const { videoConfig: template } = await validateVideoConfigOwnership(templateId, userId); + +// if (!template.isTemplate) { +// throw new AppError('The specified configuration is not a template', 400); +// } + +// const newConfig = new VideoConfig({ +// userId: new Types.ObjectId(userId), +// storyId: new Types.ObjectId(storyId), +// projectId: new Types.ObjectId(projectId), +// name, +// description: template.description, +// sceneOrder: [], // Will be populated separately +// sceneTiming: [], +// totalDuration: 0, +// narration: { ...template.narration, narrationId: undefined, audioAssetId: undefined }, +// captions: { ...template.captions }, +// soundEffects: [], // Sound effects need to be re-added +// videoEffects: template.videoEffects.map((v) => ({ ...v })), +// transitions: template.transitions.map((t) => ({ ...t })), +// backgroundAudio: { ...template.backgroundAudio, audioAssetId: undefined }, +// watermark: { ...template.watermark }, +// outputSettings: { ...template.outputSettings }, +// isTemplate: false, +// version: 1, +// }); + +// await newConfig.save(); +// return newConfig; +// } + +// // ============ Helper Functions ============ + +// /** +// * Calculate total duration from scene timing +// */ +// function calculateTotalDuration(sceneTiming: ISceneTimingConfig[]): number { +// if (!sceneTiming || sceneTiming.length === 0) { +// return 0; +// } + +// return sceneTiming.reduce((maxEnd, scene) => { +// const sceneEnd = scene.startTime + (scene.customDuration || scene.duration); +// return Math.max(maxEnd, sceneEnd); +// }, 0); +// } + +// /** +// * Generate default transitions between scenes +// */ +// function generateDefaultTransitions(sceneCount: number): ITransitionConfig[] { +// const transitions: ITransitionConfig[] = []; + +// for (let i = 0; i < sceneCount - 1; i++) { +// transitions.push({ +// fromSceneIndex: i, +// toSceneIndex: i + 1, +// type: 'fade', +// duration: 0.5, +// easing: 'ease-in-out', +// }); +// } + +// return transitions; +// } + +// export default { +// createVideoConfig, +// getVideoConfigById, +// getVideoConfigs, +// updateVideoConfig, +// deleteVideoConfig, +// updateNarrationConfig, +// updateCaptionConfig, +// addSoundEffect, +// updateSoundEffect, +// removeSoundEffect, +// updateSceneOrder, +// updateTransitions, +// updateOutputSettings, +// updateBackgroundAudio, +// updateWatermark, +// validateForRendering, +// cloneVideoConfig, +// getTemplates, +// applyTemplate, +// }; diff --git a/src/routes/api.ts b/src/routes/api.ts index 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..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 { AccountStatus } from '@constants/userConsts.js'; +import { accountStatusResponses } from '@domain/policies/accountStatusResponses.js'; export function getAccountBlockResponse(status: AccountStatus | null | undefined) { return accountStatusResponses(status); diff --git a/src/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/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/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/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/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 f9a8466..a4870f6 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,15 @@ 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, + defaultContextProfileId: project.defaultContextProfileId, + contextProfileId: project.defaultContextProfileId, generationCounts: project.generationCounts, createdAt: project.createdAt, updatedAt: project.updatedAt, @@ -38,9 +36,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/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/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/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/validateAssetOwnership.ts b/src/validators/validateAssetOwnership.ts new file mode 100644 index 0000000..12bba57 --- /dev/null +++ b/src/validators/validateAssetOwnership.ts @@ -0,0 +1,22 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { SceneAsset, SceneAssetModel } from '@models/SceneAssets.js'; +import { ClientSession } from 'mongoose'; + +export async function validateAssetOwnership( + userId: string, + assetId: string, + session?: ClientSession +): Promise { + const query = SceneAssetModel.findOne({ + _id: assetId, + userId, + }); + + if (session) query.session(session); + + const asset = await query; + if (!asset) { + throw new NotFoundError('Asset not found or access denied'); + } + return asset; +} diff --git a/src/validators/validateAudioAssetOwnership.ts b/src/validators/validateAudioAssetOwnership.ts new file mode 100644 index 0000000..bb1831b --- /dev/null +++ b/src/validators/validateAudioAssetOwnership.ts @@ -0,0 +1,22 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { AudioAsset, AudioAssetModel } from '@models/AudioAsset.js'; +import { ClientSession } from 'mongoose'; + +export async function validateAudioAssetOwnership( + userId: string, + audioAssetId: string, + session?: ClientSession +): Promise { + const query = AudioAssetModel.findOne({ + _id: audioAssetId, + userId, + }); + + if (session) query.session(session); + + const audioAsset = await query; + if (!audioAsset) { + throw new NotFoundError('Audio asset not found or access denied'); + } + return audioAsset; +} diff --git a/src/validators/validateNarrationOwnership.ts b/src/validators/validateNarrationOwnership.ts new file mode 100644 index 0000000..2168fea --- /dev/null +++ b/src/validators/validateNarrationOwnership.ts @@ -0,0 +1,22 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { StoryNarration, StoryNarrationModel } from '@models/Narration.js'; +import { ClientSession } from 'mongoose'; + +export async function validateNarrationOwnership( + userId: string, + narrationId: string, + session?: ClientSession +): Promise { + const query = StoryNarrationModel.findOne({ + _id: narrationId, + userId, + }); + + if (session) query.session(session); + + const narration = await query; + if (!narration) { + throw new NotFoundError('Narration not found or access denied'); + } + return narration; +} diff --git a/src/validators/validateSceneOwnership.ts b/src/validators/validateSceneOwnership.ts new file mode 100644 index 0000000..b6c7aaf --- /dev/null +++ b/src/validators/validateSceneOwnership.ts @@ -0,0 +1,43 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { Scene, SceneModel } from '@models/Scene.js'; +import { ClientSession } from 'mongoose'; + +export async function validateSceneOwnership( + userId: string, + sceneId: string, + session?: ClientSession +): Promise { + const query = SceneModel.findOne({ + _id: sceneId, + userId, + }); + + if (session) query.session(session); + + const scene = await query; + if (!scene) { + throw new NotFoundError('Scene not found or access denied'); + } + return scene; +} + +export async function validateStorySceneOwnership( + userId: string, + sceneId: string, + storyId: string, + session?: ClientSession +): Promise { + const query = SceneModel.findOne({ + _id: sceneId, + userId, + storyId, + }); + + if (session) query.session(session); + + const scene = await query; + if (!scene) { + throw new NotFoundError('Scene not found or access denied'); + } + return scene; +} diff --git a/src/validators/validateStoryOwnership.ts b/src/validators/validateStoryOwnership.ts new file mode 100644 index 0000000..7b80a33 --- /dev/null +++ b/src/validators/validateStoryOwnership.ts @@ -0,0 +1,26 @@ +import { ClientSession } from 'mongoose'; +import { StoryModel } from '@models/Story.js'; +import { NotFoundError } from '@middleware/error/index.js'; +import { Story } from '@models/Story.js'; + +export async function validateStoryOwnership( + userId: string, + storyId: string, + session?: ClientSession +): Promise { + const query = StoryModel.findOne({ + _id: storyId, + userId, + }); + + if (session) { + query.session(session); + } + + const story = await query; + if (!story) { + throw new NotFoundError('Story not found or access denied'); + } + + return story; +} diff --git a/src/validators/validateUser.ts b/src/validators/validateUser.ts new file mode 100644 index 0000000..650a2cf --- /dev/null +++ b/src/validators/validateUser.ts @@ -0,0 +1,13 @@ +import { NotFoundError } from '@middleware/error/index.js'; +import { User, UserModel } from '@models/User.js'; +import { ClientSession } from 'mongoose'; + +export async function validateUser(userId: string, session?: ClientSession): Promise { + const query = UserModel.findById(userId); + if (session) query.session(session); + const user = await query; + if (!user) { + throw new NotFoundError('User not found'); + } + return user; +} diff --git a/src/validators/validateVideoConfigOwnership.ts b/src/validators/validateVideoConfigOwnership.ts new file mode 100644 index 0000000..20cf679 --- /dev/null +++ b/src/validators/validateVideoConfigOwnership.ts @@ -0,0 +1,48 @@ +import { Types } from 'mongoose'; +import VideoConfig, { IVideoConfig } from '@models/VideoConfig.js'; +import { VIDEO_CONFIG_ERROR_MESSAGES } from '@constants/videoConfigConsts.js'; +import { NotFoundError, UnauthorizedError } from '@middleware/error/index.js'; + +interface ValidateVideoConfigOwnershipResult { + videoConfig: IVideoConfig; +} + +export async function validateVideoConfigOwnership( + configId: string | Types.ObjectId, + userId: string | Types.ObjectId, + options: { + populate?: string | string[]; + } = {} +): Promise { + const { populate } = options; + + let query = VideoConfig.findById(configId); + + if (populate) { + if (Array.isArray(populate)) { + populate.forEach((field) => { + query = query.populate(field); + }); + } else { + query = query.populate(populate); + } + } + + const videoConfig = await query.exec(); + + if (!videoConfig) { + throw new NotFoundError(VIDEO_CONFIG_ERROR_MESSAGES.NOT_FOUND); + } + + // Check ownership + const configUserId = videoConfig.userId.toString(); + const requestUserId = userId.toString(); + + if (configUserId !== requestUserId) { + throw new UnauthorizedError(VIDEO_CONFIG_ERROR_MESSAGES.UNAUTHORIZED); + } + + return { videoConfig }; +} + +export default validateVideoConfigOwnership; diff --git a/tsconfig.json b/tsconfig.json index 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"]