All files / src/modules/media media.service.ts

87.75% Statements 86/98
77.77% Branches 70/90
87.5% Functions 7/8
91.01% Lines 81/89

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 23119x 19x 19x 19x 19x 19x 19x 19x         19x     35x     35x 35x 35x 35x   35x   35x 35x 35x 35x     35x 34x                 34x   1x 1x                           10x 10x 10x 10x 2x       8x 8x 8x 8x 1x   7x 1x       6x 6x     6x 1x     5x 5x 5x                   3x 3x       2x                     2x 2x                     2x       8x   6x   5x   3x   3x   3x   3x 3x             6x       6x   6x   6x   6x         6x     6x                 3x   3x   1x 1x       2x 2x 1x       1x 1x 1x                       2x 2x     2x 1x       1x           1x         1x          
import { Injectable, Logger, Optional } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import { v4 as uuid } from 'uuid';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { R2SignedUrlService } from '@app/common/services/r2-signed-url.service';
 
type MediaType = 'IMAGE' | 'VIDEO' | 'FLOORPLAN';
 
@Injectable()
export class MediaService {
  private readonly r2: S3Client;
  private readonly bucket: string;
  private readonly logger = new Logger(MediaService.name);
 
  constructor(
    private readonly prisma: PrismaService,
    private readonly config: ConfigService,
    @InjectQueue('media') private readonly mediaQueue: Queue,
    @Optional() private readonly r2Signer?: R2SignedUrlService,
  ) {
    this.bucket = this.config.get<string>('R2_BUCKET', 'media-bucket');
 
    const endpoint = this.config.get<string>('R2_ENDPOINT');
    const region = this.config.get<string>('R2_REGION', 'us-east-1');
    const accessKeyId = this.config.get<string>('R2_ACCESS_KEY_ID');
    const secretAccessKey = this.config.get<string>('R2_SECRET_ACCESS_KEY');
 
    // Initialize R2 client only if credentials are available
    if (accessKeyId && secretAccessKey) {
      this.r2 = new S3Client({
        region: region,
        credentials: {
          accessKeyId,
          secretAccessKey,
        } as any,
        endpoint: endpoint || undefined,
        forcePathStyle: !!endpoint,
      });
      this.logger.log('R2 client initialized successfully');
    } else {
      this.logger.warn('R2 credentials not provided; media uploads will fail');
      this.r2 = null as any;
    }
  }
 
  /**
   * Upload raw media file, persist metadata.
   */
  async uploadMedia(
    file: any,
    type: MediaType,
    ownerId: number | null,
    listingId?: number,
  ) {
    // Validate size caps (configurable)
    const maxImageSize = parseInt(this.config.get<string>('UPLOAD_MAX_IMAGE_BYTES') || '10485760', 10); // 10MB
    const maxVideoSize = parseInt(this.config.get<string>('UPLOAD_MAX_VIDEO_BYTES') || '52428800', 10); // 50MB
    const sizeLimit = type === 'VIDEO' ? maxVideoSize : maxImageSize;
    if (!file || !file.buffer || file.buffer.length > sizeLimit) {
      throw new Error('File too large or invalid file');
    }
 
    // Enforce MIME + magic bytes detection (lightweight, no external deps)
    const mime = this.detectMimeType(file.buffer) || file.mimetype;
    const allowedImages = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    const allowedVideos = ['video/mp4', 'video/webm'];
    if (type === 'IMAGE' && !allowedImages.includes(mime)) {
      throw new Error('Invalid image type');
    }
    if (type === 'VIDEO' && !allowedVideos.includes(mime)) {
      throw new Error('Invalid video type');
    }
 
    // Sanitize filename to prevent path traversal attacks
    const sanitizedFilename = this.sanitizeFilename(file.originalname);
    const key = `media/original/${uuid()}-${sanitizedFilename}`;
 
    // Check if R2 is available
    if (!this.r2) {
      throw new Error('Media storage (R2) not configured. Cannot upload files.');
    }
 
    this.logger.debug(`Uploading media to R2. key=${key}`);
    try {
      await this.r2.send(
        new PutObjectCommand({
          Bucket: this.bucket,
          Key: key,
          Body: file.buffer,
          ContentType: mime,
          ACL: 'private', // Enforce private ACL for security
        }),
      );
    } catch (error) {
      this.logger.error(`Failed to upload media to R2: ${error}`);
      throw new Error('Failed to upload media file');
    }
 
    // @ts-ignore – generated after `prisma generate`
    const media = await this.prisma.client.media.create({
      data: {
        type,
        mimeType: mime,
        storageKey: key,
        ownerId: ownerId || undefined,
        listingId,
      },
    });
 
    // Enqueue processing job only if queue is available
    try {
      await this.mediaQueue.add('process', {
        id: media.id,
        type,
        storageKey: media.storageKey,
        mimeType: file.mimetype,
      });
    } catch (error) {
      this.logger.warn(`Failed to enqueue media processing job: ${error}`);
      // Continue without processing - media is still uploaded
    }
 
    return media;
  }
 
  private detectMimeType(buf: Buffer): string | undefined {
    if (!buf || buf.length < 4) return undefined;
    // JPEG
    if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg';
    // PNG
    if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return 'image/png';
    // GIF87a/89a
    Iif (buf.slice(0, 6).toString('ascii') === 'GIF87a' || buf.slice(0, 6).toString('ascii') === 'GIF89a') return 'image/gif';
    // WEBP (RIFF....WEBP)
    Iif (buf.slice(0, 4).toString('ascii') === 'RIFF' && buf.slice(8, 12).toString('ascii') === 'WEBP') return 'image/webp';
    // MP4 (ftyp marker at byte 4)
    Iif (buf.length > 12 && buf.slice(4, 8).toString('ascii') === 'ftyp') return 'video/mp4';
    // WebM (EBML)
    Iif (buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3) return 'video/webm';
    return undefined;
  }
 
  /**
   * Sanitize filename to prevent path traversal and other security issues
   */
  private sanitizeFilename(filename: string): string {
    Iif (!filename || typeof filename !== 'string') {
      return 'unnamed';
    }
    // Remove path traversal sequences
    let sanitized = filename.replace(/\.\./g, '').replace(/\/+/g, '').replace(/\\+/g, '');
    // Remove null bytes and other control characters
    sanitized = sanitized.replace(/\0/g, '').replace(/[\x00-\x1f\x7f]/g, '');
    // Remove leading/trailing dots and spaces (Windows issue)
    sanitized = sanitized.replace(/^[.\s]+|[.\s]+$/g, '');
    // Limit length
    Iif (sanitized.length > 255) {
      const ext = sanitized.substring(sanitized.lastIndexOf('.'));
      sanitized = sanitized.substring(0, 255 - ext.length) + ext;
    }
    // Ensure it's not empty
    Iif (!sanitized || sanitized.trim().length === 0) {
      return 'unnamed';
    }
    return sanitized;
  }
 
  /**
   * Build public URL (s3 or CDN). Override via CDN_BASE_URL env.
   * When R2_SIGNING_ENABLED=true, always returns signed URLs for private buckets.
   */
  async getPublicUrl(storageKey: string): Promise<string> {
    // 1️⃣ Feature-flag: presigned URL (enforce signed URLs for private buckets)
    const signingEnabled = this.config.get<string>('R2_SIGNING_ENABLED') === 'true' || 
                           this.config.get<boolean>('R2_SIGNING_ENABLED') === true;
    if (signingEnabled && this.r2Signer) {
      // Default TTL: 1 hour (3600 seconds)
      const ttl = parseInt(this.config.get<string>('R2_SIGNED_URL_TTL') || '3600', 10);
      return this.r2Signer.signGet(storageKey, ttl);
    }
 
    // 2️⃣ CDN rewrite (public bucket behind Cloudflare / CF Pages)
    const cdnBase = this.config.get<string>('CDN_BASE_URL');
    if (cdnBase) {
      return `${cdnBase.replace(/\/$/, '')}/${storageKey}`;
    }
 
    // 3️⃣ fallback to R2-style public URL (path-style using R2 endpoint or default hostname)
    const endpoint = this.config.get<string>('R2_ENDPOINT');
    if (endpoint) {
      return `${endpoint.replace(/\/$/, '')}/${storageKey}`;
    }
    return `https://${this.bucket}.r2.cloudflarestorage.com/${storageKey}`;
  }
 
  // @ts-ignore – generated after `prisma generate`
  findById(id: number) {
    return this.prisma.client.media.findUnique({ where: { id } });
  }
 
  async softDelete(id: number, requesterId: number, isAdmin = false) {
    // @ts-ignore – generated after `prisma generate`
    const media = await this.prisma.client.media.findUnique({ where: { id } });
    Iif (!media) {
      throw new Error('Media not found');
    }
    if (!isAdmin && media.ownerId !== requesterId) {
      throw new Error('Forbidden');
    }
 
    // Mark deletedAt; leave actual object removal to a GC job
    await this.prisma.client.media.update({
      where: { id },
      data: { deletedAt: new Date() },
    });
 
    // Optionally: enqueue a gc deletion job later
    return true;
  }
 
  async updateVariants(id: number, variants: Record<string, string>) {
    // @ts-ignore – generated after `prisma generate`
    await this.prisma.client.media.update({
      where: { id },
      data: { variants },
    });
  }
}