- Treat contacts as loaded only once the kind 3 event exists, so the first home window is fetched with the follow list, and re-fetch the initial window when contacts arrive late. - Resolve sender kind 0 profiles from the user's relays and the content's origin relays, and retry unresolved senders after the first load. - Auto-load older pages while the end sentinel stays visible via a service-side loop, guarded by hasMore and a fetch lock, with an epoch token so a mode switch invalidates in-flight fetches. - Deduplicate zap entries across window re-fetches.
732 lines
22 KiB
JavaScript
732 lines
22 KiB
JavaScript
import Service, { service } from '@ember/service';
|
|
import { tracked } from '@glimmer/tracking';
|
|
import { ProfileModel } from 'applesauce-core/models/profile';
|
|
import { getProfileContent } from 'applesauce-core/helpers/profile';
|
|
import {
|
|
parseZapReceipt,
|
|
enrichWithPhoto,
|
|
groupSocialPhotos,
|
|
} from '../utils/activity';
|
|
|
|
const SINCE_WINDOW = 30 * 24 * 60 * 60; // 30 days in seconds
|
|
const MIN_SINCE = Math.floor(new Date('2026-04-20').getTime() / 1000);
|
|
const MAX_WINDOW = 960 * 24 * 60 * 60; // 960 days in seconds
|
|
|
|
/**
|
|
* Stable identity key for a zap activity entry, used to deduplicate entries
|
|
* when the same time window is fetched more than once.
|
|
*
|
|
* @param {object} entry An `ActivityEntry` of type 'zap'
|
|
* @returns {string}
|
|
*/
|
|
function zapEntryKey(entry) {
|
|
return `${entry.photoEventId}:${entry.senderPubkey}:${entry.createdAt}`;
|
|
}
|
|
|
|
/**
|
|
* Orchestrates loading the user's incoming social activity (zaps received on
|
|
* their photos) and exposing it as a tracked `items` list for the activity
|
|
* timeline.
|
|
*
|
|
* The flow is:
|
|
* 1. Fetch kind 9735 zap receipts where the user is the recipient.
|
|
* 2. Parse each receipt into an `ActivityEntry`, filtering to zaps on the
|
|
* user's own kind 360 photos.
|
|
* 3. Resolve sender profiles asynchronously via a per-sender `ProfileModel`
|
|
* subscription, updating the tracked entry fields when they load.
|
|
* 4. Resolve place names via the shared `placeNameResolver` service.
|
|
* 5. Update `@tracked items` so the UI renders progressively.
|
|
*/
|
|
export default class ActivityService extends Service {
|
|
@service nostrData;
|
|
@service nostrAuth;
|
|
@service placeNameResolver;
|
|
|
|
@tracked items = [];
|
|
@tracked sourceMode = 'home';
|
|
@tracked isLoading = false;
|
|
@tracked isLoadingMore = false;
|
|
// Whether older activity may still be available. Used both to guard
|
|
// `loadMore` and to keep auto-loading while the end sentinel is visible.
|
|
@tracked hasMore = true;
|
|
|
|
_profileSubs = new Map();
|
|
_userPubkey = null;
|
|
_zapItems = [];
|
|
_socialItems = [];
|
|
_lastSocialEvents = [];
|
|
_since = null;
|
|
_initialSince = null;
|
|
_sourceMode = 'home';
|
|
_isLoadingMore = false;
|
|
_cacheReadyCallback = null;
|
|
_contactsUnsub = null;
|
|
// Serializes window fetches so a late-contacts refetch can't interleave with
|
|
// `loadMore` and corrupt the `_since` bookkeeping.
|
|
_fetchLock = Promise.resolve();
|
|
// End-of-list visibility reported by the component. While it stays visible,
|
|
// older pages are loaded automatically.
|
|
_sentinelVisible = false;
|
|
_autoLoading = false;
|
|
// Bumped whenever the feed resets (new load, mode switch, stop). In-flight
|
|
// fetches and the auto-load loop from the previous state check this and bail
|
|
// instead of clobbering `_since` or appending stale items.
|
|
_epoch = 0;
|
|
|
|
/**
|
|
* Loads the user's incoming zap receipts and social photo activity.
|
|
*
|
|
* When a Nostr account is connected, zaps received on the user's photos are
|
|
* loaded and the 'home' mode shows photos from followed contacts. When no
|
|
* account is connected, zaps and 'home' mode are skipped, but 'explore'
|
|
* mode still loads photos from trusted relays.
|
|
*
|
|
* If the initial 30-day window returns no events, the window expands
|
|
* exponentially (up to 960 days) until events are found or the minimum
|
|
* timestamp (2026-04-20) is reached.
|
|
*
|
|
* @param {string|null} pubkey The user's Nostr pubkey, or null
|
|
*/
|
|
async load(pubkey) {
|
|
if (this.items.length > 0) return;
|
|
this._userPubkey = pubkey || null;
|
|
this._since = Math.floor(Date.now() / 1000) - SINCE_WINDOW;
|
|
this._initialSince = this._since;
|
|
this.hasMore = true;
|
|
this._sentinelVisible = false;
|
|
this._epoch += 1;
|
|
this.isLoading = true;
|
|
this._cacheReadyCallback = () => {
|
|
this.isLoading = false;
|
|
};
|
|
|
|
try {
|
|
let contactsLoaded = true;
|
|
if (pubkey) {
|
|
await this.nostrData.loadMyContributions(pubkey);
|
|
await this.nostrData.loadProfile(pubkey);
|
|
contactsLoaded = await this.nostrData.whenContactsLoaded();
|
|
}
|
|
|
|
this._socialItems = [];
|
|
this._zapItems = [];
|
|
this._lastSocialEvents = [];
|
|
this._mergeItems();
|
|
|
|
const now = Math.floor(Date.now() / 1000);
|
|
await this._withFetchLock(() => this._fetchWithBackoff(this._since, now));
|
|
|
|
// If contacts weren't ready for the first (current) window, the followee
|
|
// photos were missed. Fetch the window again once contacts arrive, since
|
|
// nothing else re-fetches the *current* window (loadMore only extends
|
|
// further back).
|
|
if (pubkey && !contactsLoaded) {
|
|
this._contactsUnsub?.();
|
|
this._contactsUnsub = this.nostrData.onContactsLoaded(() => {
|
|
this._contactsUnsub = null;
|
|
void this._refetchInitialWindow();
|
|
});
|
|
}
|
|
|
|
// If the end sentinel is visible for a short feed, make sure auto-loading
|
|
// kicked off even if its visibility callback fired before items landed.
|
|
if (this._sentinelVisible && this.hasMore) {
|
|
void this._autoLoadWhileVisible();
|
|
}
|
|
|
|
// Retry any sender profiles the loader couldn't resolve on the first
|
|
// pass (e.g. profiles that only live on the user's relays), so names
|
|
// appear without needing to re-enter the view.
|
|
void this.retryUnresolvedProfiles();
|
|
} finally {
|
|
this.isLoading = false;
|
|
this._cacheReadyCallback = null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Re-fetches the initial (current) 30-day window and prepends any newly
|
|
* discovered items. Used when the follow list arrived after the initial
|
|
* window was fetched.
|
|
*
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async _refetchInitialWindow() {
|
|
if (this._userPubkey === null || this._initialSince === null) return;
|
|
const epoch = this._epoch;
|
|
// Fetch just the initial window (no backoff) under the shared lock so it
|
|
// never interleaves with `loadMore` and leaves `_since` untouched.
|
|
await this._withFetchLock(() => {
|
|
if (this._epoch !== epoch) return;
|
|
return this._fetchAndProcessWindow(
|
|
this._initialSince,
|
|
Math.floor(Date.now() / 1000),
|
|
epoch
|
|
);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Runs `fn` after any in-flight window fetch finishes, serializing access to
|
|
* the shared `_since` bookkeeping.
|
|
*
|
|
* @param {() => Promise<unknown>} fn
|
|
* @returns {Promise<unknown>}
|
|
*/
|
|
_withFetchLock(fn) {
|
|
const result = this._fetchLock.then(fn, fn);
|
|
this._fetchLock = result.then(
|
|
() => {},
|
|
() => {}
|
|
);
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Switches the activity source mode (e.g. 'home' for followee photos,
|
|
* 'explore' for all photos from trusted relays). Resets to a fresh
|
|
* 30-day window and re-fetches both zaps and photos with the new mode.
|
|
*
|
|
* @param {string} mode The new source mode
|
|
*/
|
|
async setSourceMode(mode) {
|
|
if (mode === this._sourceMode) return;
|
|
this._sourceMode = mode;
|
|
this.sourceMode = mode;
|
|
|
|
this._since = Math.floor(Date.now() / 1000) - SINCE_WINDOW;
|
|
this._initialSince = this._since;
|
|
this.hasMore = true;
|
|
this._sentinelVisible = false;
|
|
this._epoch += 1;
|
|
this._socialItems = [];
|
|
this._zapItems = [];
|
|
this._lastSocialEvents = [];
|
|
this._mergeItems();
|
|
|
|
this.isLoading = true;
|
|
this._cacheReadyCallback = () => {
|
|
this.isLoading = false;
|
|
};
|
|
|
|
try {
|
|
const now = Math.floor(Date.now() / 1000);
|
|
await this._withFetchLock(() => this._fetchWithBackoff(this._since, now));
|
|
} finally {
|
|
this.isLoading = false;
|
|
this._cacheReadyCallback = null;
|
|
}
|
|
|
|
void this.retryUnresolvedProfiles();
|
|
}
|
|
|
|
/**
|
|
* Re-requests kind 0 metadata for senders whose profiles could not be
|
|
* resolved. Called when the activity view is re-entered or the source mode
|
|
* changes, so a profile published after the feed was first loaded can still
|
|
* show up in the same session.
|
|
*
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async retryUnresolvedProfiles() {
|
|
const pubkeys = new Set();
|
|
for (const item of this.items) {
|
|
if (item.senderPubkey && item.senderProfileLoading) {
|
|
pubkeys.add(item.senderPubkey);
|
|
}
|
|
}
|
|
if (pubkeys.size === 0) return;
|
|
await this.nostrData.refreshProfiles([...pubkeys]);
|
|
}
|
|
|
|
/**
|
|
* Loads older events by extending the time window further back.
|
|
* Only processes newly fetched events — existing items are not re-processed.
|
|
*
|
|
* If an empty window is returned (no photos AND no zaps), the window size
|
|
* doubles (up to 960 days) and the fetch is retried automatically until
|
|
* events are found or the minimum timestamp (2026-04-20) is reached.
|
|
*
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async loadMore() {
|
|
if (
|
|
this._isLoadingMore ||
|
|
!this.hasMore ||
|
|
!this._since ||
|
|
!this.items.length
|
|
)
|
|
return;
|
|
this._isLoadingMore = true;
|
|
this.isLoadingMore = true;
|
|
const epoch = this._epoch;
|
|
|
|
try {
|
|
await this._withFetchLock(() => {
|
|
// Bail if the feed was reset while we waited for the lock.
|
|
if (this._epoch !== epoch) return;
|
|
const startSince = this._since - SINCE_WINDOW;
|
|
return this._fetchWithBackoff(startSince, this._since, epoch);
|
|
});
|
|
} finally {
|
|
this._isLoadingMore = false;
|
|
this.isLoadingMore = false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Reports whether the activity list's end sentinel is visible. While it
|
|
* stays visible, older pages are loaded automatically until the sentinel
|
|
* scrolls out of view or there is nothing left to load.
|
|
*
|
|
* @param {boolean} visible
|
|
*/
|
|
setSentinelVisible(visible) {
|
|
this._sentinelVisible = visible;
|
|
if (visible) {
|
|
void this._autoLoadWhileVisible();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Keeps loading older pages while the end sentinel is visible. Terminates
|
|
* when the sentinel scrolls out of view, `hasMore` becomes false, or a page
|
|
* fails to add anything (which would otherwise spin forever).
|
|
*
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async _autoLoadWhileVisible() {
|
|
if (this._autoLoading) return;
|
|
this._autoLoading = true;
|
|
|
|
try {
|
|
let epoch = this._epoch;
|
|
for (;;) {
|
|
while (this._sentinelVisible && this.hasMore && this._epoch === epoch) {
|
|
const before = this.items.length;
|
|
await this.loadMore();
|
|
if (this._epoch !== epoch) break;
|
|
if (this.items.length === before) break;
|
|
}
|
|
|
|
// If the feed was reset (new load / mode switch) while we were busy,
|
|
// continue for the new state instead of dropping the request.
|
|
if (this._epoch !== epoch && this._sentinelVisible && this.hasMore) {
|
|
epoch = this._epoch;
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
} finally {
|
|
this._autoLoading = false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Stops subscriptions and clears the timeline. Called when leaving the
|
|
* activity route.
|
|
*/
|
|
stop() {
|
|
this._cleanupProfileSubs();
|
|
this._contactsUnsub?.();
|
|
this._contactsUnsub = null;
|
|
this._zapItems = [];
|
|
this._socialItems = [];
|
|
this._lastSocialEvents = [];
|
|
this.items = [];
|
|
this._userPubkey = null;
|
|
this._since = null;
|
|
this._initialSince = null;
|
|
this.hasMore = true;
|
|
this._sentinelVisible = false;
|
|
this._epoch += 1;
|
|
this._isLoadingMore = false;
|
|
this.isLoadingMore = false;
|
|
this.isLoading = false;
|
|
this.placeNameResolver.reset();
|
|
}
|
|
|
|
willDestroy() {
|
|
this.stop();
|
|
super.willDestroy(...arguments);
|
|
}
|
|
|
|
/**
|
|
* Processes photo events into social items and appends them to the timeline.
|
|
*
|
|
* @param {object[]} events Photo events to process
|
|
* @returns {boolean} True if any items were added
|
|
*/
|
|
_processPhotoEvents(events) {
|
|
if (events.length === 0) return false;
|
|
|
|
this._lastSocialEvents = [...this._lastSocialEvents, ...events];
|
|
|
|
const filtered = events.filter((e) => this._matchesSourceMode(e));
|
|
if (filtered.length === 0) return false;
|
|
|
|
const newEntries = groupSocialPhotos(filtered);
|
|
|
|
const seenPhotoIds = new Set();
|
|
for (const entry of this._socialItems) {
|
|
for (const photo of entry.photos) {
|
|
seenPhotoIds.add(photo.eventId);
|
|
}
|
|
}
|
|
|
|
const dedupedEntries = newEntries.filter(
|
|
(entry) => !entry.photos.every((photo) => seenPhotoIds.has(photo.eventId))
|
|
);
|
|
|
|
if (dedupedEntries.length === 0) return false;
|
|
|
|
for (const entry of dedupedEntries) {
|
|
this._resolveSender(entry);
|
|
}
|
|
|
|
for (const entry of dedupedEntries) {
|
|
if (entry.osmId) {
|
|
const bookmarkName = this.placeNameResolver.resolveBookmark(
|
|
entry.osmId
|
|
);
|
|
if (bookmarkName) {
|
|
entry.placeName = bookmarkName;
|
|
entry.placeNameLoading = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
this._socialItems = [...this._socialItems, ...dedupedEntries];
|
|
this._mergeItems();
|
|
|
|
void this.placeNameResolver
|
|
.resolveInBackground(dedupedEntries)
|
|
.then(() => this._mergeItems());
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Processes zap receipt events and appends them to the timeline.
|
|
*
|
|
* @param {object[]} events Zap receipt events to process
|
|
* @returns {boolean} True if any items were added
|
|
*/
|
|
_processZapEventsIntoTimeline(events) {
|
|
if (events.length === 0) return false;
|
|
|
|
const newZapEntries = this._processZapEvents(events, this._userPubkey);
|
|
if (newZapEntries.length === 0) return false;
|
|
|
|
// Deduplicate against existing entries (and within this batch) so
|
|
// re-fetching a window (e.g. after contacts arrive late) doesn't append
|
|
// the same zaps twice.
|
|
const existing = new Set(this._zapItems.map(zapEntryKey));
|
|
const deduped = [];
|
|
for (const entry of newZapEntries) {
|
|
const key = zapEntryKey(entry);
|
|
if (existing.has(key)) continue;
|
|
existing.add(key);
|
|
deduped.push(entry);
|
|
}
|
|
if (deduped.length === 0) return false;
|
|
|
|
this._zapItems = [...this._zapItems, ...deduped];
|
|
this._mergeItems();
|
|
|
|
void this.placeNameResolver
|
|
.resolveInBackground(deduped)
|
|
.then(() => this._mergeItems());
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Fetches photos and zaps for a single time window, processes them, and
|
|
* appends to the respective item arrays. Cache events are processed first
|
|
* (firing `_cacheReadyCallback` to dismiss the loading spinner), then
|
|
* network events are awaited and processed.
|
|
*
|
|
* @param {number} batchSince Start of the window (seconds)
|
|
* @param {number} batchUntil End of the window (seconds)
|
|
* @returns {Promise<boolean>} True if any events were found
|
|
*/
|
|
async _fetchAndProcessWindow(batchSince, batchUntil, epoch = this._epoch) {
|
|
const photoResult = await this.nostrData.fetchActivityPhotos(
|
|
batchSince,
|
|
batchUntil,
|
|
this._sourceMode
|
|
);
|
|
if (this._epoch !== epoch) return false;
|
|
|
|
let zapResult = {
|
|
cacheEvents: [],
|
|
networkEvents: Promise.resolve([]),
|
|
};
|
|
if (this._sourceMode === 'home' && this._userPubkey) {
|
|
zapResult = await this.nostrData.fetchIncomingZaps(
|
|
this._userPubkey,
|
|
batchSince,
|
|
batchUntil
|
|
);
|
|
if (this._epoch !== epoch) return false;
|
|
}
|
|
|
|
// Phase 1: Process cache events immediately
|
|
let added = false;
|
|
|
|
if (photoResult.cacheEvents.length > 0) {
|
|
added = this._processPhotoEvents(photoResult.cacheEvents) || added;
|
|
}
|
|
if (zapResult.cacheEvents.length > 0) {
|
|
added =
|
|
this._processZapEventsIntoTimeline(zapResult.cacheEvents) || added;
|
|
}
|
|
|
|
// Signal that cached items are ready for display
|
|
if (added) {
|
|
this._cacheReadyCallback?.();
|
|
}
|
|
|
|
// Phase 2: Await network events and process them
|
|
const [networkPhotos, networkZaps] = await Promise.all([
|
|
photoResult.networkEvents,
|
|
zapResult.networkEvents,
|
|
]);
|
|
if (this._epoch !== epoch) return false;
|
|
|
|
if (networkPhotos.length > 0) {
|
|
added = this._processPhotoEvents(networkPhotos) || added;
|
|
}
|
|
if (networkZaps.length > 0) {
|
|
added = this._processZapEventsIntoTimeline(networkZaps) || added;
|
|
}
|
|
|
|
return added;
|
|
}
|
|
|
|
/**
|
|
* Fetches events with exponential backoff. Starts with a 30-day window
|
|
* and doubles the window size on each empty result (up to 960 days),
|
|
* until events are found or MIN_SINCE is reached.
|
|
*
|
|
* @param {number} startSince Start of the first window (seconds)
|
|
* @param {number} startUntil End of the first window (seconds)
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async _fetchWithBackoff(startSince, startUntil, epoch = this._epoch) {
|
|
let windowSize = SINCE_WINDOW;
|
|
let batchSince = startSince;
|
|
let batchUntil = startUntil;
|
|
|
|
while (true) {
|
|
// Stopped, or the feed was reset (new load / mode switch).
|
|
if (this._since === null || this._epoch !== epoch) return;
|
|
|
|
// Clamp to MIN_SINCE — this is the final iteration if clamped
|
|
const isFinal = batchSince < MIN_SINCE;
|
|
if (isFinal) {
|
|
batchSince = MIN_SINCE;
|
|
}
|
|
|
|
const found = await this._fetchAndProcessWindow(
|
|
batchSince,
|
|
batchUntil,
|
|
epoch
|
|
);
|
|
if (this._epoch !== epoch) return;
|
|
this._since = batchSince;
|
|
this.hasMore = !isFinal;
|
|
|
|
if (found || isFinal) break;
|
|
|
|
windowSize = Math.min(windowSize * 2, MAX_WINDOW);
|
|
batchUntil = batchSince;
|
|
batchSince = batchSince - windowSize;
|
|
}
|
|
}
|
|
|
|
_processZapEvents(receipts, pubkey) {
|
|
const entries = [];
|
|
|
|
for (const receipt of receipts) {
|
|
const entry = parseZapReceipt(receipt, pubkey);
|
|
if (!entry) continue;
|
|
|
|
if (!enrichWithPhoto(entry, this.nostrData.store, pubkey)) {
|
|
continue;
|
|
}
|
|
|
|
this._resolveSender(entry);
|
|
entries.push(entry);
|
|
}
|
|
|
|
entries.sort((a, b) => b.createdAt - a.createdAt);
|
|
|
|
for (const entry of entries) {
|
|
if (entry.osmId) {
|
|
const bookmarkName = this.placeNameResolver.resolveBookmark(
|
|
entry.osmId
|
|
);
|
|
if (bookmarkName) {
|
|
entry.placeName = bookmarkName;
|
|
entry.placeNameLoading = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
return entries;
|
|
}
|
|
|
|
_updateZapItems(receipts, pubkey) {
|
|
const entries = this._processZapEvents(receipts, pubkey);
|
|
|
|
this._zapItems = entries;
|
|
this._mergeItems();
|
|
|
|
void this.placeNameResolver.resolveInBackground(entries).then(() => {
|
|
this._mergeItems();
|
|
});
|
|
}
|
|
|
|
_updateSocialItems(events) {
|
|
const filtered = events.filter((e) => this._matchesSourceMode(e));
|
|
const entries = groupSocialPhotos(filtered);
|
|
|
|
for (const entry of entries) {
|
|
this._resolveSender(entry);
|
|
}
|
|
|
|
for (const entry of entries) {
|
|
if (entry.osmId) {
|
|
const bookmarkName = this.placeNameResolver.resolveBookmark(
|
|
entry.osmId
|
|
);
|
|
if (bookmarkName) {
|
|
entry.placeName = bookmarkName;
|
|
entry.placeNameLoading = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
this._socialItems = entries;
|
|
this._mergeItems();
|
|
|
|
void this.placeNameResolver.resolveInBackground(entries).then(() => {
|
|
this._mergeItems();
|
|
});
|
|
}
|
|
|
|
_mergeItems() {
|
|
const all =
|
|
this._sourceMode === 'explore'
|
|
? [...this._socialItems]
|
|
: [...this._zapItems, ...this._socialItems];
|
|
all.sort((a, b) => b.createdAt - a.createdAt);
|
|
this.items = all;
|
|
}
|
|
|
|
/**
|
|
* Returns true if an event should be included in the activity feed given
|
|
* the current source mode.
|
|
*
|
|
* - `'home'`: only events from followees (excluding own photos)
|
|
* - `'explore'`: events from non-followed authors trusted by relay provenance
|
|
* (excluding own photos). When no pubkey is connected, all trusted events
|
|
* pass (no own-photo or followee exclusion).
|
|
*/
|
|
_matchesSourceMode(event) {
|
|
if (this._sourceMode === 'home') {
|
|
return (
|
|
this._userPubkey &&
|
|
event.pubkey !== this._userPubkey &&
|
|
this.nostrData._contactPubkeys?.has(event.pubkey)
|
|
);
|
|
}
|
|
if (this._sourceMode === 'explore') {
|
|
if (!this._userPubkey) {
|
|
return this.nostrData.isTrustedEvent(event);
|
|
}
|
|
return (
|
|
event.pubkey !== this._userPubkey &&
|
|
!this.nostrData._contactPubkeys?.has(event.pubkey) &&
|
|
this.nostrData.isTrustedEvent(event)
|
|
);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
_resolveSender(entry) {
|
|
const pubkey = entry.senderPubkey;
|
|
if (!pubkey) return;
|
|
|
|
if (!this._profileSubs.has(pubkey)) {
|
|
const sub = this.nostrData.store
|
|
.model(ProfileModel, this._profilePointer(entry, pubkey))
|
|
.subscribe((profileContent) => {
|
|
this._applyProfileToPubkey(pubkey, profileContent);
|
|
});
|
|
this._profileSubs.set(pubkey, sub);
|
|
}
|
|
|
|
this._applySenderProfile(entry, pubkey);
|
|
}
|
|
|
|
/**
|
|
* Builds the `ProfileModel` argument for a sender, adding the relay(s) the
|
|
* underlying content was seen on as relay hints. This lets the profile loader
|
|
* find metadata on the content's relay, not only the user's relays and the
|
|
* public directory relays.
|
|
*
|
|
* @param {object} entry An `ActivityEntry`
|
|
* @param {string} pubkey The sender pubkey
|
|
* @returns {string | { pubkey: string, relays: string[] }}
|
|
*/
|
|
_profilePointer(entry, pubkey) {
|
|
const eventId = entry.photo?.eventId || entry.photos?.[0]?.eventId;
|
|
const relays = eventId ? this.nostrData.getEventRelays(eventId) : [];
|
|
return relays.length > 0 ? { pubkey, relays } : pubkey;
|
|
}
|
|
|
|
_applySenderProfile(entry, pubkey) {
|
|
let profile = this.nostrData.getProfile(pubkey);
|
|
|
|
if (!profile) {
|
|
const event = this.nostrData.store.getReplaceable(0, pubkey);
|
|
if (event) {
|
|
profile = getProfileContent(event);
|
|
}
|
|
}
|
|
|
|
if (profile) {
|
|
entry.senderName = profile.name || profile.display_name || null;
|
|
entry.senderAvatar = profile.picture || null;
|
|
entry.senderProfileLoading = false;
|
|
}
|
|
}
|
|
|
|
_applyProfileToPubkey(pubkey, profileContent) {
|
|
let changed = false;
|
|
for (const entry of this.items) {
|
|
if (entry.senderPubkey === pubkey) {
|
|
entry.senderName =
|
|
profileContent.name || profileContent.display_name || null;
|
|
entry.senderAvatar = profileContent.picture || null;
|
|
entry.senderProfileLoading = false;
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
if (changed) {
|
|
this.items = [...this.items];
|
|
}
|
|
}
|
|
|
|
_cleanupProfileSubs() {
|
|
for (const sub of this._profileSubs.values()) {
|
|
sub.unsubscribe();
|
|
}
|
|
this._profileSubs.clear();
|
|
}
|
|
}
|