nostr-session.svelte.ts (2492B)
1 import { browser } from "$app/environment"; 2 import { NDKKind, NDKNip07Signer, NDKUser, type NDKUserProfile } from "@nostr-dev-kit/ndk"; 3 import { get_store, ndk } from "@radroots/apps-lib"; 4 5 export class NostrSession { 6 user: NDKUser | null = $state(null); 7 profile: NDKUserProfile | null = $state(null); 8 follows: string[] = $state([]); 9 settings: App.SettingsNip78 | null = $state(null); 10 11 constructor(npub: string) { 12 const ndk_store = get_store(ndk); 13 this.user = ndk_store.getUser({ npub }) as unknown as NDKUser; //@todo 14 if (this.user) { 15 this.fetch_profile(); 16 this.fetch_follows(); 17 this.fetch_settings(); 18 } 19 } 20 21 async fetch_profile(): Promise<NDKUserProfile | null> { 22 if (this.user) { 23 const profile = await this.user.fetchProfile({}); 24 if (profile) this.profile = profile; 25 return profile 26 } 27 return Promise.resolve(null); 28 } 29 30 async fetch_follows(): Promise<string[]> { 31 if (this.user) { 32 const follows_set = await this.user.followSet(); 33 const follows = Array.from(follows_set).map((public_key) => public_key); 34 if (follows.length) this.follows = follows; 35 return follows; 36 } 37 return Promise.resolve([]); 38 } 39 40 async fetch_settings(): Promise<App.SettingsNip78> { 41 if (!this.user || !this.user.ndk) throw new Error(`[error] No nostr session user.`); 42 if (!browser) return Promise.resolve({ dev_mode: false }); 43 const ndk = this.user.ndk; 44 const events_app_data = await ndk.fetchEvents({ 45 kinds: [NDKKind.AppSpecificData], 46 authors: [this.user.pubkey], 47 "#d": [`radroots/settings/v1`], 48 }); 49 const list_events_app_data = Array.from(events_app_data); 50 51 let settings: App.SettingsNip78 = { dev_mode: false }; 52 if (list_events_app_data.length === 1) { 53 const event_app_data = list_events_app_data[0]; 54 let signer: NDKNip07Signer; 55 if (!ndk.signer) { 56 signer = new NDKNip07Signer(); 57 ndk.signer = signer; 58 } 59 await event_app_data.decrypt(this.user); 60 settings = JSON.parse(event_app_data.content); 61 } else if (list_events_app_data.length > 1) { 62 console.error(`[todo] Multiple app data settings events`, list_events_app_data) 63 } 64 return settings; 65 } 66 }