Open places and their photo from shared event links #131

Merged
raucao merged 1 commits from feature/nip-89-app-handler into master 2026-11-28 10:08:11 +00:00
12 changed files with 640 additions and 4 deletions

No files matched your search

+9 -1
View File
@@ -148,6 +148,14 @@ export default class PlaceDetails extends Component {
);
}
// The event id the inline carousel should focus: a deep-linked photo from the
// route's `photo` query param (see the `/e/:event_id` route), or a photo just
// uploaded on this page.
get focusPhotoEventId() {
const photo = this.router.currentRoute?.queryParams?.photo;
return photo || this.newlyUploadedPhotoId || null;
}
get hasMultipleUntrusted() {
return this.nostrData.untrustedContentCount > 1;
}
@@ -549,7 +557,7 @@ export default class PlaceDetails extends Component {
@photos={{this.photos}}
@name={{this.name}}
@resetKey={{this.place.osmId}}
@scrollToEventId={{this.newlyUploadedPhotoId}}
@scrollToEventId={{this.focusPhotoEventId}}
@onPhotoClick={{this.openGallery}}
/>
<h3>{{this.name}}</h3>
+11
View File
@@ -0,0 +1,11 @@
import Controller from '@ember/controller';
// `photo` carries the event id of a deep-linked place photo (e.g. from
// `/e/:event_id`) so the place details carousel can focus it. Declared here so
// Ember tracks it as a query parameter; `refreshModel: false` on the route
// keeps the place model from reloading when only the photo changes.
export default class PlaceController extends Controller {
queryParams = ['photo'];
photo = null;
}
+1
View File
@@ -9,6 +9,7 @@ export default class Router extends EmberRouter {
Router.map(function () {
this.route('place', { path: '/place/:place_id' });
this.route('place.new', { path: '/place/new' });
this.route('event', { path: '/e/:event_id' });
this.route('search');
this.route('menu');
this.route('lists', function () {
+47
View File
@@ -0,0 +1,47 @@
import Route from '@ember/routing/route';
import { service } from '@ember/service';
import {
parseNostrEventReference,
placeIdentifierFromEvent,
} from '../utils/nostr';
// Opens a shared NIP-19 event reference at its place. This backs the NIP-89
// app handler's `web` URL template (https://marco.earth/e/<bech32>): given a
// place photo (kind 360) or, later, a place review (kind 30360), it reads the
// event's `i` tag and redirects into the place route.
export default class EventRoute extends Route {
@service nostrData;
@service router;
@service toast;
async model(params) {
const pointer = parseNostrEventReference(params.event_id);
if (!pointer) {
return { error: 'This link is not a valid Nostr event reference.' };
}
const event = await this.nostrData.loadEventByPointer(pointer);
if (!event) {
return { error: 'Could not find this event on any relay.' };
}
const placeId = placeIdentifierFromEvent(event);
if (!placeId) {
return { error: 'This event is not linked to a place.' };
}
return { placeId, eventId: event.id };
}
redirect(model) {
if (model.placeId) {
return this.router.replaceWith('place', model.placeId, {
queryParams: { photo: model.eventId },
});
}
this.toast.show(model.error || 'Could not open this event.');
return this.router.replaceWith('index');
}
}
+4
View File
@@ -23,6 +23,10 @@ export default class PlaceRoute extends Route {
@service osm;
@service mapUi;
// `photo` is the deep-link target consumed by place-details. Keep the model
// from reloading when only the focused photo changes.
queryParams = { photo: { refreshModel: false } };
async model(params) {
const id = params.place_id;
+83 -3
View File
@@ -11,6 +11,7 @@ import {
takeUntil,
defer,
of,
firstValueFrom,
} from 'rxjs';
import { EventStore } from 'applesauce-core/event-store';
import { ProfileModel } from 'applesauce-core/models/profile';
@@ -129,6 +130,10 @@ export default class NostrDataService extends Service {
_contactsSub = null;
_blossomSub = null;
_photosSub = null;
// Live network subscription for the selected place's photos (`#i`). Unlike
// the one-shot loaders, it stays open while the place is selected so photos
// from every relay arrive even if some respond after others have EOSE'd.
_photosNetworkSub = null;
_contributionsSub = null;
_deletionsSub = null;
_insertSub = null;
@@ -474,6 +479,38 @@ export default class NostrDataService extends Service {
});
}
/**
* Opens a LIVE subscription to `filters` across `relays`, recording relay
* provenance and adding events to the store as they arrive.
*
* Unlike `_requestContentWithProvenance`, this does NOT complete on the first
* relay's EOSE. `completeOnAllEose()` only accounts for relays that have
* reported so far, so a one-shot request can finish right after the fastest
* relay and drop the rest (e.g. a place whose photos live on a relay that
* answers later than the submission relay). Keeping the subscription open
* lets every relay's events stream in, and keeps new events arriving live.
* The caller is responsible for unsubscribing.
*/
_subscribeContentWithProvenance(relays, filters, errorLabel) {
return this.nostrRelay.pool
.req(relays, filters)
.pipe(
// Only EVENT messages carry content; ignore OPEN/EOSE/CLOSED/ERROR.
// We deliberately do NOT dedupe so we see every relay's copy and can
// accumulate full provenance across relays.
filter((message) => message.type === 'EVENT')
)
.subscribe({
next: (message) => {
this._recordProvenance(message.event.id, message.from);
this.store.add(message.event);
},
error: (err) => {
console.error(errorLabel, err);
},
});
}
async loadPlacesInBounds(bbox) {
const requiredPrefixes = getGeohashPrefixesInBbox(bbox);
@@ -543,6 +580,11 @@ export default class NostrDataService extends Service {
this._photosSub = null;
}
if (this._photosNetworkSub) {
this._photosNetworkSub.unsubscribe();
this._photosNetworkSub = null;
}
this._cleanupZapReceiptSubs();
this._clearZapRefreshTimer();
@@ -594,11 +636,13 @@ export default class NostrDataService extends Service {
);
}
// Fire network request specifically for this place (captures provenance).
this._requestContentWithProvenance(
// Open a live subscription for this place (captures provenance). It stays
// open until the place changes, so photos from slower relays — and new
// photos — still arrive after the first render.
this._photosNetworkSub = this._subscribeContentWithProvenance(
this.activeReadRelays,
[{ kinds: [360, 5], '#i': [entityId] }],
'[nostr-data] Error fetching place photos for place:'
'[nostr-data] Error in place photos subscription:'
);
}
@@ -1092,6 +1136,38 @@ export default class NostrDataService extends Service {
return this.profiles[pubkey];
}
/**
* Resolves a NIP-19 event reference (an `EventPointer` or `AddressPointer`)
* to a concrete event, using the store's loader: cache first, then relay
* hints attached to the pointer, then the active read relays and the public
* directory relays. Returns `null` if nothing is found within `timeoutMs`.
*
* Used by the `/e/:event_id` route to find the place a shared event belongs
* to.
*
* @param {object|null} pointer EventPointer or AddressPointer
* @param {number} [timeoutMs=15000]
* @returns {Promise<object|null>}
*/
async loadEventByPointer(pointer, timeoutMs = 15_000) {
if (!pointer) return null;
try {
return await firstValueFrom(
this.store
.event(pointer)
.pipe(filter(Boolean), timeout({ first: timeoutMs }))
);
} catch (e) {
console.debug(
'[nostr-data] Failed to load event for pointer',
pointer,
e
);
return null;
}
}
_clearProfileSubs() {
for (const sub of this._profileModelSubs.values()) {
sub.unsubscribe();
@@ -1431,6 +1507,10 @@ export default class NostrDataService extends Service {
this._photosSub.unsubscribe();
this._photosSub = null;
}
if (this._photosNetworkSub) {
this._photosNetworkSub.unsubscribe();
this._photosNetworkSub = null;
}
if (this._contributionsSub) {
this._contributionsSub.unsubscribe();
this._contributionsSub = null;
+100
View File
@@ -1,3 +1,8 @@
import {
decodeAddressPointer,
decodeEventPointer,
} from 'applesauce-core/helpers/pointers';
import { extractMediaHashes } from './photo-tags';
export function normalizeRelayUrl(url) {
@@ -155,3 +160,98 @@ export function parsePlacePhotos(events) {
return allPhotos;
}
// --- NIP-19 / NIP-21 event references (the `/e/:event_id` handler) ---------
const HEX_EVENT_ID = /^[0-9a-f]{64}$/i;
const ADDRESS_COORDINATE = /^(\d+):([0-9a-f]{64}):(.*)$/i;
const PLACE_IDENTIFIER = /^osm:(node|way|relation):\d+$/;
// Addressable ranges: NIP-01 replaceable (10xxx/10002) and parameterized
// replaceable (30000-39999). Only the latter can be referenced by `naddr`.
function isAddressableKind(kind) {
return Number.isInteger(kind) && kind >= 30000 && kind < 40000;
}
function stripNostrScheme(value) {
return value.toLowerCase().startsWith('nostr:')
? value.slice('nostr:'.length)
: value;
}
// Reduces a full permalink (e.g. https://njump.me/nevent1…) to its last path
// segment; leaves bare references untouched.
function toReference(value) {
if (!/^https?:\/\//i.test(value)) return value;
try {
const segments = new URL(value).pathname.split('/').filter(Boolean);
return segments.length
? decodeURIComponent(segments[segments.length - 1])
: '';
} catch {
return '';
}
}
/**
* Parses a user-supplied event reference into an Applesauce pointer that
* `EventStore.event()` / the event loader can resolve.
*
* Accepts a raw 64-hex event id, `note1`/`nevent1`/`naddr1` NIP-19 codes
* (relay hints included), an optional `nostr:` scheme prefix (NIP-21), a raw
* `kind:pubkey:d` coordinate, or a full permalink to any of those (resolved
* via its last path segment).
*
* @param {string} input
* @returns {{id: string, relays?: string[], author?: string, kind?: number}
* | {kind: number, pubkey: string, identifier: string, relays?: string[]}
* | null} An EventPointer or AddressPointer, or `null` if unrecognized
*/
export function parseNostrEventReference(input) {
if (typeof input !== 'string') return null;
const candidate = toReference(stripNostrScheme(input.trim()));
if (!candidate) return null;
const reference = stripNostrScheme(candidate);
if (HEX_EVENT_ID.test(reference)) {
return { id: reference.toLowerCase() };
}
const eventPointer = decodeEventPointer(reference);
if (eventPointer) return eventPointer;
const addressPointer = decodeAddressPointer(reference);
if (addressPointer && isAddressableKind(addressPointer.kind)) {
return addressPointer;
}
const coordinate = ADDRESS_COORDINATE.exec(reference);
if (coordinate) {
const kind = Number(coordinate[1]);
if (isAddressableKind(kind)) {
return {
kind,
pubkey: coordinate[2].toLowerCase(),
identifier: coordinate[3],
};
}
}
return null;
}
/**
* Returns the place identifier (e.g. `osm:node:123`) from a place photo or
* review event's `i` tag, or `null` when the event is not linked to an OSM
* element.
*
* @param {object} event A Nostr event
* @returns {string | null}
*/
export function placeIdentifierFromEvent(event) {
if (!event || !Array.isArray(event.tags)) return null;
const value = event.tags.find((tag) => tag[0] === 'i')?.[1];
return value && PLACE_IDENTIFIER.test(value) ? value : null;
}
@@ -109,4 +109,49 @@ module('Integration | Component | photo-carousel', function (hooks) {
assert.ok(true, 'clicking next button does not throw');
});
test('it marks the deep-linked photo as active', async function (assert) {
this.photos = [
{
eventId: 'event-1',
url: 'photo1.jpg',
thumbUrl: 'thumb1.jpg',
isLandscape: true,
},
{
eventId: 'event-2',
url: 'photo2.jpg',
thumbUrl: 'thumb2.jpg',
isLandscape: true,
},
{
eventId: 'event-3',
url: 'photo3.jpg',
thumbUrl: 'thumb3.jpg',
isLandscape: true,
},
];
this.focusEventId = 'event-2';
await render(
<template>
<div class="test-container">
<PhotoCarousel
@photos={{this.photos}}
@scrollToEventId={{this.focusEventId}}
/>
</div>
</template>
);
assert
.dom('[data-event-id="event-2"]')
.hasClass('active', 'the deep-linked photo is marked active');
assert
.dom('[data-event-id="event-1"]')
.doesNotHaveClass('active', 'other photos stay inactive');
assert
.dom('[data-event-id="event-3"]')
.doesNotHaveClass('active', 'other photos stay inactive');
});
});
@@ -806,4 +806,43 @@ module('Integration | Component | place-details', function (hooks) {
assert.dom('.place-lists-manager').exists();
assert.dom('.place-lists-manager .edit-item').doesNotExist();
});
test('it focuses a deep-linked photo from the photo query param', async function (assert) {
class NostrDataStub extends Service {
placePhotos = [
{
id: 'event-2',
pubkey: 'a'.repeat(64),
kind: 360,
created_at: 1,
tags: [
['i', 'osm:node:1'],
['imeta', 'url https://example.com/a.jpg', 'dim 800x600'],
],
},
];
untrustedContentCount = 0;
showUntrustedContent = false;
toggleShowUntrustedContent() {}
}
class MockRouter extends Service {
currentRoute = { queryParams: { photo: 'event-2' } };
transitionTo() {}
urlFor() {
return '/place/osm:node:1';
}
}
this.owner.register('service:nostr-data', NostrDataStub);
this.owner.register('service:router', MockRouter);
const place = { title: 'Test Place', osmId: '1', osmType: 'node' };
await render(<template><PlaceDetails @place={{place}} /></template>);
assert
.dom('.carousel-slide[data-event-id="event-2"]')
.hasClass('active', 'the deep-linked photo is focused');
});
});
+108
View File
@@ -0,0 +1,108 @@
import { module, test } from 'qunit';
import { setupTest } from 'marco/tests/helpers';
import Service from '@ember/service';
const EVENT_ID =
'1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb';
module('Unit | Route | event', function (hooks) {
setupTest(hooks);
// Registers stubs for `nostr-data` (returns `event`), `toast` (records the
// last message) and `router` (records the last replaceWith target).
function setupStubs(owner, { event = null, onToast } = {}) {
let loadCalled = false;
let redirect = null;
class NostrDataStub extends Service {
async loadEventByPointer() {
loadCalled = true;
return event;
}
}
class ToastStub extends Service {
show(message) {
onToast?.(message);
}
}
class RouterStub extends Service {
replaceWith(name, arg, options) {
redirect = { name, arg, options };
}
}
owner.register('service:nostr-data', NostrDataStub);
owner.register('service:toast', ToastStub);
owner.register('service:router', RouterStub);
return {
wasLoaded: () => loadCalled,
getRedirect: () => redirect,
};
}
test('it exists', function (assert) {
assert.ok(this.owner.lookup('route:event'));
});
test('redirects to the place of a photo event', async function (assert) {
const stubs = setupStubs(this.owner, {
event: { id: EVENT_ID, kind: 360, tags: [['i', 'osm:node:123']] },
});
const route = this.owner.lookup('route:event');
const model = await route.model({ event_id: EVENT_ID });
assert.strictEqual(model.placeId, 'osm:node:123');
route.redirect(model);
assert.deepEqual(stubs.getRedirect(), {
name: 'place',
arg: 'osm:node:123',
options: { queryParams: { photo: EVENT_ID } },
});
});
test('toasts and returns to the map when the event has no place', async function (assert) {
let toastMessage;
const stubs = setupStubs(this.owner, {
event: { kind: 1, tags: [] },
onToast: (message) => (toastMessage = message),
});
const route = this.owner.lookup('route:event');
const model = await route.model({ event_id: EVENT_ID });
assert.ok(model.error, 'model carries an error');
route.redirect(model);
assert.strictEqual(stubs.getRedirect().name, 'index');
assert.ok(toastMessage, 'a toast was shown');
});
test('toasts and returns to the map when the event is not found', async function (assert) {
let toastMessage;
const stubs = setupStubs(this.owner, {
event: null,
onToast: (message) => (toastMessage = message),
});
const route = this.owner.lookup('route:event');
const model = await route.model({ event_id: EVENT_ID });
assert.ok(model.error, 'model carries an error');
route.redirect(model);
assert.strictEqual(stubs.getRedirect().name, 'index');
assert.ok(toastMessage, 'a toast was shown');
});
test('rejects invalid references without loading an event', async function (assert) {
const stubs = setupStubs(this.owner, { event: null });
const route = this.owner.lookup('route:event');
const model = await route.model({ event_id: 'not-a-pointer' });
assert.ok(model.error, 'model carries an error');
assert.notOk(stubs.wasLoaded(), 'loadEventByPointer was not called');
});
});
+74
View File
@@ -1134,6 +1134,80 @@ module('Unit | Service | nostr-data | place photos', function (hooks) {
);
assert.strictEqual(service.untrustedContentCount, 0);
});
test('keeps streaming place photos after a relay EOSEs', async function (assert) {
const service = this.owner.lookup('service:nostr-data');
const pk = makePubkey(90);
const slowId = makeEventId(904);
await service.loadPhotosForPlace({ osmId: '902', osmType: 'node' });
// The submission relay answers first (EOSE). A one-shot request with
// `completeOnAllEose()` would complete here and drop the slower relay.
this.reqMessages.next({
type: 'EOSE',
from: 'wss://submit.nostr.kosmos.org',
});
// The trusted relay answers afterwards with the actual place photo.
this.reqMessages.next({
type: 'EVENT',
from: 'wss://nostr.kosmos.org',
event: makePhotoEvent(pk, 'osm:node:902', { id: slowId }),
});
await wait(50);
assert.deepEqual(
service.placePhotos.map((e) => e.id),
[slowId],
'photo from the slower relay is shown'
);
});
test('keeps the live place photo subscription for the same place', async function (assert) {
const service = this.owner.lookup('service:nostr-data');
await service.loadPhotosForPlace({ osmId: '903', osmType: 'node' });
const first = service._photosNetworkSub;
await service.loadPhotosForPlace({ osmId: '903', osmType: 'node' });
assert.strictEqual(
service._photosNetworkSub,
first,
'same live subscription retained'
);
assert.notOk(first.closed, 'it is still open');
});
test('closes the live place photo subscription when switching places', async function (assert) {
const service = this.owner.lookup('service:nostr-data');
await service.loadPhotosForPlace({ osmId: '903', osmType: 'node' });
const first = service._photosNetworkSub;
await service.loadPhotosForPlace({ osmId: '904', osmType: 'node' });
assert.ok(first.closed, 'previous live subscription closed');
assert.notStrictEqual(
service._photosNetworkSub,
first,
'a new live subscription was opened'
);
});
test('closes the live place photo subscription for a null place', async function (assert) {
const service = this.owner.lookup('service:nostr-data');
await service.loadPhotosForPlace({ osmId: '905', osmType: 'node' });
const sub = service._photosNetworkSub;
await service.loadPhotosForPlace(null);
assert.ok(sub.closed, 'live subscription closed');
assert.strictEqual(service._photosNetworkSub, null);
});
});
module('Unit | Service | nostr-data | my contributions', function (hooks) {
+119
View File
@@ -3,7 +3,9 @@ import {
excludeRequiredRelays,
mergeRequiredRelays,
normalizeRelayUrl,
parseNostrEventReference,
parsePlacePhotos,
placeIdentifierFromEvent,
relayUrlMatches,
uniqNormalizedRelays,
} from 'marco/utils/nostr';
@@ -427,4 +429,121 @@ module('Unit | Utility | nostr', function () {
'null trust list'
);
});
module('parseNostrEventReference', function () {
const EVENT_ID =
'1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb';
const NOTE =
'note1raustrrh5gjwt03zdj8syn9vmt2dwsv9t467m8c3gua636uxu89sazwyqc';
const NEVENT =
'nevent1qvzqqqqpdqpzq8meqkx80g3yuklzymy0qfx2ekk56aqc2ht4ak03z3em4r4cdcwtqyfhwumn8ghj7un9d3shjtn90psk6urvv5qzq8meqkx80g3yuklzymy0qfx2ekk56aqc2ht4ak03z3em4r4cdcwtzltwfa';
const NEVENT_NOHINTS =
'nevent1qqsp77g933m6yf89hc3xerczfjkd44xhgxz46a0dnug5wwagawrwrjcfq0qqc';
const NADDR =
'naddr1qvzqqqrknqpzq8meqkx80g3yuklzymy0qfx2ekk56aqc2ht4ak03z3em4r4cdcwtqyfhwumn8ghj7un9d3shjtn90psk6urvv5qqcmmnd5axummyv5arzv3najzpek';
test('parses a raw hex event id (case-insensitive)', function (assert) {
assert.deepEqual(parseNostrEventReference(EVENT_ID), { id: EVENT_ID });
assert.deepEqual(parseNostrEventReference(EVENT_ID.toUpperCase()), {
id: EVENT_ID,
});
});
test('parses a note1 event id', function (assert) {
assert.deepEqual(parseNostrEventReference(NOTE), { id: EVENT_ID });
});
test('parses a nevent with relay hints, author and kind', function (assert) {
const pointer = parseNostrEventReference(NEVENT);
assert.strictEqual(pointer.id, EVENT_ID);
assert.deepEqual(pointer.relays, ['wss://relay.example']);
assert.strictEqual(pointer.author, EVENT_ID);
assert.strictEqual(pointer.kind, 360);
});
test('parses a nevent without hints', function (assert) {
const pointer = parseNostrEventReference(NEVENT_NOHINTS);
assert.strictEqual(pointer.id, EVENT_ID);
assert.notOk(pointer.relays?.length);
});
test('parses an naddr into an address pointer', function (assert) {
const pointer = parseNostrEventReference(NADDR);
assert.strictEqual(pointer.kind, 30360);
assert.strictEqual(pointer.pubkey, EVENT_ID);
assert.strictEqual(pointer.identifier, 'osm:node:123');
assert.deepEqual(pointer.relays, ['wss://relay.example']);
});
test('accepts a nostr: scheme prefix', function (assert) {
assert.deepEqual(parseNostrEventReference(`nostr:${NOTE}`), {
id: EVENT_ID,
});
});
test('extracts the reference from a permalink URL', function (assert) {
assert.deepEqual(
parseNostrEventReference(`https://njump.me/${NEVENT}`),
parseNostrEventReference(NEVENT)
);
assert.deepEqual(
parseNostrEventReference(`https://primal.net/e/${EVENT_ID}`),
{ id: EVENT_ID }
);
});
test('parses a raw address coordinate', function (assert) {
assert.deepEqual(
parseNostrEventReference(`30360:${EVENT_ID}:osm:node:123`),
{ kind: 30360, pubkey: EVENT_ID, identifier: 'osm:node:123' }
);
});
test('rejects unsupported input', function (assert) {
assert.strictEqual(parseNostrEventReference(''), null);
assert.strictEqual(parseNostrEventReference('not-a-pointer'), null);
assert.strictEqual(
parseNostrEventReference('naddr1qqqqqqqq'),
null,
'malformed naddr'
);
assert.strictEqual(parseNostrEventReference(null), null);
assert.strictEqual(
parseNostrEventReference('30360:nothex:osm:node:123'),
null
);
});
});
module('placeIdentifierFromEvent', function () {
test('returns the i tag place identifier', function (assert) {
assert.strictEqual(
placeIdentifierFromEvent({ tags: [['i', 'osm:node:123']] }),
'osm:node:123'
);
assert.strictEqual(
placeIdentifierFromEvent({
tags: [
['g', 'xn0'],
['i', 'osm:way:9'],
],
}),
'osm:way:9'
);
});
test('returns null without a valid OSM i tag', function (assert) {
assert.strictEqual(placeIdentifierFromEvent({ tags: [] }), null);
assert.strictEqual(
placeIdentifierFromEvent({ tags: [['i', 'geo:1,2']] }),
null
);
assert.strictEqual(
placeIdentifierFromEvent({ tags: [['i', 'osm:foo:1']] }),
null
);
assert.strictEqual(placeIdentifierFromEvent(null), null);
assert.strictEqual(placeIdentifierFromEvent({}), null);
});
});
});