mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
feat(journey): optionally place an entry where its first photo was taken (#1003)
This commit is contained in:
@@ -5440,6 +5440,16 @@ function runMigrations(db: Database.Database): void {
|
||||
if (!has('email')) db.exec('ALTER TABLE places ADD COLUMN email TEXT');
|
||||
if (!has('opening_hours')) db.exec('ALTER TABLE places ADD COLUMN opening_hours TEXT');
|
||||
},
|
||||
/**
|
||||
* A journey that puts an entry on the map where its first photo was taken
|
||||
* (#1003). Off unless the owner turns it on: an entry somebody placed by hand
|
||||
* is never moved, but an entry left without a place on purpose should not
|
||||
* grow one either just because a picture was added.
|
||||
*/
|
||||
() => {
|
||||
const cols = db.prepare("SELECT name FROM pragma_table_info('journeys')").all() as { name: string }[];
|
||||
if (!cols.some(c => c.name === 'photo_location')) db.exec('ALTER TABLE journeys ADD COLUMN photo_location INTEGER NOT NULL DEFAULT 0');
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -353,6 +353,7 @@ export class JourneyDomainService {
|
||||
status: string;
|
||||
status_override: string | null;
|
||||
show_trip_tracks: boolean | number;
|
||||
photo_location: boolean | number;
|
||||
show_verdict: boolean | number;
|
||||
show_mood: boolean | number;
|
||||
show_weather: boolean | number;
|
||||
@@ -373,13 +374,14 @@ export class JourneyDomainService {
|
||||
'status',
|
||||
'status_override',
|
||||
'show_trip_tracks',
|
||||
'photo_location',
|
||||
'show_verdict',
|
||||
'show_mood',
|
||||
'show_weather',
|
||||
];
|
||||
// Stored as INTEGER, and better-sqlite3 refuses to bind a JS boolean, so the
|
||||
// flags on this table are coerced rather than passed through.
|
||||
const BOOLEAN_FIELDS = new Set(['show_trip_tracks', 'show_verdict', 'show_mood', 'show_weather']);
|
||||
const BOOLEAN_FIELDS = new Set(['show_trip_tracks', 'show_verdict', 'show_mood', 'show_weather', 'photo_location']);
|
||||
const fields: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
for (const [key, val] of Object.entries(data)) {
|
||||
@@ -399,6 +401,50 @@ export class JourneyDomainService {
|
||||
return this.db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as Journey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entries without a place that just received a geotagged photo, on journeys
|
||||
* that asked for it (#1003): each takes the position of its first such photo.
|
||||
* An entry that already has coordinates is never moved. Answers what changed,
|
||||
* so the caller can name the places and tell the journeys.
|
||||
*/
|
||||
placeEntriesFromPhotos(trekPhotoIds: number[]): { entryId: number; journeyId: number; lat: number; lng: number }[] {
|
||||
if (!trekPhotoIds.length) return [];
|
||||
const marks = trekPhotoIds.map(() => '?').join(',');
|
||||
const rows = this.db.prepare(`
|
||||
SELECT je.id AS entryId, je.journey_id AS journeyId, tp.lat, tp.lng
|
||||
FROM trek_photos tp
|
||||
JOIN journey_photos gp ON gp.photo_id = tp.id
|
||||
JOIN journey_entry_photos jep ON jep.journey_photo_id = gp.id
|
||||
JOIN journey_entries je ON je.id = jep.entry_id
|
||||
JOIN journeys j ON j.id = je.journey_id
|
||||
WHERE tp.id IN (${marks})
|
||||
AND tp.lat IS NOT NULL AND tp.lng IS NOT NULL
|
||||
AND je.location_lat IS NULL AND je.location_lng IS NULL
|
||||
AND je.type != 'skeleton'
|
||||
AND j.photo_location = 1
|
||||
ORDER BY je.id, jep.sort_order, jep.journey_photo_id
|
||||
`).all(...trekPhotoIds) as { entryId: number; journeyId: number; lat: number; lng: number }[];
|
||||
const placed: { entryId: number; journeyId: number; lat: number; lng: number }[] = [];
|
||||
const seen = new Set<number>();
|
||||
const now = this.ts();
|
||||
const update = this.db.prepare(
|
||||
'UPDATE journey_entries SET location_lat = ?, location_lng = ?, country_code = ?, updated_at = ? WHERE id = ? AND location_lat IS NULL AND location_lng IS NULL',
|
||||
);
|
||||
for (const row of rows) {
|
||||
if (seen.has(row.entryId)) continue;
|
||||
seen.add(row.entryId);
|
||||
if (update.run(row.lat, row.lng, this.countryFor(row.lat, row.lng), now, row.entryId).changes > 0) placed.push(row);
|
||||
}
|
||||
return placed;
|
||||
}
|
||||
|
||||
/** The place name for an entry placed from a photo, only while it still has none. */
|
||||
nameEntryLocation(entryId: number, name: string): void {
|
||||
this.db.prepare(
|
||||
"UPDATE journey_entries SET location_name = ? WHERE id = ? AND (location_name IS NULL OR location_name = '')",
|
||||
).run(name, entryId);
|
||||
}
|
||||
|
||||
updateJourneyPreferences(journeyId: number, userId: number, data: { hide_skeletons?: boolean }) {
|
||||
if (!this.canAccessJourney(journeyId, userId)) return null;
|
||||
if (data.hide_skeletons !== undefined) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MemoriesModule } from '../memories/memories.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { JourneyDomainModule } from './journey-domain.module';
|
||||
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
|
||||
|
||||
@@ -14,7 +15,8 @@ import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
|
||||
* because the memories domain knows nothing about journeys.
|
||||
*/
|
||||
@Module({
|
||||
imports: [JourneyDomainModule, MemoriesModule],
|
||||
// MapsModule names an entry placed from its photo (#1003); it is a leaf.
|
||||
imports: [JourneyDomainModule, MemoriesModule, MapsModule],
|
||||
providers: [JourneyPhotoCaptureService],
|
||||
exports: [JourneyPhotoCaptureService],
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
|
||||
/** The trek_photos ids of freshly added journey photo rows, whatever shape the add answered with. */
|
||||
@@ -33,6 +34,7 @@ export class JourneyPhotoCaptureService {
|
||||
constructor(
|
||||
private readonly backfill: PhotoCaptureBackfillService,
|
||||
private readonly journey: JourneyDomainService,
|
||||
private readonly maps: MapsService,
|
||||
) {}
|
||||
|
||||
/** Provider photos just added to a journey, to its gallery or to one of its entries. Detached. */
|
||||
@@ -61,7 +63,31 @@ export class JourneyPhotoCaptureService {
|
||||
scheduleUpload(photos: readonly unknown[], userId: number): void {
|
||||
const ids = trekPhotoIdsOf(photos);
|
||||
if (!ids.length) return;
|
||||
this.backfill.schedule(ids, userId);
|
||||
void this.backfill.run(ids, userId)
|
||||
.then(() => this.placeEntries(ids))
|
||||
.catch(err => console.error('[Journey] capture for uploads failed:', err instanceof Error ? err.message : err));
|
||||
}
|
||||
|
||||
/**
|
||||
* Entries waiting for a place get the one their photo was taken at (#1003),
|
||||
* then a name for it, then everyone on the journey hears about it. The name is
|
||||
* best effort: a geocoder that does not answer leaves a pin without a label,
|
||||
* which the owner can still name by hand.
|
||||
*/
|
||||
async placeEntries(trekPhotoIds: number[]): Promise<number> {
|
||||
const placed = this.journey.placeEntriesFromPhotos(trekPhotoIds);
|
||||
if (!placed.length) return 0;
|
||||
await Promise.all(placed.map(async (p) => {
|
||||
try {
|
||||
const where = await this.maps.reverseGeocode(String(p.lat), String(p.lng), undefined, { timeoutMs: 8000, locality: true });
|
||||
const name = where.name || where.address;
|
||||
if (name) this.journey.nameEntryLocation(p.entryId, name);
|
||||
} catch { /* the pin stands without a name */ }
|
||||
}));
|
||||
for (const journeyId of new Set(placed.map(p => p.journeyId))) {
|
||||
this.journey.broadcastJourneyEvent(journeyId, 'journey:photos:updated', {});
|
||||
}
|
||||
return placed.length;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,6 +100,8 @@ export class JourneyPhotoCaptureService {
|
||||
let changed = false;
|
||||
try {
|
||||
changed = await this.backfill.run(trekPhotoIds, userId);
|
||||
// Its own broadcast when it places something; the one below is about order.
|
||||
await this.placeEntries(trekPhotoIds);
|
||||
if (changed && journeyId != null) {
|
||||
this.journey.broadcastJourneyEvent(journeyId, 'journey:photos:updated', {});
|
||||
}
|
||||
|
||||
@@ -251,6 +251,7 @@ export class JourneyMcp {
|
||||
show_verdict: z.boolean().optional().describe('Whether entries in this journey offer a pros/cons list'),
|
||||
show_mood: z.boolean().optional().describe('Whether entries in this journey offer a mood'),
|
||||
show_weather: z.boolean().optional().describe('Whether entries in this journey offer a weather note'),
|
||||
photo_location: z.boolean().optional().describe('Whether an entry without a place takes the position of the first geotagged photo added to it'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: journeyAddonOn,
|
||||
@@ -259,7 +260,7 @@ export class JourneyMcp {
|
||||
updateJourney(
|
||||
{ journeyId, ...data }: {
|
||||
journeyId: number; title?: string; subtitle?: string; status?: string; status_override?: string | null;
|
||||
show_verdict?: boolean; show_mood?: boolean; show_weather?: boolean;
|
||||
show_verdict?: boolean; show_mood?: boolean; show_weather?: boolean; photo_location?: boolean;
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
|
||||
@@ -249,7 +249,7 @@ export function createMcpTestRegistry(): McpRegistry {
|
||||
new CollectionsMcp(new CollectionsService(dbService, permissionsService, realtimeService, notificationsStub(), generalStorage), dbService, authService, addonsService),
|
||||
new TransitMcp(new TransitService(new GoogleTransitProvider(dbService, noGoogleQuota)), daysService, reservationsService, dbService, authService, guards),
|
||||
new AtlasMcp(new AtlasService(dbService), addonsService, authService),
|
||||
new JourneyMcp(journeyDomain, new JourneyShareService(dbService, journeyDomain, new SettingsService(dbService)), addonsService, authService, new JourneyPhotoCaptureService(captureBackfill, journeyDomain)),
|
||||
new JourneyMcp(journeyDomain, new JourneyShareService(dbService, journeyDomain, new SettingsService(dbService)), addonsService, authService, new JourneyPhotoCaptureService(captureBackfill, journeyDomain, { reverseGeocode: async () => ({ name: null, address: null }) } as never)),
|
||||
new MemoriesMcp(immichService, synologyService, dbService, addonsService),
|
||||
new NotificationsMcp(makeNotificationsService(dbService, realtimeService), authService),
|
||||
new AirtrailMcp(new AirtrailService(dbService, new AuditService(dbService), new AirtrailClient()), addonsService),
|
||||
|
||||
@@ -291,6 +291,57 @@ describe('getJourneyFull', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeEntriesFromPhotos (#1003)', () => {
|
||||
/** A geotagged (or not) photo on an entry, wired the way the upload wires it. */
|
||||
function photoOnEntry(journeyId: number, entryId: number, ownerId: number, coords: [number, number] | null, sort = 0) {
|
||||
const tp = testDb.prepare("INSERT INTO trek_photos (provider, owner_id, file_path, lat, lng) VALUES ('local', ?, 'journey/x.jpg', ?, ?)")
|
||||
.run(ownerId, coords?.[0] ?? null, coords?.[1] ?? null).lastInsertRowid as number;
|
||||
const gp = testDb.prepare('INSERT INTO journey_photos (journey_id, photo_id, shared, sort_order, created_at) VALUES (?, ?, 1, 0, ?)')
|
||||
.run(journeyId, tp, Date.now()).lastInsertRowid as number;
|
||||
testDb.prepare('INSERT INTO journey_entry_photos (entry_id, journey_photo_id, sort_order, created_at) VALUES (?, ?, ?, ?)').run(entryId, gp, sort, Date.now());
|
||||
return tp;
|
||||
}
|
||||
|
||||
it('JOURNEY-SVC-1003-1: with the setting on, a placeless entry takes the position of its first geotagged photo, once', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
testDb.prepare('UPDATE journeys SET photo_location = 1 WHERE id = ?').run(journey.id);
|
||||
const entry = createJourneyEntry(testDb, journey.id, user.id);
|
||||
const blank = photoOnEntry(journey.id, entry.id, user.id, null, 0);
|
||||
const first = photoOnEntry(journey.id, entry.id, user.id, [48.137, 11.575], 1);
|
||||
const second = photoOnEntry(journey.id, entry.id, user.id, [40.4, -3.7], 2);
|
||||
|
||||
expect(svc.placeEntriesFromPhotos([blank, first, second])).toEqual([{ entryId: entry.id, journeyId: journey.id, lat: 48.137, lng: 11.575 }]);
|
||||
const row = testDb.prepare('SELECT location_lat, location_lng, country_code FROM journey_entries WHERE id = ?').get(entry.id) as any;
|
||||
expect(row).toMatchObject({ location_lat: 48.137, location_lng: 11.575 });
|
||||
|
||||
// Placed now: a later photo does not move it, and a name only lands while there is none.
|
||||
expect(svc.placeEntriesFromPhotos([second])).toEqual([]);
|
||||
svc.nameEntryLocation(entry.id, 'Marienplatz');
|
||||
svc.nameEntryLocation(entry.id, 'Somewhere else');
|
||||
expect((testDb.prepare('SELECT location_name FROM journey_entries WHERE id = ?').get(entry.id) as any).location_name).toBe('Marienplatz');
|
||||
});
|
||||
|
||||
it('JOURNEY-SVC-1003-2: off by default, and it leaves entries with a place alone', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const entry = createJourneyEntry(testDb, journey.id, user.id);
|
||||
const photo = photoOnEntry(journey.id, entry.id, user.id, [1, 2]);
|
||||
expect(svc.placeEntriesFromPhotos([photo])).toEqual([]);
|
||||
|
||||
testDb.prepare('UPDATE journeys SET photo_location = 1 WHERE id = ?').run(journey.id);
|
||||
testDb.prepare('UPDATE journey_entries SET location_lat = 5, location_lng = 6 WHERE id = ?').run(entry.id);
|
||||
expect(svc.placeEntriesFromPhotos([photo])).toEqual([]);
|
||||
expect(svc.placeEntriesFromPhotos([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('JOURNEY-SVC-1003-3: the owner turns it on through updateJourney', () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
expect((svc.updateJourney(journey.id, user.id, { photo_location: true }) as any).photo_location).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateJourney', () => {
|
||||
it('JOURNEY-SVC-018: owner can update title and subtitle', () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { JourneyDomainService } from '../../../src/nest/journey/journey-dom
|
||||
import type { PhotoResolverService } from '../../../src/nest/memories/photo-resolver.service';
|
||||
import type { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
|
||||
import type { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
import type { MapsService } from '../../../src/nest/maps/maps.service';
|
||||
|
||||
function build(changed: boolean | Error = true) {
|
||||
const run = vi.fn(async () => {
|
||||
@@ -19,11 +20,15 @@ function build(changed: boolean | Error = true) {
|
||||
const schedule = vi.fn();
|
||||
const broadcastJourneyEvent = vi.fn();
|
||||
const journeyIdOfEntry = vi.fn((entryId: number) => (entryId === 4 ? 9 : null));
|
||||
const placeEntriesFromPhotos = vi.fn((): { entryId: number; journeyId: number; lat: number; lng: number }[] => []);
|
||||
const nameEntryLocation = vi.fn();
|
||||
const reverseGeocode = vi.fn(async () => ({ name: 'Marienplatz', address: 'Munich' }));
|
||||
const svc = new JourneyPhotoCaptureService(
|
||||
{ run, schedule } as unknown as PhotoCaptureBackfillService,
|
||||
{ broadcastJourneyEvent, journeyIdOfEntry } as unknown as JourneyDomainService,
|
||||
{ broadcastJourneyEvent, journeyIdOfEntry, placeEntriesFromPhotos, nameEntryLocation } as unknown as JourneyDomainService,
|
||||
{ reverseGeocode } as unknown as MapsService,
|
||||
);
|
||||
return { svc, run, schedule, broadcastJourneyEvent, journeyIdOfEntry };
|
||||
return { svc, run, schedule, broadcastJourneyEvent, journeyIdOfEntry, placeEntriesFromPhotos, nameEntryLocation, reverseGeocode };
|
||||
}
|
||||
|
||||
beforeEach(() => vi.restoreAllMocks());
|
||||
@@ -101,21 +106,61 @@ describe('JourneyPhotoCaptureService', () => {
|
||||
expect(error).toHaveBeenLastCalledWith('[Journey] capture refresh failed for journey null:', 'gone');
|
||||
});
|
||||
|
||||
it('JPCAP-008: an upload gets the plain backfill and no refresh, since one request is one file', async () => {
|
||||
const { svc, run, schedule, broadcastJourneyEvent, journeyIdOfEntry } = build(true);
|
||||
it('JPCAP-008: an upload gets the backfill and no order refresh, since one request is one file', async () => {
|
||||
const { svc, run, broadcastJourneyEvent, journeyIdOfEntry, placeEntriesFromPhotos } = build(true);
|
||||
|
||||
svc.scheduleUpload([{ id: 1, photo_id: 11 }, null, { id: 2 }], 3);
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
await vi.waitFor(() => expect(placeEntriesFromPhotos).toHaveBeenCalledWith([11]));
|
||||
|
||||
expect(schedule).toHaveBeenCalledWith([11], 3);
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(run).toHaveBeenCalledWith([11], 3);
|
||||
expect(journeyIdOfEntry).not.toHaveBeenCalled();
|
||||
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
|
||||
// Nothing with a trek photo id: nothing to schedule.
|
||||
schedule.mockClear();
|
||||
// Nothing with a trek photo id: nothing to run.
|
||||
run.mockClear();
|
||||
svc.scheduleUpload([{ id: 3 }], 3);
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('JPCAP-1003: an entry placed from its photo gets a name and the journey hears about it', async () => {
|
||||
const { svc, placeEntriesFromPhotos, nameEntryLocation, reverseGeocode, broadcastJourneyEvent } = build(false);
|
||||
placeEntriesFromPhotos.mockReturnValueOnce([
|
||||
{ entryId: 5, journeyId: 9, lat: 48.137, lng: 11.575 },
|
||||
{ entryId: 6, journeyId: 9, lat: 1, lng: 2 },
|
||||
]);
|
||||
reverseGeocode.mockResolvedValueOnce({ name: 'Marienplatz', address: 'Munich' }).mockRejectedValueOnce(new Error('timeout'));
|
||||
|
||||
await expect(svc.placeEntries([11, 12])).resolves.toBe(2);
|
||||
expect(reverseGeocode).toHaveBeenCalledWith('48.137', '11.575', undefined, { timeoutMs: 8000, locality: true });
|
||||
// The second geocode failed: its pin stands without a name.
|
||||
expect(nameEntryLocation).toHaveBeenCalledTimes(1);
|
||||
expect(nameEntryLocation).toHaveBeenCalledWith(5, 'Marienplatz');
|
||||
expect(broadcastJourneyEvent).toHaveBeenCalledTimes(1);
|
||||
expect(broadcastJourneyEvent).toHaveBeenCalledWith(9, 'journey:photos:updated', {});
|
||||
|
||||
// A provider add runs the same placing after its backfill.
|
||||
placeEntriesFromPhotos.mockClear();
|
||||
await svc.fill(9, [13], 3);
|
||||
expect(placeEntriesFromPhotos).toHaveBeenCalledWith([13]);
|
||||
});
|
||||
|
||||
it('JPCAP-1003b: nothing placed, nothing asked and nothing said; an address stands in for a missing name', async () => {
|
||||
const { svc, reverseGeocode, broadcastJourneyEvent, placeEntriesFromPhotos, nameEntryLocation } = build(false);
|
||||
await expect(svc.placeEntries([11])).resolves.toBe(0);
|
||||
expect(reverseGeocode).not.toHaveBeenCalled();
|
||||
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
|
||||
placeEntriesFromPhotos.mockReturnValueOnce([{ entryId: 7, journeyId: 9, lat: 1, lng: 2 }]);
|
||||
reverseGeocode.mockResolvedValueOnce({ name: null, address: 'Somewhere Road' } as never);
|
||||
await svc.placeEntries([11]);
|
||||
expect(nameEntryLocation).toHaveBeenCalledWith(7, 'Somewhere Road');
|
||||
});
|
||||
|
||||
it('JPCAP-1003c: an upload whose backfill throws is logged', async () => {
|
||||
const { svc } = build(new Error('disk'));
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
svc.scheduleUpload([{ photo_id: 11 }], 3);
|
||||
await vi.waitFor(() => expect(error).toHaveBeenCalledWith('[Journey] capture for uploads failed:', 'disk'));
|
||||
});
|
||||
|
||||
it('JPCAP-009: provider adds from every surface share the user\'s four lookup slots, uploads read their own files, and only the provider adds refresh', async () => {
|
||||
@@ -143,7 +188,8 @@ describe('JourneyPhotoCaptureService', () => {
|
||||
const broadcastJourneyEvent = vi.fn();
|
||||
const svc = new JourneyPhotoCaptureService(
|
||||
backfill,
|
||||
{ broadcastJourneyEvent, journeyIdOfEntry: () => 9 } as unknown as JourneyDomainService,
|
||||
{ broadcastJourneyEvent, journeyIdOfEntry: () => 9, placeEntriesFromPhotos: () => [] } as unknown as JourneyDomainService,
|
||||
{ reverseGeocode: vi.fn() } as unknown as MapsService,
|
||||
);
|
||||
const rows = (from: number) => Array.from({ length: 5 }, (_, i) => ({ photo_id: from + i }));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user