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.

5.8 KB
Raw Blame
import { ADDON_IDS } from '../../addons';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { Public } from '../auth-core/public.decorator';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import {
  answerRenditionPending,
  pendingOrNone,
  PublicMediaService,
  RENDITION_PENDING,
} from '../memories/public-media.service';
import { StorageService } from '../storage/storage.service';
import { JourneyService } from './journey.service';
import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common';
import { journeyPublicMapLayersResponseSchema, journeyPublicResponseSchema } from '@trek/shared';

import type { Response } from 'express';
import path from 'node:path';

/**
 * /api/public/journey — unauthenticated, share-token validated read + photo
 * proxy for publicly shared journeys.
 *
 * Byte-identical to the legacy Express route (server/src/routes/journeyPublic.ts):
 * no authentication, every route validates the share token (404 on failure),
 * the unified proxy streams by trek_photo_id and the legacy proxy serves local
 * files (with the uploads-dir traversal guard) or proxies immich/synology.
 * A local file never leaves here as stored: both proxies send its
 * location-free copy (PublicMediaService), or nothing.
 *
 * The addon gate is the one guard here, and it has to be: turning the Journey
 * addon off is meant to take the feature away, and without it already-published
 * journeys stayed publicly readable while the authenticated surface went dark.
 * AddonGuard only reads addon state, so it is safe in front of a @Public route.
 */
@Public('share-token validated: the whole point is a link that works without an account')
@UseGuards(AddonGuard)
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
@Controller('api/public/journey')
export class JourneyPublicController {
  constructor(
    private readonly journey: JourneyService,
    private readonly storage: StorageService,
    private readonly publicMedia: PublicMediaService,
  ) {}

  /**
   * The shared journey. Its contract is strict: a column that is not named
   * there (a storage key, an asset id, an author) fails every test that reaches
   * this route instead of going out to the public.
   */
  @Get(':token')
  @ResponseContract(journeyPublicResponseSchema)
  async get(@Param('token') token: string) {
    const data = await this.journey.getPublicJourney(token);
    if (!data) {
      throw new HttpException({ error: 'Not found' }, 404);
    }
    return data;
  }

  /**
   * What the shared map shows beside the entries and photos (JRN-04), cut to
   * the link's flags on the server: nothing while the map is not shared.
   */
  @Get(':token/map-layers')
  @ResponseContract(journeyPublicMapLayersResponseSchema)
  async mapLayers(@Param('token') token: string) {
    const layers = await this.journey.getPublicMapLayers(token);
    if (!layers) {
      throw new HttpException({ error: 'Not found' }, 404);
    }
    return layers;
  }

  @Get(':token/photos/:photoId/:kind')
  async photo(
    @Param('token') token: string,
    @Param('photoId', rowId('Not found')) photoId: number,
    @Param('kind') kind: string,
    @Res() res: Response,
  ): Promise<void> {
    const valid = await this.journey.validateShareTokenForPhoto(token, photoId);
    if (!valid) {
      throw new HttpException({ error: 'Not found' }, 404);
    }
    await this.journey.streamPhoto(res, valid.ownerId, photoId, kind === 'thumbnail' ? 'thumbnail' : 'original');
  }

  @Get(':token/photo/:provider/:assetId/:ownerId/:kind')
  async legacyPhoto(
    @Param('token') token: string,
    @Param('provider') provider: string,
    @Param('assetId') assetId: string,
    @Param('kind') kind: string,
    @Res() res: Response,
  ): Promise<void> {
    const valid = await this.journey.validateShareTokenForAsset(token, assetId);
    if (!valid) {
      throw new HttpException({ error: 'Not found' }, 404);
    }

    const wantThumb = kind === 'thumbnail' ? 'thumbnail' : 'original';

    if (provider === 'local') {
      // Local journey assets are flat filenames. basename() kept for shape;
      // containment now lives in central storage key validation
      // (storage-keys.ts), which subsumes the old journeyDir startsWith guard.
      const name = path.basename(assetId);
      if (!(await this.storage.exists('journey', name).catch(() => false))) {
        throw new HttpException({ error: 'Not found' }, 404);
      }
      // The copy without GPS and place tags, never the stored original; a file
      // that cannot be cleaned is not served at all.
      const rendition = await this.publicMedia.renditionFor('journey', name).catch(pendingOrNone);
      if (rendition === RENDITION_PENDING) {
        answerRenditionPending(res);
        return;
      }
      if (!rendition) {
        throw new HttpException({ error: 'Not found' }, 404);
      }
      res.set('Cache-Control', 'public, max-age=86400');
      await this.storage.sendToResponse('journey', rendition, res);
      return;
    }

    // :ownerId stays in the route pattern so old share links keep routing, but
    // it is not bound at all any more: the owner comes from the row the token
    // resolved to.
    const effectiveOwnerId = valid.ownerId;
    const streaming = this.journey.streamProviderAsset(
      res,
      provider,
      { userId: effectiveOwnerId, ownerId: effectiveOwnerId, assetId },
      wantThumb,
    );
    if (streaming === null) {
      res.status(404).json({ error: 'Provider not supported' });
      return;
    }
    try {
      await streaming;
    } catch {
      // Kept: a provider that throws mid-parse answered 404 here before, and a
      // share link that half-writes a response is worse than one that 404s.
      res.status(404).json({ error: 'Provider not supported' });
    }
  }
}