Merge pull request 'Add queryable x tags to kind 360 place photo events' (#129) from feature/nostr-x-tag into master
CI / Lint (push) Successful in 53s
CI / Test (push) Successful in 1m10s

Reviewed-on: #129
This commit was merged in pull request #129.
This commit is contained in:
raucao committed 2026-11-27 15:49:40 +00:00
commit 0247930e3b
10 files changed
+493 -70

No files matched your search

+14 -20
View File
@@ -320,28 +320,22 @@ export default class PhotoGallery extends Component {
// Remove from local store by adding the kind 5 to it
this.nostrData.store.add(event);
// Now that the event is published, try to delete from Blossom
// Now that the event is published, try to delete from Blossom.
// Prefer the event's `x` hashes (primary + derived images); fall back
// to extracting them from the URLs for legacy events without `x`.
const hashRegex = /[0-9a-f]{64}/i;
const hashes =
this.currentPhoto.hashes?.length > 0
? this.currentPhoto.hashes
: [this.currentPhoto.url, this.currentPhoto.thumbUrl]
.map((url) => url?.match(hashRegex)?.[0])
.filter(Boolean);
if (this.currentPhoto.url) {
const match = this.currentPhoto.url.match(hashRegex);
if (match) {
try {
await this.blossom.delete(match[0]);
} catch (e) {
console.warn('Failed to delete main image from blossom:', e);
}
}
}
if (this.currentPhoto.thumbUrl) {
const match = this.currentPhoto.thumbUrl.match(hashRegex);
if (match) {
try {
await this.blossom.delete(match[0]);
} catch (e) {
console.warn('Failed to delete thumb image from blossom:', e);
}
for (const hash of new Set(hashes)) {
try {
await this.blossom.delete(hash);
} catch (e) {
console.warn(`Failed to delete blob ${hash} from blossom:`, e);
}
}
+6 -45
View File
@@ -5,10 +5,10 @@ import { service } from '@ember/service';
import { on } from '@ember/modifier';
import { EventFactory } from 'applesauce-core';
import { task } from 'ember-concurrency';
import Geohash from 'latlon-geohash';
import PlacePhotoUploadItem from './place-photo-upload-item';
import Icon from '#components/icon';
import { getSuggestedPhotoTags } from '../utils/photo-tag-suggestions';
import { buildPlacePhotoTags } from '../utils/photo-tags';
import capitalize from '../helpers/capitalize';
import includes from '../helpers/includes';
import { fn } from '@ember/helper';
@@ -150,8 +150,7 @@ export default class PlacePhotoUpload extends Component {
return;
}
const { osmId, lat, lon } = this.place;
const osmType = this.place.osmType || 'node';
const { osmId } = this.place;
if (!osmId) {
this.error = 'This place does not have a valid OSM ID.';
@@ -162,48 +161,10 @@ export default class PlacePhotoUpload extends Component {
this.isPublishing = true;
try {
const tags = [['i', `osm:${osmType}:${osmId}`]];
for (const tag of this.selectedTags) {
tags.push(['t', tag]);
}
if (lat && lon) {
tags.push(['g', Geohash.encode(lat, lon, 4)]);
tags.push(['g', Geohash.encode(lat, lon, 6)]);
tags.push(['g', Geohash.encode(lat, lon, 7)]);
tags.push(['g', Geohash.encode(lat, lon, 9)]);
}
const photo = this.uploadedPhoto;
const imeta = ['imeta', `url ${photo.url}`];
imeta.push(`m ${photo.type}`);
if (photo.dim) {
imeta.push(`dim ${photo.dim}`);
}
const alt = this.altText.trim();
if (alt) {
imeta.push(`alt ${alt}`);
}
if (photo.fallbackUrls && photo.fallbackUrls.length > 0) {
for (const fallbackUrl of photo.fallbackUrls) {
imeta.push(`fallback ${fallbackUrl}`);
}
}
if (photo.thumbUrl) {
imeta.push(`thumb ${photo.thumbUrl}`);
}
if (photo.blurhash) {
imeta.push(`blurhash ${photo.blurhash}`);
}
tags.push(imeta);
const tags = buildPlacePhotoTags(this.uploadedPhoto, this.place, {
tags: this.selectedTags,
alt: this.altText,
});
// NIP-XX draft Place Photo event
const event = await EventFactory.fromKind(360)
+4
View File
@@ -7,6 +7,7 @@
*/
import { tracked } from '@glimmer/tracking';
import { extractMediaHashes } from './photo-tags';
const HOUR_IN_SECONDS = 60 * 60;
@@ -96,6 +97,7 @@ export function parsePhotoFromEvent(event) {
const placeIdentifier = tags.find((t) => t[0] === 'i')?.[1];
const publishedAtRaw = tags.find((t) => t[0] === 'published_at')?.[1];
const publishedAt = publishedAtRaw ? Number(publishedAtRaw) : null;
const mediaHashes = extractMediaHashes(event, imeta);
return {
eventId: event.id,
@@ -105,6 +107,8 @@ export function parsePhotoFromEvent(event) {
url,
thumbUrl,
blurhash,
hash: mediaHashes.primary,
hashes: mediaHashes.hashes,
isLandscape,
aspectRatio,
placeIdentifier,
+5
View File
@@ -1,3 +1,5 @@
import { extractMediaHashes } from './photo-tags';
export function normalizeRelayUrl(url) {
if (!url) return '';
let normalized = url.trim().toLowerCase();
@@ -119,6 +121,7 @@ export function parsePlacePhotos(events) {
}
if (url) {
const mediaHashes = extractMediaHashes(event, imeta);
allPhotos.push({
eventId: event.id,
pubkey: event.pubkey,
@@ -127,6 +130,8 @@ export function parsePlacePhotos(events) {
url,
thumbUrl,
blurhash,
hash: mediaHashes.primary,
hashes: mediaHashes.hashes,
isLandscape,
aspectRatio,
placeIdentifier,
+127
View File
@@ -0,0 +1,127 @@
import Geohash from 'latlon-geohash';
/**
* Builds the public tags for a kind 360 (Place Photo) event.
*
* One top-level `x` tag is emitted per distinct file the event references:
* the primary media first, then the thumbnail (when its hash is known). The
* primary hash is also emitted inside `imeta` (per NIP-92), where it anchors
* which of the top-level hashes belongs to the primary media. When no hash is
* available for a file, no `x` tag is emitted for it and the event remains
* valid.
*
* @param {object} photo Uploaded photo data (`url`, `type`, `hash`,
* `thumbHash`, `previewHash`, `dim`, `fallbackUrls`, `thumbUrl`, `blurhash`)
* @param {object} place Place data (`osmId`, `osmType`, `lat`, `lon`)
* @param {object} [options]
* @param {Array<string>} [options.tags] Hashtags to attach
* @param {string} [options.alt] Accessibility description/caption
* @returns {Array<Array<string>>} The event's public tags
*/
export function buildPlacePhotoTags(photo, place, options = {}) {
const { tags = [], alt = '' } = options;
const { osmId, lat, lon } = place || {};
const osmType = place?.osmType || 'node';
const result = [['i', `osm:${osmType}:${osmId}`]];
for (const tag of tags) {
result.push(['t', tag]);
}
if (lat && lon) {
result.push(['g', Geohash.encode(lat, lon, 4)]);
result.push(['g', Geohash.encode(lat, lon, 6)]);
result.push(['g', Geohash.encode(lat, lon, 7)]);
result.push(['g', Geohash.encode(lat, lon, 9)]);
}
const imeta = ['imeta', `url ${photo.url}`];
imeta.push(`m ${photo.type}`);
if (photo.hash) {
imeta.push(`x ${photo.hash}`);
}
if (photo.dim) {
imeta.push(`dim ${photo.dim}`);
}
const trimmedAlt = (alt || '').trim();
if (trimmedAlt) {
imeta.push(`alt ${trimmedAlt}`);
}
if (photo.fallbackUrls && photo.fallbackUrls.length > 0) {
for (const fallbackUrl of photo.fallbackUrls) {
imeta.push(`fallback ${fallbackUrl}`);
}
}
if (photo.thumbUrl) {
imeta.push(`thumb ${photo.thumbUrl}`);
}
if (photo.blurhash) {
imeta.push(`blurhash ${photo.blurhash}`);
}
result.push(imeta);
const hashes = [photo.hash, photo.thumbHash, photo.previewHash].filter(
(hash, index, all) => hash && all.indexOf(hash) === index
);
for (const hash of hashes) {
result.push(['x', hash]);
}
return result;
}
/**
* Extracts the media hashes from a kind 360 event.
*
* The `imeta` `x` field, when present, identifies the primary media's hash;
* top-level `x` tags cover every distinct file the event references (primary
* and derived images). If the `imeta` hash is not among the top-level values,
* the event's hashes are treated as untrusted and no hashes are returned.
*
* @param {object} event A kind 360 Nostr event
* @param {Array<string>} [imeta] The event's `imeta` tag, if already located
* @returns {{ primary: string|null, hashes: Array<string> }}
*/
export function extractMediaHashes(event, imeta) {
const topLevel = [];
for (const tag of event?.tags || []) {
if (tag[0] === 'x' && tag[1] && !topLevel.includes(tag[1])) {
topLevel.push(tag[1]);
}
}
const imetaTag = imeta || (event?.tags || []).find((t) => t[0] === 'imeta');
let nested = null;
if (imetaTag) {
for (const field of imetaTag.slice(1)) {
if (field.startsWith('x ')) {
nested = field.substring(2).trim() || null;
break;
}
}
}
if (nested && topLevel.length > 0 && !topLevel.includes(nested)) {
return { primary: null, hashes: [] };
}
let primary = nested || null;
if (!primary && topLevel.length === 1) {
primary = topLevel[0];
}
const hashes = topLevel.length > 0 ? topLevel : nested ? [nested] : [];
return { primary, hashes };
}
+46 -5
View File
@@ -57,7 +57,7 @@ This NIP adds the following requirements: events MUST include at least one high-
An event MUST contain exactly one `imeta` tag representing a single media item. Field definitions are per [NIP-92](92.md) and [NIP-94](94.md).
Clients SHOULD include `alt` (accessibility description — also the media's description/caption, see below), `dim` (dimensions), `m` (MIME type, image or video), `thumb` (URL to a smaller thumbnail image), and `blurhash` where possible. Clients MAY also include `fallback` URLs if the media is mirrored.
Clients SHOULD include `alt` (accessibility description — also the media's description/caption, see below), `dim` (dimensions), `m` (MIME type, image or video), `x` (SHA-256 of the media, see below), `thumb` (URL to a smaller thumbnail image), and `blurhash` where possible. Clients MAY also include `fallback` URLs if the media is mirrored.
`alt` serves as the description of the media (not only accessibility text); clients SHOULD prompt authors for it and MAY display it as the media's caption. Since `.content` cannot carry a caption, `alt` is the only description channel for a kind 360 item. A generic or empty `alt` is little better than none.
@@ -68,6 +68,7 @@ Authors MAY set `.content` to the primary `url` so that clients which do not par
"imeta",
"url https://blossom.example.com/8e2e28a503fa37482de5b0959ee38b2bb4de4e0a752db24c568981c2ab410260.jpg",
"m image/jpeg",
"x 8e2e28a503fa37482de5b0959ee38b2bb4de4e0a752db24c568981c2ab410260",
"dim 1440x1920",
"alt A steaming bowl of ramen on a wooden table at the restaurant.",
"fallback https://mirror.example.com/8e2e28a503fa37482de5b0959ee38b2bb4de4e0a752db24c568981c2ab410260.jpg",
@@ -84,9 +85,25 @@ Clients MAY additionally include a top-level `["m", "<mime>"]` tag for `#m` filt
- `t`: Hashtags for categorization (e.g., `["t", "food"]`, `["t", "architecture"]`).
- `content-warning`: Optional reason as defined in [NIP-36](36.md); clients MAY hide the media until the user acts. Example: `["content-warning", "nudity"]`.
- `x`: Media hashes. See below.
For kind 360, the warning applies to the media (rendering), not `.content`: clients SHOULD hide or blur the media (e.g., via the `blurhash` placeholder) until the user acts.
#### `x` — Media Hashes
Each top-level `x` tag carries the SHA-256 of one distinct file the event references, as 64 lowercase hex characters. There MUST NOT be duplicate `x` values.
```json
[
["x", "a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61"],
["x", "c5a528e20235e16cc1c18090b8f04179de76288ea4e410b0fcb8d1487e416a2d"]
]
```
The first value above is the primary media's hash; the second is its thumbnail's. The primary's hash SHOULD also appear inside `imeta` (NIP-92) and SHOULD be listed first, but the `imeta` `x` is what identifies the primary — clients MUST NOT infer roles from tag order. If the `imeta` `x` field is present and the event has any top-level `x` tags, one of them MUST equal it. Clients that know a hash (e.g. their own uploads, where the host returns the SHA-256) SHOULD include it; clients that only have a URL and cannot hash the file MAY omit it, and MUST NOT be required to fetch media in order to publish.
Each hash is of the bytes served at the corresponding URL: the primary at `imeta`'s `url` (or a `fallback` URL), derived images at their `imeta` URLs (`thumb`, and NIP-71 `image` previews). If a host serves a transformed file, the hash is of the bytes it serves; the pre-transformation hash MAY be carried as NIP-94's `ox` inside `imeta` (there is no top-level `ox`). `fallback` URLs serve the same bytes as `url` and get no extra `x`; hashes of files the event does not reference MUST NOT be included. See Querying for `#x` filters; [NIP-94](94.md) defines the tag, while the 64-character lowercase-hex format is this NIP's requirement (relay tag matching is exact-string per [NIP-01](01.md)).
## Querying
Single-item tags are filterable per [NIP-01](01.md).
@@ -99,6 +116,17 @@ Single-item tags are filterable per [NIP-01](01.md).
This returns every media item for the place regardless of geohash presence or precision, and does not require geohash tags.
**Events for a blob.** Filter by kind 360 and `#x` with the media's SHA-256:
```json
{
"kinds": [360],
"#x": ["a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61"]
}
```
Dropping `kinds` finds the same blob across other event kinds that use `x` (e.g. 20, 1063). A match may indicate the blob is the event's thumbnail or preview rather than its primary media.
**Spatial discovery.** Filter by kind 360 and `#g`:
```json
@@ -107,15 +135,17 @@ This returns every media item for the place regardless of geohash presence or pr
Clients SHOULD query a single geohash precision level per request, MAY include multiple geohash values to cover a bounding box, SHOULD limit values per query (e.g., ≤ 30), and MAY reduce precision or split queries when necessary.
Relays MAY not index arbitrary tags; clients SHOULD NOT assume all relays serve `#i`/`#g` queries for this kind.
Relays MAY not index arbitrary tags; clients SHOULD NOT assume all relays serve `#i`/`#g`/`#x` queries for this kind.
## Client Behavior
**Publishing.** Clients MUST NOT publish events that violate the required tags or the content rule above.
**Publishing.** Clients MUST NOT publish events that violate the required tags, the `x`/`m` tag invariants, or the content rule above.
**Parsing.** Clients SHOULD tolerate missing optional fields and unknown tags, and MAY use the first `imeta` if multiple are present. An event whose `imeta` lacks a `url` has no renderable media. If the `i` element cannot be resolved (e.g., a deleted OSM element), clients MAY fall back to the `g` geohash for placement, or skip the event.
**Parsing.** Clients SHOULD tolerate missing optional fields and unknown tags, and MAY use the first `imeta` if multiple are present. An event whose `imeta` lacks a `url` has no renderable media. `x` tags are optional; clients MUST NOT require them. The `imeta` `x` value, when present, identifies the primary media's hash. If the `imeta` `x` is present and top-level `x` tags exist but none equals it, clients SHOULD treat the event's hashes as untrusted for verification. With more than one top-level `x`, clients MUST NOT assume which value belongs to the primary media; a fetched file (media, thumbnail, preview) MAY instead be verified by hashing its bytes and testing membership in the `x` values. Clients MAY associate every top-level `x` with the event for blob indexing and lifecycle (e.g. Blossom garbage collection). If the `i` element cannot be resolved (e.g., a deleted OSM element), clients MAY fall back to the `g` geohash for placement, or skip the event.
**Rendering.** Clients MAY skip media they cannot render, SHOULD honor `content-warning` (media, not `.content` — see above), and SHOULD use `thumb`/`blurhash` placeholders while loading. Relays: see Querying for the `#i`/`#g` indexing caveat.
**Deletion.** When deleting a kind 360 event, clients MAY delete the blobs it references — every top-level `x` hash (for legacy events without `x`, hashes extracted from URLs) — from the author's blob servers ([NIP-B7](B7.md)). Blobs are content-addressed and may be referenced by other events; clients SHOULD first check that a hash is no longer referenced (e.g. an `#x` query) before deleting it.
**Rendering.** Clients MAY skip media they cannot render, SHOULD honor `content-warning` (media, not `.content` — see above), and SHOULD use `thumb`/`blurhash` placeholders while loading. Relays: see Querying for the `#i`/`#g`/`#x` indexing caveat.
## Example Event
@@ -136,12 +166,15 @@ Relays MAY not index arbitrary tags; clients SHOULD NOT assume all relays serve
"imeta",
"url https://blossom.example.com/a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61.jpg",
"m image/jpeg",
"x a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61",
"dim 1920x1920",
"alt A close-up of spicy miso ramen with chashu pork, soft boiled egg, and scallions.",
"fallback https://mirror.example.com/a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61.jpg",
"thumb https://example.com/c5a528e20235e16cc1c18090b8f04179de76288ea4e410b0fcb8d1487e416a2d.jpg",
"blurhash UHI=0o~q4T-o~q%MozM{x]t7RjRPt7oKkCWB"
],
["x", "a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61"],
["x", "c5a528e20235e16cc1c18090b8f04179de76288ea4e410b0fcb8d1487e416a2d"],
["t", "ramen"],
["t", "food"]
]
@@ -170,6 +203,12 @@ The `osm:<type>:<id>` scheme is defined by [NIP-73](73.md) (External Content IDs
Place Reviews (kind 30360) is a work-in-progress companion NIP, not yet published; when it is, reviews and media will interoperate as follows. Reviews and media have different lifecycles and data models. A user might upload 10 photos of a park without writing a review, or write a detailed review without attaching photos. Keeping them as separate events allows clients to query `imeta` attachments for a specific `i` tag to quickly build a media gallery for a place, regardless of whether a review was attached.
### Queryable Media Hashes (`x`)
Blob stores address files by SHA-256, and relays index single-letter tags, but a hash nested only inside `imeta` cannot be filtered on. [NIP-71](71.md) puts the hash in `imeta` alone, which voids queryability of the file; [NIP-68](68.md) puts it at the top level for exactly this reason, and this NIP follows that pattern. Kind 360 carries exactly one media item, so the `imeta` `x` — never tag order — identifies the primary hash among the event's `x` values; the rest are derived images. Including them means `#x` lookups and deletion flows see every blob the event references, not just the primary — NIP-68 lists one top-level `x` per displayed image for the same reason.
The payoff is cross-kind and cross-client: `{"#x": ["<hash>"]}` answers "which events reference this blob?" for clients, media-management UIs (e.g. Blossom blob browsers) and indexers/crawlers, and lets downloaders find mirrors and verify bytes without parsing the URL. Keeping `x` also inside `imeta` serves NIP-92-only readers, which never see top-level tags.
### Single Media Item per Event
Restricting events to a single `imeta` attachment (one media item per event) is an intentional design choice. Batching media into a single event forces all engagement (likes, zaps) to apply to the entire batch, rendering granular tagging and sorting impossible. Single-item events enable per-item engagement, fine-grained categorization (e.g., tagging one photo as "food" and another as "menu"), and richer sorting algorithms based on individual item popularity.
@@ -180,6 +219,8 @@ Restricting events to a single `imeta` attachment (one media item per event) is
- **Spam.** Clients SHOULD NOT assume all events are legitimate and SHOULD apply their own moderation/trust mechanisms.
- **Untrusted media.** `url`, `thumb`, and `fallback` point to arbitrary servers; clients SHOULD treat fetched media as untrusted content. Fetching media reveals the viewer's interest in a place to the hosting server.
- **Identifier decay.** Referenced OSM elements may be deleted or retyped; see Client Behavior for parsing fallbacks.
- **Author-asserted hash.** `x` is signed but is not proof of content. Clients SHOULD verify downloaded bytes against it before trusting, re-hosting or treating the media as verified; for large media, verification MAY be lazy/streamed. On mismatch, clients MUST NOT silently substitute other media or drop the event, and SHOULD surface the mismatch to the user.
- **Content fingerprinting.** For files whose URL already embeds the SHA-256 (e.g. Blossom media and thumbnails), `x` discloses nothing new. For other URLs it publishes a content fingerprint that lets relay watchers correlate events referencing identical bytes across hosts or places without fetching the media. This is a verification/convenience trade-off, not a reason to omit `x`.
## Future Work
+7
View File
@@ -15,3 +15,10 @@
- AppleSauce docs for AI agents: https://applesauce.build/introduction/mcp-server.html
- Live data (wss://nostr.kosmos.org, 2026-11-11): 149 kind 360 events, all
`i`=`osm:<type>:<id>`, none with a `k` tag, all with empty `.content`.
- Kind 360 carries the media SHA-256 as top-level `x` tags (primary media and
thumbnail, with the primary also inside `imeta`) when known (issue #122).
Top-level placement follows NIP-68, which already does this "to make them
queryable"; hashes nested only in `imeta` (NIP-71) cannot be filtered on.
Marco emits the tags from the hashes returned by `blossom.upload`, and parses
them back for deletion so URLs without an embedded hash still work, including
the thumbnail blob. Spec: `doc/nostr/nip-place-photos.md`.
@@ -250,6 +250,63 @@ module('Integration | Component | photo-gallery', function (hooks) {
assert.notOk(closed, 'gallery was kept open after deletion');
});
test('it deletes blobs by x hashes when the URLs do not embed them', async function (assert) {
this.nostrAuth.pubkey = USER_A;
this.settings.update('experimentalEnablePhotoDeletion', true);
Object.defineProperty(this.nostrAuth, 'signer', {
configurable: true,
get: () => ({
signEvent: async (e) => ({
...e,
id: 'a3b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1',
sig: 'b3b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1',
pubkey: USER_A,
}),
getPublicKey: async () => USER_A,
}),
});
const mainHash =
'd3b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1';
const thumbHash =
'e3b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1';
this.photos[0] = {
...this.photos[0],
url: 'https://example.com/photo.jpg',
thumbUrl: 'https://example.com/thumb.jpg',
hash: mainHash,
hashes: [mainHash, thumbHash],
};
this.selectedPhoto = this.photos[0];
sinon.stub(window, 'confirm').returns(true);
const blossomStub = sinon.stub(this.blossom, 'delete').resolves();
sinon
.stub(this.nostrRelay, 'publish')
.resolves([{ ok: true, from: 'wss://relay.test' }]);
sinon.stub(this.nostrData.store, 'add');
await render(
<template>
<div id="test-container">
<div id="modal-portal"></div>
<PhotoGallery
@photos={{this.photos}}
@selectedPhoto={{this.selectedPhoto}}
/>
</div>
</template>
);
await click('.dropdown-trigger-btn');
await click('.dropdown-item.text-danger');
assert.ok(blossomStub.calledTwice, 'deleted both referenced blobs');
assert.strictEqual(blossomStub.firstCall.args[0], mainHash);
assert.strictEqual(blossomStub.secondCall.args[0], thumbHash);
});
test('it closes the gallery when deleting the last remaining photo', async function (assert) {
this.nostrAuth.pubkey = USER_A;
this.settings.update('experimentalEnablePhotoDeletion', true);
+62
View File
@@ -271,6 +271,68 @@ module('Unit | Utility | nostr', function () {
assert.strictEqual(photos[0].publishedAt, null);
});
test('parsePlacePhotos extracts top-level x hashes', function (assert) {
const hash =
'a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61';
const thumbHash =
'c5a528e20235e16cc1c18090b8f04179de76288ea4e410b0fcb8d1487e416a2d';
const events = [
{
id: 'event-1',
pubkey: 'pubkey-1',
created_at: 100,
tags: [
['i', 'osm:node:123'],
['imeta', 'url https://example.com/photo.jpg', `x ${hash}`],
['x', hash],
['x', thumbHash],
],
},
];
const photos = parsePlacePhotos(events);
assert.strictEqual(photos[0].hash, hash, 'imeta hash is primary');
assert.deepEqual(photos[0].hashes, [hash, thumbHash]);
});
test('parsePlacePhotos falls back to an imeta x hash', function (assert) {
const hash =
'b9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61';
const events = [
{
id: 'event-1',
pubkey: 'pubkey-1',
created_at: 100,
tags: [['imeta', 'url https://example.com/photo.jpg', `x ${hash}`]],
},
];
const photos = parsePlacePhotos(events);
assert.strictEqual(photos[0].hash, hash);
assert.deepEqual(photos[0].hashes, [hash]);
});
test('parsePlacePhotos treats mismatched x hashes as untrusted', function (assert) {
const events = [
{
id: 'event-1',
pubkey: 'pubkey-1',
created_at: 100,
tags: [
['imeta', 'url https://example.com/photo.jpg', `x ${'a'.repeat(64)}`],
['x', 'b'.repeat(64)],
],
},
];
const photos = parsePlacePhotos(events);
assert.strictEqual(photos[0].hash, null);
assert.deepEqual(photos[0].hashes, []);
});
test('uniqNormalizedRelays returns normalized unique relays', function (assert) {
const relays = uniqNormalizedRelays([
'Relay.example.com',
+165
View File
@@ -0,0 +1,165 @@
import { module, test } from 'qunit';
import {
buildPlacePhotoTags,
extractMediaHashes,
} from 'marco/utils/photo-tags';
const HASH = 'a9c84e183789a74288b8e05d04cc61230e74f386925a953e6b29f957e8cc3a61';
const THUMB_HASH =
'c5a528e20235e16cc1c18090b8f04179de76288ea4e410b0fcb8d1487e416a2d';
const PHOTO = {
url: `https://blossom.example.com/${HASH}.jpg`,
type: 'image/jpeg',
hash: HASH,
thumbHash: THUMB_HASH,
dim: '1920x1920',
fallbackUrls: [`https://mirror.example.com/${HASH}.jpg`],
thumbUrl: 'https://example.com/thumb.jpg',
blurhash: 'UHI=0o~q4T-o~q%MozM{x]t7RjRPt7oKkCWB',
};
const PLACE = {
osmId: '123',
osmType: 'node',
lat: 52.52,
lon: 13.405,
};
module('Unit | Utility | photo-tags', function () {
test('buildPlacePhotoTags emits queryable x tags for media and thumbnail', function (assert) {
const tags = buildPlacePhotoTags(PHOTO, PLACE, {
tags: ['food'],
alt: ' A bowl of ramen ',
});
assert.deepEqual(tags[0], ['i', 'osm:node:123']);
assert.deepEqual(tags[1], ['t', 'food']);
const geohashes = tags.filter((t) => t[0] === 'g').map((t) => t[1]);
assert.deepEqual(
geohashes.map((g) => g.length),
[4, 6, 7, 9],
'geohashes at all four precisions'
);
const imeta = tags.find((t) => t[0] === 'imeta');
assert.ok(imeta.includes(`x ${HASH}`), 'imeta carries the primary hash');
assert.notOk(
imeta.includes(`x ${THUMB_HASH}`),
'imeta does not carry the thumbnail hash'
);
assert.ok(imeta.includes('alt A bowl of ramen'), 'alt is trimmed');
assert.ok(
imeta.includes(`fallback https://mirror.example.com/${HASH}.jpg`),
'fallback included'
);
assert.ok(imeta.includes('thumb https://example.com/thumb.jpg'));
assert.ok(imeta.includes(`blurhash ${PHOTO.blurhash}`));
const topLevelX = tags.filter((t) => t[0] === 'x');
assert.deepEqual(
topLevelX,
[
['x', HASH],
['x', THUMB_HASH],
],
'primary hash first, then thumbnail hash'
);
});
test('buildPlacePhotoTags deduplicates x hashes', function (assert) {
const tags = buildPlacePhotoTags(
{ ...PHOTO, thumbHash: HASH },
{ osmId: '1' }
);
const topLevelX = tags.filter((t) => t[0] === 'x');
assert.deepEqual(topLevelX, [['x', HASH]], 'one unique x value');
});
test('buildPlacePhotoTags omits x in both places when no hash is known', function (assert) {
const tags = buildPlacePhotoTags(
{ ...PHOTO, hash: null, thumbHash: null },
{ osmId: '456', osmType: 'way' }
);
const imeta = tags.find((t) => t[0] === 'imeta');
assert.notOk(
imeta.some((field) => field.startsWith('x ')),
'no imeta x'
);
assert.notOk(
tags.some((t) => t[0] === 'x'),
'no top-level x'
);
assert.deepEqual(tags[0], ['i', 'osm:way:456']);
assert.notOk(
tags.some((t) => t[0] === 'g'),
'no geohashes without coordinates'
);
});
test('extractMediaHashes uses the imeta x as primary and returns every top-level hash', function (assert) {
const event = {
tags: [
[
'imeta',
'url https://example.com/photo.jpg',
`x ${HASH}`,
'thumb https://example.com/thumb.jpg',
],
['x', HASH],
['x', THUMB_HASH],
],
};
const result = extractMediaHashes(event);
assert.strictEqual(result.primary, HASH);
assert.deepEqual(result.hashes, [HASH, THUMB_HASH]);
});
test('extractMediaHashes falls back to a sole top-level hash', function (assert) {
const event = { tags: [['x', THUMB_HASH]] };
const result = extractMediaHashes(event);
assert.strictEqual(result.primary, THUMB_HASH);
assert.deepEqual(result.hashes, [THUMB_HASH]);
});
test('extractMediaHashes falls back to an imeta-only hash', function (assert) {
const event = {
tags: [['imeta', 'url https://example.com/photo.jpg', `x ${HASH}`]],
};
const result = extractMediaHashes(event);
assert.strictEqual(result.primary, HASH);
assert.deepEqual(result.hashes, [HASH]);
});
test('extractMediaHashes treats a non-matching imeta hash as untrusted', function (assert) {
const event = {
tags: [
['imeta', 'url https://example.com/photo.jpg', `x ${HASH}`],
['x', THUMB_HASH],
],
};
const result = extractMediaHashes(event);
assert.strictEqual(result.primary, null);
assert.deepEqual(result.hashes, []);
});
test('extractMediaHashes returns empty results when no hash is present', function (assert) {
assert.deepEqual(
extractMediaHashes({
tags: [['imeta', 'url https://example.com/a.jpg']],
}),
{ primary: null, hashes: [] }
);
});
});