All files / services blog-images.service.ts

100% Statements 80/80
91.52% Branches 54/59
100% Functions 15/15
100% Lines 80/80

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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383            5x               5x 5x     5x                                                                                                           56x 56x             11x 11x 3x       8x 8x       8x   8x 3x                         14x     14x                     9x     9x 9x   9x         9x     9x                               1x 1x 1x   1x       1x 1x                                               6x     3x 2x   4x 1x     3x 3x                                               8x     8x 8x   1x   7x 1x           6x 6x 1x       5x     8x     5x 5x     5x   5x 8x       4x 4x                                         1x                         5x 5x 1x     4x         4x 1x     3x             2x             4x 4x 1x       3x     1x                     5x 5x 1x       4x   2x                     3x 3x 2x   1x                       3x 3x 2x   1x      
// Service Layer for Blog Images
import type { Dal } from "../dal";
import { ForbiddenError, NotFoundError, ValidationError } from "../lib/errors";
import { validateUploadedFile } from "../lib/file-validation";
import { generateId } from "../lib/utils";
 
const MIME_TO_EXT: Record<string, string> = {
	"image/jpeg": "jpg",
	"image/png": "png",
	"image/webp": "webp",
	"image/gif": "gif",
	"image/avif": "avif",
};
 
const extFromMime = (mime: string): string =>
	MIME_TO_EXT[mime.split(";")[0].trim()] || "jpg";
 
// SSRF guard: only ever fetch image bytes from Pexels' own hosts.
const PEXELS_HOSTS = ["images.pexels.com", "www.pexels.com", "pexels.com"];
 
export interface UploadBlogImageInput {
	file: File;
	altText?: string | null;
	caption?: string;
}
 
export interface AddMediaImageInput {
	mediaId: number;
	altText?: string | null;
	caption?: string;
}
 
export interface AddPexelsImageInput {
	pexelsId: string;
	url: string;
	width: number;
	height: number;
	altText?: string | null;
	photographer?: string;
	photographerUrl?: string;
}
 
export interface AddProjectImageInput {
	projectPhotoId: number;
	altText?: string | null;
	caption?: string;
}
 
export interface PexelsPhoto {
	id: number;
	width: number;
	height: number;
	url: string;
	photographer: string;
	photographer_url: string;
	src: {
		original: string;
		large: string;
		medium: string;
		small: string;
	};
}
 
export interface PexelsSearchResult {
	photos: PexelsPhoto[];
	total_results: number;
	page: number;
	per_page: number;
}
 
export class BlogImagesService {
	constructor(
		private dal: Dal,
		private env: CloudflareBindings,
	) {}
 
	/**
	 * Verify that a pro has access to a blog
	 */
	async verifyBlogAccess(blogId: string, proId: string): Promise<void> {
		const blog = await this.dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Check if pro created blog OR is featured in blog
		const isCreator = blog.ideaSourceProId === proId;
		const blogPros = await this.dal.blogPros.findAll({
			blogId,
			proId,
		});
		const isFeatured = blogPros.length > 0;
 
		if (!isCreator && !isFeatured) {
			throw new ForbiddenError("You don't have access to this blog");
		}
	}
 
	/**
	 * Build an R2 key for a blog image. Pro-authored blogs key under the pro's
	 * namespace; admin-authored blogs (no proId) key under `admin/blogs/...` —
	 * matching the existing admin cover-image key scheme.
	 */
	private blogImageKey(
		scope: { proId?: string; blogId: string },
		ext: string,
	): string {
		const base = scope.proId
			? `${scope.proId}/blogs/${scope.blogId}`
			: `admin/blogs/${scope.blogId}`;
		return `${base}/${generateId()}.${ext}`;
	}
 
	/**
	 * Upload a blog image to R2
	 */
	async uploadBlogImage(
		blogId: string,
		proId: string,
		input: UploadBlogImageInput,
	) {
		const { file, altText, caption } = input;
 
		// Upload to R2
		const ext = file.name.split(".").pop() || "jpg";
		const storageKey = this.blogImageKey({ proId, blogId }, ext);
 
		await this.env.R2.put(storageKey, await file.arrayBuffer(), {
			httpMetadata: { contentType: file.type },
		});
 
		// Get next sort order
		const sortOrder = await this.dal.blogImages.getNextSortOrder(blogId);
 
		// Create DB record
		return this.dal.blogImages.create({
			blogId,
			sourceType: "upload",
			storageKey,
			altText: altText || "",
			caption,
			fileSize: file.size,
			sortOrder,
		});
	}
 
	/**
	 * Upload a blog image for an ADMIN-authored blog (no owning pro). Gated at
	 * the route layer by requirePlatformAdmin, so no per-blog access check.
	 */
	async uploadAdminBlogImage(blogId: string, input: UploadBlogImageInput) {
		const { file, altText, caption } = input;
		const ext = file.name.split(".").pop() || "jpg";
		const storageKey = this.blogImageKey({ blogId }, ext);
 
		await this.env.R2.put(storageKey, await file.arrayBuffer(), {
			httpMetadata: { contentType: file.type },
		});
 
		const sortOrder = await this.dal.blogImages.getNextSortOrder(blogId);
		return this.dal.blogImages.create({
			blogId,
			sourceType: "upload",
			storageKey,
			altText: altText || "",
			caption,
			fileSize: file.size,
			sortOrder,
		});
	}
 
	/**
	 * Reference an existing pro-gallery media item (rooms → media) into the blog
	 * gallery. The R2 bytes are SHARED with the project gallery — we store the
	 * existing storageKey and must NEVER delete those bytes on blog-image delete.
	 *
	 * Pass `opts.proId` to scope the reference to that pro's own gallery (pro
	 * editor). Without it the caller may reference ANY pro's media (admin editor).
	 */
	async addMediaImage(
		blogId: string,
		input: AddMediaImageInput,
		opts?: { proId?: string },
	) {
		const media = opts?.proId
			? await this.dal.media.findByIdWithProId(input.mediaId)
			: await this.dal.media.findById(input.mediaId);
		if (!media) {
			throw new NotFoundError("Media not found");
		}
		if (opts?.proId && "proId" in media && media.proId !== opts.proId) {
			throw new ForbiddenError("You do not have access to this media");
		}
 
		const sortOrder = await this.dal.blogImages.getNextSortOrder(blogId);
		return this.dal.blogImages.create({
			blogId,
			sourceType: "media",
			sourceId: String(media.id),
			storageKey: media.storageKey, // reference — bytes owned by the pro gallery
			altText: input.altText ?? media.altText ?? "",
			caption: input.caption ?? media.caption ?? undefined,
			width: media.width,
			height: media.height,
			sortOrder,
		});
	}
 
	/**
	 * Add a Pexels stock image to the gallery by RE-HOSTING it to R2 (rather than
	 * hot-linking the external URL, which bypasses our /api/images rewriting and
	 * rots). Fetches the bytes server-side (SSRF-guarded to Pexels hosts),
	 * validates type/size, stores in R2, and records the R2 key as storageKey.
	 */
	async addPexelsImage(
		blogId: string,
		input: AddPexelsImageInput,
		opts?: { proId?: string },
	) {
		const { pexelsId, url, width, height, altText } = input;
 
		let host: string;
		try {
			host = new URL(url).hostname;
		} catch {
			throw new ValidationError("Invalid image URL");
		}
		if (!PEXELS_HOSTS.includes(host)) {
			throw new ValidationError("Image URL must be a Pexels URL");
		}
 
		// redirect: "manual" so the host allowlist above can't be bypassed by a
		// 3xx from a Pexels host to an arbitrary origin (a manual redirect yields
		// a non-ok response, which we reject below).
		const response = await fetch(url, { redirect: "manual" });
		if (!response.ok) {
			throw new ValidationError(
				`Failed to fetch image from Pexels (${response.status})`,
			);
		}
		const contentType = (response.headers.get("content-type") || "image/jpeg")
			.split(";")[0]
			.trim();
		const bytes = await response.arrayBuffer();
 
		// Reuse the upload validator (type + 10MB cap) by wrapping the bytes.
		const ext = extFromMime(contentType);
		const file = new File([bytes], `pexels-${pexelsId}.${ext}`, {
			type: contentType,
		});
		validateUploadedFile(file);
 
		const storageKey = this.blogImageKey({ proId: opts?.proId, blogId }, ext);
		await this.env.R2.put(storageKey, bytes, {
			httpMetadata: { contentType },
		});
 
		const sortOrder = await this.dal.blogImages.getNextSortOrder(blogId);
		return this.dal.blogImages.create({
			blogId,
			sourceType: "pexels",
			sourceId: pexelsId, // keep attribution
			storageKey, // R2 key (NOT the external URL)
			altText: altText || "",
			width,
			height,
			fileSize: bytes.byteLength,
			sortOrder,
		});
	}
 
	/**
	 * Copy a project photo to blog gallery (legacy — project_photos removed)
	 */
	async addProjectPhoto(
		_blogId: string,
		_proId: string,
		_input: AddProjectImageInput,
	) {
		throw new ValidationError(
			"Adding project photos to blogs is no longer supported via project_photos. Use media (rooms) instead.",
		);
	}
 
	/**
	 * Search Pexels API
	 */
	async searchPexels(
		query: string,
		page = 1,
		perPage = 20,
	): Promise<PexelsSearchResult> {
		const apiKey = this.env.PEXELS_API_KEY;
		if (!apiKey) {
			throw new Error("Pexels API key not configured");
		}
 
		const response = await fetch(
			`https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}`,
			{ headers: { Authorization: apiKey } },
		);
 
		if (!response.ok) {
			throw new Error(`Pexels API error: ${response.statusText}`);
		}
 
		return response.json();
	}
 
	/**
	 * Get all images for a blog
	 */
	async getBlogImages(blogId: string) {
		return this.dal.blogImages.findByBlogId(blogId);
	}
 
	/**
	 * Delete an image
	 */
	async deleteImage(imageId: number, proId: string) {
		const image = await this.dal.blogImages.findById(imageId);
		if (!image) {
			throw new NotFoundError("Image not found");
		}
 
		// Verify pro has access to the blog
		await this.verifyBlogAccess(image.blogId, proId);
 
		// Delete from DB (R2 cleanup can be done separately)
		await this.dal.blogImages.delete(imageId);
	}
 
	/**
	 * Update image metadata
	 */
	async updateImage(
		imageId: number,
		proId: string,
		data: { altText?: string; caption?: string },
	) {
		const image = await this.dal.blogImages.findById(imageId);
		if (!image) {
			throw new NotFoundError("Image not found");
		}
 
		// Verify pro has access to the blog
		await this.verifyBlogAccess(image.blogId, proId);
 
		return this.dal.blogImages.update(imageId, data);
	}
 
	/**
	 * Delete an image for an admin-authored blog (route-gated by admin auth, so
	 * no per-pro access check). Removes only the DB row — never the R2 bytes of
	 * a "media" source, which are owned by the pro gallery. The image must belong
	 * to the blog named in the URL, so a stale/forged blogId can't delete an
	 * unrelated blog's image by guessing its integer id.
	 */
	async deleteImageAdmin(imageId: number, blogId: string) {
		const image = await this.dal.blogImages.findById(imageId);
		if (!image || image.blogId !== blogId) {
			throw new NotFoundError("Image not found");
		}
		await this.dal.blogImages.delete(imageId);
	}
 
	/**
	 * Update image metadata for an admin-authored blog (route-gated by admin).
	 * The image must belong to the blog named in the URL (see deleteImageAdmin).
	 */
	async updateImageAdmin(
		imageId: number,
		blogId: string,
		data: { altText?: string; caption?: string },
	) {
		const image = await this.dal.blogImages.findById(imageId);
		if (!image || image.blogId !== blogId) {
			throw new NotFoundError("Image not found");
		}
		return this.dal.blogImages.update(imageId, data);
	}
}