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.

20.4 KB
Raw Blame
import { ADDON_IDS } from '../../addons';
import type { User } from '../../types';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write';
import { PLACE_IMAGE_FILE_FILTER } from '../common/place-image-upload';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { SpoolCleanupInterceptor } from '../common/spool-cleanup.interceptor';
import { CollectionGpxError } from '../place-import/place-import.types';
import { placeImageUrl } from '../places/place-image';
import { PlaceRatingDto } from '../places/places.dto';
import { StorageService } from '../storage/storage.service';
import {
  CollectionCreateDto,
  CollectionUpdateDto,
  CollectionReorderDto,
  CollectionDeleteManyDto,
  CollectionSavePlaceDto,
  CollectionSaveFromTripDto,
  CollectionSaveFromTripManyDto,
  CollectionPlaceUpdateDto,
  CollectionSetStatusDto,
  CollectionSetStatusManyDto,
  CollectionSetStatusFromTripDto,
  CollectionCopyToTripDto,
  CollectionInviteDto,
  CollectionInviteActionDto,
  CollectionInviteCancelDto,
  CollectionRemoveMemberDto,
  CollectionSetMemberRoleDto,
  CollectionLabelCreateDto,
  CollectionLabelUpdateDto,
  CollectionLabelAssignDto,
  CollectionImportDto,
  CollectionImportIntoDto,
  CollectionGpxReadDto,
} from './collections.dto';
import { CollectionsService } from './collections.service';
import {
  Body,
  Controller,
  Delete,
  Get,
  Headers,
  HttpCode,
  HttpException,
  Param,
  Patch,
  Post,
  Put,
  Query,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { collectionKmlExportSchema } from '@trek/shared';

import type { Options } from 'multer';
import path from 'path';

export const MAX_COVER_SIZE = 20 * 1024 * 1024;
// Duplicated on purpose from trips.controller.ts (historical parity — no
// drive-by consolidation). Quirk preserved: a plain Error without statusCode
// maps to 500, not 400. Passed inline on the cover route; the storage engine
// comes from collections.module.ts's storage-upload factory options.
const COVER_FILE_FILTER: Options['fileFilter'] = (_req, file, cb) => {
  const ext = path.extname(file.originalname).toLowerCase();
  const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
  if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) cb(null, true);
  else cb(new Error('Only jpg, png, gif, webp images allowed'));
};

/**
 * /api/addons/collections — saved-place library (lists, places, fusion sharing).
 *
 * The addon guard (404) runs before JwtAuthGuard so a disabled addon answers 404
 * regardless of auth. Access control lives in the service (assertAccess / isOwner
 * throw 404/403/400). /invite, /invite/cancel and /:id/available-users add an
 * explicit owner check in the controller so they cannot be used to enumerate.
 * The X-Socket-Id header is forwarded to the service so the originating client is
 * excluded from the WS broadcast.
 */
@Controller('api/addons/collections')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
export class CollectionsController {
  constructor(
    private readonly collections: CollectionsService,
    private readonly env: RuntimeEnvService,
    private readonly storage: StorageService,
  ) {}

  // ── Lists ─────────────────────────────────────────────────────────────────
  @Get()
  list(@CurrentUser() user: User) {
    return this.collections.listCollections(user.id);
  }

  @Post()
  create(@CurrentUser() user: User, @Body() body: CollectionCreateDto, @Headers('x-socket-id') socketId?: string) {
    return this.collections.createCollection(user.id, body, socketId);
  }

  @Post('reorder')
  @HttpCode(200)
  async reorder(
    @CurrentUser() user: User,
    @Body() body: CollectionReorderDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.reorderCollections(user.id, body.orderedIds, socketId);
    return { success: true };
  }

  // ── Places (static prefixes before /:id) ────────────────────────────────────
  @Post('places')
  @HttpCode(200)
  savePlace(
    @CurrentUser() user: User,
    @Body() body: CollectionSavePlaceDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.savePlace(user.id, body, socketId);
  }

  @Post('places/from-trip')
  @HttpCode(200)
  saveFromTrip(
    @CurrentUser() user: User,
    @Body() body: CollectionSaveFromTripDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.saveFromTripPlace(
      user.id,
      body.collection_id,
      body.source_trip_id,
      body.source_place_id,
      body.force,
      socketId,
    );
  }

  @Post('places/from-trip-many')
  @HttpCode(200)
  saveFromTripMany(
    @CurrentUser() user: User,
    @Body() body: CollectionSaveFromTripManyDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.saveFromTripPlaces(
      user.id,
      body.collection_id,
      body.source_trip_id,
      body.source_place_ids,
      body.force,
      socketId,
    );
  }

  @Post('places/delete-many')
  @HttpCode(200)
  async deleteMany(
    @CurrentUser() user: User,
    @Body() body: CollectionDeleteManyDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return { deleted: await this.collections.deletePlacesMany(user.id, body.ids, socketId) };
  }

  @Post('places/status-many')
  @HttpCode(200)
  setStatusMany(
    @CurrentUser() user: User,
    @Body() body: CollectionSetStatusManyDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.setStatusMany(user.id, body.ids, body.status, socketId);
  }

  @Post('places/status-from-trip')
  @HttpCode(200)
  setStatusFromTrip(
    @CurrentUser() user: User,
    @Body() body: CollectionSetStatusFromTripDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.setStatusFromTrip(user.id, body.trip_id, body.place_ids, body.status, socketId);
  }

  @Patch('places/:pid')
  updatePlace(
    @CurrentUser() user: User,
    @Param('pid', rowId('Place not found')) pid: number,
    @Body() body: CollectionPlaceUpdateDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.updatePlace(user.id, pid, body, socketId);
  }

  @Post('places/:pid/status')
  @HttpCode(200)
  setStatus(
    @CurrentUser() user: User,
    @Param('pid', rowId('Place not found')) pid: number,
    @Body() body: CollectionSetStatusDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.setStatus(user.id, pid, body.status, socketId);
  }

  @Put('places/:pid/rating')
  setRating(
    @CurrentUser() user: User,
    @Param('pid', rowId('Place not found')) pid: number,
    @Body() body: PlaceRatingDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.setRating(user.id, pid, body.rating, socketId);
  }

  @Delete('places/:pid/rating')
  clearRating(
    @CurrentUser() user: User,
    @Param('pid', rowId('Place not found')) pid: number,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.setRating(user.id, pid, null, socketId);
  }

  @Post('places/:pid/image')
  @HttpCode(200)
  @UseInterceptors(FileInterceptor('image', { fileFilter: PLACE_IMAGE_FILE_FILTER }), SpoolCleanupInterceptor)
  async uploadPlaceImage(
    @CurrentUser() user: User,
    @Param('pid', rowId('Place not found')) pid: number,
    @UploadedFile() file: Express.Multer.File | undefined,
    @Headers('x-socket-id') socketId?: string,
  ) {
    if (isDemoWriteBlocked(this.env, user.email)) {
      throw new HttpException(DEMO_WRITE_ERROR, 403);
    }
    if (!file) throw new HttpException({ error: 'No image uploaded' }, 400);
    // Commit the spooled upload to its final storage location (atomic
    // same-volume rename) before the DB row references the final path.
    await this.storage.put('places', file.filename, { tmpPath: file.path });
    return this.collections.setPlaceImage(user.id, pid, placeImageUrl(file.filename), socketId);
  }

  @Delete('places/:pid')
  async deletePlace(
    @CurrentUser() user: User,
    @Param('pid', rowId('Place not found')) pid: number,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.deletePlace(user.id, pid, socketId);
    return { success: true };
  }

  // ── Copy to trip ────────────────────────────────────────────────────────────
  /**
   * Read a list file back as a new list of the caller's own (#2198).
   *
   * 201, like POST / above, because it creates a list. The other POSTs here
   * are @HttpCode(200) because they act on one that already exists.
   */
  @Post('import')
  importCollection(
    @CurrentUser() user: User,
    @Body() body: CollectionImportDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.importCollection(user.id, body, socketId);
  }

  /**
   * A GPX document read into the list file it amounts to (#2301). Creates
   * nothing, hence 200: the browser shows what came out and sends it to
   * /import above, so a GPX goes through the same contract and the same one
   * transaction as a list file. A refusal carries a `code` the client
   * translates, beside the English `error` every other route has.
   */
  @Post('gpx/read')
  @HttpCode(200)
  readGpx(@Body() body: CollectionGpxReadDto) {
    try {
      return this.collections.readCollectionGpx(body);
    } catch (err) {
      if (!(err instanceof CollectionGpxError)) throw err;
      throw new HttpException({ error: err.message, code: err.code }, err.code === 'too-large' ? 413 : 400);
    }
  }

  @Post('copy-to-trip')
  @HttpCode(200)
  copyToTrip(
    @CurrentUser() user: User,
    @Body() body: CollectionCopyToTripDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.copyToTrip(user.id, body, this.collections.tripEvents(body.trip_id, socketId));
  }

  // ── Labels (per-collection custom labels; static prefixes before /:id) ───────
  @Post('labels')
  @HttpCode(200)
  createLabel(
    @CurrentUser() user: User,
    @Body() body: CollectionLabelCreateDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.createLabel(user.id, body.collection_id, body.name, body.color, socketId);
  }

  @Patch('labels/:lid')
  updateLabel(
    @CurrentUser() user: User,
    @Param('lid', rowId('Label not found')) lid: number,
    @Body() body: CollectionLabelUpdateDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.updateLabel(user.id, lid, body, socketId);
  }

  @Delete('labels/:lid')
  async deleteLabel(
    @CurrentUser() user: User,
    @Param('lid', rowId('Label not found')) lid: number,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.deleteLabel(user.id, lid, socketId);
    return { success: true };
  }

  @Post('labels/assign')
  @HttpCode(200)
  assignLabels(
    @CurrentUser() user: User,
    @Body() body: CollectionLabelAssignDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.assignLabels(user.id, body.label_ids, body.place_ids, false, socketId);
  }

  @Post('labels/unassign')
  @HttpCode(200)
  unassignLabels(
    @CurrentUser() user: User,
    @Body() body: CollectionLabelAssignDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.assignLabels(user.id, body.label_ids, body.place_ids, true, socketId);
  }

  // ── Library-wide membership lookup ──────────────────────────────────────────
  @Get('membership')
  membership(
    @CurrentUser() user: User,
    @Query('google_place_id') googlePlaceId?: string,
    @Query('google_ftid') googleFtid?: string,
    @Query('name') name?: string,
    @Query('lat') lat?: string,
    @Query('lng') lng?: string,
  ) {
    return this.collections.findMembership(user.id, {
      google_place_id: googlePlaceId,
      google_ftid: googleFtid,
      name,
      lat: lat != null && lat !== '' ? Number(lat) : undefined,
      lng: lng != null && lng !== '' ? Number(lng) : undefined,
    });
  }

  // ── Fusion invitations ──────────────────────────────────────────────────────
  @Post('invite')
  @HttpCode(200)
  async invite(
    @CurrentUser() user: User,
    @Body() body: CollectionInviteDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible (no enumeration)
    if (!(await this.collections.isOwner(user.id, body.collection_id))) {
      throw new HttpException({ error: 'Only the owner can invite' }, 403);
    }
    const { collection_id, user_id, role } = body;
    await this.collections.sendInvite(collection_id, user.id, user.username, user_id, role, socketId);
    return { success: true };
  }

  @Post('invite/accept')
  @HttpCode(200)
  async acceptInvite(
    @CurrentUser() user: User,
    @Body() body: CollectionInviteActionDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.acceptInvite(user.id, body.collection_id, socketId);
    return { success: true };
  }

  @Post('invite/decline')
  @HttpCode(200)
  async declineInvite(
    @CurrentUser() user: User,
    @Body() body: CollectionInviteActionDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.declineInvite(user.id, body.collection_id, socketId);
    return { success: true };
  }

  @Post('invite/cancel')
  @HttpCode(200)
  async cancelInvite(
    @CurrentUser() user: User,
    @Body() body: CollectionInviteCancelDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
    if (!(await this.collections.isOwner(user.id, body.collection_id))) {
      throw new HttpException({ error: 'Only the owner can cancel invites' }, 403);
    }
    await this.collections.cancelInvite(body.collection_id, user.id, body.user_id, socketId);
    return { success: true };
  }

  @Post('leave')
  @HttpCode(200)
  async leave(
    @CurrentUser() user: User,
    @Body() body: CollectionInviteActionDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.leaveCollection(user.id, body.collection_id, socketId);
    return { success: true };
  }

  @Post('members/remove')
  @HttpCode(200)
  async removeMember(@CurrentUser() user: User, @Body() body: CollectionRemoveMemberDto) {
    await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
    if (!(await this.collections.isOwner(user.id, body.collection_id))) {
      throw new HttpException({ error: 'Only the owner can remove members' }, 403);
    }
    await this.collections.removeMember(user.id, body.collection_id, body.user_id);
    return { success: true };
  }

  @Post('members/role')
  @HttpCode(200)
  async setMemberRole(@CurrentUser() user: User, @Body() body: CollectionSetMemberRoleDto) {
    await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
    if (!(await this.collections.isOwner(user.id, body.collection_id))) {
      throw new HttpException({ error: 'Only the owner can change member roles' }, 403);
    }
    await this.collections.setMemberRole(user.id, body.collection_id, body.user_id, body.role);
    return { success: true };
  }

  // ── /:id (declared last so static prefixes win) ─────────────────────────────
  @Get(':id/available-users')
  async availableUsers(@CurrentUser() user: User, @Param('id', rowId('Collection not found')) id: number) {
    await this.collections.assertAccess(user.id, id); // 404 if not visible (no enumeration)
    if (!(await this.collections.isOwner(user.id, id))) {
      throw new HttpException({ error: 'Only the owner can manage members' }, 403);
    }
    return { users: await this.collections.availableUsers(user.id, id) };
  }

  @Post(':id/cover')
  @UseInterceptors(FileInterceptor('cover', { fileFilter: COVER_FILE_FILTER }), SpoolCleanupInterceptor)
  async uploadCover(
    @CurrentUser() user: User,
    @Param('id', rowId('Collection not found')) id: number,
    @UploadedFile() file: Express.Multer.File | undefined,
    @Headers('x-socket-id') socketId?: string,
  ) {
    if (isDemoWriteBlocked(this.env, user.email)) {
      throw new HttpException(DEMO_WRITE_ERROR, 403);
    }
    if (!file) throw new HttpException({ error: 'No image uploaded' }, 400);
    // Commit the spooled upload to its final storage location (atomic
    // same-volume rename) before the DB row references the final path.
    await this.storage.put('covers', file.filename, { tmpPath: file.path });
    const coverUrl = `/uploads/covers/${file.filename}`;
    return this.collections.setCollectionCover(user.id, id, coverUrl, socketId);
  }

  /** Preview for the bulk trip import: the trip's places plus, per place, the same
   *  duplicate verdict the import itself applies. Read-only, so the dialog can grey out
   *  what would be skipped instead of reporting it afterwards. */
  /**
   * The list as a file (#2198). A plain JSON body: the browser turns it into a
   * download, so there is no Content-Disposition to get wrong here and no
   * filename decided by the server.
   */
  @Get(':id/export')
  exportCollection(@CurrentUser() user: User, @Param('id', rowId('Collection not found')) id: number) {
    return this.collections.exportCollection(user.id, id);
  }

  /**
   * The list as GPX (#2301). JSON around the document rather than the bare
   * XML, for the same reason the list file has no Content-Disposition: the
   * browser makes the download, and it also needs to say how many places had
   * no coordinates and were left out.
   */
  @Get(':id/export/gpx')
  exportCollectionGpx(@CurrentUser() user: User, @Param('id', rowId('Collection not found')) id: number) {
    return this.collections.exportCollectionGpx(user.id, id);
  }

  /** The list as KML for Google My Maps (#1866), wrapped in JSON like the GPX above, for the same reasons. */
  @Get(':id/export/kml')
  @ResponseContract(collectionKmlExportSchema)
  exportCollectionKml(@CurrentUser() user: User, @Param('id', rowId('Collection not found')) id: number) {
    return this.collections.exportCollectionKml(user.id, id);
  }

  /**
   * The same file read into a list that already exists (#2301 follow-up).
   *
   * 200, unlike POST /import above: this one adds to a list rather than making
   * one. Anyone who may add a place to the list may do it, and the socket id
   * rides along so the browser that asked does not echo its own change.
   */
  @Post(':id/import')
  @HttpCode(200)
  importIntoCollection(
    @CurrentUser() user: User,
    @Param('id', rowId('Collection not found')) id: number,
    @Body() body: CollectionImportIntoDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.importIntoCollection(user.id, id, body, socketId);
  }

  @Get(':id/importable/:tripId')
  importable(
    @CurrentUser() user: User,
    @Param('id', rowId('Collection not found')) id: number,
    @Param('tripId', rowId('Trip not found')) tripId: number,
  ) {
    return this.collections.importablePlaces(user.id, id, tripId);
  }

  @Get(':id')
  get(@CurrentUser() user: User, @Param('id', rowId('Collection not found')) id: number) {
    return this.collections.getCollection(user.id, id);
  }

  @Patch(':id')
  update(
    @CurrentUser() user: User,
    @Param('id', rowId('Collection not found')) id: number,
    @Body() body: CollectionUpdateDto,
    @Headers('x-socket-id') socketId?: string,
  ) {
    return this.collections.updateCollection(user.id, id, body, socketId);
  }

  @Delete(':id')
  async remove(
    @CurrentUser() user: User,
    @Param('id', rowId('Collection not found')) id: number,
    @Headers('x-socket-id') socketId?: string,
  ) {
    await this.collections.deleteCollection(user.id, id, socketId);
    return { success: true };
  }
}