fix: 🐛

This commit is contained in:
codytseng
2025-01-13 23:22:19 +08:00
parent d0350c6ad3
commit c62a82f673
9 changed files with 283 additions and 244 deletions

View File

@@ -21,7 +21,8 @@ export default function FeedSwitcher({ close }: { close?: () => void }) {
itemName={t('Following')} itemName={t('Following')}
isActive={feedType === 'following'} isActive={feedType === 'following'}
onClick={() => { onClick={() => {
switchFeed('following') if (!pubkey) return
switchFeed('following', { pubkey })
close?.() close?.()
}} }}
/> />

View File

@@ -17,10 +17,12 @@ export default function SaveButton({
setHasChange: (hasChange: boolean) => void setHasChange: (hasChange: boolean) => void
}) { }) {
const { toast } = useToast() const { toast } = useToast()
const { pubkey, publish, updateRelayList } = useNostr() const { pubkey, publish, updateRelayListEvent } = useNostr()
const [pushing, setPushing] = useState(false) const [pushing, setPushing] = useState(false)
const save = async () => { const save = async () => {
if (!pubkey) return
setPushing(true) setPushing(true)
const event = { const event = {
kind: kinds.RelayList, kind: kinds.RelayList,
@@ -30,11 +32,8 @@ export default function SaveButton({
), ),
created_at: dayjs().unix() created_at: dayjs().unix()
} }
await publish(event) const relayListEvent = await publish(event)
updateRelayList({ updateRelayListEvent(relayListEvent)
write: mailboxRelays.filter(({ scope }) => scope !== 'read').map(({ url }) => url),
read: mailboxRelays.filter(({ scope }) => scope !== 'write').map(({ url }) => url)
})
toast({ toast({
title: 'Save Successful', title: 'Save Successful',
description: 'Successfully saved mailbox relays' description: 'Successfully saved mailbox relays'

View File

@@ -5,9 +5,9 @@ export const StorageKey = {
FEED_TYPE: 'feedType', FEED_TYPE: 'feedType',
ACCOUNTS: 'accounts', ACCOUNTS: 'accounts',
CURRENT_ACCOUNT: 'currentAccount', CURRENT_ACCOUNT: 'currentAccount',
ACCOUNT_RELAY_LIST_MAP: 'accountRelayListMap', ACCOUNT_RELAY_LIST_EVENT_MAP: 'accountRelayListEventMap',
ACCOUNT_FOLLOWINGS_MAP: 'accountFollowingsMap', ACCOUNT_FOLLOW_LIST_EVENT_MAP: 'accountFollowListEventMap',
ACCOUNT_PROFILE_MAP: 'accountProfileMap', ACCOUNT_PROFILE_EVENT_MAP: 'accountProfileEventMap',
ADD_CLIENT_TAG: 'addClientTag' ADD_CLIENT_TAG: 'addClientTag'
} }

View File

@@ -1,7 +1,10 @@
import { COMMENT_EVENT_KIND, PICTURE_EVENT_KIND } from '@/constants' import { BIG_RELAY_URLS, COMMENT_EVENT_KIND, PICTURE_EVENT_KIND } from '@/constants'
import client from '@/services/client.service' import client from '@/services/client.service'
import { TRelayList } from '@/types'
import { Event, kinds, nip19 } from 'nostr-tools' import { Event, kinds, nip19 } from 'nostr-tools'
import { extractImageInfoFromTag, isReplyETag, isRootETag, tagNameEquals } from './tag' import { extractImageInfoFromTag, isReplyETag, isRootETag, tagNameEquals } from './tag'
import { isWebsocketUrl, normalizeUrl } from './url'
import { formatPubkey } from './pubkey'
export function isNsfwEvent(event: Event) { export function isNsfwEvent(event: Event) {
return event.tags.some( return event.tags.some(
@@ -76,6 +79,59 @@ export function getFollowingsFromFollowListEvent(event: Event) {
) )
} }
export function getRelayListFromRelayListEvent(event?: Event) {
if (!event) {
return { write: BIG_RELAY_URLS, read: BIG_RELAY_URLS }
}
const relayList = { write: [], read: [] } as TRelayList
event.tags.filter(tagNameEquals('r')).forEach(([, url, type]) => {
if (!url || !isWebsocketUrl(url)) return
const normalizedUrl = normalizeUrl(url)
switch (type) {
case 'w':
relayList.write.push(normalizedUrl)
break
case 'r':
relayList.read.push(normalizedUrl)
break
default:
relayList.write.push(normalizedUrl)
relayList.read.push(normalizedUrl)
}
})
return {
write: relayList.write.length ? relayList.write.slice(0, 10) : BIG_RELAY_URLS,
read: relayList.read.length ? relayList.read.slice(0, 10) : BIG_RELAY_URLS
}
}
export function getProfileFromProfileEvent(event: Event) {
try {
const profileObj = JSON.parse(event.content)
return {
pubkey: event.pubkey,
banner: profileObj.banner,
avatar: profileObj.picture,
username:
profileObj.display_name?.trim() ||
profileObj.name?.trim() ||
profileObj.nip05?.split('@')[0]?.trim() ||
formatPubkey(event.pubkey),
nip05: profileObj.nip05,
about: profileObj.about,
created_at: event.created_at
}
} catch (err) {
console.error(err)
return {
pubkey: event.pubkey,
username: formatPubkey(event.pubkey)
}
}
}
export async function extractMentions(content: string, parentEvent?: Event) { export async function extractMentions(content: string, parentEvent?: Event) {
const pubkeySet = new Set<string>() const pubkeySet = new Set<string>()
const relatedEventIdSet = new Set<string>() const relatedEventIdSet = new Set<string>()

View File

@@ -14,7 +14,10 @@ type TFeedContext = {
filter: Filter filter: Filter
isReady: boolean isReady: boolean
activeRelaySetId: string | null activeRelaySetId: string | null
switchFeed: (feedType: TFeedType, options?: { activeRelaySetId?: string }) => Promise<void> switchFeed: (
feedType: TFeedType,
options?: { activeRelaySetId?: string; pubkey?: string }
) => Promise<void>
} }
const FeedContext = createContext<TFeedContext | undefined>(undefined) const FeedContext = createContext<TFeedContext | undefined>(undefined)
@@ -52,32 +55,28 @@ export function FeedProvider({ children }: { children: React.ReactNode }) {
} }
if (feedType === 'following') { if (feedType === 'following') {
return await switchFeed('following') return await switchFeed('following', { pubkey })
} } else {
await switchFeed('relays', { activeRelaySetId }) await switchFeed('relays', { activeRelaySetId })
} }
}
init() init()
}, []) }, [])
useEffect(() => { useEffect(() => {
if (!isReady || feedType !== 'following') return if (pubkey && feedType === 'following') {
switchFeed('following', { pubkey })
switchFeed('following') }
}, [pubkey, feedType, isReady]) }, [feedType, pubkey])
useEffect(() => {
if (feedType !== 'relays') return
const relaySet = relaySets.find((set) => set.id === activeRelaySetId)
if (!relaySet) return
setRelayUrls(relaySet.relayUrls)
}, [relaySets])
const switchFeed = async ( const switchFeed = async (
feedType: TFeedType, feedType: TFeedType,
options: { activeRelaySetId?: string | null; temporaryRelayUrls?: string[] | null } = {} options: {
activeRelaySetId?: string | null
temporaryRelayUrls?: string[] | null
pubkey?: string | null
} = {}
) => { ) => {
setIsReady(false) setIsReady(false)
if (feedType === 'relays') { if (feedType === 'relays') {
@@ -100,14 +99,19 @@ export function FeedProvider({ children }: { children: React.ReactNode }) {
return setIsReady(true) return setIsReady(true)
} }
if (feedType === 'following') { if (feedType === 'following') {
if (!pubkey) { if (!options.pubkey) {
return setIsReady(true) return setIsReady(true)
} }
setFeedType(feedType) setFeedType(feedType)
setActiveRelaySetId(null) setActiveRelaySetId(null)
const [relayList, followings] = await Promise.all([getRelayList(), getFollowings()]) const [relayList, followings] = await Promise.all([
getRelayList(options.pubkey),
getFollowings(options.pubkey)
])
setRelayUrls(relayList.read.concat(BIG_RELAY_URLS).slice(0, 4)) setRelayUrls(relayList.read.concat(BIG_RELAY_URLS).slice(0, 4))
setFilter({ authors: followings.includes(pubkey) ? followings : [...followings, pubkey] }) setFilter({
authors: followings.includes(options.pubkey) ? followings : [...followings, options.pubkey]
})
storage.setFeedType(feedType) storage.setFeedType(feedType)
return setIsReady(true) return setIsReady(true)
} }

View File

@@ -1,6 +1,6 @@
import { TDraftEvent } from '@/types'
import { tagNameEquals } from '@/lib/tag' import { tagNameEquals } from '@/lib/tag'
import client from '@/services/client.service' import client from '@/services/client.service'
import { TDraftEvent } from '@/types'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { Event, kinds } from 'nostr-tools' import { Event, kinds } from 'nostr-tools'
import { createContext, useContext, useEffect, useMemo, useState } from 'react' import { createContext, useContext, useEffect, useMemo, useState } from 'react'
@@ -25,7 +25,7 @@ export const useFollowList = () => {
} }
export function FollowListProvider({ children }: { children: React.ReactNode }) { export function FollowListProvider({ children }: { children: React.ReactNode }) {
const { pubkey: accountPubkey, publish, updateFollowings } = useNostr() const { pubkey: accountPubkey, publish, updateFollowListEvent } = useNostr()
const [followListEvent, setFollowListEvent] = useState<Event | undefined>(undefined) const [followListEvent, setFollowListEvent] = useState<Event | undefined>(undefined)
const [isFetching, setIsFetching] = useState(true) const [isFetching, setIsFetching] = useState(true)
const followings = useMemo(() => { const followings = useMemo(() => {
@@ -65,7 +65,7 @@ export function FollowListProvider({ children }: { children: React.ReactNode })
} }
const newFollowListEvent = await publish(newFollowListDraftEvent) const newFollowListEvent = await publish(newFollowListDraftEvent)
client.updateFollowListCache(accountPubkey, newFollowListEvent) client.updateFollowListCache(accountPubkey, newFollowListEvent)
updateFollowings([...followings, pubkey]) updateFollowListEvent(newFollowListEvent)
setFollowListEvent(newFollowListEvent) setFollowListEvent(newFollowListEvent)
} }
@@ -82,7 +82,7 @@ export function FollowListProvider({ children }: { children: React.ReactNode })
} }
const newFollowListEvent = await publish(newFollowListDraftEvent) const newFollowListEvent = await publish(newFollowListDraftEvent)
client.updateFollowListCache(accountPubkey, newFollowListEvent) client.updateFollowListCache(accountPubkey, newFollowListEvent)
updateFollowings(followings.filter((followPubkey) => followPubkey !== pubkey)) updateFollowListEvent(newFollowListEvent)
setFollowListEvent(newFollowListEvent) setFollowListEvent(newFollowListEvent)
} }

View File

@@ -1,6 +1,10 @@
import LoginDialog from '@/components/LoginDialog' import LoginDialog from '@/components/LoginDialog'
import { BIG_RELAY_URLS } from '@/constants'
import { useToast } from '@/hooks' import { useToast } from '@/hooks'
import {
getFollowingsFromFollowListEvent,
getProfileFromProfileEvent,
getRelayListFromRelayListEvent
} from '@/lib/event'
import client from '@/services/client.service' import client from '@/services/client.service'
import storage from '@/services/storage.service' import storage from '@/services/storage.service'
import { ISigner, TAccount, TAccountPointer, TDraftEvent, TProfile, TRelayList } from '@/types' import { ISigner, TAccount, TAccountPointer, TDraftEvent, TProfile, TRelayList } from '@/types'
@@ -30,10 +34,10 @@ type TNostrContext = {
signHttpAuth: (url: string, method: string) => Promise<string> signHttpAuth: (url: string, method: string) => Promise<string>
signEvent: (draftEvent: TDraftEvent) => Promise<Event> signEvent: (draftEvent: TDraftEvent) => Promise<Event>
checkLogin: <T>(cb?: () => T) => Promise<T | void> checkLogin: <T>(cb?: () => T) => Promise<T | void>
getRelayList: () => Promise<TRelayList> getRelayList: (pubkey: string) => Promise<TRelayList>
updateRelayList: (relayList: TRelayList) => void updateRelayListEvent: (relayListEvent: Event) => void
getFollowings: () => Promise<string[]> getFollowings: (pubkey: string) => Promise<string[]>
updateFollowings: (followings: string[]) => void updateFollowListEvent: (followListEvent: Event) => void
} }
const NostrContext = createContext<TNostrContext | undefined>(undefined) const NostrContext = createContext<TNostrContext | undefined>(undefined)
@@ -69,34 +73,42 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
useEffect(() => { useEffect(() => {
if (!account) { if (!account) {
setRelayList(null) setRelayList(null)
setFollowings(null)
setProfile(null)
return return
} }
const storedRelayList = storage.getAccountRelayList(account.pubkey) const storedRelayListEvent = storage.getAccountRelayListEvent(account.pubkey)
if (storedRelayList) { if (storedRelayListEvent) {
setRelayList(storedRelayList) setRelayList(
storedRelayListEvent ? getRelayListFromRelayListEvent(storedRelayListEvent) : null
)
} }
const followings = storage.getAccountFollowings(account.pubkey) const followListEvent = storage.getAccountFollowListEvent(account.pubkey)
if (followings) { if (followListEvent) {
setFollowings(followings) setFollowings(getFollowingsFromFollowListEvent(followListEvent))
} }
const profile = storage.getAccountProfile(account.pubkey) const profileEvent = storage.getAccountProfileEvent(account.pubkey)
if (profile) { if (profileEvent) {
setProfile(profile) setProfile(getProfileFromProfileEvent(profileEvent))
} }
client.fetchRelayList(account.pubkey).then((relayList) => { client.fetchRelayListEvent(account.pubkey).then((relayListEvent) => {
setRelayList(relayList) if (!relayListEvent) return
storage.setAccountRelayList(account.pubkey, relayList) const isNew = storage.setAccountRelayListEvent(relayListEvent)
if (!isNew) return
setRelayList(getRelayListFromRelayListEvent(relayListEvent))
}) })
client.fetchFollowings(account.pubkey).then((followings) => { client.fetchFollowListEvent(account.pubkey).then((followListEvent) => {
setFollowings(followings) if (!followListEvent) return
storage.setAccountFollowings(account.pubkey, followings) const isNew = storage.setAccountFollowListEvent(followListEvent)
if (!isNew) return
setFollowings(getFollowingsFromFollowListEvent(followListEvent))
}) })
client.fetchProfile(account.pubkey).then((profile) => { client.fetchProfileEvent(account.pubkey).then((profileEvent) => {
if (profile) { if (!profileEvent) return
setProfile(profile) const isNew = storage.setAccountProfileEvent(profileEvent)
storage.setAccountProfile(account.pubkey, profile) if (!isNew) return
} setProfile(getProfileFromProfileEvent(profileEvent))
}) })
}, [account]) }, [account])
@@ -240,44 +252,32 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
return setOpenLoginDialog(true) return setOpenLoginDialog(true)
} }
const getRelayList = async () => { const getRelayList = async (pubkey: string) => {
if (!account) { const storedRelayListEvent = storage.getAccountRelayListEvent(pubkey)
return { write: BIG_RELAY_URLS, read: BIG_RELAY_URLS } if (storedRelayListEvent) {
return getRelayListFromRelayListEvent(storedRelayListEvent)
}
return await client.fetchRelayList(pubkey)
} }
const storedRelayList = storage.getAccountRelayList(account.pubkey) const updateRelayListEvent = (relayListEvent: Event) => {
if (storedRelayList) { const isNew = storage.setAccountRelayListEvent(relayListEvent)
return storedRelayList if (!isNew) return
} setRelayList(getRelayListFromRelayListEvent(relayListEvent))
return await client.fetchRelayList(account.pubkey)
} }
const updateRelayList = (relayList: TRelayList) => { const getFollowings = async (pubkey: string) => {
if (!account) { const followListEvent = storage.getAccountFollowListEvent(pubkey)
return if (followListEvent) {
return getFollowingsFromFollowListEvent(followListEvent)
} }
setRelayList(relayList) return await client.fetchFollowings(pubkey)
storage.setAccountRelayList(account.pubkey, relayList)
} }
const getFollowings = async () => { const updateFollowListEvent = (followListEvent: Event) => {
if (!account) { const isNew = storage.setAccountFollowListEvent(followListEvent)
return [] if (!isNew) return
} setFollowings(getFollowingsFromFollowListEvent(followListEvent))
const followings = storage.getAccountFollowings(account.pubkey)
if (followings) {
return followings
}
return await client.fetchFollowings(account.pubkey)
}
const updateFollowings = (followings: string[]) => {
if (!account) {
return
}
setFollowings(followings)
storage.setAccountFollowings(account.pubkey, followings)
} }
return ( return (
@@ -301,9 +301,9 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
checkLogin, checkLogin,
signEvent, signEvent,
getRelayList, getRelayList,
updateRelayList, updateRelayListEvent,
getFollowings, getFollowings,
updateFollowings updateFollowListEvent
}} }}
> >
{children} {children}

View File

@@ -1,8 +1,10 @@
import { BIG_RELAY_URLS } from '@/constants' import { BIG_RELAY_URLS } from '@/constants'
import { getFollowingsFromFollowListEvent } from '@/lib/event' import {
import { formatPubkey } from '@/lib/pubkey' getFollowingsFromFollowListEvent,
import { tagNameEquals } from '@/lib/tag' getProfileFromProfileEvent,
import { isWebsocketUrl, normalizeUrl } from '@/lib/url' getRelayListFromRelayListEvent
} from '@/lib/event'
import { userIdToPubkey } from '@/lib/pubkey'
import { TDraftEvent, TProfile, TRelayInfo, TRelayList } from '@/types' import { TDraftEvent, TProfile, TRelayInfo, TRelayList } from '@/types'
import { sha256 } from '@noble/hashes/sha2' import { sha256 } from '@noble/hashes/sha2'
import DataLoader from 'dataloader' import DataLoader from 'dataloader'
@@ -43,19 +45,19 @@ class ClientService extends EventTarget {
this.eventBatchLoadFn.bind(this), this.eventBatchLoadFn.bind(this),
{ cache: false } { cache: false }
) )
private profileCache = new LRUCache<string, Promise<TProfile>>({ max: 10000 }) private profileEventCache = new LRUCache<string, Promise<NEvent | undefined>>({ max: 10000 })
private profileDataloader = new DataLoader<string, TProfile>( private profileEventDataloader = new DataLoader<string, NEvent | undefined>(
(ids) => Promise.all(ids.map((id) => this._fetchProfile(id))), (ids) => Promise.all(ids.map((id) => this._fetchProfileEvent(id))),
{ cacheMap: this.profileCache } { cacheMap: this.profileEventCache }
) )
private fetchProfileFromDefaultRelaysDataloader = new DataLoader<string, TProfile | undefined>( private fetchProfileEventFromDefaultRelaysDataloader = new DataLoader<string, NEvent | undefined>(
this.profileBatchLoadFn.bind(this), this.profileEventBatchLoadFn.bind(this),
{ cache: false } { cache: false }
) )
private relayListDataLoader = new DataLoader<string, TRelayList>( private relayListEventDataLoader = new DataLoader<string, NEvent | undefined>(
this.relayListBatchLoadFn.bind(this), this.relayListEventBatchLoadFn.bind(this),
{ {
cacheMap: new LRUCache<string, Promise<TRelayList>>({ max: 10000 }) cacheMap: new LRUCache<string, Promise<NEvent | undefined>>({ max: 10000 })
} }
) )
private relayInfoDataLoader = new DataLoader<string, TRelayInfo | undefined>(async (urls) => { private relayInfoDataLoader = new DataLoader<string, TRelayInfo | undefined>(async (urls) => {
@@ -373,30 +375,28 @@ class ClientService extends EventTarget {
this.eventDataLoader.prime(event.id, Promise.resolve(event)) this.eventDataLoader.prime(event.id, Promise.resolve(event))
} }
async fetchProfile(id: string): Promise<TProfile | undefined> { async fetchProfileEvent(id: string): Promise<NEvent | undefined> {
if (!/^[0-9a-f]{64}$/.test(id)) { const pubkey = userIdToPubkey(id)
let pubkey: string | undefined const cache = await this.profileEventCache.get(pubkey)
const { data, type } = nip19.decode(id)
switch (type) {
case 'npub':
pubkey = data
break
case 'nprofile':
pubkey = data.pubkey
break
}
if (!pubkey) {
throw new Error('Invalid id')
}
const cache = await this.profileCache.get(pubkey)
if (cache) { if (cache) {
return cache return cache
} }
return await this.profileEventDataloader.load(id)
} }
return this.profileDataloader.load(id) async fetchProfile(id: string): Promise<TProfile | undefined> {
const profileEvent = await this.fetchProfileEvent(id)
if (profileEvent) {
return getProfileFromProfileEvent(profileEvent)
}
try {
const pubkey = userIdToPubkey(id)
return { pubkey, username: pubkey }
} catch {
return undefined
}
} }
async fetchProfiles(relayUrls: string[], filter: Filter): Promise<TProfile[]> { async fetchProfiles(relayUrls: string[], filter: Filter): Promise<TProfile[]> {
@@ -405,15 +405,21 @@ class ClientService extends EventTarget {
kinds: [kinds.Metadata] kinds: [kinds.Metadata]
}) })
const profiles = events const profileEvents = events.sort((a, b) => b.created_at - a.created_at)
.sort((a, b) => b.created_at - a.created_at) profileEvents.forEach((profile) => this.profileEventDataloader.prime(profile.pubkey, profile))
.map((event) => this.parseProfileFromEvent(event)) return profileEvents.map((profileEvent) => getProfileFromProfileEvent(profileEvent))
profiles.forEach((profile) => this.profileDataloader.prime(profile.pubkey, profile)) }
return profiles
async fetchRelayListEvent(pubkey: string) {
return this.relayListEventDataLoader.load(pubkey)
} }
async fetchRelayList(pubkey: string): Promise<TRelayList> { async fetchRelayList(pubkey: string): Promise<TRelayList> {
return this.relayListDataLoader.load(pubkey) const event = await this.relayListEventDataLoader.load(pubkey)
if (!event) {
return { write: BIG_RELAY_URLS, read: BIG_RELAY_URLS }
}
return getRelayListFromRelayListEvent(event)
} }
async fetchFollowListEvent(pubkey: string) { async fetchFollowListEvent(pubkey: string) {
@@ -488,7 +494,7 @@ class ClientService extends EventTarget {
return event return event
} }
private async _fetchProfile(id: string): Promise<TProfile> { private async _fetchProfileEvent(id: string): Promise<NEvent | undefined> {
let pubkey: string | undefined let pubkey: string | undefined
let relays: string[] = [] let relays: string[] = []
if (/^[0-9a-f]{64}$/.test(id)) { if (/^[0-9a-f]{64}$/.test(id)) {
@@ -509,8 +515,8 @@ class ClientService extends EventTarget {
if (!pubkey) { if (!pubkey) {
throw new Error('Invalid id') throw new Error('Invalid id')
} }
const profileFromDefaultRelays =
const profileFromDefaultRelays = await this.fetchProfileFromDefaultRelaysDataloader.load(pubkey) await this.fetchProfileEventFromDefaultRelaysDataloader.load(pubkey)
if (profileFromDefaultRelays) { if (profileFromDefaultRelays) {
return profileFromDefaultRelays return profileFromDefaultRelays
} }
@@ -524,15 +530,11 @@ class ClientService extends EventTarget {
}, },
true true
) )
const profile = profileEvent
? this.parseProfileFromEvent(profileEvent)
: { pubkey, username: formatPubkey(pubkey) }
if (pubkey !== id) { if (pubkey !== id) {
this.profileDataloader.prime(pubkey, Promise.resolve(profile)) this.profileEventDataloader.prime(pubkey, Promise.resolve(profileEvent))
} }
return profile return profileEvent
} }
private async tryHarderToFetchEvent( private async tryHarderToFetchEvent(
@@ -567,7 +569,7 @@ class ClientService extends EventTarget {
return ids.map((id) => eventsMap.get(id)) return ids.map((id) => eventsMap.get(id))
} }
private async profileBatchLoadFn(pubkeys: readonly string[]) { private async profileEventBatchLoadFn(pubkeys: readonly string[]) {
const events = await this.pool.querySync(this.defaultRelayUrls, { const events = await this.pool.querySync(this.defaultRelayUrls, {
authors: Array.from(new Set(pubkeys)), authors: Array.from(new Set(pubkeys)),
kinds: [kinds.Metadata], kinds: [kinds.Metadata],
@@ -583,12 +585,11 @@ class ClientService extends EventTarget {
} }
return pubkeys.map((pubkey) => { return pubkeys.map((pubkey) => {
const event = eventsMap.get(pubkey) return eventsMap.get(pubkey)
return event ? this.parseProfileFromEvent(event) : undefined
}) })
} }
private async relayListBatchLoadFn(pubkeys: readonly string[]) { private async relayListEventBatchLoadFn(pubkeys: readonly string[]) {
const events = await this.pool.querySync(this.defaultRelayUrls, { const events = await this.pool.querySync(this.defaultRelayUrls, {
authors: pubkeys as string[], authors: pubkeys as string[],
kinds: [kinds.RelayList], kinds: [kinds.RelayList],
@@ -603,34 +604,7 @@ class ClientService extends EventTarget {
} }
} }
return pubkeys.map((pubkey) => { return pubkeys.map((pubkey) => eventsMap.get(pubkey))
const event = eventsMap.get(pubkey)
const relayList = { write: [], read: [] } as TRelayList
if (!event) {
return { write: BIG_RELAY_URLS, read: BIG_RELAY_URLS }
}
event.tags.filter(tagNameEquals('r')).forEach(([, url, type]) => {
if (!url || !isWebsocketUrl(url)) return
const normalizedUrl = normalizeUrl(url)
switch (type) {
case 'w':
relayList.write.push(normalizedUrl)
break
case 'r':
relayList.read.push(normalizedUrl)
break
default:
relayList.write.push(normalizedUrl)
relayList.read.push(normalizedUrl)
}
})
return {
write: relayList.write.length ? relayList.write.slice(0, 10) : BIG_RELAY_URLS,
read: relayList.read.length ? relayList.read.slice(0, 10) : BIG_RELAY_URLS
}
})
} }
private async _fetchFollowListEvent(pubkey: string) { private async _fetchFollowListEvent(pubkey: string) {
@@ -645,31 +619,6 @@ class ClientService extends EventTarget {
return followListEvents.sort((a, b) => b.created_at - a.created_at)[0] return followListEvents.sort((a, b) => b.created_at - a.created_at)[0]
} }
private parseProfileFromEvent(event: NEvent): TProfile {
try {
const profileObj = JSON.parse(event.content)
return {
pubkey: event.pubkey,
banner: profileObj.banner,
avatar: profileObj.picture,
username:
profileObj.display_name?.trim() ||
profileObj.name?.trim() ||
profileObj.nip05?.split('@')[0]?.trim() ||
formatPubkey(event.pubkey),
nip05: profileObj.nip05,
about: profileObj.about,
created_at: event.created_at
}
} catch (err) {
console.error(err)
return {
pubkey: event.pubkey,
username: formatPubkey(event.pubkey)
}
}
}
} }
const instance = ClientService.getInstance() const instance = ClientService.getInstance()

View File

@@ -1,15 +1,8 @@
import { StorageKey } from '@/constants' import { StorageKey } from '@/constants'
import { isSameAccount } from '@/lib/account' import { isSameAccount } from '@/lib/account'
import { randomString } from '@/lib/random' import { randomString } from '@/lib/random'
import { import { TAccount, TAccountPointer, TFeedType, TRelaySet, TThemeSetting } from '@/types'
TAccount, import { Event } from 'nostr-tools'
TAccountPointer,
TFeedType,
TProfile,
TRelayList,
TRelaySet,
TThemeSetting
} from '@/types'
const DEFAULT_RELAY_SETS: TRelaySet[] = [ const DEFAULT_RELAY_SETS: TRelaySet[] = [
{ {
@@ -33,9 +26,9 @@ class StorageService {
private themeSetting: TThemeSetting = 'system' private themeSetting: TThemeSetting = 'system'
private accounts: TAccount[] = [] private accounts: TAccount[] = []
private currentAccount: TAccount | null = null private currentAccount: TAccount | null = null
private accountRelayListMap: Record<string, TRelayList | undefined> = {} // pubkey -> relayList private accountRelayListEventMap: Record<string, Event | undefined> = {} // pubkey -> relayListEvent
private accountFollowingsMap: Record<string, string[] | undefined> = {} // pubkey -> followings private accountFollowListEventMap: Record<string, Event | undefined> = {} // pubkey -> followListEvent
private accountProfileMap: Record<string, TProfile> = {} // pubkey -> profile private accountProfileEventMap: Record<string, Event> = {} // pubkey -> profileEvent
constructor() { constructor() {
if (!StorageService.instance) { if (!StorageService.instance) {
@@ -54,12 +47,25 @@ class StorageService {
this.currentAccount = currentAccountStr ? JSON.parse(currentAccountStr) : null this.currentAccount = currentAccountStr ? JSON.parse(currentAccountStr) : null
const feedTypeStr = window.localStorage.getItem(StorageKey.FEED_TYPE) const feedTypeStr = window.localStorage.getItem(StorageKey.FEED_TYPE)
this.feedType = feedTypeStr ? JSON.parse(feedTypeStr) : 'relays' this.feedType = feedTypeStr ? JSON.parse(feedTypeStr) : 'relays'
const accountRelayListMapStr = window.localStorage.getItem(StorageKey.ACCOUNT_RELAY_LIST_MAP)
this.accountRelayListMap = accountRelayListMapStr ? JSON.parse(accountRelayListMapStr) : {} const accountRelayListEventMapStr = window.localStorage.getItem(
const accountFollowingsMapStr = window.localStorage.getItem(StorageKey.ACCOUNT_FOLLOWINGS_MAP) StorageKey.ACCOUNT_RELAY_LIST_EVENT_MAP
this.accountFollowingsMap = accountFollowingsMapStr ? JSON.parse(accountFollowingsMapStr) : {} )
const accountProfileMapStr = window.localStorage.getItem(StorageKey.ACCOUNT_PROFILE_MAP) this.accountRelayListEventMap = accountRelayListEventMapStr
this.accountProfileMap = accountProfileMapStr ? JSON.parse(accountProfileMapStr) : {} ? JSON.parse(accountRelayListEventMapStr)
: {}
const accountFollowListEventMapStr = window.localStorage.getItem(
StorageKey.ACCOUNT_FOLLOW_LIST_EVENT_MAP
)
this.accountFollowListEventMap = accountFollowListEventMapStr
? JSON.parse(accountFollowListEventMapStr)
: {}
const accountProfileEventMapStr = window.localStorage.getItem(
StorageKey.ACCOUNT_PROFILE_EVENT_MAP
)
this.accountProfileEventMap = accountProfileEventMapStr
? JSON.parse(accountProfileEventMapStr)
: {}
const relaySetsStr = window.localStorage.getItem(StorageKey.RELAY_SETS) const relaySetsStr = window.localStorage.getItem(StorageKey.RELAY_SETS)
if (!relaySetsStr) { if (!relaySetsStr) {
@@ -155,21 +161,21 @@ class StorageService {
removeAccount(account: TAccount) { removeAccount(account: TAccount) {
this.accounts = this.accounts.filter((act) => !isSameAccount(act, account)) this.accounts = this.accounts.filter((act) => !isSameAccount(act, account))
delete this.accountFollowingsMap[account.pubkey] delete this.accountFollowListEventMap[account.pubkey]
delete this.accountRelayListMap[account.pubkey] delete this.accountRelayListEventMap[account.pubkey]
delete this.accountProfileMap[account.pubkey] delete this.accountProfileEventMap[account.pubkey]
window.localStorage.setItem(StorageKey.ACCOUNTS, JSON.stringify(this.accounts)) window.localStorage.setItem(StorageKey.ACCOUNTS, JSON.stringify(this.accounts))
window.localStorage.setItem( window.localStorage.setItem(
StorageKey.ACCOUNT_FOLLOWINGS_MAP, StorageKey.ACCOUNT_FOLLOW_LIST_EVENT_MAP,
JSON.stringify(this.accountFollowingsMap) JSON.stringify(this.accountFollowListEventMap)
) )
window.localStorage.setItem( window.localStorage.setItem(
StorageKey.ACCOUNT_RELAY_LIST_MAP, StorageKey.ACCOUNT_RELAY_LIST_EVENT_MAP,
JSON.stringify(this.accountRelayListMap) JSON.stringify(this.accountRelayListEventMap)
) )
window.localStorage.setItem( window.localStorage.setItem(
StorageKey.ACCOUNT_PROFILE_MAP, StorageKey.ACCOUNT_PROFILE_EVENT_MAP,
JSON.stringify(this.accountProfileMap) JSON.stringify(this.accountProfileEventMap)
) )
} }
@@ -185,40 +191,64 @@ class StorageService {
window.localStorage.setItem(StorageKey.CURRENT_ACCOUNT, JSON.stringify(act)) window.localStorage.setItem(StorageKey.CURRENT_ACCOUNT, JSON.stringify(act))
} }
getAccountRelayList(pubkey: string) { getAccountRelayListEvent(pubkey: string) {
return this.accountRelayListMap[pubkey] return this.accountRelayListEventMap[pubkey]
} }
setAccountRelayList(pubkey: string, relayList: TRelayList) { setAccountRelayListEvent(relayListEvent: Event) {
this.accountRelayListMap[pubkey] = relayList const pubkey = relayListEvent.pubkey
if (
this.accountRelayListEventMap[pubkey] &&
this.accountRelayListEventMap[pubkey].created_at > relayListEvent.created_at
) {
return false
}
this.accountRelayListEventMap[pubkey] = relayListEvent
window.localStorage.setItem( window.localStorage.setItem(
StorageKey.ACCOUNT_RELAY_LIST_MAP, StorageKey.ACCOUNT_RELAY_LIST_EVENT_MAP,
JSON.stringify(this.accountRelayListMap) JSON.stringify(this.accountRelayListEventMap)
) )
return true
} }
getAccountFollowings(pubkey: string) { getAccountFollowListEvent(pubkey: string) {
return this.accountFollowingsMap[pubkey] return this.accountFollowListEventMap[pubkey]
} }
setAccountFollowings(pubkey: string, followings: string[]) { setAccountFollowListEvent(followListEvent: Event) {
this.accountFollowingsMap[pubkey] = followings const pubkey = followListEvent.pubkey
if (
this.accountFollowListEventMap[pubkey] &&
this.accountFollowListEventMap[pubkey].created_at > followListEvent.created_at
) {
return false
}
this.accountFollowListEventMap[pubkey] = followListEvent
window.localStorage.setItem( window.localStorage.setItem(
StorageKey.ACCOUNT_FOLLOWINGS_MAP, StorageKey.ACCOUNT_FOLLOW_LIST_EVENT_MAP,
JSON.stringify(this.accountFollowingsMap) JSON.stringify(this.accountFollowListEventMap)
) )
return true
} }
getAccountProfile(pubkey: string) { getAccountProfileEvent(pubkey: string) {
return this.accountProfileMap[pubkey] return this.accountProfileEventMap[pubkey]
} }
setAccountProfile(pubkey: string, profile: TProfile) { setAccountProfileEvent(profileEvent: Event) {
this.accountProfileMap[pubkey] = profile const pubkey = profileEvent.pubkey
if (
this.accountProfileEventMap[pubkey] &&
this.accountProfileEventMap[pubkey].created_at > profileEvent.created_at
) {
return false
}
this.accountProfileEventMap[pubkey] = profileEvent
window.localStorage.setItem( window.localStorage.setItem(
StorageKey.ACCOUNT_PROFILE_MAP, StorageKey.ACCOUNT_PROFILE_EVENT_MAP,
JSON.stringify(this.accountProfileMap) JSON.stringify(this.accountProfileEventMap)
) )
return true
} }
} }