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.

refactor(server): lift the memories vocabulary and the uploads anchor into nest

Maurice67c1633155f0
diff --git a/server/src/nest/memories/memories.helpers.ts b/server/src/nest/memories/memories.helpers.ts
new file mode 100644
index 000000000..2b5ce00c4
--- /dev/null
+++ b/server/src/nest/memories/memories.helpers.ts
@@ -0,0 +1,161 @@
+import { pipeline } from 'node:stream/promises';
+import { Readable } from 'node:stream';
+import { Response } from 'express';
+import { safeFetch, SsrfBlockedError, type SafeFetchOptions } from '../../utils/ssrfGuard';
+
+/**
+ * The shared vocabulary of the memories domain: the ServiceResult envelope, the
+ * provider-agnostic asset shapes, and the asset proxy.
+ *
+ * No database and no DI, so the provider services, the resolver and the
+ * controllers can all name these without importing each other — the same reason
+ * notifications/notification-events.ts exists.
+ */
+
+// helpers for handling return types
+
+type ServiceError = { success: false; error: { message: string; status: number } };
+export type ServiceResult<T> = { success: true; data: T } | ServiceError;
+
+
+export function fail(error: string, status: number): ServiceError {
+ return { success: false, error: { message: error, status } };
+}
+
+
+export function success<T>(data: T): ServiceResult<T> {
+ return { success: true, data: data };
+}
+
+
+export function mapDbError(error: Error, fallbackMessage: string): ServiceError {
+ if (error && /unique|constraint/i.test(error.message)) {
+ return fail('Resource already exists', 409);
+ }
+ return fail(error.message, 500);
+}
+
+
+export function handleServiceResult<T>(res: Response, result: ServiceResult<T>): void {
+ if ('error' in result) {
+ res.status(result.error.status).json({ error: result.error.message });
+ }
+ else {
+ res.json(result.data);
+ }
+}
+
+// ----------------------------------------------
+// types used across memories services
+export type Selection = {
+ provider: string;
+ asset_ids: string[];
+ passphrase?: string;
+};
+
+export type StatusResult = {
+ connected: true;
+ user: { name: string }
+} | {
+ connected: false;
+ error: string
+};
+
+export type SyncAlbumResult = {
+ added: number;
+ total: number
+};
+
+
+export type AlbumsList = {
+ albums: Array<{ id: string; albumName: string; assetCount: number; passphrase?: string }>
+};
+
+export type Asset = {
+ id: string;
+ takenAt: string;
+ mediaType?: string;
+ city?: string | null;
+ country?: string | null;
+ lat?: number | null;
+ lng?: number | null;
+};
+
+export type AssetsList = {
+ assets: Asset[],
+ total: number,
+ hasMore: boolean
+};
+
+
+export type AssetInfo = {
+ id: string;
+ takenAt: string | null;
+ city: string | null;
+ country: string | null;
+ state?: string | null;
+ camera?: string | null;
+ lens?: string | null;
+ focalLength?: string | number | null;
+ aperture?: string | number | null;
+ shutter?: string | number | null;
+ iso?: string | number | null;
+ lat?: number | null;
+ lng?: number | null;
+ orientation?: number | null;
+ description?: string | null;
+ width?: number | null;
+ height?: number | null;
+ fileSize?: number | null;
+ fileName?: string | null;
+}
+
+/**
+ * Proxy an upstream asset straight to the client.
+ *
+ * It writes status, headers and body onto the Express response itself and is
+ * NOT a candidate for StreamableFile: it forwards the upstream's 206 and
+ * Content-Range so a <video> can seek (#823), swaps Cache-Control to no-store
+ * on an error status, and has to answer differently once headers are already
+ * sent. All three controllers take @Res() anyway.
+ */
+export async function pipeAsset(url: string, response: Response, headers?: Record<string, string>, signal?: AbortSignal, defaultCacheControl?: string, fetchOptions?: SafeFetchOptions): Promise<void> {
+ try {
+ const resp = await safeFetch(url, { headers, signal: signal as any }, fetchOptions);
+
+ response.status(resp.status);
+ if (resp.headers.get('content-type')) response.set('Content-Type', resp.headers.get('content-type') as string);
+ if (!resp.ok) {
+ response.set('Cache-Control', 'no-store, max-age=0');
+ } else if (resp.headers.get('cache-control')) {
+ response.set('Cache-Control', resp.headers.get('cache-control') as string);
+ } else if (defaultCacheControl) {
+ response.set('Cache-Control', defaultCacheControl);
+ }
+ if (resp.headers.get('content-length')) response.set('Content-Length', resp.headers.get('content-length') as string);
+ if (resp.headers.get('content-disposition')) response.set('Content-Disposition', resp.headers.get('content-disposition') as string);
+ // Pass byte-range metadata through so a <video> can seek (#823). Upstream
+ // returns 206 + Content-Range when the caller forwarded a Range header.
+ if (resp.headers.get('accept-ranges')) response.set('Accept-Ranges', resp.headers.get('accept-ranges') as string);
+ if (resp.headers.get('content-range')) response.set('Content-Range', resp.headers.get('content-range') as string);
+
+ if (!resp.body) {
+ response.end();
+ } else {
+ await pipeline(Readable.fromWeb(resp.body as any), response);
+ }
+ } catch (error) {
+ if (response.headersSent) {
+ response.end();
+ return;
+ }
+ if (error instanceof SsrfBlockedError) {
+ response.status(400).json({ error: error.message });
+ } else {
+ // Don't log the URL — it can carry a Synology _sid / passphrase.
+ console.error('pipeAsset: upstream fetch failed:', error);
+ response.status(500).json({ error: 'Failed to fetch asset' });
+ }
+ }
+}
+
diff --git a/server/src/nest/memories/memories.service.ts b/server/src/nest/memories/memories.service.ts
index 414e8956b..4995cdd01 100644
--- a/server/src/nest/memories/memories.service.ts
+++ b/server/src/nest/memories/memories.service.ts
@@ -37,7 +37,7 @@ import {
streamSynologyAsset,
} from '../../services/memories/synologyService';
import { canAccessUserPhoto } from '../../services/memories/helpersService';
-import type { Selection } from '../../services/memories/helpersService';
+import type { Selection } from './memories.helpers';
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
diff --git a/server/src/nest/memories/synology.controller.ts b/server/src/nest/memories/synology.controller.ts
index 4e9cb676d..1f07605c7 100644
--- a/server/src/nest/memories/synology.controller.ts
+++ b/server/src/nest/memories/synology.controller.ts
@@ -1,8 +1,8 @@
import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, Query, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import type { User } from '../../types';
-import type { ServiceResult } from '../../services/memories/helpersService';
-import { fail, success } from '../../services/memories/helpersService';
+import type { ServiceResult } from './memories.helpers';
+import { fail, success } from './memories.helpers';
import { MemoriesService } from './memories.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
diff --git a/server/src/nest/memories/unified.controller.ts b/server/src/nest/memories/unified.controller.ts
index 06e19ec41..3810af95a 100644
--- a/server/src/nest/memories/unified.controller.ts
+++ b/server/src/nest/memories/unified.controller.ts
@@ -1,7 +1,7 @@
import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, Put, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import type { User } from '../../types';
-import type { Selection } from '../../services/memories/helpersService';
+import type { Selection } from './memories.helpers';
import { MemoriesService } from './memories.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
diff --git a/server/src/nest/memories/uploads-root.ts b/server/src/nest/memories/uploads-root.ts
new file mode 100644
index 000000000..b0b5d0492
--- /dev/null
+++ b/server/src/nest/memories/uploads-root.ts
@@ -0,0 +1,14 @@
+import path from 'node:path';
+
+/**
+ * `<server>/uploads`, the one anchor for everything the app stores on disk.
+ *
+ * `__dirname` moves with the file, and three separate copies of this join used
+ * to live in services/memories/ — every one of them a silent breakage waiting
+ * for the next move (multer would have created the wrong directory without a
+ * word). One constant, one test (UPLOADS-ROOT-001), and the depth is stated
+ * rather than counted by hand: `server/{src,dist}/nest/memories` sits three
+ * levels under `server/`, the same depth `services/memories/` sat at — so the
+ * resolved path is unchanged by the move.
+ */
+export const UPLOADS_ROOT = path.resolve(__dirname, '..', '..', '..', 'uploads');
diff --git a/server/src/services/memories/helpersService.ts b/server/src/services/memories/helpersService.ts
index 6ce0dd412..5ab62f52b 100644
--- a/server/src/services/memories/helpersService.ts
+++ b/server/src/services/memories/helpersService.ts
@@ -1,108 +1,10 @@
-import { pipeline } from 'node:stream/promises';
-import { Readable } from 'node:stream';
-import { Response } from 'express';
import { canAccessTrip, db } from "../../db/database";
-import { safeFetch, SsrfBlockedError, type SafeFetchOptions } from '../../utils/ssrfGuard';
import { decrypt_api_key } from '../../nest/common/crypto/apiKeyCrypto';
-
-// helpers for handling return types
-
-type ServiceError = { success: false; error: { message: string; status: number } };
-export type ServiceResult<T> = { success: true; data: T } | ServiceError;
-
-
-export function fail(error: string, status: number): ServiceError {
- return { success: false, error: { message: error, status } };
-}
-
-
-export function success<T>(data: T): ServiceResult<T> {
- return { success: true, data: data };
-}
-
-
-export function mapDbError(error: Error, fallbackMessage: string): ServiceError {
- if (error && /unique|constraint/i.test(error.message)) {
- return fail('Resource already exists', 409);
- }
- return fail(error.message, 500);
-}
-
-
-export function handleServiceResult<T>(res: Response, result: ServiceResult<T>): void {
- if ('error' in result) {
- res.status(result.error.status).json({ error: result.error.message });
- }
- else {
- res.json(result.data);
- }
-}
-
-// ----------------------------------------------
-// types used across memories services
-export type Selection = {
- provider: string;
- asset_ids: string[];
- passphrase?: string;
-};
-
-export type StatusResult = {
- connected: true;
- user: { name: string }
-} | {
- connected: false;
- error: string
-};
-
-export type SyncAlbumResult = {
- added: number;
- total: number
-};
-
-
-export type AlbumsList = {
- albums: Array<{ id: string; albumName: string; assetCount: number; passphrase?: string }>
-};
-
-export type Asset = {
- id: string;
- takenAt: string;
- mediaType?: string;
- city?: string | null;
- country?: string | null;
- lat?: number | null;
- lng?: number | null;
-};
-
-export type AssetsList = {
- assets: Asset[],
- total: number,
- hasMore: boolean
-};
-
-
-export type AssetInfo = {
- id: string;
- takenAt: string | null;
- city: string | null;
- country: string | null;
- state?: string | null;
- camera?: string | null;
- lens?: string | null;
- focalLength?: string | number | null;
- aperture?: string | number | null;
- shutter?: string | number | null;
- iso?: string | number | null;
- lat?: number | null;
- lng?: number | null;
- orientation?: number | null;
- description?: string | null;
- width?: number | null;
- height?: number | null;
- fileSize?: number | null;
- fileName?: string | null;
-}
-
+// The ServiceResult envelope, the asset shapes and pipeAsset moved to
+// nest/memories/memories.helpers.ts — this file is down to the DB-backed
+// access checks and album-link lookups, and folds with the providers.
+import { fail, success, type ServiceResult } from '../../nest/memories/memories.helpers';
+export * from '../../nest/memories/memories.helpers';
//for loading routes to settings page, and validating which services user has connected
type PhotoProviderConfig = {
@@ -255,43 +157,3 @@ export function getAlbumLinkForSync(tripId: string, linkId: string, userId: numb
export function updateSyncTimeForAlbumLink(linkId: string): void {
db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId);
}
-
-export async function pipeAsset(url: string, response: Response, headers?: Record<string, string>, signal?: AbortSignal, defaultCacheControl?: string, fetchOptions?: SafeFetchOptions): Promise<void> {
- try {
- const resp = await safeFetch(url, { headers, signal: signal as any }, fetchOptions);
-
- response.status(resp.status);
- if (resp.headers.get('content-type')) response.set('Content-Type', resp.headers.get('content-type') as string);
- if (!resp.ok) {
- response.set('Cache-Control', 'no-store, max-age=0');
- } else if (resp.headers.get('cache-control')) {
- response.set('Cache-Control', resp.headers.get('cache-control') as string);
- } else if (defaultCacheControl) {
- response.set('Cache-Control', defaultCacheControl);
- }
- if (resp.headers.get('content-length')) response.set('Content-Length', resp.headers.get('content-length') as string);
- if (resp.headers.get('content-disposition')) response.set('Content-Disposition', resp.headers.get('content-disposition') as string);
- // Pass byte-range metadata through so a <video> can seek (#823). Upstream
- // returns 206 + Content-Range when the caller forwarded a Range header.
- if (resp.headers.get('accept-ranges')) response.set('Accept-Ranges', resp.headers.get('accept-ranges') as string);
- if (resp.headers.get('content-range')) response.set('Content-Range', resp.headers.get('content-range') as string);
-
- if (!resp.body) {
- response.end();
- } else {
- await pipeline(Readable.fromWeb(resp.body as any), response);
- }
- } catch (error) {
- if (response.headersSent) {
- response.end();
- return;
- }
- if (error instanceof SsrfBlockedError) {
- response.status(400).json({ error: error.message });
- } else {
- // Don't log the URL — it can carry a Synology _sid / passphrase.
- console.error('pipeAsset: upstream fetch failed:', error);
- response.status(500).json({ error: 'Failed to fetch asset' });
- }
- }
-}
diff --git a/server/src/services/memories/immichService.ts b/server/src/services/memories/immichService.ts
index b3cdef105..955cb4119 100644
--- a/server/src/services/memories/immichService.ts
+++ b/server/src/services/memories/immichService.ts
@@ -4,6 +4,7 @@ import { maybe_encrypt_api_key, decrypt_api_key } from '../../nest/common/crypto
import { checkSsrf, safeFetch } from '../../utils/ssrfGuard';
import { writeAudit } from '../../nest/audit/audit.bridge';
import { getAlbumIdFromLink, updateSyncTimeForAlbumLink, Selection, pipeAsset } from './helpersService';
+import { UPLOADS_ROOT } from '../../nest/memories/uploads-root';
// ── Credentials ────────────────────────────────────────────────────────────
@@ -534,7 +535,7 @@ export async function uploadToImmich(userId: number, filePath: string, fileName:
const fs = await import('node:fs');
const path = await import('node:path');
- const fullPath = path.join(__dirname, '../../../uploads', filePath);
+ const fullPath = path.join(UPLOADS_ROOT, filePath);
if (!fs.existsSync(fullPath)) return null;
try {
diff --git a/server/src/services/memories/photoResolverService.ts b/server/src/services/memories/photoResolverService.ts
index 2cbfd8d19..7b598a2c2 100644
--- a/server/src/services/memories/photoResolverService.ts
+++ b/server/src/services/memories/photoResolverService.ts
@@ -6,6 +6,7 @@ import type { TrekPhoto } from '../../types';
// The trek_photos rows live in nest/photos now — this module is the provider
// dispatch half of what used to be one file.
import { resolveTrekPhoto } from '../../nest/photos/photos.bridge';
+import { UPLOADS_ROOT } from '../../nest/memories/uploads-root';
import { streamImmichAsset, fetchImmichThumbnailBytes, getAssetInfo as getImmichAssetInfo } from './immichService';
import { streamSynologyAsset, fetchSynologyThumbnailBytes, getSynologyAssetInfo } from './synologyService';
import type { ServiceResult, AssetInfo } from './helpersService';
@@ -60,7 +61,7 @@ export async function streamPhoto(
}
if (photo.file_path) {
- const uploadsRoot = path.join(__dirname, '../../../uploads');
+ const uploadsRoot = UPLOADS_ROOT;
if (kind === 'thumbnail') {
const isVideo = photo.media_type === 'video';
diff --git a/server/src/services/memories/trekPhotoCache.ts b/server/src/services/memories/trekPhotoCache.ts
index 4ee45a808..e1dae5a1b 100644
--- a/server/src/services/memories/trekPhotoCache.ts
+++ b/server/src/services/memories/trekPhotoCache.ts
@@ -4,8 +4,9 @@ import fsPromises from 'node:fs/promises';
import crypto from 'node:crypto';
import { Response } from 'express';
import { db } from '../../db/database';
+import { UPLOADS_ROOT } from '../../nest/memories/uploads-root';
-const TREK_PHOTO_DIR = path.join(__dirname, '../../../uploads/photos/trek');
+const TREK_PHOTO_DIR = path.join(UPLOADS_ROOT, 'photos/trek');
export const CACHE_TTL = 60 * 60 * 1000; // 1 hour
const inFlight = new Map<string, Promise<Buffer | null>>();
diff --git a/server/tests/unit/nest/uploads-root.test.ts b/server/tests/unit/nest/uploads-root.test.ts
new file mode 100644
index 000000000..769135be1
--- /dev/null
+++ b/server/tests/unit/nest/uploads-root.test.ts
@@ -0,0 +1,17 @@
+import { describe, it, expect } from 'vitest';
+import path from 'node:path';
+import { UPLOADS_ROOT } from '../../../src/nest/memories/uploads-root';
+
+/**
+ * The anchor three separate `__dirname` joins used to duplicate. A wrong depth
+ * does not throw — multer and mkdirSync would happily create the wrong tree and
+ * every stored photo would land somewhere nobody serves from.
+ */
+describe('UPLOADS_ROOT', () => {
+ it('UPLOADS-ROOT-001: resolves to <server>/uploads, whatever the process cwd is', () => {
+ // tests run from server/, so the repo-relative answer is unambiguous
+ expect(UPLOADS_ROOT).toBe(path.resolve(process.cwd(), 'uploads'));
+ expect(path.basename(UPLOADS_ROOT)).toBe('uploads');
+ expect(path.basename(path.dirname(UPLOADS_ROOT))).toBe('server');
+ });
+});