[+] Unsplash

This commit is contained in:
Azalea
2026-06-21 07:43:39 +00:00
committed by Maurice
parent c7e8a5614d
commit 8c941b52f9
11 changed files with 288 additions and 52 deletions
+21
View File
@@ -71,6 +71,21 @@ export class TripsController {
return { trips: this.trips.list(user.id, archived === '1' ? 1 : 0) };
}
@Get('cover-images/search')
async coverImages(@CurrentUser() user: User, @Query('query') query?: string) {
try {
const result = await this.trips.searchCoverImages(user.id, query || '');
if ('error' in result) {
throw new HttpException({ error: result.error }, result.status);
}
return { photos: result.photos };
} catch (err: unknown) {
if (err instanceof HttpException) throw err;
console.error('Unsplash cover image error:', err);
throw new HttpException({ error: 'Error searching for cover images' }, 500);
}
}
@Post()
@HttpCode(201)
create(@CurrentUser() user: User, @Body() body: Record<string, unknown>, @Req() req: Request) {
@@ -122,8 +137,14 @@ export class TripsController {
if (editFields.some((f) => body[f] !== undefined) && !this.trips.can('trip_edit', user.role, ownerId, user.id, isMember)) {
throw new HttpException({ error: 'No permission to edit this trip' }, 403);
}
const oldCover = body.cover_image !== undefined
? (this.trips.getRaw(id) as { cover_image: string | null } | undefined)?.cover_image
: undefined;
try {
const result = this.trips.update(id, user.id, body, user.role);
if (body.cover_image !== undefined && body.cover_image !== oldCover) {
this.trips.deleteOldCover(oldCover);
}
if (Object.keys(result.changes).length > 0) {
writeAudit({ userId: user.id, action: 'trip.update', ip: getClientIp(req), details: { tripId: Number(id), trip: result.newTitle, ...(result.ownerEmail ? { owner: result.ownerEmail } : {}), ...result.changes } });
if (result.isAdminEdit && result.ownerEmail) logInfo(`Admin ${user.email} edited trip "${result.newTitle}" owned by ${result.ownerEmail}`);
+5
View File
@@ -11,6 +11,7 @@ import { listItems as listTodoItems } from '../../services/todoService';
import { listBudgetItems } from '../../services/budgetService';
import { listReservations } from '../../services/reservationService';
import { listFiles } from '../../services/fileService';
import { searchUnsplashPhotos } from '../../services/unsplashService';
/**
* Thin Nest wrapper around the existing trip service + the per-domain list
@@ -49,6 +50,10 @@ export class TripsService {
return tripSvc.getTripRaw(tripId);
}
searchCoverImages(userId: number, query: string) {
return searchUnsplashPhotos(userId, query, 9);
}
getOwner(tripId: string) {
return tripSvc.getTripOwner(tripId);
}
+2 -30
View File
@@ -15,6 +15,7 @@ import {
} from './kmlImport';
import { enrichImportedPlaces, type EnrichablePlace } from './placeEnrichment';
import * as placePhotoCache from './placePhotoCache';
import { searchUnsplashPhotos } from './unsplashService';
// Reclaim a deleted place's cached marker photo if nothing else references it.
// The cache key is the Google place_id, or — for coordinate-only places — the
@@ -42,11 +43,6 @@ interface PlaceWithCategory extends Place {
category_icon: string | null;
}
interface UnsplashSearchResponse {
results?: { id: string; urls?: { regular?: string; thumb?: string }; description?: string; alt_description?: string; user?: { name?: string }; links?: { html?: string } }[];
errors?: string[];
}
export interface PlaceImportResult {
places: any[];
count: number;
@@ -947,29 +943,5 @@ export async function searchPlaceImage(tripId: string, placeId: string, userId:
const place = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId) as Place | undefined;
if (!place) return { error: 'Place not found', status: 404 };
const user = db.prepare('SELECT unsplash_api_key FROM users WHERE id = ?').get(userId) as { unsplash_api_key: string | null } | undefined;
if (!user || !user.unsplash_api_key) {
return { error: 'No Unsplash API key configured', status: 400 };
}
const query = encodeURIComponent(place.name + (place.address ? ' ' + place.address : ''));
const response = await fetch(
`https://api.unsplash.com/search/photos?query=${query}&per_page=5&client_id=${user.unsplash_api_key}`,
);
const data = await response.json() as UnsplashSearchResponse;
if (!response.ok) {
return { error: data.errors?.[0] || 'Unsplash API error', status: response.status };
}
const photos = (data.results || []).map((p: NonNullable<UnsplashSearchResponse['results']>[number]) => ({
id: p.id,
url: p.urls?.regular,
thumb: p.urls?.thumb,
description: p.description || p.alt_description,
photographer: p.user?.name,
link: p.links?.html,
}));
return { photos };
return searchUnsplashPhotos(userId, place.name + (place.address ? ' ' + place.address : ''), 5);
}
+69
View File
@@ -0,0 +1,69 @@
interface UnsplashSearchResponse {
results?: {
id: string;
urls?: { regular?: string; small?: string; thumb?: string };
description?: string | null;
alt_description?: string | null;
user?: { name?: string };
links?: { html?: string };
}[];
errors?: string[];
error?: string;
}
export interface UnsplashPhoto {
id: string;
url: string;
thumb: string;
description: string | null;
photographer: string | null;
link: string | null;
}
export async function searchUnsplashPhotos(_userId: number, query: string, perPage = 9) {
const trimmed = query.trim();
if (!trimmed) {
return { error: 'Search query is required', status: 400 };
}
const params = new URLSearchParams({
page: '1',
query: trimmed,
per_page: String(perPage),
});
const response = await fetch(`https://unsplash.com/napi/search/photos?${params.toString()}`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0',
Accept: '*/*',
'Accept-Language': 'en-US',
Referer: `https://unsplash.com/s/photos/${encodeURIComponent(trimmed)}`,
'client-geo-region': 'global',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Site': 'same-origin',
},
});
let data: UnsplashSearchResponse;
try {
data = await response.json() as UnsplashSearchResponse;
} catch {
return { error: 'Unsplash search unavailable', status: response.ok ? 502 : response.status };
}
if (!response.ok) {
return { error: data.errors?.[0] || data.error || 'Unsplash search unavailable', status: response.status };
}
const photos: UnsplashPhoto[] = (data.results || [])
.map((p) => ({
id: p.id,
url: p.urls?.regular || '',
thumb: p.urls?.small || p.urls?.thumb || p.urls?.regular || '',
description: p.description || p.alt_description || null,
photographer: p.user?.name || null,
link: p.links?.html || null,
}))
.filter((p) => p.url && p.thumb)
.slice(0, perPage);
return { photos };
}