All files / services media.service.ts

100% Statements 110/110
100% Branches 78/78
100% Functions 17/17
100% Lines 106/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                                                        5x 5x 5x     53x     1x       26x 26x 2x   24x       13x     13x 7x 1x       6x     6x 6x     13x 1x     6x                                 6x               4x 4x 1x       3x 6x     3x 3x   6x                                 3x       5x     5x 3x   3x 3x 2x   1x     3x 3x 1x     2x       4x     3x 2x 3x 2x 1x       3x             7x     7x 7x 1x       6x 6x 2x       4x 2x 3x 2x 1x       4x 4x 1x     3x                   4x 4x 4x 1x     3x 3x 2x     1x             3x 3x 1x     2x 2x 1x                 4x 12x   4x 1x         3x 3x 1x     2x 6x 1x           1x               2x 2x 1x     1x       19x 1x     18x 1x     17x 1x       16x 3x       1x         2x 1x             14x 13x 1x              
// Media Service - Business Logic Layer for images and videos
import type { Dal } from "../dal";
import type { Media, NewMedia } from "../db/schema";
import { NotFoundError, ValidationError, ForbiddenError } from "../lib/errors";
 
export type CreateMediaInput = {
	roomId: number;
	mediaType: "image" | "video";
	filename: string;
	originalFilename?: string;
	storageKey: string;
	thumbnailKey?: string;
	width?: number;
	height?: number;
	fileSize?: number;
	durationSeconds?: number;
	caption?: string;
	altText?: string;
	isCover?: boolean;
};
 
export type UpdateMediaInput = {
	caption?: string;
	altText?: string;
	isCover?: boolean;
};
 
// Video constraints
const MAX_VIDEO_DURATION_SECONDS = 5 * 60; // 5 minutes
const MAX_VIDEO_FILE_SIZE = 500 * 1024 * 1024; // 500 MB
const MAX_IMAGE_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
 
export class MediaService {
	constructor(private dal: Dal) {}
 
	async getByRoomId(roomId: number): Promise<Media[]> {
		return this.dal.media.findByRoomId(roomId);
	}
 
	async getById(id: number): Promise<Media> {
		const media = await this.dal.media.findById(id);
		if (!media) {
			throw new NotFoundError("Media", String(id));
		}
		return media;
	}
 
	async create(input: CreateMediaInput): Promise<Media> {
		this.validateInput(input);
 
		// Verify room exists
		const room = await this.dal.rooms.findById(input.roomId);
		if (!room) {
			throw new NotFoundError("Room", String(input.roomId));
		}
 
		// Auto-assign sort order
		const maxSort = await this.dal.media.getMaxSortOrder(input.roomId);
 
		// Check if this is the first media item in the room - make it cover
		const mediaCount = await this.dal.media.countByRoomId(input.roomId);
		const isCover = input.isCover ?? mediaCount === 0;
 
		// If setting as cover, clear existing cover
		if (isCover && mediaCount > 0) {
			await this.dal.media.setCoverImage(input.roomId, -1); // Clears existing
		}
 
		const mediaData: NewMedia = {
			roomId: input.roomId,
			mediaType: input.mediaType,
			filename: input.filename,
			originalFilename: input.originalFilename,
			storageKey: input.storageKey,
			thumbnailKey: input.thumbnailKey,
			width: input.width,
			height: input.height,
			fileSize: input.fileSize,
			durationSeconds: input.durationSeconds,
			caption: input.caption,
			altText: input.altText,
			sortOrder: maxSort + 1,
			isCover,
		};
 
		return this.dal.media.create(mediaData);
	}
 
	async createMany(
		roomId: number,
		items: Array<Omit<CreateMediaInput, "roomId">>,
	): Promise<Media[]> {
		// Verify room exists
		const room = await this.dal.rooms.findById(roomId);
		if (!room) {
			throw new NotFoundError("Room", String(roomId));
		}
 
		// Validate all items
		for (const item of items) {
			this.validateInput({ ...item, roomId });
		}
 
		const maxSort = await this.dal.media.getMaxSortOrder(roomId);
		const existingCount = await this.dal.media.countByRoomId(roomId);
 
		const mediaData: NewMedia[] = items.map((item, idx) => ({
			roomId,
			mediaType: item.mediaType,
			filename: item.filename,
			originalFilename: item.originalFilename,
			storageKey: item.storageKey,
			thumbnailKey: item.thumbnailKey,
			width: item.width,
			height: item.height,
			fileSize: item.fileSize,
			durationSeconds: item.durationSeconds,
			caption: item.caption,
			altText: item.altText,
			sortOrder: maxSort + idx + 1,
			isCover: existingCount === 0 && idx === 0, // First item becomes cover if room is empty
		}));
 
		return this.dal.media.createMany(mediaData);
	}
 
	async update(id: number, input: UpdateMediaInput): Promise<Media> {
		const media = await this.getById(id);
 
		// If setting as cover, handle cover switching
		if (input.isCover === true) {
			await this.dal.media.setCoverImage(media.roomId, id);
			// Remove isCover from input since we handled it
			const { isCover: _, ...restInput } = input;
			if (Object.keys(restInput).length === 0) {
				return this.getById(id); // Return updated media
			}
			input = restInput as UpdateMediaInput;
		}
 
		const updated = await this.dal.media.update(id, input);
		if (!updated) {
			throw new NotFoundError("Media", String(id));
		}
 
		return updated;
	}
 
	async delete(id: number): Promise<void> {
		const media = await this.getById(id);
 
		// If deleting cover, assign next item as cover
		if (media.isCover) {
			const roomMedia = await this.dal.media.findByRoomId(media.roomId);
			const nextCover = roomMedia.find((m) => m.id !== id);
			if (nextCover) {
				await this.dal.media.update(nextCover.id, { isCover: true });
			}
		}
 
		await this.dal.media.delete(id);
	}
 
	/**
	 * Move media to a different room
	 */
	async moveToRoom(mediaId: number, newRoomId: number): Promise<Media> {
		const media = await this.getById(mediaId);
 
		// Verify new room exists
		const newRoom = await this.dal.rooms.findById(newRoomId);
		if (!newRoom) {
			throw new NotFoundError("Room", String(newRoomId));
		}
 
		// Verify both rooms belong to the same project
		const oldRoom = await this.dal.rooms.findById(media.roomId);
		if (!oldRoom || oldRoom.projectId !== newRoom.projectId) {
			throw new ValidationError("Cannot move media between different projects");
		}
 
		// If moving the cover, assign new cover in old room
		if (media.isCover) {
			const roomMedia = await this.dal.media.findByRoomId(media.roomId);
			const nextCover = roomMedia.find((m) => m.id !== mediaId);
			if (nextCover) {
				await this.dal.media.update(nextCover.id, { isCover: true });
			}
		}
 
		const moved = await this.dal.media.moveToRoom(mediaId, newRoomId);
		if (!moved) {
			throw new NotFoundError("Media", String(mediaId));
		}
 
		return moved;
	}
 
	/**
	 * Verifies that media belongs to a pro's project
	 */
	async verifyProOwnership(
		mediaId: number,
		proId: string,
	): Promise<Media> {
		const media = await this.getById(mediaId);
		const room = await this.dal.rooms.findById(media.roomId);
		if (!room) {
			throw new NotFoundError("Room", String(media.roomId));
		}
 
		const project = await this.dal.projects.findById(room.projectId);
		if (!project || project.proId !== proId) {
			throw new ForbiddenError("Media does not belong to your pro");
		}
 
		return media;
	}
 
	/**
	 * Verifies that a room belongs to a pro's project
	 */
	async verifyRoomOwnership(roomId: number, proId: string): Promise<void> {
		const room = await this.dal.rooms.findById(roomId);
		if (!room) {
			throw new NotFoundError("Room", String(roomId));
		}
 
		const project = await this.dal.projects.findById(room.projectId);
		if (!project || project.proId !== proId) {
			throw new ForbiddenError("Room does not belong to your pro");
		}
	}
 
	/**
	 * Reorder media within a room
	 */
	async reorder(roomId: number, mediaIds: number[]): Promise<void> {
		// Verify all media belongs to the room
		const existingMedia = await this.dal.media.findByRoomId(roomId);
		const existingIds = new Set(existingMedia.map((m) => m.id));
 
		if (mediaIds.length !== existingMedia.length) {
			throw new ValidationError(
				`All ${existingMedia.length} media items must be included in reorder`,
			);
		}
 
		const uniqueIds = new Set(mediaIds);
		if (uniqueIds.size !== mediaIds.length) {
			throw new ValidationError("Duplicate media IDs in reorder request");
		}
 
		for (const id of mediaIds) {
			if (!existingIds.has(id)) {
				throw new ValidationError(
					`Media ${id} does not belong to room ${roomId}`,
				);
			}
		}
 
		await this.dal.media.updateSortOrder(mediaIds);
	}
 
	/**
	 * Set cover image for a room
	 */
	async setCoverImage(roomId: number, mediaId: number): Promise<void> {
		// Verify media belongs to room
		const media = await this.getById(mediaId);
		if (media.roomId !== roomId) {
			throw new ValidationError("Media does not belong to this room");
		}
 
		await this.dal.media.setCoverImage(roomId, mediaId);
	}
 
	private validateInput(input: CreateMediaInput): void {
		if (!input.filename?.trim()) {
			throw new ValidationError("Filename is required");
		}
 
		if (!input.storageKey?.trim()) {
			throw new ValidationError("Storage key is required");
		}
 
		if (!["image", "video"].includes(input.mediaType)) {
			throw new ValidationError("Media type must be 'image' or 'video'");
		}
 
		// Validate video constraints
		if (input.mediaType === "video") {
			if (
				input.durationSeconds &&
				input.durationSeconds > MAX_VIDEO_DURATION_SECONDS
			) {
				throw new ValidationError(
					`Video duration cannot exceed ${MAX_VIDEO_DURATION_SECONDS / 60} minutes`,
				);
			}
 
			if (input.fileSize && input.fileSize > MAX_VIDEO_FILE_SIZE) {
				throw new ValidationError(
					`Video file size cannot exceed ${MAX_VIDEO_FILE_SIZE / (1024 * 1024)} MB`,
				);
			}
		}
 
		// Validate image constraints
		if (input.mediaType === "image") {
			if (input.fileSize && input.fileSize > MAX_IMAGE_FILE_SIZE) {
				throw new ValidationError(
					`Image file size cannot exceed ${MAX_IMAGE_FILE_SIZE / (1024 * 1024)} MB`,
				);
			}
		}
	}
}