feat: interaction cache

This commit is contained in:
Kieran 2023-04-25 12:57:09 +01:00
parent ce6a4ce35c
commit 69ec48141b
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
6 changed files with 115 additions and 59 deletions

View File

@ -0,0 +1,44 @@
import { db, EventInteraction } from "Db";
import { LoginStore } from "Login";
import { sha256 } from "Util";
import FeedCache from "./FeedCache";
class EventInteractionCache extends FeedCache<EventInteraction> {
constructor() {
super("EventInteraction", db.eventInteraction);
}
key(of: EventInteraction): string {
return sha256(of.event + of.by);
}
override async preload(): Promise<void> {
await super.preload();
const data = window.localStorage.getItem("zap-cache");
if (data) {
const toImport = [...new Set<string>(JSON.parse(data) as Array<string>)].map(a => {
const ret = {
event: a,
by: LoginStore.takeSnapshot().publicKey,
zapped: true,
reacted: false,
reposted: false,
} as EventInteraction;
ret.id = this.key(ret);
return ret;
});
await this.bulkSet(toImport);
console.debug(`Imported dumb-zap-cache events: `, toImport.length);
window.localStorage.removeItem("zap-cache");
}
await this.buffer([...this.onTable]);
}
takeSnapshot(): EventInteraction[] {
return [...this.cache.values()];
}
}
export const InteractionCache = new EventInteractionCache();

View File

@ -1,6 +1,7 @@
import { HexKey, RawEvent, UserMetadata } from "@snort/nostr"; import { HexKey, RawEvent, UserMetadata } from "@snort/nostr";
import { hexToBech32, unixNowMs } from "Util"; import { hexToBech32, unixNowMs } from "Util";
import { DmCache } from "./DMCache"; import { DmCache } from "./DMCache";
import { InteractionCache } from "./EventInteractionCache";
import { UserCache } from "./UserCache"; import { UserCache } from "./UserCache";
export interface MetadataCache extends UserMetadata { export interface MetadataCache extends UserMetadata {
@ -48,6 +49,7 @@ export function mapEventToProfile(ev: RawEvent) {
export async function preload() { export async function preload() {
await UserCache.preload(); await UserCache.preload();
await DmCache.preload(); await DmCache.preload();
await InteractionCache.preload();
} }
export { UserCache, DmCache }; export { UserCache, DmCache };

View File

@ -3,7 +3,7 @@ import { FullRelaySettings, HexKey, RawEvent, u256 } from "@snort/nostr";
import { MetadataCache } from "Cache"; import { MetadataCache } from "Cache";
export const NAME = "snortDB"; export const NAME = "snortDB";
export const VERSION = 7; export const VERSION = 8;
export interface SubCache { export interface SubCache {
id: string; id: string;
@ -24,12 +24,22 @@ export interface UsersRelays {
relays: FullRelaySettings[]; relays: FullRelaySettings[];
} }
export interface EventInteraction {
id: u256;
event: u256;
by: HexKey;
reacted: boolean;
zapped: boolean;
reposted: boolean;
}
const STORES = { const STORES = {
users: "++pubkey, name, display_name, picture, nip05, npub", users: "++pubkey, name, display_name, picture, nip05, npub",
relays: "++addr", relays: "++addr",
userRelays: "++pubkey", userRelays: "++pubkey",
events: "++id, pubkey, created_at", events: "++id, pubkey, created_at",
dms: "++id, pubkey", dms: "++id, pubkey",
eventInteraction: "++id",
}; };
export class SnortDB extends Dexie { export class SnortDB extends Dexie {
@ -39,6 +49,7 @@ export class SnortDB extends Dexie {
userRelays!: Table<UsersRelays>; userRelays!: Table<UsersRelays>;
events!: Table<RawEvent>; events!: Table<RawEvent>;
dms!: Table<RawEvent>; dms!: Table<RawEvent>;
eventInteraction!: Table<EventInteraction>;
constructor() { constructor() {
super(NAME); super(NAME);

View File

@ -25,42 +25,10 @@ import { DonateLNURL } from "Pages/DonatePage";
import { useWallet } from "Wallet"; import { useWallet } from "Wallet";
import useLogin from "Hooks/useLogin"; import useLogin from "Hooks/useLogin";
import { setBookmarked, setPinned } from "Login"; import { setBookmarked, setPinned } from "Login";
import { useInteractionCache } from "Hooks/useInteractionCache";
import messages from "./messages"; import messages from "./messages";
// a dumb cache to remember which notes we zapped
class DumbZapCache {
#set: Set<u256> = new Set();
constructor() {
this.#load();
}
add(id: u256) {
this.#set.add(this.#truncId(id));
this.#save();
}
has(id: u256) {
return this.#set.has(this.#truncId(id));
}
#truncId(id: u256) {
return id.slice(0, 12);
}
#save() {
window.localStorage.setItem("zap-cache", JSON.stringify([...this.#set]));
}
#load() {
const data = window.localStorage.getItem("zap-cache");
if (data) {
this.#set = new Set<u256>(JSON.parse(data) as Array<u256>);
}
}
}
const ZapCache = new DumbZapCache();
let isZapperBusy = false; let isZapperBusy = false;
const barrierZapper = async <T,>(then: () => Promise<T>): Promise<T> => { const barrierZapper = async <T,>(then: () => Promise<T>): Promise<T> => {
while (isZapperBusy) { while (isZapperBusy) {
@ -99,6 +67,7 @@ export default function NoteFooter(props: NoteFooterProps) {
const { pinned, bookmarked, publicKey, preferences: prefs, relays } = login; const { pinned, bookmarked, publicKey, preferences: prefs, relays } = login;
const { mute, block } = useModeration(); const { mute, block } = useModeration();
const author = useUserProfile(ev.pubkey); const author = useUserProfile(ev.pubkey);
const interactionCache = useInteractionCache(publicKey, ev.id);
const publisher = useEventPublisher(); const publisher = useEventPublisher();
const showNoteCreatorModal = useSelector((s: RootState) => s.noteCreator.show); const showNoteCreatorModal = useSelector((s: RootState) => s.noteCreator.show);
const replyTo = useSelector((s: RootState) => s.noteCreator.replyTo); const replyTo = useSelector((s: RootState) => s.noteCreator.replyTo);
@ -114,7 +83,7 @@ export default function NoteFooter(props: NoteFooterProps) {
type: "language", type: "language",
}); });
const zapTotal = zaps.reduce((acc, z) => acc + z.amount, 0); const zapTotal = zaps.reduce((acc, z) => acc + z.amount, 0);
const didZap = ZapCache.has(ev.id) || zaps.some(a => a.sender === publicKey); const didZap = interactionCache.data.zapped || zaps.some(a => a.sender === publicKey);
const longPress = useLongPress( const longPress = useLongPress(
e => { e => {
e.stopPropagation(); e.stopPropagation();
@ -126,17 +95,21 @@ export default function NoteFooter(props: NoteFooterProps) {
); );
function hasReacted(emoji: string) { function hasReacted(emoji: string) {
return positive?.some(({ pubkey, content }) => normalizeReaction(content) === emoji && pubkey === publicKey); return (
interactionCache.data.reacted ||
positive?.some(({ pubkey, content }) => normalizeReaction(content) === emoji && pubkey === publicKey)
);
} }
function hasReposted() { function hasReposted() {
return reposts.some(a => a.pubkey === publicKey); return interactionCache.data.reposted || reposts.some(a => a.pubkey === publicKey);
} }
async function react(content: string) { async function react(content: string) {
if (!hasReacted(content) && publisher) { if (!hasReacted(content) && publisher) {
const evLike = await publisher.react(ev, content); const evLike = await publisher.react(ev, content);
publisher.broadcast(evLike); publisher.broadcast(evLike);
await interactionCache.react();
} }
} }
@ -152,6 +125,7 @@ export default function NoteFooter(props: NoteFooterProps) {
if (!prefs.confirmReposts || window.confirm(formatMessage(messages.ConfirmRepost, { id: ev.id }))) { if (!prefs.confirmReposts || window.confirm(formatMessage(messages.ConfirmRepost, { id: ev.id }))) {
const evRepost = await publisher.repost(ev); const evRepost = await publisher.repost(ev);
publisher.broadcast(evRepost); publisher.broadcast(evRepost);
await interactionCache.repost();
} }
} }
} }
@ -201,6 +175,8 @@ export default function NoteFooter(props: NoteFooterProps) {
const zap = handler.canZap && publisher ? await publisher.zap(amount * 1000, key, zr, id) : undefined; const zap = handler.canZap && publisher ? await publisher.zap(amount * 1000, key, zr, id) : undefined;
const invoice = await handler.getInvoice(amount, undefined, zap); const invoice = await handler.getInvoice(amount, undefined, zap);
await wallet?.payInvoice(unwrap(invoice.pr)); await wallet?.payInvoice(unwrap(invoice.pr));
await interactionCache.zap();
}); });
} }
@ -220,14 +196,13 @@ export default function NoteFooter(props: NoteFooterProps) {
} }
useEffect(() => { useEffect(() => {
if (prefs.autoZap && !ZapCache.has(ev.id) && !isMine && !zapping) { if (prefs.autoZap && !didZap && !isMine && !zapping) {
const lnurl = getLNURL(); const lnurl = getLNURL();
if (wallet?.isReady() && lnurl) { if (wallet?.isReady() && lnurl) {
setZapping(true); setZapping(true);
queueMicrotask(async () => { queueMicrotask(async () => {
try { try {
await fastZapInner(lnurl, prefs.defaultZapAmount, ev.pubkey, ev.id); await fastZapInner(lnurl, prefs.defaultZapAmount, ev.pubkey, ev.id);
ZapCache.add(ev.id);
fastZapDonate(); fastZapDonate();
} catch { } catch {
// ignored // ignored

View File

@ -1,20 +0,0 @@
import { useRef, useState, useEffect } from "react";
export default function useClientWidth() {
const ref = useRef<HTMLDivElement | null>(document.querySelector(".page"));
const [width, setWidth] = useState(0);
useEffect(() => {
const updateSize = () => {
if (ref.current) {
setWidth(ref.current.offsetWidth);
}
};
window.addEventListener("resize", updateSize);
updateSize();
return () => window.removeEventListener("resize", updateSize);
}, [ref]);
return width;
}

View File

@ -0,0 +1,44 @@
import { useSyncExternalStore } from "react";
import { HexKey, u256 } from "@snort/nostr";
import { InteractionCache } from "Cache/EventInteractionCache";
import { EventInteraction } from "Db";
import { sha256, unwrap } from "Util";
export function useInteractionCache(pubkey?: HexKey, event?: u256) {
const id = event && pubkey ? sha256(event + pubkey) : undefined;
const EmptyInteraction = {
id,
event,
by: pubkey,
} as EventInteraction;
const data =
useSyncExternalStore(
c => InteractionCache.hook(c, id),
() => InteractionCache.snapshot()[0]
) || EmptyInteraction;
return {
data: data,
react: () =>
InteractionCache.set({
...data,
event: unwrap(event),
by: unwrap(pubkey),
reacted: true,
}),
zap: () =>
InteractionCache.set({
...data,
event: unwrap(event),
by: unwrap(pubkey),
zapped: true,
}),
repost: () =>
InteractionCache.set({
...data,
event: unwrap(event),
by: unwrap(pubkey),
reposted: true,
}),
};
}