Publish and consume x tags on kind 360 place photos
CI / Lint (pull_request) Successful in 59s
CI / Test (pull_request) Successful in 1m24s
Release Drafter / Update release notes draft (pull_request) Successful in 16s

Emit top-level x tags for the primary media and thumbnail SHA-256 hashes (with the primary also inside imeta) when publishing. Parsed photos expose the hash set, and photo deletion prefers it over extracting hashes from Blossom URLs, keeping URL extraction as a fallback for legacy events.
This commit is contained in:
raucao committed 2026-11-27 19:23:16 +04:00
1 parent 98f361e2d5
commit 748bc626a8
9 files changed
+447 -65

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 };
}
+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: [] }
);
});
});