Files
marco/app/utils/nostr.js
T
raucao 4d5e36f4f8
CI / Lint (pull_request) Successful in 52s
CI / Test (pull_request) Successful in 1m13s
Release Drafter / Update release notes draft (pull_request) Successful in 14s
Open places and their photo from shared event links
Add an /e/:event_id route that resolves a NIP-19 event reference (nevent
with relay hints, note, naddr, raw hex id, an optional nostr: prefix, or a
full permalink) to the event, reads its i tag and opens the place. When the
event is a place photo, focus it in the place details carousel via a
?photo= query param.

Also keep the selected place's photo subscription open instead of completing
on the first relay's EOSE, so photos that live on a slower relay are no
longer dropped (the submission relay holds only a subset).
2026-11-28 13:49:58 +04:00

258 lines
7.9 KiB
JavaScript

import {
decodeAddressPointer,
decodeEventPointer,
} from 'applesauce-core/helpers/pointers';
import { extractMediaHashes } from './photo-tags';
export function normalizeRelayUrl(url) {
if (!url) return '';
let normalized = url.trim().toLowerCase();
if (!normalized) return '';
if (!normalized.startsWith('ws://') && !normalized.startsWith('wss://')) {
normalized = 'wss://' + normalized;
}
while (normalized.endsWith('/')) {
normalized = normalized.slice(0, -1);
}
return normalized;
}
export function uniqNormalizedRelays(relays = []) {
return Array.from(new Set(relays.map(normalizeRelayUrl).filter(Boolean)));
}
export function mergeRequiredRelays(requiredRelays = [], customRelays = []) {
const requiredSet = new Set(requiredRelays.filter(Boolean));
const merged = [...requiredRelays.filter(Boolean)];
for (const relay of uniqNormalizedRelays(customRelays)) {
if (!requiredSet.has(relay)) {
merged.push(relay);
}
}
return merged;
}
export function excludeRequiredRelays(customRelays = [], requiredRelays = []) {
const requiredSet = new Set(requiredRelays.filter(Boolean));
return uniqNormalizedRelays(customRelays).filter((relay) => {
return !requiredSet.has(relay);
});
}
/**
* Returns true if `relayUrl` matches any entry in `trustedRelays`.
*
* Comparison is performed on normalized relay URLs (lowercased, `wss://`
* scheme ensured, trailing slashes stripped) via `normalizeRelayUrl`, so
* callers may pass raw `wss://` URLs received from relays or bare hostnames.
*
* @param {string} relayUrl The relay URL a content event was seen on
* @param {Array<string>} trustedRelays List of trusted relay URLs
* @returns {boolean}
*/
export function relayUrlMatches(relayUrl, trustedRelays = []) {
if (!relayUrl) return false;
const target = normalizeRelayUrl(relayUrl);
if (!target) return false;
const trustedSet = new Set(
uniqNormalizedRelays(trustedRelays || []).filter(Boolean)
);
return trustedSet.has(target);
}
/**
* Extracts and normalizes photo data from NIP-360 (Place Photos) events.
* Sorts chronologically and guarantees the first landscape photo (or first portrait) is at index 0.
*
* @param {Array} events NIP-360 events
* @returns {Array} Array of photo objects
*/
export function parsePlacePhotos(events) {
if (!events || events.length === 0) return [];
// Sort by created_at ascending (oldest first)
const sortedEvents = [...events].sort((a, b) => a.created_at - b.created_at);
const allPhotos = [];
for (const event of sortedEvents) {
const eventTagValues = event.tags
.filter((t) => t[0] === 't')
.map((t) => t[1])
.filter(Boolean);
// Find all imeta tags
const imetas = event.tags.filter((t) => t[0] === 'imeta');
for (const imeta of imetas) {
let url = null;
let thumbUrl = null;
let blurhash = null;
let isLandscape = false;
let aspectRatio = 16 / 9; // default
let altText = null;
let placeIdentifier = event.tags.find((t) => t[0] === 'i')?.[1];
const publishedAtRaw = event.tags.find(
(t) => t[0] === 'published_at'
)?.[1];
const publishedAt = publishedAtRaw ? Number(publishedAtRaw) : null;
for (const tag of imeta.slice(1)) {
if (tag.startsWith('url ')) {
url = tag.substring(4);
} else if (tag.startsWith('thumb ')) {
thumbUrl = tag.substring(6);
} else if (tag.startsWith('blurhash ')) {
blurhash = tag.substring(9);
} else if (tag.startsWith('dim ')) {
const dimStr = tag.substring(4);
const [width, height] = dimStr.split('x').map(Number);
if (width && height) {
aspectRatio = width / height;
if (width > height) {
isLandscape = true;
}
}
} else if (tag.startsWith('alt ')) {
const alt = tag.substring(4).trim();
// Strip the legacy placeholder we used to write on every event
altText = alt === 'A photo of a place' ? null : alt || null;
}
}
if (url) {
const mediaHashes = extractMediaHashes(event, imeta);
allPhotos.push({
eventId: event.id,
pubkey: event.pubkey,
createdAt: event.created_at,
publishedAt: publishedAt && publishedAt > 0 ? publishedAt : null,
url,
thumbUrl,
blurhash,
hash: mediaHashes.primary,
hashes: mediaHashes.hashes,
isLandscape,
aspectRatio,
placeIdentifier,
tags: eventTagValues,
alt: altText,
});
}
}
}
if (allPhotos.length === 0) return [];
// Find the first landscape photo
const firstLandscapeIndex = allPhotos.findIndex((p) => p.isLandscape);
if (firstLandscapeIndex > 0) {
// Move the first landscape photo to the front
const [firstLandscape] = allPhotos.splice(firstLandscapeIndex, 1);
allPhotos.unshift(firstLandscape);
}
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;
}