92 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-11-06 17:33:15 +01:00
import { NDKFilter, NDKKind } from '@nostr-dev-kit/ndk'
import { NDKContextType } from 'contexts/NDKContext'
import { nip19 } from 'nostr-tools'
import { LoaderFunctionArgs, redirect } from 'react-router-dom'
import { appRoutes, getProfilePageRoute } from 'routes'
import { store } from 'store'
import { UserProfile, UserRelaysType } from 'types'
import { log, LogType } from 'utils'
export interface ProfilePageLoaderResult {
profile: UserProfile
isBlocked: boolean
isOwnProfile: boolean
}
export const profileRouteLoader =
(ndkContext: NDKContextType) =>
async ({ params }: LoaderFunctionArgs) => {
let profileRoute = appRoutes.home
// Try to decode nprofile parameter
const { nprofile } = params
let profilePubkey: string | undefined
try {
const value = nprofile
? nip19.decode(nprofile as `nprofile1${string}`)
: undefined
profilePubkey = value?.data.pubkey
} catch (error) {
// Silently ignore and redirect to home or logged in user
log(true, LogType.Error, 'Failed to decode nprofile.', error)
}
// Get the current state
const userState = store.getState().user
// Redirect route
// Redirect home if user is not logged in or profile naddr is missing
if (!profilePubkey && userState.auth && userState.user?.pubkey) {
// Redirect to user's profile is no profile is linked
const userHexKey = userState.user.pubkey as string
if (userHexKey) {
profileRoute = getProfilePageRoute(
nip19.nprofileEncode({
pubkey: userHexKey
})
)
}
}
if (!profilePubkey) return redirect(profileRoute)
const result: ProfilePageLoaderResult = {
profile: {},
isBlocked: false,
isOwnProfile: false
}
result.profile = await ndkContext.findMetadata(profilePubkey)
// Check if user the user is logged in
if (userState.auth && userState.user?.pubkey) {
result.isOwnProfile = userState.user.pubkey === profilePubkey
const userHexKey = userState.user.pubkey as string
// Check if user has blocked this profile
const muteListFilter: NDKFilter = {
kinds: [NDKKind.MuteList],
authors: [userHexKey]
}
const muteList = await ndkContext.fetchEventFromUserRelays(
muteListFilter,
userHexKey,
UserRelaysType.Write
)
if (muteList) {
// get a list of tags
const tags = muteList.tags
const blocked =
tags.findIndex(
(item) => item[0] === 'p' && item[1] === profilePubkey
) !== -1
result.isBlocked = blocked
}
}
return result
}