Add Nostr photo feeds and wallpaper selection
Read the curated photo feeds from wss://nostr.kosmos.org, verify events, cache originals and thumbnails, and let users pick a wallpaper from the Photos section. Nature is the default feed; City Nights is opt-in. Adds the manual publishing scripts, real event fixtures, protocol documentation, and tests with stubbed network connections.
This commit is contained in:
43 files changed
+4471
-8
No files matched your search
@@ -0,0 +1,39 @@
|
||||
import Component from '@glimmer/component';
|
||||
import { tracked } from '@glimmer/tracking';
|
||||
import { service } from '@ember/service';
|
||||
|
||||
// Settings-grid thumbnail. Prefers the cached object URL and falls back to the
|
||||
// remote Blossom thumbnail while the cache is warming.
|
||||
export default class PhotoThumbnailComponent extends Component {
|
||||
@service photoCache;
|
||||
|
||||
@tracked src = null;
|
||||
|
||||
constructor(owner, args) {
|
||||
super(owner, args);
|
||||
this.src = this.args.photo.thumbUrl;
|
||||
this.loadCached();
|
||||
}
|
||||
|
||||
async loadCached() {
|
||||
try {
|
||||
const url = await this.photoCache.thumbUrl(this.args.photo);
|
||||
if (url) {
|
||||
this.src = url;
|
||||
}
|
||||
} catch {
|
||||
// The remote thumbnail remains as the fallback.
|
||||
}
|
||||
}
|
||||
|
||||
<template>
|
||||
<img
|
||||
src={{this.src}}
|
||||
alt={{@photo.alt}}
|
||||
data-test-photo-thumbnail
|
||||
loading="lazy"
|
||||
draggable="false"
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
</template>
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import Component from '@glimmer/component';
|
||||
import { fn } from '@ember/helper';
|
||||
import { on } from '@ember/modifier';
|
||||
import { service } from '@ember/service';
|
||||
import PhotoThumbnail from '../../../photo-thumbnail.gjs';
|
||||
|
||||
// One feed card in the Photos settings section. Kept separate from the section
|
||||
// shell so the thumbnail grid and feed toggle stay easy to test.
|
||||
export default class SettingsPhotoFeedComponent extends Component {
|
||||
@service photos;
|
||||
|
||||
get enabled() {
|
||||
return this.photos.isFeedEnabled(this.args.feed.id);
|
||||
}
|
||||
|
||||
get photosForFeed() {
|
||||
return this.photos.photosForFeed(this.args.feed.id);
|
||||
}
|
||||
|
||||
get currentPhotoId() {
|
||||
return this.photos.currentPhoto?.id ?? null;
|
||||
}
|
||||
|
||||
isCurrent = (photoId) => this.currentPhotoId === photoId;
|
||||
|
||||
select = async (photoId) => {
|
||||
await this.photos.setCurrentPhoto(photoId);
|
||||
};
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="rounded-xl border border-gray-200 p-4"
|
||||
data-test-photo-feed={{@feed.id}}
|
||||
>
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<h4 class="text-sm font-semibold text-gray-900">
|
||||
{{@feed.title}}
|
||||
</h4>
|
||||
<p class="mt-1 text-sm text-gray-500">
|
||||
{{@feed.description}}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<label
|
||||
class="relative inline-flex shrink-0 cursor-pointer items-center"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={{this.enabled}}
|
||||
data-test-photo-feed-toggle={{@feed.id}}
|
||||
{{on "change" (fn @onToggle @feed.id)}}
|
||||
class="peer sr-only"
|
||||
/>
|
||||
<span class="sr-only">{{@feed.title}}</span>
|
||||
<span
|
||||
class="h-5 w-9 rounded-full bg-gray-200 transition-colors peer-checked:bg-indigo-600 peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-indigo-600"
|
||||
></span>
|
||||
<span
|
||||
class="absolute left-0.5 h-4 w-4 rounded-full bg-white shadow transition-transform peer-checked:translate-x-4"
|
||||
></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{{#if this.enabled}}
|
||||
{{#if this.photosForFeed.length}}
|
||||
<ul
|
||||
class="mt-4 grid grid-cols-4 gap-2"
|
||||
data-test-photo-grid={{@feed.id}}
|
||||
>
|
||||
{{#each this.photosForFeed key="id" as |photo|}}
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
data-test-photo={{photo.id}}
|
||||
aria-pressed={{if (this.isCurrent photo.id) "true" "false"}}
|
||||
{{on "click" (fn this.select photo.id)}}
|
||||
class="group relative block aspect-video w-full overflow-hidden rounded-md bg-gray-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
|
||||
>
|
||||
<PhotoThumbnail @photo={{photo}} />
|
||||
{{#if (this.isCurrent photo.id)}}
|
||||
<span
|
||||
class="absolute top-1.5 right-1.5 rounded-full bg-indigo-600 p-1 text-white shadow-sm"
|
||||
aria-label="Current wallpaper"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2.5"
|
||||
aria-hidden="true"
|
||||
class="size-3"
|
||||
>
|
||||
<path
|
||||
d="m5 13 4 4L19 7"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
{{/if}}
|
||||
</button>
|
||||
</li>
|
||||
{{/each}}
|
||||
</ul>
|
||||
{{else if this.photos.refreshing}}
|
||||
<p class="mt-4 text-sm text-gray-400">Loading photos...</p>
|
||||
{{else}}
|
||||
<p class="mt-4 text-sm text-gray-400">
|
||||
No photos available yet.
|
||||
</p>
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
</section>
|
||||
</template>
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import Component from '@glimmer/component';
|
||||
import { action } from '@ember/object';
|
||||
import { service } from '@ember/service';
|
||||
import PhotoFeed from './photo-feed.gjs';
|
||||
|
||||
// The Photos settings section: enable feeds and pick the current wallpaper.
|
||||
// Creator attribution intentionally lives on the dashboard, next to Settings.
|
||||
export default class SettingsPhotosSection extends Component {
|
||||
@service photos;
|
||||
|
||||
get feeds() {
|
||||
return this.photos.feeds;
|
||||
}
|
||||
|
||||
@action
|
||||
async toggleFeed(feedId, event) {
|
||||
await this.photos.setFeedEnabled(feedId, event.target.checked);
|
||||
}
|
||||
|
||||
<template>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto px-6 py-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<p class="max-w-prose text-sm text-gray-500">
|
||||
Choose which photo feeds are available and pick the wallpaper shown on
|
||||
your dashboard.
|
||||
</p>
|
||||
{{#if this.photos.refreshing}}
|
||||
<span class="text-xs text-gray-400">Refreshing...</span>
|
||||
{{/if}}
|
||||
</div>
|
||||
|
||||
{{#if this.photos.error}}
|
||||
<p class="mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||
{{this.photos.error}}
|
||||
</p>
|
||||
{{/if}}
|
||||
|
||||
{{#if this.feeds.length}}
|
||||
<div class="mt-6 space-y-4">
|
||||
{{#each this.feeds as |feed|}}
|
||||
<PhotoFeed @feed={{feed}} @onToggle={{this.toggleFeed}} />
|
||||
{{/each}}
|
||||
</div>
|
||||
|
||||
<p class="mt-8 text-xs text-gray-400">
|
||||
Weekly rotation is planned for a later update.
|
||||
</p>
|
||||
{{else if this.photos.refreshing}}
|
||||
<p class="mt-6 text-sm text-gray-400">Loading photo feeds...</p>
|
||||
{{else}}
|
||||
<p
|
||||
class="mt-6 rounded-xl bg-gray-50 p-6 text-center text-sm text-gray-500"
|
||||
>
|
||||
No photo feeds loaded yet.
|
||||
</p>
|
||||
{{/if}}
|
||||
</div>
|
||||
</template>
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import Component from '@glimmer/component';
|
||||
import { service } from '@ember/service';
|
||||
|
||||
// Discreet attribution for the current wallpaper, shown next to the settings
|
||||
// button. Kept out of Settings by design.
|
||||
export default class WallpaperCreditComponent extends Component {
|
||||
@service photos;
|
||||
|
||||
get credit() {
|
||||
return this.photos.currentCredit;
|
||||
}
|
||||
|
||||
get label() {
|
||||
if (!this.credit) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `Photo by ${this.credit.name}`;
|
||||
}
|
||||
|
||||
<template>
|
||||
{{#if this.credit}}
|
||||
<a
|
||||
href={{this.credit.url}}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
data-test-wallpaper-credit
|
||||
class="text-xs text-white/60 transition-colors hover:text-white/90 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white/70"
|
||||
>
|
||||
{{this.label}}
|
||||
</a>
|
||||
{{/if}}
|
||||
</template>
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import Component from '@glimmer/component';
|
||||
import { service } from '@ember/service';
|
||||
|
||||
// Full-bleed wallpaper. Pass @photo for route-specific images (the welcome
|
||||
// screen); otherwise the selected feed photo is used. A bundled fallback sits
|
||||
// behind the current image so a failed/remote load never leaves a blank page.
|
||||
export default class WallpaperComponent extends Component {
|
||||
@service photos;
|
||||
|
||||
get photo() {
|
||||
return this.args.photo ?? this.photos.currentWallpaper;
|
||||
}
|
||||
|
||||
get src() {
|
||||
return this.photo?.displayUrl ?? this.photo?.url ?? null;
|
||||
}
|
||||
|
||||
get fallbackSrc() {
|
||||
return this.photos.fallbackPhoto.displayUrl;
|
||||
}
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="pointer-events-none fixed inset-0 -z-10 overflow-hidden bg-gray-900"
|
||||
data-test-wallpaper-container
|
||||
>
|
||||
<img
|
||||
src={{this.fallbackSrc}}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
draggable="false"
|
||||
class="absolute inset-0 h-full w-full object-cover"
|
||||
/>
|
||||
{{#if this.src}}
|
||||
<img
|
||||
src={{this.src}}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
draggable="false"
|
||||
data-test-wallpaper
|
||||
class="absolute inset-0 h-full w-full object-cover"
|
||||
/>
|
||||
{{/if}}
|
||||
</div>
|
||||
</template>
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import Component from '@glimmer/component';
|
||||
import { action } from '@ember/object';
|
||||
import { on } from '@ember/modifier';
|
||||
import { service } from '@ember/service';
|
||||
import Wallpaper from './wallpaper.gjs';
|
||||
import { WELCOME_WALLPAPER_URL } from '../config/nostr';
|
||||
import autofocus from '../modifiers/autofocus';
|
||||
|
||||
// First-run onboarding step: ask the user what to call them. Kept presentational
|
||||
@@ -11,6 +13,14 @@ export default class WelcomeComponent extends Component {
|
||||
@service user;
|
||||
@service router;
|
||||
|
||||
get welcomePhoto() {
|
||||
return {
|
||||
url: WELCOME_WALLPAPER_URL,
|
||||
displayUrl: WELCOME_WALLPAPER_URL,
|
||||
alt: '',
|
||||
};
|
||||
}
|
||||
|
||||
@action
|
||||
handleSubmit(event) {
|
||||
event.preventDefault();
|
||||
@@ -28,6 +38,8 @@ export default class WelcomeComponent extends Component {
|
||||
}
|
||||
|
||||
<template>
|
||||
<Wallpaper @photo={{this.welcomePhoto}} />
|
||||
|
||||
<div
|
||||
class="col-span-3 row-span-3 flex flex-col items-center justify-center px-6 text-center text-white"
|
||||
data-test-welcome
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// Nostr photo feeds. The protocol profile is documented in
|
||||
// doc/nostr-photo-feeds.md. Keep these identifiers in sync with the published
|
||||
// feed events and scripts/nostr/manifest.json.
|
||||
|
||||
export const NOSTR_RELAY_URL = 'wss://nostr.kosmos.org';
|
||||
|
||||
// Râu Cao (raucao@kosmos.org), the curator that publishes the official feeds.
|
||||
export const NOSTR_PHOTO_CURATOR =
|
||||
'1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb';
|
||||
|
||||
// Marks kind-30006 events that belong to the Dashtab photo-feed profile.
|
||||
export const PHOTO_FEED_TAG = 'dashtab-photo-feed';
|
||||
|
||||
// Feed ids use a namespace so they cannot clash with other picture sets.
|
||||
export const PHOTO_FEED_PREFIX = 'dt:';
|
||||
export const NATURE_FEED_ID = 'dt:nature';
|
||||
export const CITY_NIGHTS_FEED_ID = 'dt:city-nights';
|
||||
|
||||
// Nature is the default feed. City Nights is available but opt-in.
|
||||
export const DEFAULT_ENABLED_FEED_IDS = [NATURE_FEED_ID];
|
||||
|
||||
// The welcome screen uses a separate bundled image while the first feed photos
|
||||
// are being prefetched. Replace this when the real welcome photo is added.
|
||||
export const WELCOME_WALLPAPER_URL =
|
||||
'/img/wallpapers/meiying-ng-iB7gjOsLrEQ-unsplash.jpg';
|
||||
|
||||
// Shown on the dashboard until a cached/remote feed original is available.
|
||||
export const FALLBACK_WALLPAPER_URL =
|
||||
'/img/wallpapers/aleksandr-popov-ez4pqCpEfuI-unsplash.jpg';
|
||||
|
||||
// Storage.
|
||||
export const PHOTO_STORAGE_NAMESPACE = 'photos';
|
||||
export const PHOTO_PREFERENCES_NAMESPACE = 'preferences';
|
||||
export const PHOTO_CONFIG_KEY = 'photos.config';
|
||||
export const PHOTO_CACHE_NAME = 'dashtab-photo-cache-v1';
|
||||
export const PHOTO_CACHE_ORIGIN = 'https://dashtab.local';
|
||||
|
||||
// Protocol/query limits.
|
||||
export const NOSTR_QUERY_TIMEOUT = 10_000;
|
||||
export const PHOTO_ID_CHUNK_SIZE = 300;
|
||||
export const PHOTO_PREFETCH_ORIGINAL_COUNT = 3;
|
||||
|
||||
// Rotation is intentionally out of this phase; the persisted config keeps the
|
||||
// field so the next phase can add it without a storage migration.
|
||||
export const DEFAULT_ROTATION = 'off';
|
||||
export const ROTATION_MODES = ['off', 'weekly'];
|
||||
@@ -1,5 +1,6 @@
|
||||
import Events from '../components/settings/global-settings/sections/events.gjs';
|
||||
import MarketTicker from '../components/settings/global-settings/sections/market-ticker.gjs';
|
||||
import Photos from '../components/settings/global-settings/sections/photos.gjs';
|
||||
import ProtocolGateway from '../components/settings/global-settings/sections/protocol-gateway.gjs';
|
||||
import SiteLinks from '../components/settings/global-settings/sections/site-links.gjs';
|
||||
|
||||
@@ -7,6 +8,7 @@ import SiteLinks from '../components/settings/global-settings/sections/site-link
|
||||
// entry fall back to the generic placeholder, so this grows one section at a
|
||||
// time. Mirrors the integration form registry in `integration-forms.js`.
|
||||
const CONTENT = {
|
||||
photos: Photos,
|
||||
'site-links': SiteLinks,
|
||||
events: Events,
|
||||
'market-ticker': MarketTicker,
|
||||
|
||||
@@ -6,12 +6,17 @@ import { service } from '@ember/service';
|
||||
export default class IndexRoute extends Route {
|
||||
@service user;
|
||||
@service router;
|
||||
@service photos;
|
||||
|
||||
async beforeModel() {
|
||||
await this.user.ready;
|
||||
|
||||
if (!this.user.hasName) {
|
||||
this.router.replaceWith('welcome');
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the dashboard current without blocking the first paint.
|
||||
this.photos.refreshInBackground();
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,18 @@ import { service } from '@ember/service';
|
||||
export default class WelcomeRoute extends Route {
|
||||
@service user;
|
||||
@service router;
|
||||
@service photos;
|
||||
|
||||
async beforeModel() {
|
||||
await this.user.ready;
|
||||
|
||||
if (this.user.hasName) {
|
||||
this.router.replaceWith('index');
|
||||
return;
|
||||
}
|
||||
|
||||
// Download the first feed photos while the user is naming the dashboard.
|
||||
// The prefetch handles its own errors and never blocks the welcome form.
|
||||
this.photos.prefetchForWelcome();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import Service from '@ember/service';
|
||||
import {
|
||||
NOSTR_PHOTO_CURATOR,
|
||||
NOSTR_QUERY_TIMEOUT,
|
||||
NOSTR_RELAY_URL,
|
||||
PHOTO_FEED_TAG,
|
||||
PHOTO_ID_CHUNK_SIZE,
|
||||
} from '../config/nostr';
|
||||
import { verifyEvent } from '../utils/nostr-events';
|
||||
|
||||
let subscriptionCounter = 0;
|
||||
|
||||
// Minimal read-only Nostr relay client. Each query opens one WebSocket,
|
||||
// subscribes, collects verified events until EOSE, and closes. Signing and
|
||||
// publishing are deliberately out of scope for the app.
|
||||
export default class NostrService extends Service {
|
||||
url = NOSTR_RELAY_URL;
|
||||
|
||||
createSocket(url) {
|
||||
return new WebSocket(url);
|
||||
}
|
||||
|
||||
query(
|
||||
filters,
|
||||
{ timeout = NOSTR_QUERY_TIMEOUT, signal, verify = true } = {}
|
||||
) {
|
||||
const subscriptionId = `dashtab-${(subscriptionCounter += 1)}`;
|
||||
const socket = this.createSocket(this.url);
|
||||
const events = [];
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let timer;
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
try {
|
||||
socket.close();
|
||||
} catch {
|
||||
// The socket may already be closed.
|
||||
}
|
||||
};
|
||||
|
||||
const finish = (error) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
cleanup();
|
||||
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(events);
|
||||
}
|
||||
};
|
||||
|
||||
const onAbort = () => finish(new Error('Nostr query aborted'));
|
||||
|
||||
const onOpen = () => {
|
||||
try {
|
||||
socket.send(JSON.stringify(['REQ', subscriptionId, ...filters]));
|
||||
} catch (error) {
|
||||
finish(error);
|
||||
}
|
||||
};
|
||||
|
||||
const onMessage = (messageEvent) => {
|
||||
let message;
|
||||
|
||||
try {
|
||||
message = JSON.parse(messageEvent.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Array.isArray(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [type, id] = message;
|
||||
if (id !== subscriptionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === 'EVENT') {
|
||||
const event = message[2];
|
||||
if (!verify || verifyEvent(event)) {
|
||||
events.push(event);
|
||||
}
|
||||
} else if (type === 'EOSE') {
|
||||
finish();
|
||||
} else if (type === 'CLOSED') {
|
||||
finish(new Error(message[2] || 'Nostr subscription closed'));
|
||||
}
|
||||
};
|
||||
|
||||
const onError = () => finish(new Error('Nostr relay connection failed'));
|
||||
const onClose = () => finish(new Error('Nostr relay connection closed'));
|
||||
|
||||
socket.addEventListener('open', onOpen);
|
||||
socket.addEventListener('message', onMessage);
|
||||
socket.addEventListener('error', onError);
|
||||
socket.addEventListener('close', onClose);
|
||||
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
finish(new Error('Nostr query aborted'));
|
||||
return;
|
||||
}
|
||||
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
|
||||
timer = setTimeout(
|
||||
() => finish(new Error('Nostr query timed out')),
|
||||
timeout
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
queryFeedEvents() {
|
||||
return this.query([
|
||||
{
|
||||
kinds: [30006],
|
||||
authors: [NOSTR_PHOTO_CURATOR],
|
||||
'#t': [PHOTO_FEED_TAG],
|
||||
limit: 20,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
async queryPhotos(photoIds) {
|
||||
const uniqueIds = [...new Set(photoIds)];
|
||||
const events = [];
|
||||
|
||||
for (
|
||||
let index = 0;
|
||||
index < uniqueIds.length;
|
||||
index += PHOTO_ID_CHUNK_SIZE
|
||||
) {
|
||||
const ids = uniqueIds.slice(index, index + PHOTO_ID_CHUNK_SIZE);
|
||||
const chunk = await this.query([{ kinds: [20], ids, limit: ids.length }]);
|
||||
events.push(...chunk);
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import Service from '@ember/service';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import { bytesToHex } from '@noble/hashes/utils.js';
|
||||
import { PHOTO_CACHE_NAME, PHOTO_CACHE_ORIGIN } from '../config/nostr';
|
||||
|
||||
// Cache Storage wrapper for full-size originals and thumbnails. Originals are
|
||||
// keyed by their content hash; thumbnails are keyed by their Blossom URL.
|
||||
// Object URLs are reused for the lifetime of the service.
|
||||
export default class PhotoCacheService extends Service {
|
||||
objectUrls = new Map();
|
||||
|
||||
get cacheStorage() {
|
||||
return typeof caches === 'undefined' ? null : caches;
|
||||
}
|
||||
|
||||
async openCache() {
|
||||
if (!this.cacheStorage) {
|
||||
throw new Error('Cache Storage is unavailable');
|
||||
}
|
||||
|
||||
return this.cacheStorage.open(PHOTO_CACHE_NAME);
|
||||
}
|
||||
|
||||
originalKey(photo) {
|
||||
return `${PHOTO_CACHE_ORIGIN}/photos/${photo.sha256 ?? photo.id}`;
|
||||
}
|
||||
|
||||
thumbKey(photo) {
|
||||
return photo.thumbUrl;
|
||||
}
|
||||
|
||||
async cachedResponse(key) {
|
||||
try {
|
||||
const cache = await this.openCache();
|
||||
return await cache.match(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async put(url, key, { expectedSha256 } = {}) {
|
||||
const response = await fetch(url, { credentials: 'omit' });
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch photo: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const blob = await response.clone().blob();
|
||||
|
||||
if (expectedSha256) {
|
||||
const actual = bytesToHex(
|
||||
sha256(new Uint8Array(await blob.arrayBuffer()))
|
||||
);
|
||||
if (actual !== expectedSha256) {
|
||||
throw new Error('Photo hash mismatch');
|
||||
}
|
||||
}
|
||||
|
||||
const cache = await this.openCache();
|
||||
await cache.put(key, response.clone());
|
||||
return blob;
|
||||
}
|
||||
|
||||
async objectUrlFor(key) {
|
||||
const existing = this.objectUrls.get(key);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const response = await this.cachedResponse(key);
|
||||
if (!response) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
this.objectUrls.set(key, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
originalUrl(photo) {
|
||||
return this.objectUrlFor(this.originalKey(photo));
|
||||
}
|
||||
|
||||
thumbUrl(photo) {
|
||||
return this.objectUrlFor(this.thumbKey(photo));
|
||||
}
|
||||
|
||||
async prefetchOriginal(photo) {
|
||||
const key = this.originalKey(photo);
|
||||
const cached = await this.objectUrlFor(key);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const blob = await this.put(photo.url, key, {
|
||||
expectedSha256: photo.sha256,
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
this.objectUrls.set(key, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
async prefetchThumb(photo) {
|
||||
const key = this.thumbKey(photo);
|
||||
const cached = await this.objectUrlFor(key);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const blob = await this.put(photo.thumbUrl, key);
|
||||
const url = URL.createObjectURL(blob);
|
||||
this.objectUrls.set(key, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
willDestroy() {
|
||||
for (const url of this.objectUrls.values()) {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
this.objectUrls.clear();
|
||||
super.willDestroy(...arguments);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
import Service, { service } from '@ember/service';
|
||||
import { tracked } from '@glimmer/tracking';
|
||||
import {
|
||||
DEFAULT_ENABLED_FEED_IDS,
|
||||
DEFAULT_ROTATION,
|
||||
FALLBACK_WALLPAPER_URL,
|
||||
NATURE_FEED_ID,
|
||||
PHOTO_CONFIG_KEY,
|
||||
PHOTO_PREFERENCES_NAMESPACE,
|
||||
PHOTO_PREFETCH_ORIGINAL_COUNT,
|
||||
PHOTO_STORAGE_NAMESPACE,
|
||||
WELCOME_WALLPAPER_URL,
|
||||
} from '../config/nostr';
|
||||
import { parseFeedEvents, parsePhotoEvents } from '../utils/nostr-photo-events';
|
||||
|
||||
// Owns the read-only photo feed state, the selected wallpaper, and the
|
||||
// prefetch/cache policy. The protocol is documented in doc/nostr-photo-feeds.md.
|
||||
export default class PhotosService extends Service {
|
||||
@service storage;
|
||||
@service nostr;
|
||||
@service photoCache;
|
||||
|
||||
@tracked feeds = [];
|
||||
@tracked photos = [];
|
||||
@tracked enabledFeedIds = [...DEFAULT_ENABLED_FEED_IDS];
|
||||
@tracked currentPhotoId = null;
|
||||
@tracked displayUrl = null;
|
||||
@tracked refreshing = false;
|
||||
@tracked error = null;
|
||||
@tracked initialized = false;
|
||||
|
||||
ready = null;
|
||||
refreshPromise = null;
|
||||
prefetchPromise = null;
|
||||
displayToken = 0;
|
||||
|
||||
get welcomePhoto() {
|
||||
return {
|
||||
url: WELCOME_WALLPAPER_URL,
|
||||
displayUrl: WELCOME_WALLPAPER_URL,
|
||||
alt: '',
|
||||
};
|
||||
}
|
||||
|
||||
get fallbackPhoto() {
|
||||
return {
|
||||
url: FALLBACK_WALLPAPER_URL,
|
||||
displayUrl: FALLBACK_WALLPAPER_URL,
|
||||
alt: '',
|
||||
};
|
||||
}
|
||||
|
||||
get enabledFeeds() {
|
||||
return this.feeds.filter((feed) => this.enabledFeedIds.includes(feed.id));
|
||||
}
|
||||
|
||||
get defaultFeed() {
|
||||
return (
|
||||
this.enabledFeeds.find((feed) => feed.id === NATURE_FEED_ID) ??
|
||||
this.enabledFeeds[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
get defaultPhoto() {
|
||||
const feed = this.defaultFeed;
|
||||
if (!feed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.photosForFeed(feed.id)[0] ?? null;
|
||||
}
|
||||
|
||||
get currentPhoto() {
|
||||
const selected = this.currentPhotoId
|
||||
? this.photoById(this.currentPhotoId)
|
||||
: null;
|
||||
|
||||
if (selected?.attributed) {
|
||||
return selected;
|
||||
}
|
||||
|
||||
return this.defaultPhoto;
|
||||
}
|
||||
|
||||
get currentWallpaper() {
|
||||
const photo = this.currentPhoto;
|
||||
if (!photo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...photo,
|
||||
displayUrl: this.displayUrl,
|
||||
};
|
||||
}
|
||||
|
||||
get currentCredit() {
|
||||
const creator = this.currentPhoto?.creator;
|
||||
if (!creator?.name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = creator.profile ?? creator.source;
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
name: creator.name,
|
||||
url,
|
||||
platform: creator.platform,
|
||||
};
|
||||
}
|
||||
|
||||
get visiblePhotos() {
|
||||
const seen = new Set();
|
||||
const photos = [];
|
||||
|
||||
for (const feed of this.enabledFeeds) {
|
||||
for (const photo of this.photosForFeed(feed.id)) {
|
||||
if (!seen.has(photo.id)) {
|
||||
seen.add(photo.id);
|
||||
photos.push(photo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return photos;
|
||||
}
|
||||
|
||||
photoById(id) {
|
||||
return this.photos.find((photo) => photo.id === id) ?? null;
|
||||
}
|
||||
|
||||
photosForFeed(feedId) {
|
||||
const feed = this.feeds.find((candidate) => candidate.id === feedId);
|
||||
if (!feed) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return feed.photoIds
|
||||
.map((id) => this.photoById(id))
|
||||
.filter((photo) => photo?.attributed);
|
||||
}
|
||||
|
||||
isFeedEnabled(feedId) {
|
||||
return this.enabledFeedIds.includes(feedId);
|
||||
}
|
||||
|
||||
loadCached() {
|
||||
if (!this.ready) {
|
||||
this.ready = this.doLoadCached();
|
||||
}
|
||||
|
||||
return this.ready;
|
||||
}
|
||||
|
||||
async doLoadCached() {
|
||||
try {
|
||||
const config = await this.storage.get(
|
||||
PHOTO_PREFERENCES_NAMESPACE,
|
||||
PHOTO_CONFIG_KEY
|
||||
);
|
||||
|
||||
if (config) {
|
||||
if (Array.isArray(config.enabledFeedIds)) {
|
||||
this.enabledFeedIds = config.enabledFeedIds;
|
||||
}
|
||||
if (config.currentPhotoId) {
|
||||
this.currentPhotoId = config.currentPhotoId;
|
||||
}
|
||||
}
|
||||
|
||||
const keys = await this.storage.keys(PHOTO_STORAGE_NAMESPACE);
|
||||
const feedEvents = [];
|
||||
const photoEvents = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const event = await this.storage.get(PHOTO_STORAGE_NAMESPACE, key);
|
||||
if (!event) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.kind === 30006) {
|
||||
feedEvents.push(event);
|
||||
} else if (event.kind === 20) {
|
||||
photoEvents.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
this.applyEvents(feedEvents, photoEvents);
|
||||
await this.resolveCurrentWallpaper();
|
||||
} catch (error) {
|
||||
console.error('Error loading cached photos:', error);
|
||||
} finally {
|
||||
this.initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
applyEvents(feedEvents, photoEvents) {
|
||||
this.feeds = parseFeedEvents(feedEvents);
|
||||
this.photos = parsePhotoEvents(photoEvents);
|
||||
}
|
||||
|
||||
refreshInBackground() {
|
||||
this.refresh().catch((error) => {
|
||||
console.error('Error refreshing photo feeds:', error);
|
||||
});
|
||||
}
|
||||
|
||||
refresh({ prefetch = true } = {}) {
|
||||
if (!this.refreshPromise) {
|
||||
this.refreshPromise = this.doRefresh({ prefetch }).finally(() => {
|
||||
this.refreshPromise = null;
|
||||
});
|
||||
}
|
||||
|
||||
return this.refreshPromise;
|
||||
}
|
||||
|
||||
async doRefresh({ prefetch }) {
|
||||
await this.loadCached();
|
||||
|
||||
this.refreshing = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const feedEvents = await this.nostr.queryFeedEvents();
|
||||
const feeds = parseFeedEvents(feedEvents);
|
||||
|
||||
if (feeds.length > 0) {
|
||||
this.feeds = feeds;
|
||||
}
|
||||
|
||||
const ids = this.enabledFeeds.flatMap((feed) => feed.photoIds);
|
||||
const photoEvents = ids.length ? await this.nostr.queryPhotos(ids) : [];
|
||||
const freshPhotos = parsePhotoEvents(photoEvents);
|
||||
|
||||
// Keep cached photos for feeds that were not refreshed, but prefer the
|
||||
// freshly relayed copy when the same event id comes back.
|
||||
const byId = new Map(this.photos.map((photo) => [photo.id, photo]));
|
||||
for (const photo of freshPhotos) {
|
||||
byId.set(photo.id, photo);
|
||||
}
|
||||
this.photos = [...byId.values()];
|
||||
|
||||
await this.cacheEvents(this.feeds, freshPhotos);
|
||||
await this.resolveCurrentWallpaper();
|
||||
|
||||
if (prefetch) {
|
||||
this.prefetchAssets();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error refreshing photo feeds:', error);
|
||||
this.error = error?.message ?? 'Unable to refresh photo feeds';
|
||||
} finally {
|
||||
this.refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async cacheEvents(feeds, photos) {
|
||||
try {
|
||||
for (const feed of feeds) {
|
||||
await this.storage.set(
|
||||
PHOTO_STORAGE_NAMESPACE,
|
||||
`feed:${feed.id}`,
|
||||
feed.event
|
||||
);
|
||||
}
|
||||
|
||||
for (const photo of photos) {
|
||||
await this.storage.set(
|
||||
PHOTO_STORAGE_NAMESPACE,
|
||||
`photo:${photo.id}`,
|
||||
photo.event
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error caching photo events:', error);
|
||||
}
|
||||
}
|
||||
|
||||
prefetchAssets() {
|
||||
const photos = this.enabledFeeds.flatMap((feed) =>
|
||||
this.photosForFeed(feed.id)
|
||||
);
|
||||
const originals = photos.slice(0, PHOTO_PREFETCH_ORIGINAL_COUNT);
|
||||
const tasks = [
|
||||
...photos.map((photo) =>
|
||||
this.photoCache.prefetchThumb(photo).catch(() => null)
|
||||
),
|
||||
...originals.map((photo) =>
|
||||
this.photoCache.prefetchOriginal(photo).catch(() => null)
|
||||
),
|
||||
];
|
||||
|
||||
return Promise.allSettled(tasks).catch(() => null);
|
||||
}
|
||||
|
||||
prefetchForWelcome() {
|
||||
if (!this.prefetchPromise) {
|
||||
this.prefetchPromise = (async () => {
|
||||
await this.loadCached();
|
||||
await this.refresh({ prefetch: true });
|
||||
})()
|
||||
.catch((error) => {
|
||||
console.error('Error prefetching welcome photos:', error);
|
||||
})
|
||||
.finally(() => {
|
||||
this.prefetchPromise = null;
|
||||
});
|
||||
}
|
||||
|
||||
return this.prefetchPromise;
|
||||
}
|
||||
|
||||
async resolveCurrentWallpaper() {
|
||||
const photo = this.currentPhoto;
|
||||
const token = (this.displayToken += 1);
|
||||
|
||||
if (!photo) {
|
||||
this.displayUrl = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.photoCache.originalUrl(photo);
|
||||
if (token !== this.displayToken) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (cached) {
|
||||
this.displayUrl = cached;
|
||||
return;
|
||||
}
|
||||
|
||||
this.displayUrl = null;
|
||||
const url = await this.photoCache.prefetchOriginal(photo);
|
||||
if (token === this.displayToken) {
|
||||
this.displayUrl = url;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error resolving the wallpaper:', error);
|
||||
if (token === this.displayToken) {
|
||||
this.displayUrl = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async setCurrentPhoto(id) {
|
||||
const photo = this.photoById(id);
|
||||
if (!photo?.attributed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.currentPhotoId = id;
|
||||
await this.persistConfig();
|
||||
await this.resolveCurrentWallpaper();
|
||||
}
|
||||
|
||||
async setFeedEnabled(id, enabled) {
|
||||
const ids = new Set(this.enabledFeedIds);
|
||||
if (enabled) {
|
||||
ids.add(id);
|
||||
} else {
|
||||
ids.delete(id);
|
||||
}
|
||||
|
||||
this.enabledFeedIds = [...ids];
|
||||
await this.persistConfig();
|
||||
|
||||
if (enabled) {
|
||||
await this.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
async persistConfig() {
|
||||
try {
|
||||
await this.storage.set(PHOTO_PREFERENCES_NAMESPACE, PHOTO_CONFIG_KEY, {
|
||||
enabledFeedIds: [...this.enabledFeedIds],
|
||||
currentPhotoId: this.currentPhotoId,
|
||||
rotation: DEFAULT_ROTATION, // TODO: next phase
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error saving photo settings:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export default class StorageService extends Service {
|
||||
{ name: 'settings', storeName: 'settings' },
|
||||
{ name: 'icons', storeName: 'icons' },
|
||||
{ name: 'events', storeName: 'events' },
|
||||
{ name: 'photos', storeName: 'photos' },
|
||||
];
|
||||
|
||||
dbConfigs.forEach(({ name, storeName }) => {
|
||||
|
||||
@@ -4,10 +4,7 @@ import ModalHost from '../components/modal-host.gjs';
|
||||
<template>
|
||||
{{pageTitle "Dashtab"}}
|
||||
|
||||
<div
|
||||
id="wrapper"
|
||||
class="bg-[url(/img/wallpapers/aleksandr-popov-ez4pqCpEfuI-unsplash.jpg)] bg-cover bg-center min-h-screen w-full grid grid-cols-3 grid-rows-3"
|
||||
>
|
||||
<div id="wrapper" class="min-h-screen w-full grid grid-cols-3 grid-rows-3">
|
||||
{{outlet}}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -4,18 +4,26 @@ import BitcoinTicker from '../components/bitcoin-ticker.gjs';
|
||||
import SiteLinks from '../components/site-links.gjs';
|
||||
import SettingsButton from '../components/settings-button.gjs';
|
||||
import UpcomingEvents from '../components/upcoming-events.gjs';
|
||||
import Wallpaper from '../components/wallpaper.gjs';
|
||||
import WallpaperCredit from '../components/wallpaper-credit.gjs';
|
||||
|
||||
<template>
|
||||
{{pageTitle "New Tab"}}
|
||||
|
||||
<Wallpaper />
|
||||
|
||||
<div class="col-start-1 row-start-1 row-span-2 flex items-start p-12">
|
||||
<UpcomingEvents />
|
||||
</div>
|
||||
|
||||
<div class="col-start-1 row-start-3 flex items-end pl-12 pb-12">
|
||||
<div class="fixed bottom-12 left-12 z-10 flex items-center">
|
||||
<SettingsButton />
|
||||
</div>
|
||||
|
||||
<div class="fixed right-12 bottom-12 z-10 flex items-center justify-end">
|
||||
<WallpaperCredit />
|
||||
</div>
|
||||
|
||||
<div class="col-start-3 row-start-1 flex items-start justify-end pt-12 pr-12">
|
||||
<SiteLinks />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { schnorr } from '@noble/curves/secp256k1.js';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
||||
|
||||
// NIP-01 canonical serialization. The event id is the SHA-256 of this JSON
|
||||
// array, not of the full event object (which contains the id and signature).
|
||||
export function canonicalEvent(event) {
|
||||
return JSON.stringify([
|
||||
0,
|
||||
event.pubkey,
|
||||
event.created_at,
|
||||
event.kind,
|
||||
event.tags,
|
||||
event.content,
|
||||
]);
|
||||
}
|
||||
|
||||
export function eventId(event) {
|
||||
return bytesToHex(sha256(utf8ToBytes(canonicalEvent(event))));
|
||||
}
|
||||
|
||||
export function isHex(value, length) {
|
||||
if (typeof value !== 'string' || value.length !== length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return /^[0-9a-f]+$/.test(value);
|
||||
}
|
||||
|
||||
export function hasValidEventId(event) {
|
||||
try {
|
||||
return isHex(event?.id, 64) && eventId(event) === event.id;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function hasValidSignature(event) {
|
||||
try {
|
||||
if (
|
||||
!isHex(event?.id, 64) ||
|
||||
!isHex(event?.pubkey, 64) ||
|
||||
!isHex(event?.sig, 128)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return schnorr.verify(
|
||||
hexToBytes(event.sig),
|
||||
hexToBytes(event.id),
|
||||
hexToBytes(event.pubkey)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyEvent(event) {
|
||||
if (!event || typeof event !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hasValidEventId(event) && hasValidSignature(event);
|
||||
}
|
||||
|
||||
export function tagValues(event, name) {
|
||||
return (event?.tags ?? []).filter((tag) => tag?.[0] === name);
|
||||
}
|
||||
|
||||
export function tagValue(event, name) {
|
||||
return tagValues(event, name)[0]?.[1] ?? null;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
import { isHex, tagValue, tagValues } from './nostr-events';
|
||||
import {
|
||||
NATURE_FEED_ID,
|
||||
PHOTO_FEED_PREFIX,
|
||||
PHOTO_FEED_TAG,
|
||||
} from '../config/nostr';
|
||||
|
||||
// NIP-68's accepted image types.
|
||||
export const IMAGE_MIME_TYPES = new Set([
|
||||
'image/apng',
|
||||
'image/avif',
|
||||
'image/gif',
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/webp',
|
||||
]);
|
||||
|
||||
function isHttps(value) {
|
||||
return typeof value === 'string' && value.startsWith('https://');
|
||||
}
|
||||
|
||||
function splitImetaEntry(entry) {
|
||||
if (typeof entry !== 'string') {
|
||||
return ['', ''];
|
||||
}
|
||||
|
||||
const index = entry.indexOf(' ');
|
||||
if (index === -1) {
|
||||
return [entry, ''];
|
||||
}
|
||||
|
||||
return [entry.slice(0, index), entry.slice(index + 1)];
|
||||
}
|
||||
|
||||
export function parseImeta(tag) {
|
||||
const fields = { fallback: [] };
|
||||
|
||||
for (const entry of tag.slice(1)) {
|
||||
const [key, value] = splitImetaEntry(entry);
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (key === 'fallback') {
|
||||
fields.fallback.push(value);
|
||||
} else {
|
||||
fields[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return fields;
|
||||
}
|
||||
|
||||
export function parseDimensions(value) {
|
||||
const match = /^(\d+)x(\d+)$/.exec(value ?? '');
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { width: Number(match[1]), height: Number(match[2]) };
|
||||
}
|
||||
|
||||
function parseOriginMeta(value) {
|
||||
if (typeof value !== 'string' || !value.trim()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function uniqueStrings(values) {
|
||||
return [
|
||||
...new Set(values.filter((value) => typeof value === 'string' && value)),
|
||||
];
|
||||
}
|
||||
|
||||
export function parsePhotoEvent(event) {
|
||||
if (!event || event.kind !== 20) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const imetaTag = tagValues(event, 'imeta').find((tag) =>
|
||||
tag.slice(1).some((entry) => entry.startsWith('url '))
|
||||
);
|
||||
if (!imetaTag) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const imeta = parseImeta(imetaTag);
|
||||
const url = isHttps(imeta.url) ? imeta.url : null;
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mime = imeta.m || tagValue(event, 'm') || '';
|
||||
if (!IMAGE_MIME_TYPES.has(mime)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sha256 = imeta.x || tagValue(event, 'x') || null;
|
||||
const dim = parseDimensions(imeta.dim);
|
||||
const title = tagValue(event, 'title') || imeta.alt || 'Untitled photo';
|
||||
const alt = imeta.alt || title;
|
||||
const thumbUrl = isHttps(imeta.thumb) ? imeta.thumb : url;
|
||||
const fallback = imeta.fallback.filter(isHttps);
|
||||
const tags = uniqueStrings(
|
||||
tagValues(event, 't').map((tag) => tag[1]?.toLowerCase())
|
||||
);
|
||||
const originTag = tagValues(event, 'origin')[0] ?? [];
|
||||
const originMeta = parseOriginMeta(originTag[4]);
|
||||
const platform = originTag[1] || null;
|
||||
const originId = originTag[2] || null;
|
||||
const sourceUrl = isHttps(originTag[3]) ? originTag[3] : null;
|
||||
const rTag = tagValue(event, 'r');
|
||||
const profile = isHttps(originMeta.profile)
|
||||
? originMeta.profile
|
||||
: isHttps(rTag)
|
||||
? rTag
|
||||
: null;
|
||||
const creatorName =
|
||||
typeof originMeta.creator === 'string' && originMeta.creator.trim()
|
||||
? originMeta.creator.trim()
|
||||
: null;
|
||||
|
||||
const creator = {
|
||||
name: creatorName,
|
||||
profile,
|
||||
source: sourceUrl,
|
||||
platform,
|
||||
originId,
|
||||
license: originMeta.license ?? null,
|
||||
licenseUrl: isHttps(originMeta.licenseUrl) ? originMeta.licenseUrl : null,
|
||||
portfolio: isHttps(originMeta.portfolio) ? originMeta.portfolio : null,
|
||||
};
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
event,
|
||||
kind: 20,
|
||||
title,
|
||||
content: event.content ?? '',
|
||||
alt,
|
||||
url,
|
||||
thumbUrl,
|
||||
fallback,
|
||||
sha256,
|
||||
size: imeta.size ? Number(imeta.size) : null,
|
||||
width: dim?.width ?? null,
|
||||
height: dim?.height ?? null,
|
||||
mime,
|
||||
tags,
|
||||
contentWarning: tagValue(event, 'content-warning'),
|
||||
createdAt: event.created_at,
|
||||
creator,
|
||||
sourceUrl,
|
||||
// Client-side rule: un-attributed photos must never render.
|
||||
attributed: Boolean(creator.name && (creator.profile || creator.source)),
|
||||
};
|
||||
}
|
||||
|
||||
export function parsePhotoEvents(events) {
|
||||
const byId = new Map();
|
||||
|
||||
for (const event of events ?? []) {
|
||||
const photo = parsePhotoEvent(event);
|
||||
if (photo) {
|
||||
byId.set(photo.id, photo);
|
||||
}
|
||||
}
|
||||
|
||||
return [...byId.values()];
|
||||
}
|
||||
|
||||
export function parseFeedEvent(event) {
|
||||
if (!event || event.kind !== 30006) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = tagValue(event, 'd');
|
||||
if (!id || !id.startsWith(PHOTO_FEED_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const title = tagValue(event, 'title');
|
||||
if (!title) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const tTags = uniqueStrings(
|
||||
tagValues(event, 't').map((tag) => tag[1]?.toLowerCase())
|
||||
);
|
||||
if (!tTags.includes(PHOTO_FEED_TAG)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const eTags = tagValues(event, 'e').filter((tag) => isHex(tag[1], 64));
|
||||
|
||||
return {
|
||||
id,
|
||||
eventId: event.id,
|
||||
event,
|
||||
title,
|
||||
description: tagValue(event, 'description') || '',
|
||||
coverUrl: isHttps(tagValue(event, 'image'))
|
||||
? tagValue(event, 'image')
|
||||
: null,
|
||||
photoIds: uniqueStrings(eTags.map((tag) => tag[1])),
|
||||
relayHints: Object.fromEntries(
|
||||
eTags.filter((tag) => tag[2]).map((tag) => [tag[1], tag[2]])
|
||||
),
|
||||
tags: tTags,
|
||||
createdAt: event.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
// Nature is always the first feed. The remaining feeds use their event
|
||||
// createdAt for now; a true "first published" order can be persisted later.
|
||||
export function sortFeeds(feeds, defaultFeedId = NATURE_FEED_ID) {
|
||||
return [...feeds].sort((a, b) => {
|
||||
if (a.id === defaultFeedId) {
|
||||
return -1;
|
||||
}
|
||||
if (b.id === defaultFeedId) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return (
|
||||
(a.createdAt ?? 0) - (b.createdAt ?? 0) || a.title.localeCompare(b.title)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function parseFeedEvents(events) {
|
||||
const byId = new Map();
|
||||
|
||||
for (const event of events ?? []) {
|
||||
const feed = parseFeedEvent(event);
|
||||
if (!feed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const current = byId.get(feed.id);
|
||||
if (!current || feed.createdAt > current.createdAt) {
|
||||
byId.set(feed.id, feed);
|
||||
}
|
||||
}
|
||||
|
||||
return sortFeeds([...byId.values()]);
|
||||
}
|
||||
|
||||
function originMetadata(creator) {
|
||||
return JSON.stringify({
|
||||
creator: creator.name,
|
||||
profile: creator.profile,
|
||||
license: creator.license,
|
||||
licenseUrl: creator.licenseUrl,
|
||||
...(creator.portfolio ? { portfolio: creator.portfolio } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function photoToEventDraft(
|
||||
photo,
|
||||
createdAt = Math.floor(Date.now() / 1000)
|
||||
) {
|
||||
const tags = [
|
||||
['title', photo.title],
|
||||
[
|
||||
'imeta',
|
||||
`url ${photo.url}`,
|
||||
`m ${photo.mime}`,
|
||||
`x ${photo.sha256}`,
|
||||
`size ${photo.size}`,
|
||||
`dim ${photo.width}x${photo.height}`,
|
||||
`thumb ${photo.thumbUrl}`,
|
||||
`alt ${photo.alt}`,
|
||||
...photo.fallback.map((url) => `fallback ${url}`),
|
||||
],
|
||||
['m', photo.mime],
|
||||
['x', photo.sha256],
|
||||
...photo.tags.map((tag) => ['t', tag]),
|
||||
[
|
||||
'origin',
|
||||
photo.creator.platform,
|
||||
photo.creator.originId,
|
||||
photo.sourceUrl,
|
||||
originMetadata(photo.creator),
|
||||
],
|
||||
...(photo.creator.profile ? [['r', photo.creator.profile]] : []),
|
||||
];
|
||||
|
||||
return {
|
||||
kind: 20,
|
||||
created_at: createdAt,
|
||||
content: photo.content,
|
||||
tags,
|
||||
};
|
||||
}
|
||||
|
||||
export function feedToEventDraft(
|
||||
feed,
|
||||
createdAt = Math.floor(Date.now() / 1000)
|
||||
) {
|
||||
return {
|
||||
kind: 30006,
|
||||
created_at: createdAt,
|
||||
content: '',
|
||||
tags: [
|
||||
['d', feed.id],
|
||||
['title', feed.title],
|
||||
['description', feed.description],
|
||||
...(feed.coverUrl ? [['image', feed.coverUrl]] : []),
|
||||
...feed.photoIds.map((photoId) => [
|
||||
'e',
|
||||
photoId,
|
||||
feed.relayHints?.[photoId] ?? '',
|
||||
]),
|
||||
['t', PHOTO_FEED_TAG],
|
||||
...feed.tags
|
||||
.filter((tag) => tag !== PHOTO_FEED_TAG)
|
||||
.map((tag) => ['t', tag]),
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
# Nostr photo feeds
|
||||
|
||||
Dashtab reads curated photo feeds from Nostr and uses the selected original as
|
||||
the dashboard wallpaper. This document freezes the event format so publishing,
|
||||
subscriptions, and future clients do not need a migration.
|
||||
|
||||
- Relay: `wss://nostr.kosmos.org`
|
||||
- Curator: `1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb`
|
||||
(`raucao@kosmos.org`)
|
||||
- Media: Kosmos Blossom, `https://blossom.kosmos.org`
|
||||
- Feed namespace: `dt:` (for example `dt:nature`, `dt:city-nights`)
|
||||
|
||||
## Feed event — kind 30006
|
||||
|
||||
Parameterized replaceable picture set (`d` is the feed id).
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 30006,
|
||||
"content": "",
|
||||
"tags": [
|
||||
["d", "dt:nature"],
|
||||
["title", "Nature"],
|
||||
["description", "Landscapes, forests, mountains, and deserts."],
|
||||
["image", "https://blossom.kosmos.org/<cover-thumb>.jpeg"],
|
||||
["e", "<photo-event-id>", "wss://nostr.kosmos.org"],
|
||||
["t", "dashtab-photo-feed"],
|
||||
["t", "nature"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `d` must start with `dt:`.
|
||||
- `e` tags are in Dashtab display order; removing one de-lists a photo without
|
||||
deleting the kind-20 event.
|
||||
- Keep the list at or below 500 photos; a larger feed needs a future partition
|
||||
scheme.
|
||||
- `t` includes `dashtab-photo-feed` and optional category tags (lowercase).
|
||||
|
||||
## Photo event — kind 20
|
||||
|
||||
One image per event, one `imeta` tag.
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 20,
|
||||
"content": "Winding road through autumn forest.\n\nPhoto by Adrian Infernus on Unsplash.",
|
||||
"tags": [
|
||||
["title", "Winding road through autumn forest"],
|
||||
[
|
||||
"imeta",
|
||||
"url https://blossom.kosmos.org/<full-sha256>",
|
||||
"m image/jpeg",
|
||||
"x <sha256>",
|
||||
"size 2100280",
|
||||
"dim 2560x1440",
|
||||
"thumb https://blossom.kosmos.org/<thumb-sha256>.jpeg",
|
||||
"alt An aerial view of a winding road through a dense forest with vibrant autumn foliage"
|
||||
],
|
||||
["m", "image/jpeg"],
|
||||
["x", "<sha256>"],
|
||||
["t", "nature"],
|
||||
[
|
||||
"origin",
|
||||
"unsplash",
|
||||
"iRwbP4QPmGI",
|
||||
"https://unsplash.com/photos/winding-road-through-autumn-forest-iRwbP4QPmGI",
|
||||
"{\"creator\":\"Adrian Infernus\",\"profile\":\"https://unsplash.com/@adrian_infernus\",\"license\":\"unsplash\",\"licenseUrl\":\"https://unsplash.com/license\",\"portfolio\":\"https://adrianinfernus.de/\"}"
|
||||
],
|
||||
["r", "https://unsplash.com/@adrian_infernus"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `url` is the original; `thumb` is the same-aspect thumbnail used **only** in
|
||||
the photo picker. The wallpaper uses `url` exclusively.
|
||||
- `x` is the SHA-256 of the exact bytes at `url`. Referenced events must carry a
|
||||
valid `x`; clients skip events without one.
|
||||
- `m` is one of NIP-68's image types. Media URLs must be `https:`.
|
||||
- `origin` is a profile-level extension of NIP-71's pattern; its fifth element
|
||||
is JSON with `creator`, `profile`, `license`, `licenseUrl`, and optional
|
||||
`portfolio`.
|
||||
- `r` points at the creator's verified profile.
|
||||
- A `p` tag with role `author` is used only when the creator has a Nostr
|
||||
identity. None of the current Unsplash creators do.
|
||||
- The client skips photos without a creator name and a profile/source link.
|
||||
|
||||
## Fetching and trust
|
||||
|
||||
1. Query kind `30006` from the curator with `#t=dashtab-photo-feed`.
|
||||
2. Keep the latest event per `d`.
|
||||
3. Fetch photo events by `e`-tag ids in chunks of <=300, never by author scan.
|
||||
4. Verify every event's canonical NIP-01 id and Schnorr signature.
|
||||
5. The curator is the trust root for feed definitions only; a feed may reference
|
||||
photos authored by anyone.
|
||||
|
||||
## Caching
|
||||
|
||||
- Thumbnails: cached for the Settings grid; small and retained.
|
||||
- Originals: cached on demand for the current wallpaper and the first three
|
||||
photos of enabled feeds; LRU budget 30 originals / 250 MB.
|
||||
- Wallpaper: cached original or bundled fallback with zero network on first
|
||||
paint; never a thumbnail.
|
||||
|
||||
## App behavior
|
||||
|
||||
- The welcome screen shows a bundled placeholder wallpaper while
|
||||
`photos.prefetchForWelcome()` fetches the feed definitions, Nature's photo
|
||||
events, all enabled thumbnails, and the first three originals in the
|
||||
background.
|
||||
- Nature is enabled by default. City Nights is available as an opt-in toggle.
|
||||
- The dashboard wallpaper uses the original, never the thumbnail. A discreet
|
||||
creator credit link sits next to the Settings button; Settings itself shows no
|
||||
attribution text.
|
||||
- Tests use the published events in `tests/fixtures/nostr/`; all relay,
|
||||
Blossom, and image connections are stubbed.
|
||||
|
||||
## Rotation
|
||||
|
||||
Weekly rotation is intentionally out of the current phase. The persisted
|
||||
`photos.config` keeps a `rotation` field (`off`) so it can be added without a
|
||||
storage migration. The next phase will use a UTC-Monday week index and a
|
||||
persisted shuffle-bag queue.
|
||||
@@ -4,7 +4,7 @@
|
||||
"version": "0.0.0",
|
||||
"description": "Dashtab new-tab dashboard — development shell.",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqUOWNvCBFYXD+6LOT+Qm/rK3A/5QGsWDKDFn5WDG2TcX0CIPlDOcrJoCk0oxjFDrVlEYvp3QvITCBZTWTkq36sR9olqConwVUSnvXd14+WgzEI7dAlazv/KeLrBGBmdpETbXzoRt3WpKMDzEGWORk+DvO+SQ7JwT1T7HkwSohG1i9BUwsouOPHhjX6Lq4eNpBXQZUTdHoliiC1j2TThnIkKKcK3xcEw/dfnPz5F28A/B+KmbIIYcrWXq/Wc6a98fdTpQyN8IFCSIARTH6aYcPWQExBYDoGcU48dFORHp/PGC1p9w7KNXr0VHf8Mup4bya2MaxnacGXu71qHwvOxt3wIDAQAB",
|
||||
"permissions": ["identity"],
|
||||
"permissions": ["identity", "unlimitedStorage"],
|
||||
"host_permissions": ["https://*/*", "http://*/*"],
|
||||
"content_security_policy": {
|
||||
"extension_pages": "script-src 'self'; object-src 'self';"
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"permissions": ["identity"],
|
||||
"permissions": ["identity", "unlimitedStorage"],
|
||||
"host_permissions": ["https://*/*", "http://*/*"],
|
||||
"content_security_policy": {
|
||||
"extension_pages": "script-src 'self'; object-src 'self';"
|
||||
|
||||
+5
-1
@@ -101,5 +101,9 @@
|
||||
"ember": {
|
||||
"edition": "octane"
|
||||
},
|
||||
"packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621"
|
||||
"packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.4.0",
|
||||
"@noble/hashes": "^2.4.0"
|
||||
}
|
||||
}
|
||||
Generated
+21
@@ -10,6 +10,13 @@ patchedDependencies:
|
||||
importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@noble/curves':
|
||||
specifier: ^2.4.0
|
||||
version: 2.4.0
|
||||
'@noble/hashes':
|
||||
specifier: ^2.4.0
|
||||
version: 2.4.0
|
||||
devDependencies:
|
||||
'@babel/core':
|
||||
specifier: ^7.29.7
|
||||
@@ -1248,6 +1255,14 @@ packages:
|
||||
'@nicolo-ribaudo/eslint-scope-5-internals@5.1.1-v1':
|
||||
resolution: {integrity: sha512-54/JRvkLIzzDWshCWfuhadfrfZVPiElY8Fcgmg1HroEly/EDSszzhBAsarCux+D/kOslTRquNzuyGSmUSTTHGg==}
|
||||
|
||||
'@noble/curves@2.4.0':
|
||||
resolution: {integrity: sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==}
|
||||
engines: {node: '>= 20.19.0'}
|
||||
|
||||
'@noble/hashes@2.4.0':
|
||||
resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}
|
||||
engines: {node: '>= 20.19.0'}
|
||||
|
||||
'@nodelib/fs.scandir@2.1.5':
|
||||
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
|
||||
engines: {node: '>= 8'}
|
||||
@@ -8136,6 +8151,12 @@ snapshots:
|
||||
dependencies:
|
||||
eslint-scope: 5.1.1
|
||||
|
||||
'@noble/curves@2.4.0':
|
||||
dependencies:
|
||||
'@noble/hashes': 2.4.0
|
||||
|
||||
'@noble/hashes@2.4.0': {}
|
||||
|
||||
'@nodelib/fs.scandir@2.1.5':
|
||||
dependencies:
|
||||
'@nodelib/fs.stat': 2.0.5
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
# Nostr photo publishing
|
||||
|
||||
Interactive scripts that generate thumbnails, upload them to Kosmos Blossom, verify
|
||||
creator attribution, and publish the Dashtab photo feeds to `wss://nostr.kosmos.org`.
|
||||
|
||||
The private key is **never** passed to the scripts, captured in a variable, or written
|
||||
to disk. Every signing step uses `nak --prompt-sec`, so `nak` asks for the key in your
|
||||
terminal. When an event is piped through stdin, `nak` reads the key from `/dev/tty`, so
|
||||
the event data and the prompt do not conflict.
|
||||
|
||||
Because the Kosmos relay is members-only, publishing uses NIP-42 auth. With the default
|
||||
interactive mode, `nak` may ask twice per event: once to sign the event and once to
|
||||
authenticate the relay connection. To avoid repeated prompts, you can export the key in
|
||||
your own shell for the run; the scripts never read or store it:
|
||||
|
||||
```sh
|
||||
export NOSTR_SECRET_KEY='nsec1...' # your shell only, never committed
|
||||
./scripts/nostr/run.sh all
|
||||
unset NOSTR_SECRET_KEY
|
||||
```
|
||||
|
||||
The scripts still verify the signed event `pubkey` against the curator before publishing,
|
||||
so a wrong key aborts before anything is sent.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- `nak` in `PATH` (the same tool used for the originals)
|
||||
- ImageMagick (`magick`)
|
||||
- `jq`, `curl`, `sha256sum`, `stat`, `file`
|
||||
- A terminal (the key prompts need a TTY)
|
||||
|
||||
## Workflow
|
||||
|
||||
```sh
|
||||
cd /path/to/dashtab
|
||||
|
||||
# 1. Generate 480x270 JPEG thumbnails and verify the local originals
|
||||
./scripts/nostr/run.sh thumbnails
|
||||
|
||||
# 2. Upload them to https://blossom.kosmos.org
|
||||
# nak prompts once for the Blossom upload key.
|
||||
./scripts/nostr/run.sh upload-thumbnails
|
||||
|
||||
# 3. Verify every original, thumbnail, and attribution link
|
||||
./scripts/nostr/run.sh preflight
|
||||
|
||||
# 4. Build unsigned photo/feed event drafts
|
||||
./scripts/nostr/run.sh build
|
||||
|
||||
# 5. Sign and publish the five kind-20 photo events
|
||||
# nak prompts for the curator key once per photo.
|
||||
./scripts/nostr/run.sh publish-photos
|
||||
|
||||
# 6. Sign and publish the kind-30006 feed events
|
||||
# nak prompts for the curator key once per feed.
|
||||
./scripts/nostr/run.sh publish-feeds
|
||||
```
|
||||
|
||||
`./scripts/nostr/run.sh all` runs the whole sequence.
|
||||
|
||||
Useful options:
|
||||
|
||||
```sh
|
||||
./scripts/nostr/run.sh all --yes # skip confirmation prompts
|
||||
./scripts/nostr/run.sh thumbnails --force # regenerate thumbnails
|
||||
./scripts/nostr/run.sh upload-thumbnails --force
|
||||
./scripts/nostr/run.sh publish-feeds --force # republish replaceable feeds
|
||||
./scripts/nostr/run.sh preflight --attribution-only
|
||||
./scripts/nostr/run.sh --dry-run publish-photos
|
||||
./scripts/nostr/run.sh status
|
||||
```
|
||||
|
||||
## What the scripts guarantee
|
||||
|
||||
- **Attribution is a hard gate.** `preflight` refuses to continue unless every photo
|
||||
has a creator name, an HTTPS profile/source/license URL that returns HTTP 200, the
|
||||
creator name present on the profile and source pages, an original whose SHA-256
|
||||
matches `x`, and a reachable image thumbnail.
|
||||
- **Correct signer.** After `nak` signs, the script checks the event's `pubkey` against
|
||||
the curator pubkey before publishing. A wrong key aborts before anything is sent.
|
||||
- **No duplicates.** Photo events are non-replaceable; the script skips any whose `x`
|
||||
or recorded event ID already exists on the relay. Feed events are replaceable; the
|
||||
script skips them when the on-relay tag content already matches the draft.
|
||||
- **No secrets on disk.** Only public event JSON, hashes, and IDs are stored.
|
||||
|
||||
## State
|
||||
|
||||
Everything generated lives under `tmp/nostr-photos/` (gitignored):
|
||||
|
||||
```
|
||||
tmp/nostr-photos/
|
||||
thumbs/ generated thumbnails
|
||||
events/
|
||||
photos/ draft, signed, and published kind-20 events
|
||||
feeds/ draft, signed, and published kind-30006 events
|
||||
state/
|
||||
thumbs.json thumbnail hashes and Blossom URLs
|
||||
photos.json published photo event IDs
|
||||
feeds.json published feed event IDs
|
||||
preflight.json
|
||||
logs/ nak upload output
|
||||
```
|
||||
|
||||
To start over, remove `tmp/nostr-photos/`. The manifest itself is
|
||||
`scripts/nostr/manifest.json` and is the source of truth for the feed/photo metadata,
|
||||
verified creator links, and Blossom hashes.
|
||||
|
||||
## Editing the manifest
|
||||
|
||||
Add a new photo by appending an entry to `.photos` with:
|
||||
|
||||
- `file`, `url` (Blossom original), `sha256`, `size`, `dim`, `mime`
|
||||
- `feed` (must match a feed `id`)
|
||||
- `title`, `alt`, `content`, `tags`
|
||||
- `creator`, `profile`, `source`, `license`, `licenseUrl`, optional `portfolio`, `originId`
|
||||
|
||||
Then add it to the feed's `order` (and optionally make it the `cover`) and rerun the
|
||||
workflow. `preflight` will reject anything missing verified attribution.
|
||||
|
||||
## Attribution rules
|
||||
|
||||
- Nostr-native creators would get a `p ... "author"` tag. None of the current Unsplash
|
||||
creators have a verified Nostr identity, so events use `origin` + `r`.
|
||||
- `origin` carries `{"creator", "profile", "license", "licenseUrl", "portfolio"?}`.
|
||||
- Meiying Ng's Tumblr portfolio returns HTTP 403 and is omitted; her verified Unsplash
|
||||
profile is used instead.
|
||||
- Publishing is blocked if any link fails verification. There is no override.
|
||||
Executable
+161
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build unsigned kind-20 photo events and kind-30006 feed events.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/lib.sh"
|
||||
|
||||
require_cmd jq
|
||||
validate_manifest
|
||||
ensure_workdirs
|
||||
mkdir -p "$EVENTS_DIR/photos" "$EVENTS_DIR/feeds"
|
||||
|
||||
THUMB_STATE="$STATE_DIR/thumbs.json"
|
||||
PHOTO_STATE="$STATE_DIR/photos.json"
|
||||
[[ -f "$THUMB_STATE" ]] || die "no thumbnail state; run ./scripts/nostr/run.sh thumbnails first"
|
||||
state_init "$PHOTO_STATE"
|
||||
|
||||
now="$(date +%s)"
|
||||
|
||||
info "Building photo event drafts."
|
||||
while IFS= read -r file; do
|
||||
sha="$(photo_field "$file" sha256)"
|
||||
size="$(photo_field "$file" size)"
|
||||
dim="$(photo_field "$file" dim)"
|
||||
mime="$(photo_field "$file" mime)"
|
||||
url="$(photo_field "$file" url)"
|
||||
title="$(photo_field "$file" title)"
|
||||
alt="$(photo_field "$file" alt)"
|
||||
content="$(photo_field "$file" content)"
|
||||
creator="$(photo_field "$file" creator)"
|
||||
profile="$(photo_field "$file" profile)"
|
||||
source="$(photo_field "$file" source)"
|
||||
license="$(photo_field "$file" license)"
|
||||
license_url="$(photo_field "$file" licenseUrl)"
|
||||
portfolio="$(photo_field "$file" portfolio)"
|
||||
origin_id="$(photo_field "$file" originId)"
|
||||
|
||||
thumb_url="$(jq -r --arg f "$file" '.[$f].url // empty' "$THUMB_STATE")"
|
||||
[[ -n "$thumb_url" ]] || die "thumbnail not uploaded for $file; run ./scripts/nostr/run.sh upload-thumbnails first"
|
||||
|
||||
origin_json="$(jq -cn \
|
||||
--arg creator "$creator" \
|
||||
--arg profile "$profile" \
|
||||
--arg license "$license" \
|
||||
--arg licenseUrl "$license_url" \
|
||||
--arg portfolio "$portfolio" \
|
||||
'{creator: $creator, profile: $profile, license: $license, licenseUrl: $licenseUrl}
|
||||
+ (if $portfolio != "" then {portfolio: $portfolio} else {} end)')"
|
||||
|
||||
tags_json="$(jq -c --arg f "$file" '.photos[] | select(.file == $f) | .tags | map(ascii_downcase) | unique' "$MANIFEST")"
|
||||
|
||||
out="$EVENTS_DIR/photos/$sha.json"
|
||||
jq -n \
|
||||
--argjson created_at "$now" \
|
||||
--arg content "$content" \
|
||||
--arg title "$title" \
|
||||
--arg url "$url" \
|
||||
--arg mime "$mime" \
|
||||
--arg x "$sha" \
|
||||
--argjson size "$size" \
|
||||
--arg dim "$dim" \
|
||||
--arg thumb "$thumb_url" \
|
||||
--arg alt "$alt" \
|
||||
--arg origin_id "$origin_id" \
|
||||
--arg source "$source" \
|
||||
--arg origin_json "$origin_json" \
|
||||
--arg profile "$profile" \
|
||||
--argjson tags "$tags_json" \
|
||||
'{
|
||||
kind: 20,
|
||||
created_at: $created_at,
|
||||
content: $content,
|
||||
tags: (
|
||||
[
|
||||
["title", $title],
|
||||
["imeta",
|
||||
("url " + $url),
|
||||
("m " + $mime),
|
||||
("x " + $x),
|
||||
("size " + ($size | tostring)),
|
||||
("dim " + $dim),
|
||||
("thumb " + $thumb),
|
||||
("alt " + $alt)
|
||||
],
|
||||
["m", $mime],
|
||||
["x", $x]
|
||||
]
|
||||
+ ($tags | map(["t", .]))
|
||||
+ [
|
||||
["origin", "unsplash", $origin_id, $source, $origin_json],
|
||||
["r", $profile]
|
||||
]
|
||||
)
|
||||
}' > "$out"
|
||||
|
||||
info " $out"
|
||||
done < <(photo_files)
|
||||
|
||||
info ""
|
||||
info "Building feed event drafts."
|
||||
while IFS= read -r feed; do
|
||||
ids=()
|
||||
missing=()
|
||||
while IFS= read -r order_file; do
|
||||
id="$(jq -r --arg f "$order_file" '.[$f].id // empty' "$PHOTO_STATE")"
|
||||
if [[ -n "$id" ]]; then
|
||||
ids+=("$id")
|
||||
else
|
||||
missing+=("$order_file")
|
||||
fi
|
||||
done < <(jq -r --arg f "$feed" '.feeds[] | select(.id == $f) | .order[]' "$MANIFEST")
|
||||
|
||||
if [[ "${#missing[@]}" -gt 0 ]]; then
|
||||
warn "skipping feed $feed: unpublished photo(s):"
|
||||
for file in "${missing[@]}"; do
|
||||
warn " $file"
|
||||
done
|
||||
continue
|
||||
fi
|
||||
|
||||
title="$(feed_field "$feed" title)"
|
||||
description="$(feed_field "$feed" description)"
|
||||
cover="$(feed_field "$feed" cover)"
|
||||
cover_url="$(jq -r --arg f "$cover" '.[$f].url // empty' "$THUMB_STATE")"
|
||||
if [[ -z "$cover_url" ]]; then
|
||||
cover_url="$(photo_field "$cover" url)"
|
||||
fi
|
||||
e_tags="$(for id in "${ids[@]}"; do jq -cn --arg id "$id" --arg relay "$RELAY" '["e", $id, $relay]'; done | jq -s '.')"
|
||||
feed_tags="$(jq -c --arg f "$feed" '.feeds[] | select(.id == $f) | .tags | map(ascii_downcase) | unique' "$MANIFEST")"
|
||||
|
||||
out="$EVENTS_DIR/feeds/$(feed_slug "$feed").json"
|
||||
jq -n \
|
||||
--argjson created_at "$now" \
|
||||
--arg d "$feed" \
|
||||
--arg title "$title" \
|
||||
--arg description "$description" \
|
||||
--arg image "$cover_url" \
|
||||
--argjson e_tags "$e_tags" \
|
||||
--argjson feed_tags "$feed_tags" \
|
||||
'{
|
||||
kind: 30006,
|
||||
created_at: $created_at,
|
||||
content: "",
|
||||
tags: (
|
||||
[
|
||||
["d", $d],
|
||||
["title", $title],
|
||||
["description", $description],
|
||||
["image", $image]
|
||||
]
|
||||
+ $e_tags
|
||||
+ [["t", "dashtab-photo-feed"]]
|
||||
+ ($feed_tags | map(["t", .]))
|
||||
)
|
||||
}' > "$out"
|
||||
|
||||
info " $out"
|
||||
done < <(feed_ids)
|
||||
|
||||
info ""
|
||||
info "Drafts built. Next: ./scripts/nostr/run.sh publish-photos"
|
||||
Executable
+262
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shared helpers for the Dashtab Nostr photo publishing scripts.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||
MANIFEST="${NOSTR_PHOTOS_MANIFEST:-$SCRIPT_DIR/manifest.json}"
|
||||
WORK_DIR="${NOSTR_PHOTOS_WORK_DIR:-$ROOT/tmp/nostr-photos}"
|
||||
THUMBS_DIR="$WORK_DIR/thumbs"
|
||||
EVENTS_DIR="$WORK_DIR/events"
|
||||
STATE_DIR="$WORK_DIR/state"
|
||||
LOG_DIR="$WORK_DIR/logs"
|
||||
|
||||
DRY_RUN="${DRY_RUN:-0}"
|
||||
ASSUME_YES="${ASSUME_YES:-0}"
|
||||
FORCE="${FORCE:-0}"
|
||||
USER_AGENT="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"
|
||||
|
||||
RELAY="$(jq -r '.relay' "$MANIFEST")"
|
||||
BLOSSOM="$(jq -r '.blossom' "$MANIFEST")"
|
||||
CURATOR="$(jq -r '.curator' "$MANIFEST")"
|
||||
|
||||
# Interactive key prompts by default. Users may export NOSTR_SECRET_KEY in their
|
||||
# own shell to let nak read it from the environment instead; the scripts never
|
||||
# read, store, or print it.
|
||||
NAK_PROMPT_ARGS=()
|
||||
if [[ -z "${NOSTR_SECRET_KEY:-}" ]]; then
|
||||
NAK_PROMPT_ARGS=(--prompt-sec)
|
||||
fi
|
||||
|
||||
die() {
|
||||
printf 'error: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
warn() {
|
||||
printf 'warning: %s\n' "$*" >&2
|
||||
}
|
||||
|
||||
info() {
|
||||
printf '%s\n' "$*"
|
||||
}
|
||||
|
||||
require_cmd() {
|
||||
command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"
|
||||
}
|
||||
|
||||
ensure_workdirs() {
|
||||
mkdir -p "$THUMBS_DIR" "$EVENTS_DIR" "$STATE_DIR" "$LOG_DIR"
|
||||
}
|
||||
|
||||
validate_manifest() {
|
||||
[[ -f "$MANIFEST" ]] || die "manifest not found: $MANIFEST"
|
||||
jq -e '
|
||||
(.relay | type == "string" and startswith("wss://")) and
|
||||
(.blossom | type == "string" and startswith("https://")) and
|
||||
(.curator | type == "string" and test("^[0-9a-f]{64}$")) and
|
||||
(.feeds | type == "array" and length > 0) and
|
||||
(.photos | type == "array" and length > 0) and
|
||||
([.feeds[].id] | length == (unique | length)) and
|
||||
([.photos[].file] | length == (unique | length)) and
|
||||
(all(.feeds[];
|
||||
(.id | startswith("dt:")) and
|
||||
(.title | length > 0) and
|
||||
(.description | type == "string") and
|
||||
(.tags | type == "array") and
|
||||
(.order | type == "array" and length > 0)
|
||||
)) and
|
||||
(all(.photos[];
|
||||
(.file | length > 0) and
|
||||
(.url | startswith("https://")) and
|
||||
(.feed | startswith("dt:")) and
|
||||
(.title | length > 0) and
|
||||
(.alt | length > 0) and
|
||||
(.content | length > 0) and
|
||||
(.tags | type == "array") and
|
||||
(.sha256 | test("^[0-9a-f]{64}$")) and
|
||||
(.size | type == "number" and . > 0) and
|
||||
(.dim | test("^[0-9]+x[0-9]+$")) and
|
||||
(.mime | startswith("image/")) and
|
||||
(.creator | length > 0) and
|
||||
(.profile | startswith("https://")) and
|
||||
(.source | startswith("https://")) and
|
||||
(.license | length > 0) and
|
||||
(.licenseUrl | startswith("https://")) and
|
||||
(.portfolio | type == "string") and
|
||||
(.verified | type == "object" and (.at | length > 0) and
|
||||
(.profile.status == 200 and .profile.name == true) and
|
||||
(.source.status == 200 and .source.name == true) and
|
||||
(.license.status == 200)) and
|
||||
(.originId | length > 0)
|
||||
))
|
||||
' "$MANIFEST" >/dev/null || die "manifest validation failed: $MANIFEST"
|
||||
|
||||
jq -e '([.feeds[].id] | unique) as $feeds | all(.photos[]; (.feed as $f | $feeds | index($f)) != null)' "$MANIFEST" >/dev/null ||
|
||||
die "a photo references an unknown feed"
|
||||
|
||||
jq -e '([.photos[] | {key: .file, value: .feed}] | from_entries) as $photo_feeds | all(.feeds[]; .id as $id | all(.order[]; . as $file | $photo_feeds[$file] == $id))' "$MANIFEST" >/dev/null ||
|
||||
die "a feed order references a photo that is not assigned to that feed"
|
||||
|
||||
jq -e '([.photos[].file] | unique) as $files | all(.feeds[]; . as $feed | ($feed.cover == "") or (($files | index($feed.cover)) != null))' "$MANIFEST" >/dev/null ||
|
||||
die "a feed cover references an unknown photo"
|
||||
}
|
||||
|
||||
photo_count() {
|
||||
jq '.photos | length' "$MANIFEST"
|
||||
}
|
||||
|
||||
photo_files() {
|
||||
jq -r '.photos[].file' "$MANIFEST"
|
||||
}
|
||||
|
||||
feed_ids() {
|
||||
jq -r '.feeds[].id' "$MANIFEST"
|
||||
}
|
||||
|
||||
photo_field() {
|
||||
jq -r --arg f "$1" --arg k "$2" '.photos[] | select(.file == $f) | .[$k] // empty' "$MANIFEST"
|
||||
}
|
||||
|
||||
feed_field() {
|
||||
jq -r --arg f "$1" --arg k "$2" '.feeds[] | select(.id == $f) | .[$k] // empty' "$MANIFEST"
|
||||
}
|
||||
|
||||
feed_slug() {
|
||||
printf '%s' "${1#dt:}"
|
||||
}
|
||||
|
||||
sha256_file() {
|
||||
sha256sum "$1" | awk '{print $1}'
|
||||
}
|
||||
|
||||
file_size() {
|
||||
stat -c '%s' "$1"
|
||||
}
|
||||
|
||||
image_dim() {
|
||||
magick identify -format '%wx%h' "$1"
|
||||
}
|
||||
|
||||
file_mime() {
|
||||
file --mime-type -b "$1"
|
||||
}
|
||||
|
||||
is_https() {
|
||||
[[ "$1" == https://* ]]
|
||||
}
|
||||
|
||||
http_status() {
|
||||
curl -A "$USER_AGENT" -L -sS -o /dev/null -w '%{http_code}' \
|
||||
--max-time 60 --retry 2 "$1" 2>/dev/null || true
|
||||
}
|
||||
|
||||
fetch_text() {
|
||||
curl -A "$USER_AGENT" -L -fsS --max-time 60 --retry 2 "$1"
|
||||
}
|
||||
|
||||
url_contains_sha() {
|
||||
local url="$1" sha="$2"
|
||||
[[ "$url" == *"$sha"* ]]
|
||||
}
|
||||
|
||||
confirm() {
|
||||
if [[ "$ASSUME_YES" == "1" ]]; then
|
||||
return 0
|
||||
fi
|
||||
local reply
|
||||
read -r -p "$1 [y/N] " reply
|
||||
[[ "$reply" =~ ^[Yy]$ ]]
|
||||
}
|
||||
|
||||
print_cmd() {
|
||||
printf ' '
|
||||
printf '%q ' "$@"
|
||||
printf '\n'
|
||||
}
|
||||
|
||||
run_cmd() {
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
print_cmd "$@"
|
||||
else
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
|
||||
state_init() {
|
||||
local path="$1"
|
||||
if [[ ! -f "$path" ]]; then
|
||||
printf '{}\n' > "$path"
|
||||
fi
|
||||
}
|
||||
|
||||
event_body() {
|
||||
jq -S -c '{kind: .kind, content: .content, tags: .tags}' "$1"
|
||||
}
|
||||
|
||||
relay_photo_by_x() {
|
||||
local sha="$1"
|
||||
nak req --quiet -k 20 -a "$CURATOR" --tag "x=$sha" -l 1 "$RELAY" < /dev/null 2>/dev/null | head -n 1 || true
|
||||
}
|
||||
|
||||
relay_photo_by_id() {
|
||||
local id="$1"
|
||||
nak req --quiet -k 20 -i "$id" -l 1 "$RELAY" < /dev/null 2>/dev/null | head -n 1 || true
|
||||
}
|
||||
|
||||
relay_feed() {
|
||||
local d="$1"
|
||||
nak req --quiet -k 30006 -a "$CURATOR" -d "$d" -l 1 "$RELAY" < /dev/null 2>/dev/null | head -n 1 || true
|
||||
}
|
||||
|
||||
parse_common_args() {
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--force) FORCE=1; export FORCE ;;
|
||||
--yes) ASSUME_YES=1; export ASSUME_YES ;;
|
||||
--dry-run) DRY_RUN=1; export DRY_RUN ;;
|
||||
*) die "unknown option: $arg" ;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
require_nak() {
|
||||
require_cmd nak
|
||||
command -v nak >/dev/null 2>&1 || die "nak is required"
|
||||
}
|
||||
|
||||
require_publish_tools() {
|
||||
require_cmd jq
|
||||
require_cmd curl
|
||||
require_cmd sha256sum
|
||||
require_cmd stat
|
||||
require_cmd file
|
||||
require_nak
|
||||
}
|
||||
|
||||
summary() {
|
||||
local thumbs_state="$STATE_DIR/thumbs.json"
|
||||
local photos_state="$STATE_DIR/photos.json"
|
||||
local feeds_state="$STATE_DIR/feeds.json"
|
||||
local total_photos uploaded_photos published_photos published_feeds
|
||||
total_photos=$(photo_count)
|
||||
uploaded_photos=0
|
||||
published_photos=0
|
||||
published_feeds=0
|
||||
if [[ -f "$thumbs_state" ]]; then
|
||||
uploaded_photos=$(jq '[to_entries[] | select((.value.url // "") != "")] | length' "$thumbs_state")
|
||||
fi
|
||||
if [[ -f "$photos_state" ]]; then
|
||||
published_photos=$(jq '[to_entries[] | select((.value.id // "") != "")] | length' "$photos_state")
|
||||
fi
|
||||
if [[ -f "$feeds_state" ]]; then
|
||||
published_feeds=$(jq '[to_entries[] | select((.value.id // "") != "")] | length' "$feeds_state")
|
||||
fi
|
||||
info "Manifest: $MANIFEST"
|
||||
info "Relay: $RELAY"
|
||||
info "Blossom: $BLOSSOM"
|
||||
info "Curator: $CURATOR"
|
||||
info "Photos: $published_photos/$total_photos published, $uploaded_photos/$total_photos thumbnails uploaded"
|
||||
info "Feeds: $published_feeds/$(jq '.feeds | length' "$MANIFEST") published"
|
||||
info "Work dir: $WORK_DIR"
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
{
|
||||
"relay": "wss://nostr.kosmos.org",
|
||||
"blossom": "https://blossom.kosmos.org",
|
||||
"curator": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"feeds": [
|
||||
{
|
||||
"id": "dt:nature",
|
||||
"title": "Nature",
|
||||
"description": "Landscapes, forests, mountains, and deserts.",
|
||||
"cover": "public/img/wallpapers/adrian-infernus-iRwbP4QPmGI-unsplash.jpg",
|
||||
"tags": ["nature"],
|
||||
"order": [
|
||||
"public/img/wallpapers/adrian-infernus-iRwbP4QPmGI-unsplash.jpg",
|
||||
"public/img/wallpapers/meiying-ng-H-8zTDArbaQ-unsplash.jpg",
|
||||
"public/img/wallpapers/meiying-ng-iB7gjOsLrEQ-unsplash.jpg",
|
||||
"public/img/wallpapers/wolfgang-hasselmann-pVr6wvUneMk-unsplash.jpg"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "dt:city-nights",
|
||||
"title": "City Nights",
|
||||
"description": "After-dark city scenes.",
|
||||
"cover": "public/img/wallpapers/aleksandr-popov-ez4pqCpEfuI-unsplash.jpg",
|
||||
"tags": ["city-nights"],
|
||||
"order": [
|
||||
"public/img/wallpapers/aleksandr-popov-ez4pqCpEfuI-unsplash.jpg"
|
||||
]
|
||||
}
|
||||
],
|
||||
"photos": [
|
||||
{
|
||||
"file": "public/img/wallpapers/adrian-infernus-iRwbP4QPmGI-unsplash.jpg",
|
||||
"url": "https://blossom.kosmos.org/82d3d49b859c31152f0d779b11feaab6814c3346b550286a3faf1597b32366f1",
|
||||
"feed": "dt:nature",
|
||||
"title": "Winding road through autumn forest",
|
||||
"alt": "An aerial view of a winding road through a dense forest with vibrant autumn foliage",
|
||||
"content": "Winding road through autumn forest.\n\nPhoto by Adrian Infernus on Unsplash.",
|
||||
"tags": ["nature", "forest", "autumn", "road"],
|
||||
"sha256": "82d3d49b859c31152f0d779b11feaab6814c3346b550286a3faf1597b32366f1",
|
||||
"size": 2100280,
|
||||
"dim": "2560x1440",
|
||||
"mime": "image/jpeg",
|
||||
"creator": "Adrian Infernus",
|
||||
"profile": "https://unsplash.com/@adrian_infernus",
|
||||
"source": "https://unsplash.com/photos/winding-road-through-autumn-forest-iRwbP4QPmGI",
|
||||
"license": "unsplash",
|
||||
"licenseUrl": "https://unsplash.com/license",
|
||||
"portfolio": "https://adrianinfernus.de/",
|
||||
"verified": {
|
||||
"at": "2026-11-08",
|
||||
"by": "planning-verification",
|
||||
"profile": { "status": 200, "name": true },
|
||||
"source": { "status": 200, "name": true },
|
||||
"license": { "status": 200 },
|
||||
"portfolio": { "status": 200 }
|
||||
},
|
||||
"originId": "iRwbP4QPmGI"
|
||||
},
|
||||
{
|
||||
"file": "public/img/wallpapers/aleksandr-popov-ez4pqCpEfuI-unsplash.jpg",
|
||||
"url": "https://blossom.kosmos.org/eb7d8634ef676f9b029a0e06fc64689f5365cdbfae9f6e11c4181a353fbfaf83",
|
||||
"feed": "dt:city-nights",
|
||||
"title": "Train at night",
|
||||
"alt": "train at night",
|
||||
"content": "Train at night.\n\nPhoto by Aleksandr Popov on Unsplash.",
|
||||
"tags": ["city", "night", "train", "street"],
|
||||
"sha256": "eb7d8634ef676f9b029a0e06fc64689f5365cdbfae9f6e11c4181a353fbfaf83",
|
||||
"size": 1058801,
|
||||
"dim": "2559x1440",
|
||||
"mime": "image/jpeg",
|
||||
"creator": "Aleksandr Popov",
|
||||
"profile": "https://unsplash.com/@5tep5",
|
||||
"source": "https://unsplash.com/photos/train-at-night-ez4pqCpEfuI",
|
||||
"license": "unsplash",
|
||||
"licenseUrl": "https://unsplash.com/license",
|
||||
"portfolio": "",
|
||||
"verified": {
|
||||
"at": "2026-11-08",
|
||||
"by": "planning-verification",
|
||||
"profile": { "status": 200, "name": true },
|
||||
"source": { "status": 200, "name": true },
|
||||
"license": { "status": 200 }
|
||||
},
|
||||
"originId": "ez4pqCpEfuI"
|
||||
},
|
||||
{
|
||||
"file": "public/img/wallpapers/meiying-ng-H-8zTDArbaQ-unsplash.jpg",
|
||||
"url": "https://blossom.kosmos.org/2ddf3cdb1ac53628e0404ae61e776816dffc3690f1a3c621788f1da1f0f26bdf",
|
||||
"feed": "dt:nature",
|
||||
"title": "Awakening trees",
|
||||
"alt": "Awakening trees",
|
||||
"content": "Awakening trees.\n\nPhoto by Meiying Ng on Unsplash.",
|
||||
"tags": ["nature", "forest", "snow", "trees"],
|
||||
"sha256": "2ddf3cdb1ac53628e0404ae61e776816dffc3690f1a3c621788f1da1f0f26bdf",
|
||||
"size": 381052,
|
||||
"dim": "2560x1440",
|
||||
"mime": "image/jpeg",
|
||||
"creator": "Meiying Ng",
|
||||
"profile": "https://unsplash.com/@meiying",
|
||||
"source": "https://unsplash.com/photos/H-8zTDArbaQ",
|
||||
"license": "unsplash",
|
||||
"licenseUrl": "https://unsplash.com/license",
|
||||
"portfolio": "",
|
||||
"verified": {
|
||||
"at": "2026-11-08",
|
||||
"by": "planning-verification",
|
||||
"profile": { "status": 200, "name": true },
|
||||
"source": { "status": 200, "name": true },
|
||||
"license": { "status": 200 }
|
||||
},
|
||||
"originId": "H-8zTDArbaQ"
|
||||
},
|
||||
{
|
||||
"file": "public/img/wallpapers/meiying-ng-iB7gjOsLrEQ-unsplash.jpg",
|
||||
"url": "https://blossom.kosmos.org/b55f5643c4780165f51fdbf82e64e23d9da851b85b0050c7958463b5746281ab",
|
||||
"feed": "dt:nature",
|
||||
"title": "Mountain surrounded by water",
|
||||
"alt": "mountain surround by body of water",
|
||||
"content": "Mountain surrounded by water.\n\nPhoto by Meiying Ng on Unsplash.",
|
||||
"tags": ["nature", "mountain", "lake", "sunrise"],
|
||||
"sha256": "b55f5643c4780165f51fdbf82e64e23d9da851b85b0050c7958463b5746281ab",
|
||||
"size": 412576,
|
||||
"dim": "2560x1440",
|
||||
"mime": "image/jpeg",
|
||||
"creator": "Meiying Ng",
|
||||
"profile": "https://unsplash.com/@meiying",
|
||||
"source": "https://unsplash.com/photos/mountain-surround-by-body-of-water-iB7gjOsLrEQ",
|
||||
"license": "unsplash",
|
||||
"licenseUrl": "https://unsplash.com/license",
|
||||
"portfolio": "",
|
||||
"verified": {
|
||||
"at": "2026-11-08",
|
||||
"by": "planning-verification",
|
||||
"profile": { "status": 200, "name": true },
|
||||
"source": { "status": 200, "name": true },
|
||||
"license": { "status": 200 }
|
||||
},
|
||||
"originId": "iB7gjOsLrEQ"
|
||||
},
|
||||
{
|
||||
"file": "public/img/wallpapers/wolfgang-hasselmann-pVr6wvUneMk-unsplash.jpg",
|
||||
"url": "https://blossom.kosmos.org/2efc1f556cbf250d7d5999fb587fb51522e11c04737e2bcffcb9f4b9aa6eeedf",
|
||||
"feed": "dt:nature",
|
||||
"title": "Rolling sand dunes",
|
||||
"alt": "rolling sand dunes in desert landscape",
|
||||
"content": "Rolling sand dunes.\n\nPhoto by Wolfgang Hasselmann on Unsplash.",
|
||||
"tags": ["nature", "desert", "sand", "dunes"],
|
||||
"sha256": "2efc1f556cbf250d7d5999fb587fb51522e11c04737e2bcffcb9f4b9aa6eeedf",
|
||||
"size": 334302,
|
||||
"dim": "2560x1440",
|
||||
"mime": "image/jpeg",
|
||||
"creator": "Wolfgang Hasselmann",
|
||||
"profile": "https://unsplash.com/@wolfgang_hasselmann",
|
||||
"source": "https://unsplash.com/photos/rolling-sand-dunes-in-desert-landscape-pVr6wvUneMk",
|
||||
"license": "unsplash",
|
||||
"licenseUrl": "https://unsplash.com/license",
|
||||
"portfolio": "https://www.youtube.com/@wolfgang_hasselmann/videos",
|
||||
"verified": {
|
||||
"at": "2026-11-08",
|
||||
"by": "planning-verification",
|
||||
"profile": { "status": 200, "name": true },
|
||||
"source": { "status": 200, "name": true },
|
||||
"license": { "status": 200 },
|
||||
"portfolio": { "status": 200 }
|
||||
},
|
||||
"originId": "pVr6wvUneMk"
|
||||
}
|
||||
]
|
||||
}
|
||||
Executable
+351
@@ -0,0 +1,351 @@
|
||||
#!/usr/bin/env bash
|
||||
# Verify originals, thumbnails, and creator attribution before anything is published.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/lib.sh"
|
||||
|
||||
require_publish_tools
|
||||
require_cmd magick
|
||||
validate_manifest
|
||||
ensure_workdirs
|
||||
|
||||
ATTRIBUTION_ONLY=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--attribution-only) ATTRIBUTION_ONLY=1 ;;
|
||||
--force|--yes|--dry-run) parse_common_args "$arg" ;;
|
||||
*) die "unknown option: $arg" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
THUMB_STATE="$STATE_DIR/thumbs.json"
|
||||
[[ -f "$THUMB_STATE" ]] || die "no thumbnail state; run ./scripts/nostr/run.sh thumbnails first"
|
||||
|
||||
TMP_DIR="$WORK_DIR/preflight"
|
||||
rm -rf "$TMP_DIR"
|
||||
mkdir -p "$TMP_DIR"
|
||||
|
||||
fail_count=0
|
||||
declare -A CONFIRMED_DOMAINS=()
|
||||
pass() { info " ok: $1"; }
|
||||
fail() { warn " FAIL: $1"; fail_count=$((fail_count + 1)); }
|
||||
|
||||
check_https() {
|
||||
local label="$1" url="$2"
|
||||
if [[ -z "$url" ]]; then
|
||||
fail "$label is empty"
|
||||
elif ! is_https "$url"; then
|
||||
fail "$label is not https: $url"
|
||||
else
|
||||
pass "$label is https"
|
||||
fi
|
||||
}
|
||||
|
||||
chrome_bin() {
|
||||
local bin
|
||||
for bin in google-chrome-stable google-chrome chromium chromium-browser; do
|
||||
if command -v "$bin" >/dev/null 2>&1; then
|
||||
printf '%s\n' "$bin"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
probe_with_chrome() {
|
||||
local url="$1" dest="$2" bin
|
||||
bin="$(chrome_bin 2>/dev/null || true)"
|
||||
[[ -n "$bin" ]] || return 1
|
||||
mkdir -p "$WORK_DIR/chrome-profile"
|
||||
if timeout 90 "$bin" --headless=new --no-sandbox --disable-gpu --disable-dev-shm-usage \
|
||||
--no-first-run --no-default-browser-check \
|
||||
--user-data-dir="$WORK_DIR/chrome-profile" \
|
||||
--virtual-time-budget=15000 --dump-dom "$url" > "$dest" 2>/dev/null; then
|
||||
[[ -s "$dest" ]] && return 0
|
||||
fi
|
||||
timeout 90 "$bin" --headless --no-sandbox --disable-gpu --disable-dev-shm-usage \
|
||||
--no-first-run --no-default-browser-check \
|
||||
--user-data-dir="$WORK_DIR/chrome-profile" \
|
||||
--virtual-time-budget=15000 --dump-dom "$url" > "$dest" 2>/dev/null || return 1
|
||||
[[ -s "$dest" ]]
|
||||
}
|
||||
|
||||
looks_like_bot_challenge() {
|
||||
local status="$1" body="$2"
|
||||
[[ "$status" == "307" || "$status" == "401" || "$status" == "403" ]] && return 0
|
||||
[[ -f "$body" ]] && grep -Eqi 'anubis|within\.website|Authorization required|Just a moment|Something went wrong' "$body" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
is_hard_bot_block() {
|
||||
local status="$1" body="$2"
|
||||
[[ "$status" == "401" ]] && return 0
|
||||
[[ -f "$body" ]] && grep -qi 'Authorization required' "$body" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
recorded_status() {
|
||||
jq -r --arg f "$1" --arg k "$2" '.photos[] | select(.file == $f) | .verified[$k].status // empty' "$MANIFEST"
|
||||
}
|
||||
|
||||
recorded_name() {
|
||||
jq -r --arg f "$1" --arg k "$2" '.photos[] | select(.file == $f) | .verified[$k].name // false' "$MANIFEST"
|
||||
}
|
||||
|
||||
recorded_at() {
|
||||
jq -r --arg f "$1" '.photos[] | select(.file == $f) | .verified.at // empty' "$MANIFEST"
|
||||
}
|
||||
|
||||
accept_recorded() {
|
||||
local label="$1" url="$2" creator="$3" file="$4" key="$5" need_name="$6"
|
||||
local rec_status rec_name
|
||||
rec_status="$(recorded_status "$file" "$key")"
|
||||
rec_name="$(recorded_name "$file" "$key")"
|
||||
if [[ "$rec_status" != "200" ]]; then
|
||||
fail "$label: live check blocked and no recorded HTTP 200 verification"
|
||||
return
|
||||
fi
|
||||
if [[ "$need_name" == "1" && "$rec_name" != "true" ]]; then
|
||||
fail "$label: live check blocked and no recorded name verification"
|
||||
return
|
||||
fi
|
||||
local domain
|
||||
domain="$(printf '%s' "$url" | sed -E 's#^https?://([^/]+).*#\1#')"
|
||||
if [[ "${CONFIRMED_DOMAINS[$domain]:-0}" == "1" ]]; then
|
||||
pass "$label: previously confirmed for $domain"
|
||||
return
|
||||
fi
|
||||
warn "$label: live check blocked by provider bot protection."
|
||||
if [[ "$need_name" == "1" ]]; then
|
||||
info " Recorded verification: $(recorded_at "$file") — HTTP 200 and name '$creator' present"
|
||||
else
|
||||
info " Recorded verification: $(recorded_at "$file") — HTTP 200"
|
||||
fi
|
||||
if [[ "$ASSUME_YES" == "1" ]]; then
|
||||
CONFIRMED_DOMAINS[$domain]=1
|
||||
pass "$label: accepted recorded verification (--yes)"
|
||||
return
|
||||
fi
|
||||
if confirm "Open $url and confirm it still works${need_name:+ and shows '$creator'}? (asked once per domain)"; then
|
||||
CONFIRMED_DOMAINS[$domain]=1
|
||||
pass "$label: confirmed by user"
|
||||
else
|
||||
fail "$label: not confirmed"
|
||||
fi
|
||||
}
|
||||
|
||||
check_page() {
|
||||
local label="$1" url="$2" creator="$3" file="$4" key="$5"
|
||||
if [[ -z "$url" || "$url" != https://* ]]; then
|
||||
fail "$label is missing or not https"
|
||||
return
|
||||
fi
|
||||
local body="$TMP_DIR/page-$key-$(basename "$file")"
|
||||
local status
|
||||
status="$(curl -A "$USER_AGENT" -L -sS -o "$body" -w '%{http_code}' --max-time 60 --retry 2 "$url" 2>/dev/null || true)"
|
||||
if [[ "$status" == "200" ]]; then
|
||||
pass "$label returned HTTP 200"
|
||||
if grep -Fqi -- "$creator" "$body"; then
|
||||
pass "$label contains creator name '$creator'"
|
||||
else
|
||||
fail "$label does not contain creator name '$creator'"
|
||||
fi
|
||||
return
|
||||
fi
|
||||
if [[ "$status" == "404" || "$status" == "410" ]]; then
|
||||
fail "$label returned HTTP $status: $url"
|
||||
return
|
||||
fi
|
||||
if looks_like_bot_challenge "$status" "$body"; then
|
||||
if ! is_hard_bot_block "$status" "$body"; then
|
||||
local chrome_body="$TMP_DIR/chrome-$key-$(basename "$file")"
|
||||
if probe_with_chrome "$url" "$chrome_body" && grep -Fqi -- "$creator" "$chrome_body"; then
|
||||
pass "$label verified via headless browser"
|
||||
return
|
||||
fi
|
||||
fi
|
||||
accept_recorded "$label" "$url" "$creator" "$file" "$key" 1
|
||||
return
|
||||
fi
|
||||
fail "$label returned HTTP $status: $url"
|
||||
}
|
||||
|
||||
check_license() {
|
||||
local label="$1" url="$2" file="$3"
|
||||
if [[ -z "$url" || "$url" != https://* ]]; then
|
||||
fail "$label is missing or not https"
|
||||
return
|
||||
fi
|
||||
local body="$TMP_DIR/license-$(basename "$file")"
|
||||
local status
|
||||
status="$(curl -A "$USER_AGENT" -L -sS -o "$body" -w '%{http_code}' --max-time 60 --retry 2 "$url" 2>/dev/null || true)"
|
||||
if [[ "$status" == "200" ]]; then
|
||||
pass "$label returned HTTP 200"
|
||||
return
|
||||
fi
|
||||
if looks_like_bot_challenge "$status" "$body"; then
|
||||
accept_recorded "$label" "$url" "" "$file" license 0
|
||||
return
|
||||
fi
|
||||
fail "$label returned HTTP $status: $url"
|
||||
}
|
||||
|
||||
check_portfolio() {
|
||||
local label="$1" url="$2" file="$3"
|
||||
[[ -n "$url" ]] || return 0
|
||||
if [[ "$url" != https://* ]]; then
|
||||
fail "$label is not https"
|
||||
return
|
||||
fi
|
||||
local body="$TMP_DIR/portfolio-$(basename "$file")"
|
||||
local status
|
||||
status="$(curl -A "$USER_AGENT" -L -sS -o "$body" -w '%{http_code}' --max-time 60 --retry 2 "$url" 2>/dev/null || true)"
|
||||
if [[ "$status" == "200" ]]; then
|
||||
pass "$label returned HTTP 200"
|
||||
return
|
||||
fi
|
||||
if looks_like_bot_challenge "$status" "$body"; then
|
||||
accept_recorded "$label" "$url" "" "$file" portfolio 0
|
||||
return
|
||||
fi
|
||||
fail "$label returned HTTP $status: $url"
|
||||
}
|
||||
|
||||
check_remote_image() {
|
||||
local label="$1" url="$2" expected_sha="$3" expected_size="$4" dest="$5"
|
||||
if [[ -z "$url" || "$url" != https://* ]]; then
|
||||
fail "$label is missing or not https"
|
||||
return
|
||||
fi
|
||||
if ! url_contains_sha "$url" "$expected_sha"; then
|
||||
fail "$label URL does not contain its sha256: $url"
|
||||
fi
|
||||
local meta status content_type
|
||||
meta="$(curl -A "$USER_AGENT" -L -sS -o "$dest" -w '%{http_code} %{content_type}' --max-time 120 --retry 2 "$url" 2>/dev/null || true)"
|
||||
read -r status content_type <<<"$meta"
|
||||
[[ "$status" == "200" ]] || {
|
||||
fail "$label returned HTTP $status: $url"
|
||||
return
|
||||
}
|
||||
pass "$label returned HTTP 200"
|
||||
[[ "$content_type" == image/* ]] || fail "$label returned non-image content type: $content_type"
|
||||
[[ "$content_type" == image/* ]] && pass "$label has image content type: $content_type"
|
||||
local actual_sha actual_size
|
||||
actual_sha="$(sha256_file "$dest")"
|
||||
actual_size="$(file_size "$dest")"
|
||||
[[ "$actual_sha" == "$expected_sha" ]] && pass "$label sha256 matches" || fail "$label sha256 mismatch (expected $expected_sha, got $actual_sha)"
|
||||
if [[ -n "$expected_size" && "$expected_size" != "0" ]]; then
|
||||
[[ "$actual_size" == "$expected_size" ]] && pass "$label size matches" || fail "$label size mismatch (expected $expected_size, got $actual_size)"
|
||||
fi
|
||||
}
|
||||
|
||||
info "Preflight: $MANIFEST"
|
||||
info "Attribution only: $ATTRIBUTION_ONLY"
|
||||
info ""
|
||||
|
||||
while IFS= read -r file; do
|
||||
info "== $file =="
|
||||
src="$ROOT/$file"
|
||||
sha="$(photo_field "$file" sha256)"
|
||||
size="$(photo_field "$file" size)"
|
||||
dim="$(photo_field "$file" dim)"
|
||||
mime="$(photo_field "$file" mime)"
|
||||
url="$(photo_field "$file" url)"
|
||||
feed="$(photo_field "$file" feed)"
|
||||
title="$(photo_field "$file" title)"
|
||||
alt="$(photo_field "$file" alt)"
|
||||
content="$(photo_field "$file" content)"
|
||||
creator="$(photo_field "$file" creator)"
|
||||
profile="$(photo_field "$file" profile)"
|
||||
source="$(photo_field "$file" source)"
|
||||
license="$(photo_field "$file" license)"
|
||||
license_url="$(photo_field "$file" licenseUrl)"
|
||||
portfolio="$(photo_field "$file" portfolio)"
|
||||
origin_id="$(photo_field "$file" originId)"
|
||||
|
||||
for field in sha size dim mime url feed title alt content creator profile source license license_url origin_id; do
|
||||
[[ -n "${!field}" ]] || fail "required field '$field' is empty"
|
||||
done
|
||||
[[ -n "$(feed_field "$feed" title)" ]] || fail "unknown feed: $feed"
|
||||
|
||||
if [[ -f "$src" ]]; then
|
||||
pass "local file exists"
|
||||
[[ "$(sha256_file "$src")" == "$sha" ]] && pass "local sha256 matches manifest" || fail "local sha256 mismatch"
|
||||
[[ "$(file_size "$src")" == "$size" ]] && pass "local size matches manifest" || fail "local size mismatch"
|
||||
[[ "$(image_dim "$src")" == "$dim" ]] && pass "local dimensions match manifest" || fail "local dimensions mismatch"
|
||||
[[ "$(file_mime "$src")" == "$mime" ]] && pass "local MIME matches manifest" || fail "local MIME mismatch"
|
||||
else
|
||||
fail "local file missing: $src"
|
||||
fi
|
||||
|
||||
check_https "original url" "$url"
|
||||
check_https "profile" "$profile"
|
||||
check_https "source" "$source"
|
||||
check_https "license url" "$license_url"
|
||||
[[ -z "$portfolio" ]] || check_https "portfolio" "$portfolio"
|
||||
|
||||
check_remote_image "original" "$url" "$sha" "$size" "$TMP_DIR/$(basename "$file")"
|
||||
|
||||
if [[ "$ATTRIBUTION_ONLY" != "1" ]]; then
|
||||
thumb_url="$(jq -r --arg f "$file" '.[$f].url // empty' "$THUMB_STATE")"
|
||||
thumb_sha="$(jq -r --arg f "$file" '.[$f].sha256 // empty' "$THUMB_STATE")"
|
||||
thumb_size="$(jq -r --arg f "$file" '.[$f].size // empty' "$THUMB_STATE")"
|
||||
thumb_file="$(jq -r --arg f "$file" '.[$f].thumb // empty' "$THUMB_STATE")"
|
||||
if [[ -z "$thumb_url" || -z "$thumb_sha" ]]; then
|
||||
fail "thumbnail has not been uploaded"
|
||||
else
|
||||
check_https "thumbnail url" "$thumb_url"
|
||||
check_remote_image "thumbnail" "$thumb_url" "$thumb_sha" "$thumb_size" "$TMP_DIR/thumb-$(basename "$file")"
|
||||
if [[ -f "$thumb_file" ]]; then
|
||||
[[ "$(sha256_file "$thumb_file")" == "$thumb_sha" ]] && pass "local thumbnail sha256 matches" || fail "local thumbnail sha256 mismatch"
|
||||
else
|
||||
fail "local thumbnail missing: $thumb_file"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
check_page "profile page" "$profile" "$creator" "$file" profile
|
||||
check_page "source page" "$source" "$creator" "$file" source
|
||||
check_license "license url" "$license_url" "$file"
|
||||
check_portfolio "portfolio" "$portfolio" "$file"
|
||||
|
||||
info ""
|
||||
done < <(photo_files)
|
||||
|
||||
# Feed-level checks: every order entry exists (manifest validation) and, unless attribution-only,
|
||||
# every photo has a thumbnail URL. Feed publication additionally requires published photo IDs.
|
||||
while IFS= read -r feed; do
|
||||
info "== feed $feed =="
|
||||
cover="$(feed_field "$feed" cover)"
|
||||
if [[ -n "$cover" && "$ATTRIBUTION_ONLY" != "1" ]]; then
|
||||
cover_thumb="$(jq -r --arg f "$cover" '.[$f].url // empty' "$THUMB_STATE")"
|
||||
[[ -n "$cover_thumb" ]] && pass "cover thumbnail is uploaded" || fail "cover thumbnail is not uploaded ($cover)"
|
||||
fi
|
||||
while IFS= read -r order_file; do
|
||||
[[ -n "$(photo_field "$order_file" sha256)" ]] || fail "feed order references unknown photo: $order_file"
|
||||
done < <(jq -r --arg f "$feed" '.feeds[] | select(.id == $f) | .order[]' "$MANIFEST")
|
||||
info ""
|
||||
done < <(feed_ids)
|
||||
|
||||
now="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
ok=false
|
||||
[[ "$fail_count" -eq 0 ]] && ok=true
|
||||
jq -n \
|
||||
--argjson ok "$ok" \
|
||||
--argjson attributionOnly "$([[ "$ATTRIBUTION_ONLY" == "1" ]] && echo true || echo false)" \
|
||||
--arg checkedAt "$now" \
|
||||
--argjson failures "$fail_count" \
|
||||
'{ok: $ok, attributionOnly: $attributionOnly, checkedAt: $checkedAt, failures: $failures}' \
|
||||
> "$STATE_DIR/preflight.json"
|
||||
|
||||
if [[ "$fail_count" -gt 0 ]]; then
|
||||
die "preflight failed with $fail_count issue(s)"
|
||||
fi
|
||||
|
||||
info "Preflight passed."
|
||||
if [[ "$ATTRIBUTION_ONLY" == "1" ]]; then
|
||||
info "This was an attribution-only run; run the full preflight before publishing."
|
||||
else
|
||||
info "Publishing is allowed."
|
||||
fi
|
||||
Executable
+159
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env bash
|
||||
# Sign and publish the replaceable kind-30006 feed events.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/lib.sh"
|
||||
|
||||
require_publish_tools
|
||||
validate_manifest
|
||||
ensure_workdirs
|
||||
|
||||
parse_common_args "$@"
|
||||
|
||||
PHOTO_STATE="$STATE_DIR/photos.json"
|
||||
FEED_STATE="$STATE_DIR/feeds.json"
|
||||
state_init "$PHOTO_STATE"
|
||||
state_init "$FEED_STATE"
|
||||
|
||||
info "Building event drafts (feed drafts require published photo IDs)."
|
||||
"$SCRIPT_DIR/build-events.sh"
|
||||
|
||||
to_publish=()
|
||||
for feed in $(feed_ids); do
|
||||
draft="$EVENTS_DIR/feeds/$(feed_slug "$feed").json"
|
||||
[[ -f "$draft" ]] || die "missing feed draft for $feed; publish the photos first"
|
||||
|
||||
# The e list may only contain photo event IDs confirmed published on the relay.
|
||||
while IFS= read -r order_file; do
|
||||
photo_id="$(jq -r --arg f "$order_file" '.[$f].id // empty' "$PHOTO_STATE")"
|
||||
[[ -n "$photo_id" ]] || die "feed $feed references a photo with no published event ID: $order_file"
|
||||
[[ -n "$(relay_photo_by_id "$photo_id")" ]] || die "feed $feed references a photo that is not on the relay: $order_file ($photo_id)"
|
||||
done < <(jq -r --arg f "$feed" '.feeds[] | select(.id == $f) | .order[]' "$MANIFEST")
|
||||
|
||||
existing="$(relay_feed "$feed")"
|
||||
if [[ -n "$existing" && "$FORCE" != "1" ]]; then
|
||||
current_summary="$(jq -S -c '{
|
||||
title: ([.tags[] | select(.[0] == "title")][0][1] // ""),
|
||||
description: ([.tags[] | select(.[0] == "description")][0][1] // ""),
|
||||
image: ([.tags[] | select(.[0] == "image")][0][1] // ""),
|
||||
e: [.tags[] | select(.[0] == "e") | .[1]]
|
||||
}' <<<"$existing")"
|
||||
draft_summary="$(jq -S -c '{
|
||||
title: ([.tags[] | select(.[0] == "title")][0][1] // ""),
|
||||
description: ([.tags[] | select(.[0] == "description")][0][1] // ""),
|
||||
image: ([.tags[] | select(.[0] == "image")][0][1] // ""),
|
||||
e: [.tags[] | select(.[0] == "e") | .[1]]
|
||||
}' "$draft")"
|
||||
if [[ "$current_summary" == "$draft_summary" ]]; then
|
||||
id="$(jq -r '.id' <<<"$existing")"
|
||||
created_at="$(jq -r '.created_at' <<<"$existing")"
|
||||
e_ids="$(jq -c '[.tags[] | select(.[0] == "e") | .[1]]' <<<"$existing")"
|
||||
tmp="$FEED_STATE.tmp"
|
||||
jq --arg f "$feed" --arg id "$id" --arg pubkey "$CURATOR" \
|
||||
--argjson created_at "$created_at" --argjson e_ids "$e_ids" \
|
||||
'.[$f] = {id: $id, pubkey: $pubkey, created_at: $created_at, e_ids: $e_ids}' \
|
||||
"$FEED_STATE" > "$tmp"
|
||||
mv "$tmp" "$FEED_STATE"
|
||||
info "skip (already current): $feed -> $id"
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
|
||||
to_publish+=("$feed")
|
||||
done
|
||||
|
||||
if [[ "${#to_publish[@]}" -eq 0 ]]; then
|
||||
info "Nothing to publish. All feeds are already current."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
info ""
|
||||
info "Will publish ${#to_publish[@]} feed event(s) as $CURATOR to $RELAY:"
|
||||
for feed in "${to_publish[@]}"; do
|
||||
info " $feed ($(feed_field "$feed" title))"
|
||||
done
|
||||
info ""
|
||||
if [[ "${#NAK_PROMPT_ARGS[@]}" -gt 0 ]]; then
|
||||
info "nak will prompt for the curator secret key for each feed signature, and again to authenticate the relay connection."
|
||||
info "Paste the nsec/hex when prompted; it is used only by nak and never stored."
|
||||
else
|
||||
info "NOSTR_SECRET_KEY is set; nak will use it from the environment (no prompts)."
|
||||
fi
|
||||
|
||||
if ! confirm "Publish these feed events now?"; then
|
||||
info "Aborted."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for feed in "${to_publish[@]}"; do
|
||||
slug="$(feed_slug "$feed")"
|
||||
draft="$EVENTS_DIR/feeds/$slug.json"
|
||||
signed="$EVENTS_DIR/feeds/$slug.signed.json"
|
||||
published="$EVENTS_DIR/feeds/$slug.published.json"
|
||||
[[ -f "$draft" ]] || die "missing feed draft: $draft"
|
||||
|
||||
if [[ "$FORCE" == "1" ]]; then
|
||||
rm -f "$signed" "$published"
|
||||
fi
|
||||
|
||||
if [[ -f "$signed" ]]; then
|
||||
if ! jq -e --arg pk "$CURATOR" '.kind == 30006 and .pubkey == $pk and (.id | length > 0)' "$signed" >/dev/null 2>&1; then
|
||||
warn "ignoring invalid/foreign signed feed: $signed"
|
||||
rm -f "$signed"
|
||||
elif [[ "$(event_body "$signed")" != "$(event_body "$draft")" ]]; then
|
||||
warn "signed feed no longer matches the draft; re-signing: $feed"
|
||||
rm -f "$signed" "$published"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ ! -f "$signed" ]]; then
|
||||
info ""
|
||||
info "Signing feed: $feed ($(feed_field "$feed" title))"
|
||||
if [[ "${#NAK_PROMPT_ARGS[@]}" -gt 0 ]]; then
|
||||
info "nak is asking for the curator secret key now."
|
||||
fi
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
print_cmd nak event "${NAK_PROMPT_ARGS[@]}" "<" "$draft" ">" "$signed"
|
||||
continue
|
||||
fi
|
||||
if ! nak event "${NAK_PROMPT_ARGS[@]}" < "$draft" > "$signed"; then
|
||||
rm -f "$signed"
|
||||
die "signing failed for feed $feed"
|
||||
fi
|
||||
if ! jq -e --arg pk "$CURATOR" '.kind == 30006 and .pubkey == $pk and (.id | length > 0)' "$signed" >/dev/null; then
|
||||
rm -f "$signed"
|
||||
die "signed feed $feed is not kind 30006 or was not signed by the curator ($CURATOR); nothing was published"
|
||||
fi
|
||||
fi
|
||||
|
||||
id="$(jq -r '.id' "$signed")"
|
||||
info "Publishing $id ..."
|
||||
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
print_cmd nak event --auth "${NAK_PROMPT_ARGS[@]}" "$RELAY" "<" "$signed" ">" "$published"
|
||||
continue
|
||||
fi
|
||||
|
||||
if ! nak event --auth "${NAK_PROMPT_ARGS[@]}" "$RELAY" < "$signed" > "$published"; then
|
||||
die "relay publish failed for feed $feed ($id)"
|
||||
fi
|
||||
|
||||
if [[ -z "$(relay_feed "$feed")" ]]; then
|
||||
die "relay verification failed for feed $feed ($id)"
|
||||
fi
|
||||
|
||||
created_at="$(jq -r '.created_at' "$signed")"
|
||||
e_ids="$(jq -c '[.tags[] | select(.[0] == "e") | .[1]]' "$signed")"
|
||||
tmp="$FEED_STATE.tmp"
|
||||
jq --arg f "$feed" --arg id "$id" --arg pubkey "$CURATOR" \
|
||||
--argjson created_at "$created_at" --argjson e_ids "$e_ids" \
|
||||
'.[$f] = {id: $id, pubkey: $pubkey, created_at: $created_at, e_ids: $e_ids}' \
|
||||
"$FEED_STATE" > "$tmp"
|
||||
mv "$tmp" "$FEED_STATE"
|
||||
|
||||
info "published: $feed -> $id"
|
||||
done
|
||||
|
||||
info ""
|
||||
info "Feed publishing complete."
|
||||
Executable
+153
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env bash
|
||||
# Sign and publish kind-20 photo events. nak prompts for the curator key per event.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/lib.sh"
|
||||
|
||||
require_publish_tools
|
||||
validate_manifest
|
||||
ensure_workdirs
|
||||
|
||||
parse_common_args "$@"
|
||||
|
||||
PHOTO_STATE="$STATE_DIR/photos.json"
|
||||
state_init "$PHOTO_STATE"
|
||||
|
||||
info "Running full preflight before publishing."
|
||||
"$SCRIPT_DIR/preflight.sh"
|
||||
|
||||
info ""
|
||||
info "Building event drafts."
|
||||
"$SCRIPT_DIR/build-events.sh"
|
||||
|
||||
to_publish=()
|
||||
|
||||
info ""
|
||||
info "Checking for already-published photo events."
|
||||
while IFS= read -r file; do
|
||||
sha="$(photo_field "$file" sha256)"
|
||||
state_id="$(jq -r --arg f "$file" '.[$f].id // empty' "$PHOTO_STATE")"
|
||||
|
||||
if [[ "$FORCE" != "1" && -n "$state_id" ]]; then
|
||||
if [[ -n "$(relay_photo_by_id "$state_id")" ]]; then
|
||||
info " skip (state + relay): $file"
|
||||
continue
|
||||
fi
|
||||
warn "state id for $file is not on the relay; will re-check by x"
|
||||
fi
|
||||
|
||||
if [[ "$FORCE" != "1" ]]; then
|
||||
existing="$(relay_photo_by_x "$sha")"
|
||||
if [[ -n "$existing" ]]; then
|
||||
id="$(jq -r '.id' <<<"$existing")"
|
||||
created_at="$(jq -r '.created_at' <<<"$existing")"
|
||||
tmp="$PHOTO_STATE.tmp"
|
||||
jq --arg f "$file" --arg id "$id" --arg pubkey "$CURATOR" \
|
||||
--argjson created_at "$created_at" --arg sha "$sha" \
|
||||
'.[$f] = {id: $id, pubkey: $pubkey, created_at: $created_at, sha256: $sha}' \
|
||||
"$PHOTO_STATE" > "$tmp"
|
||||
mv "$tmp" "$PHOTO_STATE"
|
||||
info " skip (already on relay by x): $file -> $id"
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
|
||||
to_publish+=("$file")
|
||||
done < <(photo_files)
|
||||
|
||||
if [[ "${#to_publish[@]}" -eq 0 ]]; then
|
||||
info ""
|
||||
info "Nothing to publish. All photo events are already on the relay."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
info ""
|
||||
info "Will publish ${#to_publish[@]} photo event(s) as $CURATOR to $RELAY:"
|
||||
for file in "${to_publish[@]}"; do
|
||||
info " $file"
|
||||
done
|
||||
info ""
|
||||
if [[ "${#NAK_PROMPT_ARGS[@]}" -gt 0 ]]; then
|
||||
info "nak will prompt for the curator secret key for each signature, and again to authenticate the relay connection."
|
||||
info "Paste the nsec/hex when prompted; it is used only by nak and never stored."
|
||||
else
|
||||
info "NOSTR_SECRET_KEY is set; nak will use it from the environment (no prompts)."
|
||||
fi
|
||||
|
||||
if ! confirm "Publish these photo events now?"; then
|
||||
info "Aborted."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for file in "${to_publish[@]}"; do
|
||||
sha="$(photo_field "$file" sha256)"
|
||||
draft="$EVENTS_DIR/photos/$sha.json"
|
||||
signed="$EVENTS_DIR/photos/$sha.signed.json"
|
||||
published="$EVENTS_DIR/photos/$sha.published.json"
|
||||
[[ -f "$draft" ]] || die "missing draft: $draft"
|
||||
|
||||
if [[ "$FORCE" == "1" ]]; then
|
||||
rm -f "$signed" "$published"
|
||||
fi
|
||||
|
||||
if [[ -f "$signed" ]]; then
|
||||
if ! jq -e --arg pk "$CURATOR" '.kind == 20 and .pubkey == $pk and (.id | length > 0)' "$signed" >/dev/null 2>&1; then
|
||||
warn "ignoring invalid/foreign signed event: $signed"
|
||||
rm -f "$signed"
|
||||
elif [[ "$(event_body "$signed")" != "$(event_body "$draft")" ]]; then
|
||||
warn "signed event no longer matches the draft; re-signing: $file"
|
||||
rm -f "$signed" "$published"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ ! -f "$signed" ]]; then
|
||||
info ""
|
||||
info "Signing: $file"
|
||||
if [[ "${#NAK_PROMPT_ARGS[@]}" -gt 0 ]]; then
|
||||
info "nak is asking for the curator secret key now."
|
||||
fi
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
print_cmd nak event "${NAK_PROMPT_ARGS[@]}" "<" "$draft" ">" "$signed"
|
||||
continue
|
||||
fi
|
||||
if ! nak event "${NAK_PROMPT_ARGS[@]}" < "$draft" > "$signed"; then
|
||||
rm -f "$signed"
|
||||
die "signing failed for $file"
|
||||
fi
|
||||
if ! jq -e --arg pk "$CURATOR" '.kind == 20 and .pubkey == $pk and (.id | length > 0)' "$signed" >/dev/null; then
|
||||
rm -f "$signed"
|
||||
die "signed event for $file is not kind 20 or was not signed by the curator ($CURATOR); nothing was published"
|
||||
fi
|
||||
fi
|
||||
|
||||
id="$(jq -r '.id' "$signed")"
|
||||
info "Publishing $id ..."
|
||||
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
print_cmd nak event --auth "${NAK_PROMPT_ARGS[@]}" "$RELAY" "<" "$signed" ">" "$published"
|
||||
continue
|
||||
fi
|
||||
|
||||
if ! nak event --auth "${NAK_PROMPT_ARGS[@]}" "$RELAY" < "$signed" > "$published"; then
|
||||
die "relay publish failed for $file ($id)"
|
||||
fi
|
||||
|
||||
if [[ -z "$(relay_photo_by_id "$id")" ]]; then
|
||||
die "relay verification failed for $file ($id)"
|
||||
fi
|
||||
|
||||
created_at="$(jq -r '.created_at' "$signed")"
|
||||
tmp="$PHOTO_STATE.tmp"
|
||||
jq --arg f "$file" --arg id "$id" --arg pubkey "$CURATOR" \
|
||||
--argjson created_at "$created_at" --arg sha "$sha" \
|
||||
'.[$f] = {id: $id, pubkey: $pubkey, created_at: $created_at, sha256: $sha}' \
|
||||
"$PHOTO_STATE" > "$tmp"
|
||||
mv "$tmp" "$PHOTO_STATE"
|
||||
|
||||
info "published: $file -> $id"
|
||||
done
|
||||
|
||||
info ""
|
||||
info "Photo publishing complete."
|
||||
info "Next: ./scripts/nostr/run.sh publish-feeds"
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
# Entry point for the Dashtab Nostr photo publishing workflow.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/lib.sh"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: ./scripts/nostr/run.sh <command> [options]
|
||||
|
||||
Commands:
|
||||
thumbnails Generate 480x270 JPEG thumbnails in tmp/nostr-photos/thumbs
|
||||
upload-thumbnails Upload thumbnails to Kosmos Blossom (nak prompts once)
|
||||
preflight Verify files, Blossom URLs, thumbnails, and attribution
|
||||
build Build unsigned photo/feed event drafts
|
||||
publish-photos Sign (nak prompts per photo) and publish kind-20 events
|
||||
publish-feeds Sign (nak prompts per feed) and publish kind-30006 feeds
|
||||
all thumbnails -> upload -> preflight -> build -> photos -> feeds
|
||||
status Show current state
|
||||
|
||||
Options:
|
||||
--force Regenerate/upload/republish even if state says done
|
||||
--yes Skip confirmation prompts
|
||||
--dry-run Print the nak commands without signing or publishing
|
||||
--attribution-only For 'preflight': skip thumbnail checks
|
||||
|
||||
The curator key is never stored. nak uses --prompt-sec to ask for it in the
|
||||
terminal (via /dev/tty when an event is piped through stdin). The scripts verify
|
||||
the signed event pubkey matches the curator before publishing.
|
||||
EOF
|
||||
}
|
||||
|
||||
command=""
|
||||
attribution_only=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--force) export FORCE=1 ;;
|
||||
--yes) export ASSUME_YES=1 ;;
|
||||
--dry-run) export DRY_RUN=1 ;;
|
||||
--attribution-only) attribution_only=1 ;;
|
||||
*)
|
||||
if [[ -z "$command" ]]; then
|
||||
command="$arg"
|
||||
else
|
||||
die "unexpected argument: $arg"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
command="${command:-help}"
|
||||
|
||||
case "$command" in
|
||||
thumbnails)
|
||||
"$SCRIPT_DIR/thumbnails.sh"
|
||||
;;
|
||||
upload-thumbnails|upload)
|
||||
"$SCRIPT_DIR/upload-thumbnails.sh"
|
||||
;;
|
||||
preflight)
|
||||
if [[ "$attribution_only" == "1" ]]; then
|
||||
"$SCRIPT_DIR/preflight.sh" --attribution-only
|
||||
else
|
||||
"$SCRIPT_DIR/preflight.sh"
|
||||
fi
|
||||
;;
|
||||
build|events)
|
||||
"$SCRIPT_DIR/build-events.sh"
|
||||
;;
|
||||
publish-photos|photos)
|
||||
"$SCRIPT_DIR/publish-photos.sh"
|
||||
;;
|
||||
publish-feeds|feeds)
|
||||
"$SCRIPT_DIR/publish-feeds.sh"
|
||||
;;
|
||||
all)
|
||||
"$SCRIPT_DIR/thumbnails.sh"
|
||||
"$SCRIPT_DIR/upload-thumbnails.sh"
|
||||
"$SCRIPT_DIR/preflight.sh"
|
||||
"$SCRIPT_DIR/build-events.sh"
|
||||
"$SCRIPT_DIR/publish-photos.sh"
|
||||
"$SCRIPT_DIR/publish-feeds.sh"
|
||||
;;
|
||||
status)
|
||||
summary
|
||||
;;
|
||||
help|-h|--help)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
die "unknown command: $command"
|
||||
;;
|
||||
esac
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env bash
|
||||
# Generate the Settings-grid thumbnails from the verified originals.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/lib.sh"
|
||||
|
||||
require_cmd magick
|
||||
require_cmd jq
|
||||
validate_manifest
|
||||
ensure_workdirs
|
||||
|
||||
THUMB_STATE="$STATE_DIR/thumbs.json"
|
||||
state_init "$THUMB_STATE"
|
||||
|
||||
parse_common_args "$@"
|
||||
|
||||
info "Generating 480x270 JPEG thumbnails from $(photo_count) photos."
|
||||
info "Output: $THUMBS_DIR"
|
||||
info ""
|
||||
|
||||
while IFS= read -r file; do
|
||||
src="$ROOT/$file"
|
||||
[[ -f "$src" ]] || die "missing local file: $src"
|
||||
|
||||
expected_sha="$(photo_field "$file" sha256)"
|
||||
expected_size="$(photo_field "$file" size)"
|
||||
expected_dim="$(photo_field "$file" dim)"
|
||||
expected_mime="$(photo_field "$file" mime)"
|
||||
|
||||
actual_sha="$(sha256_file "$src")"
|
||||
actual_size="$(file_size "$src")"
|
||||
actual_dim="$(image_dim "$src")"
|
||||
actual_mime="$(file_mime "$src")"
|
||||
|
||||
[[ "$actual_sha" == "$expected_sha" ]] || die "sha256 mismatch for $file (expected $expected_sha, got $actual_sha)"
|
||||
[[ "$actual_size" == "$expected_size" ]] || die "size mismatch for $file (expected $expected_size, got $actual_size)"
|
||||
[[ "$actual_dim" == "$expected_dim" ]] || die "dimension mismatch for $file (expected $expected_dim, got $actual_dim)"
|
||||
[[ "$actual_mime" == "$expected_mime" ]] || die "MIME mismatch for $file (expected $expected_mime, got $actual_mime)"
|
||||
|
||||
base="$(basename "$file")"
|
||||
thumb="$THUMBS_DIR/$base"
|
||||
|
||||
if [[ "$FORCE" != "1" && -f "$thumb" && "$thumb" -nt "$src" ]]; then
|
||||
info "keep: $thumb"
|
||||
else
|
||||
magick "$src" -auto-orient -resize 480x270 -strip -quality 82 "$thumb"
|
||||
info "made: $thumb"
|
||||
fi
|
||||
|
||||
thumb_sha="$(sha256_file "$thumb")"
|
||||
thumb_size="$(file_size "$thumb")"
|
||||
thumb_dim="$(image_dim "$thumb")"
|
||||
thumb_mime="$(file_mime "$thumb")"
|
||||
|
||||
old_sha="$(jq -r --arg f "$file" '.[$f].sha256 // empty' "$THUMB_STATE")"
|
||||
if [[ "$old_sha" != "$thumb_sha" ]]; then
|
||||
tmp="$THUMB_STATE.tmp"
|
||||
jq --arg f "$file" '.[$f] |= del(.url, .uploadedAt, .server)' "$THUMB_STATE" > "$tmp"
|
||||
mv "$tmp" "$THUMB_STATE"
|
||||
fi
|
||||
|
||||
tmp="$THUMB_STATE.tmp"
|
||||
jq --arg f "$file" \
|
||||
--arg thumb "$thumb" \
|
||||
--arg sha "$thumb_sha" \
|
||||
--arg dim "$thumb_dim" \
|
||||
--arg mime "$thumb_mime" \
|
||||
--argjson size "$thumb_size" \
|
||||
'.[$f] = ((.[$f] // {}) + {
|
||||
thumb: $thumb,
|
||||
sha256: $sha,
|
||||
size: $size,
|
||||
dim: $dim,
|
||||
mime: $mime
|
||||
})' "$THUMB_STATE" > "$tmp"
|
||||
mv "$tmp" "$THUMB_STATE"
|
||||
|
||||
info " $thumb_dim, $thumb_size bytes, sha256=$thumb_sha"
|
||||
done < <(photo_files)
|
||||
|
||||
info ""
|
||||
info "Thumbnails ready. Next: ./scripts/nostr/run.sh upload-thumbnails"
|
||||
info "Publishing is blocked until every thumbnail is uploaded and preflight passes."
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env bash
|
||||
# Upload generated thumbnails to Kosmos Blossom. nak prompts for the key once.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/lib.sh"
|
||||
|
||||
require_nak
|
||||
require_cmd jq
|
||||
require_cmd curl
|
||||
validate_manifest
|
||||
ensure_workdirs
|
||||
|
||||
THUMB_STATE="$STATE_DIR/thumbs.json"
|
||||
[[ -f "$THUMB_STATE" ]] || die "no thumbnail state; run ./scripts/nostr/run.sh thumbnails first"
|
||||
|
||||
parse_common_args "$@"
|
||||
|
||||
mapfile -t files < <(
|
||||
jq -r --argjson force "$FORCE" \
|
||||
'to_entries[] | select(($force == 1) or ((.value.url // "") == "")) | .key' \
|
||||
"$THUMB_STATE"
|
||||
)
|
||||
|
||||
if [[ "${#files[@]}" -eq 0 ]]; then
|
||||
info "All thumbnails already have Blossom URLs."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
thumbs=()
|
||||
for file in "${files[@]}"; do
|
||||
thumb="$(jq -r --arg f "$file" '.[$f].thumb // empty' "$THUMB_STATE")"
|
||||
[[ -n "$thumb" && -f "$thumb" ]] || die "missing generated thumbnail for $file; run thumbnails again"
|
||||
thumbs+=("$thumb")
|
||||
done
|
||||
|
||||
info "Uploading ${#files[@]} thumbnail(s) to $BLOSSOM"
|
||||
for i in "${!files[@]}"; do
|
||||
info " ${files[$i]} -> ${thumbs[$i]}"
|
||||
done
|
||||
info ""
|
||||
if [[ "${#NAK_PROMPT_ARGS[@]}" -gt 0 ]]; then
|
||||
info "nak will ask for the key. Paste the Kosmos Blossom upload key (nsec/hex)."
|
||||
info "The key is used only by nak and is never written to disk."
|
||||
else
|
||||
info "NOSTR_SECRET_KEY is set; nak will use it from the environment (no prompt)."
|
||||
fi
|
||||
|
||||
if ! confirm "Upload these thumbnails now?"; then
|
||||
info "Aborted."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
upload_out="$LOG_DIR/upload-thumbs-$(date -u +%Y%m%dT%H%M%SZ).ndjson"
|
||||
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
print_cmd nak "${NAK_PROMPT_ARGS[@]}" blossom --server "$BLOSSOM" upload "${thumbs[@]}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
nak "${NAK_PROMPT_ARGS[@]}" blossom --server "$BLOSSOM" upload "${thumbs[@]}" > "$upload_out"
|
||||
|
||||
upload_json="$upload_out.json"
|
||||
jq -s 'map(select(type == "object"))' "$upload_out" > "$upload_json"
|
||||
count="$(jq 'length' "$upload_json")"
|
||||
[[ "$count" -eq "${#files[@]}" ]] || die "expected ${#files[@]} upload result(s), got $count; see $upload_out"
|
||||
|
||||
now="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
|
||||
for i in "${!files[@]}"; do
|
||||
file="${files[$i]}"
|
||||
blob="$(jq -c ".[$i]" "$upload_json")"
|
||||
sha="$(jq -r '.sha256 // empty' <<<"$blob")"
|
||||
url="$(jq -r '.url // empty' <<<"$blob")"
|
||||
remote_size="$(jq -r '.size // empty' <<<"$blob")"
|
||||
remote_type="$(jq -r '.type // empty' <<<"$blob")"
|
||||
|
||||
expected_sha="$(jq -r --arg f "$file" '.[$f].sha256 // empty' "$THUMB_STATE")"
|
||||
expected_size="$(jq -r --arg f "$file" '.[$f].size // empty' "$THUMB_STATE")"
|
||||
|
||||
[[ -n "$sha" && -n "$url" ]] || die "Blossom returned no sha256/url for $file: $blob"
|
||||
[[ "$sha" == "$expected_sha" ]] || die "Blossom hash mismatch for $file (expected $expected_sha, got $sha)"
|
||||
[[ -z "$remote_size" || "$remote_size" == "$expected_size" ]] || die "Blossom size mismatch for $file (expected $expected_size, got $remote_size)"
|
||||
[[ -z "$remote_type" || "$remote_type" == image/* ]] || die "Blossom returned non-image type for $file: $remote_type"
|
||||
is_https "$url" || die "Blossom returned a non-https URL for $file: $url"
|
||||
url_contains_sha "$url" "$sha" || warn "Blossom URL does not contain the hash for $file: $url"
|
||||
|
||||
status="$(http_status "$url")"
|
||||
[[ "$status" == "200" ]] || die "uploaded thumbnail is not reachable for $file: HTTP $status ($url)"
|
||||
|
||||
tmp="$THUMB_STATE.tmp"
|
||||
jq --arg f "$file" \
|
||||
--arg url "$url" \
|
||||
--arg server "$BLOSSOM" \
|
||||
--arg uploadedAt "$now" \
|
||||
'.[$f] = ((.[$f] // {}) + {
|
||||
url: $url,
|
||||
server: $server,
|
||||
uploadedAt: $uploadedAt
|
||||
})' "$THUMB_STATE" > "$tmp"
|
||||
mv "$tmp" "$THUMB_STATE"
|
||||
|
||||
info "ok: $file"
|
||||
info " $url"
|
||||
done
|
||||
|
||||
info ""
|
||||
info "Thumbnails uploaded. Next: ./scripts/nostr/run.sh preflight"
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
[
|
||||
{
|
||||
"kind": 30006,
|
||||
"id": "52c8e2359b70de0367e40b9ad3fdc0fbebf6ef7bb5c1d1b44569e485512eac1f",
|
||||
"pubkey": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"created_at": 1794156547,
|
||||
"tags": [
|
||||
["d", "dt:city-nights"],
|
||||
["title", "City Nights"],
|
||||
["description", "After-dark city scenes."],
|
||||
[
|
||||
"image",
|
||||
"https://blossom.kosmos.org/abb24129793d623c418051a73a389c1535fb6495b6aeca8bd8f176133a6e79d4.jpeg"
|
||||
],
|
||||
[
|
||||
"e",
|
||||
"a2b9b2fe3243b5bd5d5ebe0bec40ce6293003a2de9798e09fdc3526e778c0519",
|
||||
"wss://nostr.kosmos.org"
|
||||
],
|
||||
["t", "dashtab-photo-feed"],
|
||||
["t", "city-nights"]
|
||||
],
|
||||
"content": "",
|
||||
"sig": "6634e31a2bab247b92ec70f28186faf2e6682d24a527474bfc6c14caf8e83b0c2117da756f775a38b014ba3734644151f99bee77783dc15acb33946f78df6adf"
|
||||
},
|
||||
{
|
||||
"kind": 30006,
|
||||
"id": "63c37d6abf948b3ca343c0d38f482258d78be8b7f7fcda616215b8a3fd02e299",
|
||||
"pubkey": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"created_at": 1794156547,
|
||||
"tags": [
|
||||
["d", "dt:nature"],
|
||||
["title", "Nature"],
|
||||
["description", "Landscapes, forests, mountains, and deserts."],
|
||||
[
|
||||
"image",
|
||||
"https://blossom.kosmos.org/472dea81bebd41b9b40ce5960ea0da897f9a95f52eaed6291ed880ad4d8742c6.jpeg"
|
||||
],
|
||||
[
|
||||
"e",
|
||||
"0de53a65f872081d2453ab8363956d764a3eb8f563830e75f04657208bfdab4a",
|
||||
"wss://nostr.kosmos.org"
|
||||
],
|
||||
[
|
||||
"e",
|
||||
"06c256bcf02d72227b151865fd697146c5a9e7a936ec0cbea3ea1a1a276d35e6",
|
||||
"wss://nostr.kosmos.org"
|
||||
],
|
||||
[
|
||||
"e",
|
||||
"dba3f5d16cccff66471fa31f6d38fe3fc7498cce9d7f6e1bd8942a9f03f43510",
|
||||
"wss://nostr.kosmos.org"
|
||||
],
|
||||
[
|
||||
"e",
|
||||
"0c489708cc0c3bb9d1a528e5fba252859d82ba16ba7463e0a43fd5eb004ff394",
|
||||
"wss://nostr.kosmos.org"
|
||||
],
|
||||
["t", "dashtab-photo-feed"],
|
||||
["t", "nature"]
|
||||
],
|
||||
"content": "",
|
||||
"sig": "16467eb5d9bd4b925de914c405d3e77e72f084881a6c0c198984a71db591c72ad7578c16493d86b518dd959c823e1d0085af7d002efccb4c739696c7384623ce"
|
||||
}
|
||||
]
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
[
|
||||
{
|
||||
"kind": 20,
|
||||
"id": "0c489708cc0c3bb9d1a528e5fba252859d82ba16ba7463e0a43fd5eb004ff394",
|
||||
"pubkey": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"created_at": 1794156487,
|
||||
"tags": [
|
||||
["title", "Rolling sand dunes"],
|
||||
[
|
||||
"imeta",
|
||||
"url https://blossom.kosmos.org/2efc1f556cbf250d7d5999fb587fb51522e11c04737e2bcffcb9f4b9aa6eeedf",
|
||||
"m image/jpeg",
|
||||
"x 2efc1f556cbf250d7d5999fb587fb51522e11c04737e2bcffcb9f4b9aa6eeedf",
|
||||
"size 334302",
|
||||
"dim 2560x1440",
|
||||
"thumb https://blossom.kosmos.org/471f23c247fbf956089593a326bc4fac1b5300267a6df0238c68e345acb25069.jpeg",
|
||||
"alt rolling sand dunes in desert landscape"
|
||||
],
|
||||
["m", "image/jpeg"],
|
||||
["x", "2efc1f556cbf250d7d5999fb587fb51522e11c04737e2bcffcb9f4b9aa6eeedf"],
|
||||
["t", "desert"],
|
||||
["t", "dunes"],
|
||||
["t", "nature"],
|
||||
["t", "sand"],
|
||||
[
|
||||
"origin",
|
||||
"unsplash",
|
||||
"pVr6wvUneMk",
|
||||
"https://unsplash.com/photos/rolling-sand-dunes-in-desert-landscape-pVr6wvUneMk",
|
||||
"{\"creator\":\"Wolfgang Hasselmann\",\"profile\":\"https://unsplash.com/@wolfgang_hasselmann\",\"license\":\"unsplash\",\"licenseUrl\":\"https://unsplash.com/license\",\"portfolio\":\"https://www.youtube.com/@wolfgang_hasselmann/videos\"}"
|
||||
],
|
||||
["r", "https://unsplash.com/@wolfgang_hasselmann"]
|
||||
],
|
||||
"content": "Rolling sand dunes.\n\nPhoto by Wolfgang Hasselmann on Unsplash.",
|
||||
"sig": "570a0b56cab2aedba24541bc593b024369cd6bce340ff5bde0d9a157eaec5779507e425a31335e5ee87216fae97f76d057b448d0bfc1bead13c9185dd9b9ba69"
|
||||
},
|
||||
{
|
||||
"kind": 20,
|
||||
"id": "dba3f5d16cccff66471fa31f6d38fe3fc7498cce9d7f6e1bd8942a9f03f43510",
|
||||
"pubkey": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"created_at": 1794156487,
|
||||
"tags": [
|
||||
["title", "Mountain surrounded by water"],
|
||||
[
|
||||
"imeta",
|
||||
"url https://blossom.kosmos.org/b55f5643c4780165f51fdbf82e64e23d9da851b85b0050c7958463b5746281ab",
|
||||
"m image/jpeg",
|
||||
"x b55f5643c4780165f51fdbf82e64e23d9da851b85b0050c7958463b5746281ab",
|
||||
"size 412576",
|
||||
"dim 2560x1440",
|
||||
"thumb https://blossom.kosmos.org/62e00c0e2abf153482b92ef1992de89f4fb002ace7b058d9c96e3f9a047701c9.jpeg",
|
||||
"alt mountain surround by body of water"
|
||||
],
|
||||
["m", "image/jpeg"],
|
||||
["x", "b55f5643c4780165f51fdbf82e64e23d9da851b85b0050c7958463b5746281ab"],
|
||||
["t", "lake"],
|
||||
["t", "mountain"],
|
||||
["t", "nature"],
|
||||
["t", "sunrise"],
|
||||
[
|
||||
"origin",
|
||||
"unsplash",
|
||||
"iB7gjOsLrEQ",
|
||||
"https://unsplash.com/photos/mountain-surround-by-body-of-water-iB7gjOsLrEQ",
|
||||
"{\"creator\":\"Meiying Ng\",\"profile\":\"https://unsplash.com/@meiying\",\"license\":\"unsplash\",\"licenseUrl\":\"https://unsplash.com/license\"}"
|
||||
],
|
||||
["r", "https://unsplash.com/@meiying"]
|
||||
],
|
||||
"content": "Mountain surrounded by water.\n\nPhoto by Meiying Ng on Unsplash.",
|
||||
"sig": "58861f9abbedeae080eb9c94e32acdae6a55e221070681413444e1768037524405f84d6cbcf1db67525d7792dd45ec43e58140f6066e1eb839085c412095dd67"
|
||||
},
|
||||
{
|
||||
"kind": 20,
|
||||
"id": "06c256bcf02d72227b151865fd697146c5a9e7a936ec0cbea3ea1a1a276d35e6",
|
||||
"pubkey": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"created_at": 1794156487,
|
||||
"tags": [
|
||||
["title", "Awakening trees"],
|
||||
[
|
||||
"imeta",
|
||||
"url https://blossom.kosmos.org/2ddf3cdb1ac53628e0404ae61e776816dffc3690f1a3c621788f1da1f0f26bdf",
|
||||
"m image/jpeg",
|
||||
"x 2ddf3cdb1ac53628e0404ae61e776816dffc3690f1a3c621788f1da1f0f26bdf",
|
||||
"size 381052",
|
||||
"dim 2560x1440",
|
||||
"thumb https://blossom.kosmos.org/38e6e68f1e737ac0d6e50f644ecc9b174d5cf847835cbacb4ca819ef10cce427.jpeg",
|
||||
"alt Awakening trees"
|
||||
],
|
||||
["m", "image/jpeg"],
|
||||
["x", "2ddf3cdb1ac53628e0404ae61e776816dffc3690f1a3c621788f1da1f0f26bdf"],
|
||||
["t", "forest"],
|
||||
["t", "nature"],
|
||||
["t", "snow"],
|
||||
["t", "trees"],
|
||||
[
|
||||
"origin",
|
||||
"unsplash",
|
||||
"H-8zTDArbaQ",
|
||||
"https://unsplash.com/photos/H-8zTDArbaQ",
|
||||
"{\"creator\":\"Meiying Ng\",\"profile\":\"https://unsplash.com/@meiying\",\"license\":\"unsplash\",\"licenseUrl\":\"https://unsplash.com/license\"}"
|
||||
],
|
||||
["r", "https://unsplash.com/@meiying"]
|
||||
],
|
||||
"content": "Awakening trees.\n\nPhoto by Meiying Ng on Unsplash.",
|
||||
"sig": "4e1053deaeee954da4c1528ce2d6b493fa664a022a4ae8d41e19ea90c68a8fc9a6e93e1139b469cf5b50d10b106acbed0bca8d9d51ed0c2b7613c46c1800f6ba"
|
||||
},
|
||||
{
|
||||
"kind": 20,
|
||||
"id": "a2b9b2fe3243b5bd5d5ebe0bec40ce6293003a2de9798e09fdc3526e778c0519",
|
||||
"pubkey": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"created_at": 1794156487,
|
||||
"tags": [
|
||||
["title", "Train at night"],
|
||||
[
|
||||
"imeta",
|
||||
"url https://blossom.kosmos.org/eb7d8634ef676f9b029a0e06fc64689f5365cdbfae9f6e11c4181a353fbfaf83",
|
||||
"m image/jpeg",
|
||||
"x eb7d8634ef676f9b029a0e06fc64689f5365cdbfae9f6e11c4181a353fbfaf83",
|
||||
"size 1058801",
|
||||
"dim 2559x1440",
|
||||
"thumb https://blossom.kosmos.org/abb24129793d623c418051a73a389c1535fb6495b6aeca8bd8f176133a6e79d4.jpeg",
|
||||
"alt train at night"
|
||||
],
|
||||
["m", "image/jpeg"],
|
||||
["x", "eb7d8634ef676f9b029a0e06fc64689f5365cdbfae9f6e11c4181a353fbfaf83"],
|
||||
["t", "city"],
|
||||
["t", "night"],
|
||||
["t", "street"],
|
||||
["t", "train"],
|
||||
[
|
||||
"origin",
|
||||
"unsplash",
|
||||
"ez4pqCpEfuI",
|
||||
"https://unsplash.com/photos/train-at-night-ez4pqCpEfuI",
|
||||
"{\"creator\":\"Aleksandr Popov\",\"profile\":\"https://unsplash.com/@5tep5\",\"license\":\"unsplash\",\"licenseUrl\":\"https://unsplash.com/license\"}"
|
||||
],
|
||||
["r", "https://unsplash.com/@5tep5"]
|
||||
],
|
||||
"content": "Train at night.\n\nPhoto by Aleksandr Popov on Unsplash.",
|
||||
"sig": "ab299bd107b35b13edbe2cbc57a2a792f11cfb986cb0e8f380f3b11151237ff393319beb8fe318684a5df4e33cfbae839bd012f854801621ec16a3da013f0dbd"
|
||||
},
|
||||
{
|
||||
"kind": 20,
|
||||
"id": "0de53a65f872081d2453ab8363956d764a3eb8f563830e75f04657208bfdab4a",
|
||||
"pubkey": "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb",
|
||||
"created_at": 1794156487,
|
||||
"tags": [
|
||||
["title", "Winding road through autumn forest"],
|
||||
[
|
||||
"imeta",
|
||||
"url https://blossom.kosmos.org/82d3d49b859c31152f0d779b11feaab6814c3346b550286a3faf1597b32366f1",
|
||||
"m image/jpeg",
|
||||
"x 82d3d49b859c31152f0d779b11feaab6814c3346b550286a3faf1597b32366f1",
|
||||
"size 2100280",
|
||||
"dim 2560x1440",
|
||||
"thumb https://blossom.kosmos.org/472dea81bebd41b9b40ce5960ea0da897f9a95f52eaed6291ed880ad4d8742c6.jpeg",
|
||||
"alt An aerial view of a winding road through a dense forest with vibrant autumn foliage"
|
||||
],
|
||||
["m", "image/jpeg"],
|
||||
["x", "82d3d49b859c31152f0d779b11feaab6814c3346b550286a3faf1597b32366f1"],
|
||||
["t", "autumn"],
|
||||
["t", "forest"],
|
||||
["t", "nature"],
|
||||
["t", "road"],
|
||||
[
|
||||
"origin",
|
||||
"unsplash",
|
||||
"iRwbP4QPmGI",
|
||||
"https://unsplash.com/photos/winding-road-through-autumn-forest-iRwbP4QPmGI",
|
||||
"{\"creator\":\"Adrian Infernus\",\"profile\":\"https://unsplash.com/@adrian_infernus\",\"license\":\"unsplash\",\"licenseUrl\":\"https://unsplash.com/license\",\"portfolio\":\"https://adrianinfernus.de/\"}"
|
||||
],
|
||||
["r", "https://unsplash.com/@adrian_infernus"]
|
||||
],
|
||||
"content": "Winding road through autumn forest.\n\nPhoto by Adrian Infernus on Unsplash.",
|
||||
"sig": "3ea489cb708cec744c66344e91a305439205cab927fabdf3cb73ca76d2c76e3a61f1067d47e2dcf714a733d6663c4275aaeb946411a817be724a4b758c42c634"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,55 @@
|
||||
import { tracked } from '@glimmer/tracking';
|
||||
|
||||
// Test double for the `photos` service. Components can render against it while
|
||||
// tests assert the actions that would reach the real service.
|
||||
export default class FakePhotos {
|
||||
@tracked feeds = [];
|
||||
@tracked enabledFeedIds = [];
|
||||
@tracked currentPhotoId = null;
|
||||
@tracked refreshing = false;
|
||||
@tracked error = null;
|
||||
@tracked currentWallpaper = null;
|
||||
@tracked currentCredit = null;
|
||||
|
||||
fallbackPhoto = {
|
||||
url: '/img/wallpapers/fallback.jpg',
|
||||
displayUrl: '/img/wallpapers/fallback.jpg',
|
||||
alt: '',
|
||||
};
|
||||
|
||||
calls = {
|
||||
setFeedEnabled: [],
|
||||
setCurrentPhoto: [],
|
||||
};
|
||||
|
||||
get currentPhoto() {
|
||||
const photos = this.feeds.flatMap((feed) => feed.photos ?? []);
|
||||
return (
|
||||
photos.find((photo) => photo.id === this.currentPhotoId) ??
|
||||
photos[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
isFeedEnabled(feedId) {
|
||||
return this.enabledFeedIds.includes(feedId);
|
||||
}
|
||||
|
||||
photosForFeed(feedId) {
|
||||
return this.feeds.find((feed) => feed.id === feedId)?.photos ?? [];
|
||||
}
|
||||
|
||||
async setFeedEnabled(feedId, enabled) {
|
||||
this.calls.setFeedEnabled.push([feedId, enabled]);
|
||||
if (enabled) {
|
||||
this.enabledFeedIds = [...new Set([...this.enabledFeedIds, feedId])];
|
||||
} else {
|
||||
this.enabledFeedIds = this.enabledFeedIds.filter((id) => id !== feedId);
|
||||
}
|
||||
}
|
||||
|
||||
async setCurrentPhoto(photoId) {
|
||||
this.calls.setCurrentPhoto.push(photoId);
|
||||
this.currentPhotoId = photoId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'dashtab/tests/helpers';
|
||||
import { render, click } from '@ember/test-helpers';
|
||||
import SettingsPhotosSection from 'dashtab/components/settings/global-settings/sections/photos';
|
||||
import FakePhotos from 'dashtab/tests/helpers/fake-photos';
|
||||
|
||||
const PHOTO_CACHE = {
|
||||
async thumbUrl() {
|
||||
return null;
|
||||
},
|
||||
async originalUrl() {
|
||||
return null;
|
||||
},
|
||||
async prefetchThumb() {
|
||||
return null;
|
||||
},
|
||||
async prefetchOriginal() {
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
function photo(id, title, thumbUrl) {
|
||||
return {
|
||||
id,
|
||||
title,
|
||||
alt: title,
|
||||
thumbUrl,
|
||||
url: thumbUrl.replace('/thumb', '/full'),
|
||||
attributed: true,
|
||||
creator: { name: 'Creator Name' },
|
||||
};
|
||||
}
|
||||
|
||||
module('Integration | Component | settings/photos', function (hooks) {
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
function setup(context) {
|
||||
const photos = new FakePhotos();
|
||||
photos.feeds = [
|
||||
{
|
||||
id: 'dt:nature',
|
||||
title: 'Nature',
|
||||
description: 'Landscapes and forests.',
|
||||
photos: [
|
||||
photo(
|
||||
'nature-1',
|
||||
'Winding road',
|
||||
'https://blossom.example/thumb-1.jpg'
|
||||
),
|
||||
photo(
|
||||
'nature-2',
|
||||
'Awakening trees',
|
||||
'https://blossom.example/thumb-2.jpg'
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'dt:city-nights',
|
||||
title: 'City Nights',
|
||||
description: 'After-dark city scenes.',
|
||||
photos: [
|
||||
photo(
|
||||
'city-1',
|
||||
'Train at night',
|
||||
'https://blossom.example/thumb-3.jpg'
|
||||
),
|
||||
],
|
||||
},
|
||||
];
|
||||
photos.enabledFeedIds = ['dt:nature'];
|
||||
photos.currentPhotoId = 'nature-1';
|
||||
|
||||
context.owner.register('service:photos', photos, {
|
||||
instantiate: false,
|
||||
});
|
||||
context.owner.register('service:photo-cache', PHOTO_CACHE, {
|
||||
instantiate: false,
|
||||
});
|
||||
|
||||
return photos;
|
||||
}
|
||||
|
||||
test('shows Nature enabled and City Nights disabled by default', async function (assert) {
|
||||
setup(this);
|
||||
|
||||
await render(<template><SettingsPhotosSection /></template>);
|
||||
|
||||
assert.dom('[data-test-photo-feed="dt:nature"]').exists();
|
||||
assert.dom('[data-test-photo-feed="dt:city-nights"]').exists();
|
||||
assert.dom('[data-test-photo-feed-toggle="dt:nature"]').isChecked();
|
||||
assert.dom('[data-test-photo-feed-toggle="dt:city-nights"]').isNotChecked();
|
||||
assert.dom('[data-test-photo-grid="dt:nature"]').exists();
|
||||
assert.dom('[data-test-photo-grid="dt:nature"]').hasClass('grid-cols-4');
|
||||
assert.dom('[data-test-photo-grid="dt:city-nights"]').doesNotExist();
|
||||
|
||||
const feedOrder = [
|
||||
...this.element.querySelectorAll('[data-test-photo-feed]'),
|
||||
].map((element) => element.getAttribute('data-test-photo-feed'));
|
||||
assert.deepEqual(feedOrder, ['dt:nature', 'dt:city-nights']);
|
||||
});
|
||||
|
||||
test('does not render attribution text in Settings', async function (assert) {
|
||||
setup(this);
|
||||
|
||||
await render(<template><SettingsPhotosSection /></template>);
|
||||
|
||||
assert.notOk(this.element.textContent.includes('Photo by'));
|
||||
assert.notOk(this.element.textContent.includes('Unsplash'));
|
||||
assert.dom('[data-test-wallpaper-credit]').doesNotExist();
|
||||
});
|
||||
|
||||
test('enabling City Nights reveals its grid', async function (assert) {
|
||||
const photos = setup(this);
|
||||
|
||||
await render(<template><SettingsPhotosSection /></template>);
|
||||
await click('[data-test-photo-feed-toggle="dt:city-nights"]');
|
||||
|
||||
assert.deepEqual(photos.calls.setFeedEnabled, [['dt:city-nights', true]]);
|
||||
assert.true(photos.isFeedEnabled('dt:city-nights'));
|
||||
assert.dom('[data-test-photo-grid="dt:city-nights"]').exists();
|
||||
});
|
||||
|
||||
test('clicking a photo selects it immediately', async function (assert) {
|
||||
const photos = setup(this);
|
||||
|
||||
await render(<template><SettingsPhotosSection /></template>);
|
||||
|
||||
assert.dom('[data-test-use-now]').doesNotExist();
|
||||
|
||||
await click('[data-test-photo="nature-2"]');
|
||||
|
||||
assert.deepEqual(photos.calls.setCurrentPhoto, ['nature-2']);
|
||||
assert.strictEqual(photos.currentPhotoId, 'nature-2');
|
||||
assert
|
||||
.dom('[data-test-photo="nature-2"]')
|
||||
.hasAttribute('aria-pressed', 'true');
|
||||
assert
|
||||
.dom('[data-test-photo="nature-1"]')
|
||||
.hasAttribute('aria-pressed', 'false');
|
||||
assert
|
||||
.dom('[data-test-photo="nature-2"] [aria-label="Current wallpaper"]')
|
||||
.exists();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'dashtab/tests/helpers';
|
||||
import { render } from '@ember/test-helpers';
|
||||
import WallpaperCredit from 'dashtab/components/wallpaper-credit';
|
||||
import FakePhotos from 'dashtab/tests/helpers/fake-photos';
|
||||
|
||||
module('Integration | Component | wallpaper-credit', function (hooks) {
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
function registerPhotos(context, currentCredit) {
|
||||
const photos = new FakePhotos();
|
||||
photos.currentCredit = currentCredit;
|
||||
context.owner.register('service:photos', photos, {
|
||||
instantiate: false,
|
||||
});
|
||||
return photos;
|
||||
}
|
||||
|
||||
test('links the credit to the creator profile', async function (assert) {
|
||||
registerPhotos(this, {
|
||||
name: 'Adrian Infernus',
|
||||
url: 'https://unsplash.com/@adrian_infernus',
|
||||
platform: 'unsplash',
|
||||
});
|
||||
|
||||
await render(<template><WallpaperCredit /></template>);
|
||||
|
||||
assert
|
||||
.dom('[data-test-wallpaper-credit]')
|
||||
.hasText('Photo by Adrian Infernus');
|
||||
assert
|
||||
.dom('[data-test-wallpaper-credit]')
|
||||
.hasAttribute('href', 'https://unsplash.com/@adrian_infernus');
|
||||
assert.dom('[data-test-wallpaper-credit]').hasAttribute('target', '_blank');
|
||||
assert
|
||||
.dom('[data-test-wallpaper-credit]')
|
||||
.hasAttribute('rel', 'noopener noreferrer');
|
||||
});
|
||||
|
||||
test('does not render without creator data', async function (assert) {
|
||||
registerPhotos(this, null);
|
||||
|
||||
await render(<template><WallpaperCredit /></template>);
|
||||
|
||||
assert.dom('[data-test-wallpaper-credit]').doesNotExist();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'dashtab/tests/helpers';
|
||||
import { render } from '@ember/test-helpers';
|
||||
import Wallpaper from 'dashtab/components/wallpaper';
|
||||
import FakePhotos from 'dashtab/tests/helpers/fake-photos';
|
||||
|
||||
module('Integration | Component | wallpaper', function (hooks) {
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
function registerPhotos(context, overrides = {}) {
|
||||
const photos = new FakePhotos();
|
||||
Object.assign(photos, overrides);
|
||||
context.owner.register('service:photos', photos, {
|
||||
instantiate: false,
|
||||
});
|
||||
return photos;
|
||||
}
|
||||
|
||||
test('renders the current wallpaper object URL and not the thumbnail', async function (assert) {
|
||||
registerPhotos(this, {
|
||||
currentWallpaper: {
|
||||
url: 'https://blossom.example/full.jpg',
|
||||
thumbUrl: 'https://blossom.example/thumb.jpg',
|
||||
displayUrl: 'blob:cached-full',
|
||||
},
|
||||
});
|
||||
|
||||
await render(<template><Wallpaper /></template>);
|
||||
|
||||
assert.dom('[data-test-wallpaper]').hasAttribute('src', 'blob:cached-full');
|
||||
assert.notOk(
|
||||
this.element
|
||||
.querySelector('[data-test-wallpaper]')
|
||||
.getAttribute('src')
|
||||
.includes('thumb')
|
||||
);
|
||||
assert.dom('[data-test-wallpaper-container]').exists();
|
||||
});
|
||||
|
||||
test('falls back to the remote original while the cache warms', async function (assert) {
|
||||
registerPhotos(this, {
|
||||
currentWallpaper: {
|
||||
url: 'https://blossom.example/full.jpg',
|
||||
thumbUrl: 'https://blossom.example/thumb.jpg',
|
||||
displayUrl: null,
|
||||
},
|
||||
});
|
||||
|
||||
await render(<template><Wallpaper /></template>);
|
||||
|
||||
assert
|
||||
.dom('[data-test-wallpaper]')
|
||||
.hasAttribute('src', 'https://blossom.example/full.jpg');
|
||||
});
|
||||
|
||||
test('accepts a route-specific photo for the welcome screen', async function (assert) {
|
||||
registerPhotos(this);
|
||||
this.welcomePhoto = {
|
||||
url: '/img/wallpapers/welcome.jpg',
|
||||
displayUrl: '/img/wallpapers/welcome.jpg',
|
||||
alt: '',
|
||||
};
|
||||
|
||||
await render(
|
||||
<template><Wallpaper @photo={{this.welcomePhoto}} /></template>
|
||||
);
|
||||
|
||||
assert
|
||||
.dom('[data-test-wallpaper]')
|
||||
.hasAttribute('src', '/img/wallpapers/welcome.jpg');
|
||||
});
|
||||
|
||||
test('renders only the fallback when no wallpaper is selected', async function (assert) {
|
||||
registerPhotos(this, { currentWallpaper: null });
|
||||
|
||||
await render(<template><Wallpaper /></template>);
|
||||
|
||||
assert.dom('[data-test-wallpaper]').doesNotExist();
|
||||
assert.dom('[data-test-wallpaper-container] img').exists({ count: 1 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupTest } from 'dashtab/tests/helpers';
|
||||
import photoEvents from '../../fixtures/nostr/photo-events.json';
|
||||
|
||||
class FakeSocket {
|
||||
constructor() {
|
||||
this.listeners = new Map();
|
||||
this.sent = [];
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
addEventListener(type, callback) {
|
||||
const listeners = this.listeners.get(type) ?? [];
|
||||
listeners.push(callback);
|
||||
this.listeners.set(type, listeners);
|
||||
}
|
||||
|
||||
send(data) {
|
||||
this.sent.push(JSON.parse(data));
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
this.fire('close');
|
||||
}
|
||||
|
||||
fire(type, event = {}) {
|
||||
for (const callback of this.listeners.get(type) ?? []) {
|
||||
callback(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module('Unit | Service | nostr', function (hooks) {
|
||||
setupTest(hooks);
|
||||
|
||||
function setup(context) {
|
||||
const service = context.owner.lookup('service:nostr');
|
||||
const sockets = [];
|
||||
service.url = 'wss://relay.example.org';
|
||||
service.createSocket = () => {
|
||||
const socket = new FakeSocket();
|
||||
sockets.push(socket);
|
||||
return socket;
|
||||
};
|
||||
return { service, sockets };
|
||||
}
|
||||
|
||||
test('queries a relay and resolves after EOSE', async function (assert) {
|
||||
const { service, sockets } = setup(this);
|
||||
const event = photoEvents[0];
|
||||
const promise = service.query([{ kinds: [20], ids: [event.id] }]);
|
||||
|
||||
const socket = sockets[0];
|
||||
socket.fire('open');
|
||||
const subscriptionId = socket.sent[0][1];
|
||||
|
||||
assert.deepEqual(socket.sent[0], [
|
||||
'REQ',
|
||||
subscriptionId,
|
||||
{ kinds: [20], ids: [event.id] },
|
||||
]);
|
||||
|
||||
socket.fire('message', {
|
||||
data: JSON.stringify(['EVENT', subscriptionId, event]),
|
||||
});
|
||||
socket.fire('message', {
|
||||
data: JSON.stringify(['EOSE', subscriptionId]),
|
||||
});
|
||||
|
||||
assert.deepEqual(await promise, [event]);
|
||||
assert.true(socket.closed);
|
||||
});
|
||||
|
||||
test('drops invalid events', async function (assert) {
|
||||
const { service, sockets } = setup(this);
|
||||
const event = structuredClone(photoEvents[0]);
|
||||
event.content = 'tampered';
|
||||
const promise = service.query([{ kinds: [20] }]);
|
||||
|
||||
const socket = sockets[0];
|
||||
socket.fire('open');
|
||||
const subscriptionId = socket.sent[0][1];
|
||||
socket.fire('message', {
|
||||
data: JSON.stringify(['EVENT', subscriptionId, event]),
|
||||
});
|
||||
socket.fire('message', {
|
||||
data: JSON.stringify(['EOSE', subscriptionId]),
|
||||
});
|
||||
|
||||
assert.deepEqual(await promise, []);
|
||||
});
|
||||
|
||||
test('times out when the relay does not answer', async function (assert) {
|
||||
const { service } = setup(this);
|
||||
|
||||
await assert.rejects(
|
||||
service.query([{ kinds: [20] }], { timeout: 5 }),
|
||||
/timed out/
|
||||
);
|
||||
});
|
||||
|
||||
test('aborts an in-flight query', async function (assert) {
|
||||
const { service } = setup(this);
|
||||
const controller = new AbortController();
|
||||
const promise = service.query([{ kinds: [20] }], {
|
||||
signal: controller.signal,
|
||||
timeout: 1000,
|
||||
});
|
||||
|
||||
controller.abort();
|
||||
|
||||
await assert.rejects(promise, /aborted/);
|
||||
});
|
||||
|
||||
test('queries the curated feed definitions', async function (assert) {
|
||||
const { service } = setup(this);
|
||||
const calls = [];
|
||||
service.query = async (filters) => {
|
||||
calls.push(filters);
|
||||
return [];
|
||||
};
|
||||
|
||||
await service.queryFeedEvents();
|
||||
|
||||
assert.deepEqual(calls[0], [
|
||||
{
|
||||
kinds: [30006],
|
||||
authors: [
|
||||
'1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb',
|
||||
],
|
||||
'#t': ['dashtab-photo-feed'],
|
||||
limit: 20,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('chunks photo id queries at 300 ids', async function (assert) {
|
||||
const { service } = setup(this);
|
||||
const calls = [];
|
||||
service.query = async (filters) => {
|
||||
calls.push(filters[0]);
|
||||
return [];
|
||||
};
|
||||
const ids = Array.from({ length: 301 }, (_, index) =>
|
||||
String(index).padStart(64, '0')
|
||||
);
|
||||
|
||||
await service.queryPhotos(ids);
|
||||
|
||||
assert.strictEqual(calls.length, 2);
|
||||
assert.strictEqual(calls[0].ids.length, 300);
|
||||
assert.strictEqual(calls[1].ids.length, 1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupTest } from 'dashtab/tests/helpers';
|
||||
import photoEvents from '../../fixtures/nostr/photo-events.json';
|
||||
import feedEvents from '../../fixtures/nostr/feed-events.json';
|
||||
|
||||
class FakeStorage {
|
||||
data = new Map();
|
||||
|
||||
key(namespace, key) {
|
||||
return `${namespace}:${key}`;
|
||||
}
|
||||
|
||||
async get(namespace, key) {
|
||||
return this.data.get(this.key(namespace, key)) ?? null;
|
||||
}
|
||||
|
||||
async set(namespace, key, value) {
|
||||
this.data.set(this.key(namespace, key), value);
|
||||
}
|
||||
|
||||
async keys(namespace) {
|
||||
const prefix = `${namespace}:`;
|
||||
return [...this.data.keys()]
|
||||
.filter((key) => key.startsWith(prefix))
|
||||
.map((key) => key.slice(prefix.length));
|
||||
}
|
||||
}
|
||||
|
||||
class FakeNostr {
|
||||
feedEvents = feedEvents;
|
||||
photoEvents = photoEvents;
|
||||
calls = [];
|
||||
|
||||
async queryFeedEvents() {
|
||||
this.calls.push('feeds');
|
||||
return this.feedEvents;
|
||||
}
|
||||
|
||||
async queryPhotos(ids) {
|
||||
this.calls.push({ ids });
|
||||
return this.photoEvents.filter((event) => ids.includes(event.id));
|
||||
}
|
||||
}
|
||||
|
||||
class FakePhotoCache {
|
||||
cached = new Map();
|
||||
calls = [];
|
||||
|
||||
async originalUrl(photo) {
|
||||
return this.cached.get(photo.id) ?? null;
|
||||
}
|
||||
|
||||
async prefetchOriginal(photo) {
|
||||
this.calls.push(['original', photo.id]);
|
||||
const url = `blob:original:${photo.id}`;
|
||||
this.cached.set(photo.id, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
async thumbUrl(photo) {
|
||||
return this.cached.get(`thumb:${photo.id}`) ?? null;
|
||||
}
|
||||
|
||||
async prefetchThumb(photo) {
|
||||
this.calls.push(['thumb', photo.id]);
|
||||
const url = `blob:thumb:${photo.id}`;
|
||||
this.cached.set(`thumb:${photo.id}`, url);
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function photoByTitle(title) {
|
||||
return photoEvents.find((event) =>
|
||||
event.tags.some((tag) => tag[0] === 'title' && tag[1] === title)
|
||||
);
|
||||
}
|
||||
|
||||
module('Unit | Service | photos', function (hooks) {
|
||||
setupTest(hooks);
|
||||
|
||||
function setup(context) {
|
||||
const storage = new FakeStorage();
|
||||
const nostr = new FakeNostr();
|
||||
const photoCache = new FakePhotoCache();
|
||||
|
||||
context.owner.register('service:storage', storage, {
|
||||
instantiate: false,
|
||||
});
|
||||
context.owner.register('service:nostr', nostr, { instantiate: false });
|
||||
context.owner.register('service:photo-cache', photoCache, {
|
||||
instantiate: false,
|
||||
});
|
||||
|
||||
return {
|
||||
photos: context.owner.lookup('service:photos'),
|
||||
storage,
|
||||
nostr,
|
||||
photoCache,
|
||||
};
|
||||
}
|
||||
|
||||
test('defaults to Nature enabled and no feed loaded yet', async function (assert) {
|
||||
const { photos } = setup(this);
|
||||
|
||||
await photos.loadCached();
|
||||
|
||||
assert.deepEqual(photos.enabledFeedIds, ['dt:nature']);
|
||||
assert.deepEqual(photos.feeds, []);
|
||||
assert.deepEqual(photos.photos, []);
|
||||
assert.strictEqual(photos.currentPhoto, null);
|
||||
assert.true(photos.initialized);
|
||||
});
|
||||
|
||||
test('refreshes enabled feeds and selects the first Nature photo', async function (assert) {
|
||||
const { photos, nostr } = setup(this);
|
||||
|
||||
await photos.refresh();
|
||||
|
||||
assert.strictEqual(photos.feeds.length, 2);
|
||||
assert.strictEqual(photos.feeds[0].id, 'dt:nature');
|
||||
assert.strictEqual(photos.feeds[1].id, 'dt:city-nights');
|
||||
assert.strictEqual(photos.photos.length, 4);
|
||||
assert.deepEqual(photos.enabledFeedIds, ['dt:nature']);
|
||||
assert.strictEqual(
|
||||
photos.currentPhoto.title,
|
||||
'Winding road through autumn forest'
|
||||
);
|
||||
assert.strictEqual(
|
||||
photos.currentWallpaper.url,
|
||||
'https://blossom.kosmos.org/82d3d49b859c31152f0d779b11feaab6814c3346b550286a3faf1597b32366f1'
|
||||
);
|
||||
assert.notStrictEqual(
|
||||
photos.currentWallpaper.url,
|
||||
photos.currentWallpaper.thumbUrl
|
||||
);
|
||||
assert.strictEqual(photos.currentCredit.name, 'Adrian Infernus');
|
||||
assert.strictEqual(
|
||||
photos.currentCredit.url,
|
||||
'https://unsplash.com/@adrian_infernus'
|
||||
);
|
||||
assert.deepEqual(nostr.calls[0], 'feeds');
|
||||
});
|
||||
|
||||
test('prefetches all thumbs and the first three originals', async function (assert) {
|
||||
const { photos, photoCache } = setup(this);
|
||||
|
||||
await photos.refresh();
|
||||
photoCache.calls = [];
|
||||
await photos.prefetchAssets();
|
||||
|
||||
const originals = photoCache.calls.filter(([type]) => type === 'original');
|
||||
const thumbs = photoCache.calls.filter(([type]) => type === 'thumb');
|
||||
|
||||
assert.strictEqual(thumbs.length, 4);
|
||||
assert.strictEqual(originals.length, 3);
|
||||
assert.deepEqual(
|
||||
originals.map(([, id]) => id),
|
||||
[
|
||||
photoByTitle('Winding road through autumn forest').id,
|
||||
photoByTitle('Awakening trees').id,
|
||||
photoByTitle('Mountain surrounded by water').id,
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('instantly paints from cached events and an object URL', async function (assert) {
|
||||
const { photos, storage, photoCache } = setup(this);
|
||||
const adrian = photoByTitle('Winding road through autumn forest');
|
||||
|
||||
for (const event of feedEvents) {
|
||||
await storage.set('photos', `feed:${event.id}`, event);
|
||||
}
|
||||
for (const event of photoEvents) {
|
||||
await storage.set('photos', `photo:${event.id}`, event);
|
||||
}
|
||||
await storage.set('preferences', 'photos.config', {
|
||||
enabledFeedIds: ['dt:nature'],
|
||||
currentPhotoId: adrian.id,
|
||||
rotation: 'off',
|
||||
});
|
||||
photoCache.cached.set(adrian.id, 'blob:cached:adrian');
|
||||
|
||||
await photos.loadCached();
|
||||
|
||||
assert.strictEqual(photos.feeds.length, 2);
|
||||
assert.strictEqual(photos.photos.length, 5);
|
||||
assert.strictEqual(photos.currentPhoto.id, adrian.id);
|
||||
assert.strictEqual(photos.displayUrl, 'blob:cached:adrian');
|
||||
assert.strictEqual(
|
||||
photos.currentWallpaper.displayUrl,
|
||||
'blob:cached:adrian'
|
||||
);
|
||||
});
|
||||
|
||||
test('filters un-attributed photos out of the feed grid', async function (assert) {
|
||||
const { photos, nostr } = setup(this);
|
||||
const adrian = structuredClone(
|
||||
photoByTitle('Winding road through autumn forest')
|
||||
);
|
||||
adrian.tags = adrian.tags.filter(
|
||||
(tag) => tag[0] !== 'origin' && tag[0] !== 'r'
|
||||
);
|
||||
nostr.photoEvents = [
|
||||
adrian,
|
||||
...photoEvents.filter((event) => event.id !== adrian.id),
|
||||
];
|
||||
|
||||
await photos.refresh();
|
||||
|
||||
assert.strictEqual(photos.photosForFeed('dt:nature').length, 3);
|
||||
assert.notOk(
|
||||
photos
|
||||
.photosForFeed('dt:nature')
|
||||
.some((photo) => photo.title === 'Winding road through autumn forest')
|
||||
);
|
||||
});
|
||||
|
||||
test('enabling City Nights fetches its photos and persists the choice', async function (assert) {
|
||||
const { photos, storage } = setup(this);
|
||||
|
||||
await photos.refresh();
|
||||
await photos.setFeedEnabled('dt:city-nights', true);
|
||||
|
||||
assert.deepEqual(photos.enabledFeedIds.sort(), [
|
||||
'dt:city-nights',
|
||||
'dt:nature',
|
||||
]);
|
||||
assert.strictEqual(photos.photos.length, 5);
|
||||
assert.strictEqual(photos.photosForFeed('dt:city-nights').length, 1);
|
||||
|
||||
const config = await storage.get('preferences', 'photos.config');
|
||||
assert.deepEqual(config.enabledFeedIds.sort(), [
|
||||
'dt:city-nights',
|
||||
'dt:nature',
|
||||
]);
|
||||
});
|
||||
|
||||
test('keeps cached feeds when the relay fails', async function (assert) {
|
||||
const { photos, storage, nostr } = setup(this);
|
||||
|
||||
for (const event of feedEvents) {
|
||||
await storage.set('photos', `feed:${event.id}`, event);
|
||||
}
|
||||
for (const event of photoEvents) {
|
||||
await storage.set('photos', `photo:${event.id}`, event);
|
||||
}
|
||||
nostr.queryFeedEvents = async () => {
|
||||
throw new Error('relay down');
|
||||
};
|
||||
|
||||
await photos.refresh();
|
||||
|
||||
assert.strictEqual(photos.error, 'relay down');
|
||||
assert.strictEqual(photos.feeds.length, 2);
|
||||
assert.strictEqual(photos.photos.length, 5);
|
||||
});
|
||||
|
||||
test('prefetchForWelcome loads and refreshes in the background', async function (assert) {
|
||||
const { photos, nostr } = setup(this);
|
||||
|
||||
await photos.prefetchForWelcome();
|
||||
|
||||
assert.deepEqual(nostr.calls[0], 'feeds');
|
||||
assert.strictEqual(photos.feeds.length, 2);
|
||||
assert.strictEqual(photos.photos.length, 4);
|
||||
});
|
||||
|
||||
test('selecting a photo updates the credit and persists it', async function (assert) {
|
||||
const { photos, storage } = setup(this);
|
||||
const alexander = photoByTitle('Train at night');
|
||||
|
||||
await photos.setFeedEnabled('dt:city-nights', true);
|
||||
await photos.setCurrentPhoto(alexander.id);
|
||||
|
||||
assert.strictEqual(photos.currentCredit.name, 'Aleksandr Popov');
|
||||
assert.strictEqual(photos.currentCredit.url, 'https://unsplash.com/@5tep5');
|
||||
|
||||
const config = await storage.get('preferences', 'photos.config');
|
||||
assert.strictEqual(config.currentPhotoId, alexander.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { module, test } from 'qunit';
|
||||
import {
|
||||
canonicalEvent,
|
||||
eventId,
|
||||
hasValidEventId,
|
||||
hasValidSignature,
|
||||
tagValue,
|
||||
verifyEvent,
|
||||
} from 'dashtab/utils/nostr-events';
|
||||
import photoEvents from '../../fixtures/nostr/photo-events.json';
|
||||
import feedEvents from '../../fixtures/nostr/feed-events.json';
|
||||
|
||||
module('Unit | Utility | nostr-events', function () {
|
||||
test('computes the canonical NIP-01 id for real events', function (assert) {
|
||||
for (const event of [...photoEvents, ...feedEvents]) {
|
||||
assert.strictEqual(eventId(event), event.id, event.id);
|
||||
assert.true(hasValidEventId(event), event.id);
|
||||
}
|
||||
});
|
||||
|
||||
test('verifies real event signatures', function (assert) {
|
||||
for (const event of [...photoEvents, ...feedEvents]) {
|
||||
assert.true(hasValidSignature(event), event.id);
|
||||
assert.true(verifyEvent(event), event.id);
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects a tampered event', function (assert) {
|
||||
const event = structuredClone(photoEvents[0]);
|
||||
event.content = `${event.content} tampered`;
|
||||
|
||||
assert.false(hasValidEventId(event));
|
||||
// The signature covers the id, not the event body, so it still validates
|
||||
// against the unchanged id. The combined check must fail.
|
||||
assert.true(hasValidSignature(event));
|
||||
assert.false(verifyEvent(event));
|
||||
});
|
||||
|
||||
test('rejects a tampered signature', function (assert) {
|
||||
const event = structuredClone(photoEvents[0]);
|
||||
event.sig = `${event.sig.slice(0, -2)}00`;
|
||||
|
||||
assert.false(hasValidSignature(event));
|
||||
assert.false(verifyEvent(event));
|
||||
});
|
||||
|
||||
test('canonical serialization is the six-element NIP-01 array', function (assert) {
|
||||
const event = photoEvents[0];
|
||||
const parsed = JSON.parse(canonicalEvent(event));
|
||||
|
||||
assert.deepEqual(parsed, [
|
||||
0,
|
||||
event.pubkey,
|
||||
event.created_at,
|
||||
event.kind,
|
||||
event.tags,
|
||||
event.content,
|
||||
]);
|
||||
});
|
||||
|
||||
test('tagValue returns the first matching tag value', function (assert) {
|
||||
const event = photoEvents[0];
|
||||
|
||||
assert.strictEqual(tagValue(event, 'title'), 'Rolling sand dunes');
|
||||
assert.strictEqual(tagValue(event, 'missing'), null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { module, test } from 'qunit';
|
||||
import {
|
||||
feedToEventDraft,
|
||||
parseFeedEvent,
|
||||
parseFeedEvents,
|
||||
parsePhotoEvent,
|
||||
parsePhotoEvents,
|
||||
photoToEventDraft,
|
||||
sortFeeds,
|
||||
} from 'dashtab/utils/nostr-photo-events';
|
||||
import photoEvents from '../../fixtures/nostr/photo-events.json';
|
||||
import feedEvents from '../../fixtures/nostr/feed-events.json';
|
||||
|
||||
module('Unit | Utility | nostr-photo-events', function () {
|
||||
test('parses the published feeds', function (assert) {
|
||||
const feeds = parseFeedEvents(feedEvents);
|
||||
const nature = feeds.find((feed) => feed.id === 'dt:nature');
|
||||
const city = feeds.find((feed) => feed.id === 'dt:city-nights');
|
||||
|
||||
assert.strictEqual(feeds.length, 2);
|
||||
assert.strictEqual(feeds[0].id, 'dt:nature');
|
||||
assert.strictEqual(feeds[1].id, 'dt:city-nights');
|
||||
assert.strictEqual(nature.title, 'Nature');
|
||||
assert.strictEqual(nature.photoIds.length, 4);
|
||||
assert.true(nature.tags.includes('dashtab-photo-feed'));
|
||||
assert.strictEqual(city.title, 'City Nights');
|
||||
assert.strictEqual(city.photoIds.length, 1);
|
||||
assert.true(nature.coverUrl.startsWith('https://blossom.kosmos.org/'));
|
||||
});
|
||||
|
||||
test('parses the published photos, including attribution', function (assert) {
|
||||
const photos = parsePhotoEvents(photoEvents);
|
||||
const adrian = photos.find(
|
||||
(photo) => photo.title === 'Winding road through autumn forest'
|
||||
);
|
||||
|
||||
assert.strictEqual(photos.length, 5);
|
||||
assert.strictEqual(adrian.mime, 'image/jpeg');
|
||||
assert.strictEqual(adrian.width, 2560);
|
||||
assert.strictEqual(adrian.height, 1440);
|
||||
assert.strictEqual(adrian.size, 2100280);
|
||||
assert.strictEqual(adrian.creator.name, 'Adrian Infernus');
|
||||
assert.strictEqual(
|
||||
adrian.creator.profile,
|
||||
'https://unsplash.com/@adrian_infernus'
|
||||
);
|
||||
assert.strictEqual(
|
||||
adrian.sourceUrl,
|
||||
'https://unsplash.com/photos/winding-road-through-autumn-forest-iRwbP4QPmGI'
|
||||
);
|
||||
assert.strictEqual(adrian.creator.license, 'unsplash');
|
||||
assert.strictEqual(
|
||||
adrian.creator.licenseUrl,
|
||||
'https://unsplash.com/license'
|
||||
);
|
||||
assert.true(adrian.attributed);
|
||||
assert.notStrictEqual(adrian.thumbUrl, adrian.url);
|
||||
assert.true(adrian.thumbUrl.endsWith('.jpeg'));
|
||||
});
|
||||
|
||||
test('keeps the newest feed per d tag', function (assert) {
|
||||
const older = structuredClone(
|
||||
feedEvents.find((event) => {
|
||||
const d = event.tags.find((tag) => tag[0] === 'd');
|
||||
return d?.[1] === 'dt:nature';
|
||||
})
|
||||
);
|
||||
const newer = structuredClone(older);
|
||||
newer.created_at += 10;
|
||||
newer.tags = newer.tags.map((tag) =>
|
||||
tag[0] === 'title' ? ['title', 'Nature (new)'] : tag
|
||||
);
|
||||
|
||||
const nature = parseFeedEvents([newer, older]).find(
|
||||
(feed) => feed.id === 'dt:nature'
|
||||
);
|
||||
|
||||
assert.strictEqual(nature.title, 'Nature (new)');
|
||||
});
|
||||
|
||||
test('puts Nature first and other feeds in createdAt order', function (assert) {
|
||||
const feeds = [
|
||||
{ id: 'dt:city-nights', title: 'City Nights', createdAt: 2 },
|
||||
{ id: 'dt:older', title: 'Older feed', createdAt: 1 },
|
||||
{ id: 'dt:nature', title: 'Nature', createdAt: 99 },
|
||||
];
|
||||
|
||||
assert.deepEqual(
|
||||
sortFeeds(feeds).map((feed) => feed.id),
|
||||
['dt:nature', 'dt:older', 'dt:city-nights']
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects a feed without the dt: namespace', function (assert) {
|
||||
const event = structuredClone(feedEvents[0]);
|
||||
event.tags = event.tags.map((tag) =>
|
||||
tag[0] === 'd' ? ['d', 'nature'] : tag
|
||||
);
|
||||
|
||||
assert.strictEqual(parseFeedEvent(event), null);
|
||||
});
|
||||
|
||||
test('marks a photo without creator data as unattributed', function (assert) {
|
||||
const event = structuredClone(photoEvents[0]);
|
||||
event.tags = event.tags.filter(
|
||||
(tag) => tag[0] !== 'origin' && tag[0] !== 'r'
|
||||
);
|
||||
|
||||
const photo = parsePhotoEvent(event);
|
||||
|
||||
assert.strictEqual(photo.creator.name, null);
|
||||
assert.false(photo.attributed);
|
||||
});
|
||||
|
||||
test('round-trips a photo event draft', function (assert) {
|
||||
const photo = parsePhotoEvents(photoEvents)[0];
|
||||
const draft = photoToEventDraft(photo, 1700000000);
|
||||
const parsed = parsePhotoEvent({ ...draft, id: 'unused' });
|
||||
|
||||
assert.strictEqual(draft.kind, 20);
|
||||
assert.strictEqual(parsed.title, photo.title);
|
||||
assert.strictEqual(parsed.url, photo.url);
|
||||
assert.strictEqual(parsed.thumbUrl, photo.thumbUrl);
|
||||
assert.strictEqual(parsed.creator.name, photo.creator.name);
|
||||
assert.strictEqual(parsed.creator.profile, photo.creator.profile);
|
||||
assert.deepEqual(parsed.tags, photo.tags);
|
||||
});
|
||||
|
||||
test('round-trips a feed event draft', function (assert) {
|
||||
const feed = parseFeedEvents(feedEvents)[0];
|
||||
const draft = feedToEventDraft(feed, 1700000000);
|
||||
const parsed = parseFeedEvent({ ...draft, id: 'unused' });
|
||||
|
||||
assert.strictEqual(draft.kind, 30006);
|
||||
assert.strictEqual(parsed.id, feed.id);
|
||||
assert.strictEqual(parsed.title, feed.title);
|
||||
assert.deepEqual(parsed.photoIds, feed.photoIds);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user