Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

12.1 KB
Raw Blame
import type { TrekPhoto } from '../../types';
import { decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { TrekPhotoRegistrationService } from '../photos/trek-photo-registration.service';
import { StorageService } from '../storage/storage.service';
import { fail, success, type AssetInfo, type ServiceResult } from './memories.helpers';
import type { PhotoAssetRef } from './photo-provider';
import { PhotoProviderRegistry } from './photo-provider.registry';
import { answerRenditionPending, pendingOrNone, PublicMediaService, RENDITION_PENDING } from './public-media.service';
import { ThumbnailService } from './thumbnail.service';
import { TrekPhotoCacheService } from './trek-photo-cache.service';
import { Injectable } from '@nestjs/common';

import { Response } from 'express';
import fsPromises from 'node:fs/promises';

/**
 * What a photo's quality signals are measured on (photos/photo-signals.service.ts):
 * a local original, or a provider's thumbnail with the original's size as the
 * provider reports it. `none` is nothing to measure, `unavailable` a provider
 * that did not answer now, which a later try may reach.
 */
export type PhotoSignalSource =
  | { kind: 'original'; bytes: Buffer }
  | { kind: 'thumbnail'; bytes: Buffer; width: number | null; height: number | null }
  | { kind: 'none' }
  | { kind: 'unavailable' };

/** Who a local file goes to: its owner or a member as stored, the public as a location-free copy. */
type Audience = 'owner' | 'public';

const THUMB_CACHE = 'public, max-age=86400, immutable';
const ORIGINAL_CACHE = 'public, max-age=86400';

/**
 * Resolves a stored trek_photo to bytes or metadata by asking whichever provider
 * owns it. The storage half of the old photoResolverService lives in
 * nest/photos/trek-photo-registration.service.ts; this is the dispatch half.
 *
 * It no longer knows WHICH providers exist (#584). It held ImmichService and
 * SynologyService and a `switch` over their ids; it holds the registry now, so
 * a third backend is a registration in memories.module.ts rather than a case
 * added in two places here and a third in journey-public.controller.ts.
 */
@Injectable()
export class PhotoResolverService {
  constructor(
    private readonly photos: TrekPhotoRegistrationService,
    private readonly thumbnails: ThumbnailService,
    private readonly cache: TrekPhotoCacheService,
    private readonly providers: PhotoProviderRegistry,
    private readonly storage: StorageService,
    private readonly publicMedia: PublicMediaService,
  ) {}

  /** photos.file_path / thumbnail_path are uploads-relative 'journey/…' by
   * every writer; anything else reads as a local miss, matching the old
   * existsSync(join(uploadsRoot, file_path)) === false path. */
  private storageName(relPath: string): string | null {
    return relPath.startsWith('journey/') ? relPath.slice('journey/'.length) : null;
  }

  // ── Streaming ────────────────────────────────────────────────────────────

  private async streamCachedThumbnail(
    res: Response,
    photo: TrekPhoto,
    fetchBytes: () => Promise<{ bytes: Buffer; contentType: string } | { error: string; status: number }>,
    fallback: () => Promise<unknown>,
  ): Promise<void> {
    const key = this.cache.cacheKey(photo.provider!, photo.asset_id!, 'thumbnail', photo.owner_id!);

    if (await this.cache.serveFresh(res, key)) return;

    const existing = this.cache.getInFlight(key);
    if (existing !== undefined) {
      const bytes = await existing;
      if (bytes && (await this.cache.serveFresh(res, key))) return;
      await fallback();
      return;
    }

    const promise = fetchBytes().then(async (result) => {
      if ('error' in result) return null;
      await this.cache.put(key, result.bytes, result.contentType);
      return result.bytes;
    });
    this.cache.setInFlight(key, promise);

    const bytes = await promise;
    if (bytes && (await this.cache.serveFresh(res, key))) return;
    await fallback();
  }

  /** An owner's or member's view: local files go out as stored. */
  async streamPhoto(
    res: Response,
    userId: number,
    photoId: number,
    kind: 'thumbnail' | 'original',
    range?: string,
  ): Promise<void> {
    await this.stream(res, userId, photoId, kind, range, 'owner');
  }

  /**
   * A public share's view. A local file goes out as its location-free copy
   * (PublicMediaService) and never as stored; one that cannot be cleaned falls
   * back to the thumbnail TREK re-encoded itself, else a 404. A provider is
   * told the asset goes to the public, so it can send a rendition without the
   * stored location in place of the original file.
   */
  async streamPublicPhoto(
    res: Response,
    ownerId: number,
    photoId: number,
    kind: 'thumbnail' | 'original',
  ): Promise<void> {
    await this.stream(res, ownerId, photoId, kind, undefined, 'public');
  }

  /**
   * Sends one local journey object. For the public a re-encoded thumbnail
   * (thumbs/, written by ThumbnailService, no metadata) goes out as is, anything
   * else as its location-free copy. False when there is nothing safe to send.
   */
  private async sendLocal(res: Response, relPath: string, audience: Audience, cacheControl: string): Promise<boolean> {
    const name = this.storageName(relPath);
    if (!name || !(await this.storage.exists('journey', name).catch(() => false))) return false;
    let served = name;
    if (audience === 'public' && !name.startsWith('thumbs/')) {
      const rendition = await this.publicMedia.renditionFor('journey', name).catch(pendingOrNone);
      if (rendition === RENDITION_PENDING) {
        answerRenditionPending(res);
        return true;
      }
      if (!rendition) return false;
      served = rendition;
    }
    res.set('Cache-Control', cacheControl);
    res.set('X-Content-Type-Options', 'nosniff');
    await this.storage.sendToResponse('journey', served, res);
    return true;
  }

  /**
   * The thumbnail row path, generated for a raster image that has none yet.
   *
   * @txStandalone an idempotent lazy provision: the row only records a
   * thumbnail that already exists in storage, whatever the caller does next.
   */
  private async localThumbnail(photo: TrekPhoto): Promise<string | null> {
    if (photo.thumbnail_path) return photo.thumbnail_path;
    // Only raster images get a lazily-generated Jimp thumbnail; Jimp can't decode
    // video, so a video relies on the poster captured at upload (#823).
    if (photo.media_type === 'video' || !photo.file_path) return null;
    const result = await this.thumbnails.ensureLocalThumbnail(photo.file_path);
    if (!result) return null;
    await this.photos.recordLocalThumbnail(photo.id, result.thumbnailRelPath, result.width, result.height);
    return result.thumbnailRelPath;
  }

  private async stream(
    res: Response,
    userId: number,
    photoId: number,
    kind: 'thumbnail' | 'original',
    range: string | undefined,
    audience: Audience,
  ): Promise<void> {
    const photo = await this.photos.resolve(photoId);
    if (!photo) {
      res.status(404).json({ error: 'Photo not found' });
      return;
    }

    if (photo.file_path) {
      if (kind === 'thumbnail') {
        const thumbRel = await this.localThumbnail(photo);
        if (thumbRel && (await this.sendLocal(res, thumbRel, audience, THUMB_CACHE))) return;
        // A poster-less video must NOT fall through to streaming the whole file as a
        // "thumbnail"; let the client render its own placeholder instead.
        if (photo.media_type === 'video') {
          res.status(404).json({ error: 'No poster available' });
          return;
        }
        // Images fall through to original if the thumbnail is unavailable.
      }

      if (await this.sendLocal(res, photo.file_path, audience, ORIGINAL_CACHE)) return;

      // A public original that could not be cleaned is stood in for by the
      // re-encoded thumbnail, never by the stored bytes.
      if (audience === 'public' && kind === 'original' && photo.media_type !== 'video') {
        const thumbRel = await this.localThumbnail(photo);
        if (thumbRel && (await this.sendLocal(res, thumbRel, audience, THUMB_CACHE))) return;
      }
    }

    // 'local' is not a provider: the bytes are on this disk, the block above
    // already tried to send them, and there is no backend left to ask.
    if (photo.provider === 'local') {
      res.status(404).json({ error: 'File not found' });
      return;
    }

    const provider = this.providers.get(photo.provider);
    if (!provider) {
      res.status(400).json({ error: `Unknown provider: ${photo.provider}` });
      return;
    }

    const ref = this.refFor(photo, userId);
    if (kind === 'thumbnail') {
      await this.streamCachedThumbnail(
        res,
        photo,
        () => provider.fetchThumbnailBytes(ref),
        // The fallback streams the thumbnail itself, so it carries no Range.
        () => provider.streamAsset(res, ref, kind),
      );
      return;
    }
    await provider.streamAsset(res, { ...ref, range, audience }, kind);
  }

  /**
   * The bytes a photo's quality signals are measured on, read with its
   * owner's access rather than a viewer's: the signals belong to the photo,
   * whoever asks. A local photo answers its original whole, so the size it
   * decodes to is the original's; a provider photo its thumbnail, since an
   * original can be hundreds of megabytes, with the size the provider reports.
   * `none` for a photo that is gone, a video, a local original over
   * `maxBytes` or missing, a provider TREK does not know.
   */
  async readForSignals(photoId: number, maxBytes: number): Promise<PhotoSignalSource> {
    const photo = await this.photos.resolve(photoId);
    if (!photo || photo.media_type === 'video') return { kind: 'none' };
    if (photo.file_path) {
      const name = this.storageName(photo.file_path);
      const stat = name ? await this.storage.stat('journey', name).catch(() => null) : null;
      if (!name || !stat || stat.size > maxBytes) return { kind: 'none' };
      const bytes = await this.storage.withLocalFile('journey', name, (p) => fsPromises.readFile(p));
      return { kind: 'original', bytes };
    }
    const provider = this.providers.get(photo.provider);
    if (!provider || photo.owner_id == null || !photo.asset_id) return { kind: 'none' };
    const ref = this.refFor(photo, photo.owner_id);
    const thumbnail = await provider.fetchThumbnailBytes(ref);
    if ('error' in thumbnail) return { kind: 'unavailable' };
    const info = await provider.getAssetInfo(ref);
    const size = info.success ? info.data : null;
    return { kind: 'thumbnail', bytes: thumbnail.bytes, width: size?.width ?? null, height: size?.height ?? null };
  }

  /**
   * The stored row as a provider-shaped request. One place decrypts the
   * Synology share passphrase, and one place decides which of the two user ids
   * means "whose credentials".
   */
  private refFor(photo: TrekPhoto, userId: number): PhotoAssetRef {
    return {
      userId,
      ownerId: photo.owner_id!,
      assetId: photo.asset_id!,
      passphrase: photo.passphrase ? decrypt_api_key(photo.passphrase) || undefined : undefined,
      mediaType: photo.media_type,
    };
  }

  // ── Asset Info ────────────────────────────────────────────────────────────

  async getPhotoInfo(userId: number, photoId: number): Promise<ServiceResult<AssetInfo>> {
    const photo = await this.photos.resolve(photoId);
    if (!photo) return fail('Photo not found', 404);

    // Local rows answer from the row itself — nothing to ask.
    if (photo.provider === 'local') {
      return success({
        id: String(photo.id),
        takenAt: photo.created_at,
        city: null,
        country: null,
        width: photo.width,
        height: photo.height,
        fileName: photo.file_path?.split('/').pop() || null,
      } as AssetInfo);
    }

    const provider = this.providers.get(photo.provider);
    if (!provider) return fail(`Unknown provider: ${photo.provider}`, 400);
    return provider.getAssetInfo(this.refFor(photo, userId));
  }
}