feat: support sending only to current relays

This commit is contained in:
codytseng
2025-02-05 15:18:58 +08:00
parent 29f5ccc4bb
commit ccf8c21954
11 changed files with 199 additions and 75 deletions

View File

@@ -6,8 +6,8 @@ import client from '@/services/client.service'
import { Heart, Loader } from 'lucide-react'
import { Event } from 'nostr-tools'
import { useEffect, useMemo, useState } from 'react'
import { formatCount } from './utils'
import { useTranslation } from 'react-i18next'
import { formatCount } from './utils'
export default function LikeButton({
event,
@@ -56,7 +56,7 @@ export default function LikeButton({
const targetRelayList = await client.fetchRelayList(event.pubkey)
const reaction = createReactionDraftEvent(event)
await publish(reaction, targetRelayList.read.slice(0, 3))
await publish(reaction, { additionalRelayUrls: targetRelayList.read.slice(0, 3) })
markNoteAsLiked(event.id)
} catch (error) {
console.error('like failed', error)

View File

@@ -64,7 +64,7 @@ export default function RepostButton({
const targetRelayList = await client.fetchRelayList(event.pubkey)
const repost = createRepostDraftEvent(event)
await publish(repost, targetRelayList.read.slice(0, 5))
await publish(repost, { additionalRelayUrls: targetRelayList.read.slice(0, 5) })
markNoteAsReposted(event.id)
} catch (error) {
console.error('repost failed', error)

View File

@@ -1,18 +1,18 @@
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { StorageKey } from '@/constants'
import { useToast } from '@/hooks/use-toast'
import { createCommentDraftEvent, createShortTextNoteDraftEvent } from '@/lib/draft-event'
import { useFeed } from '@/providers/FeedProvider.tsx'
import { useNostr } from '@/providers/NostrProvider'
import client from '@/services/client.service'
import { ChevronDown, ImageUp, LoaderCircle } from 'lucide-react'
import { Event, kinds } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import TextareaWithMentions from '../TextareaWithMentions.tsx'
import Mentions from './Mentions'
import PostOptions from './PostOptions.tsx'
import Preview from './Preview'
import { TPostOptions } from './types.ts'
import Uploader from './Uploader'
export default function NormalPostContent({
@@ -27,18 +27,15 @@ export default function NormalPostContent({
const { t } = useTranslation()
const { toast } = useToast()
const { publish, checkLogin } = useNostr()
const { relayUrls } = useFeed()
const [content, setContent] = useState(defaultContent)
const [pictureInfos, setPictureInfos] = useState<{ url: string; tags: string[][] }[]>([])
const [posting, setPosting] = useState(false)
const [showMoreOptions, setShowMoreOptions] = useState(false)
const [addClientTag, setAddClientTag] = useState(false)
const [postOptions, setPostOptions] = useState<TPostOptions>({})
const [uploadingPicture, setUploadingPicture] = useState(false)
const canPost = !!content && !posting
useEffect(() => {
setAddClientTag(window.localStorage.getItem(StorageKey.ADD_CLIENT_TAG) === 'true')
}, [])
const post = async (e: React.MouseEvent) => {
e.stopPropagation()
checkLogin(async () => {
@@ -54,14 +51,26 @@ export default function NormalPostContent({
const relayList = await client.fetchRelayList(parentEvent.pubkey)
additionalRelayUrls.push(...relayList.read.slice(0, 5))
}
let protectedEvent = false
if (postOptions.sendOnlyToCurrentRelays) {
const relayInfos = await client.fetchRelayInfos(relayUrls)
protectedEvent = relayInfos.every((info) => info?.supported_nips?.includes(70))
}
const draftEvent =
parentEvent && parentEvent.kind !== kinds.ShortTextNote
? await createCommentDraftEvent(content, parentEvent, pictureInfos, { addClientTag })
? await createCommentDraftEvent(content, parentEvent, pictureInfos, {
addClientTag: postOptions.addClientTag,
protectedEvent
})
: await createShortTextNoteDraftEvent(content, pictureInfos, {
parentEvent,
addClientTag
addClientTag: postOptions.addClientTag,
protectedEvent
})
await publish(draftEvent, additionalRelayUrls)
await publish(draftEvent, {
additionalRelayUrls,
specifiedRelayUrls: postOptions.sendOnlyToCurrentRelays ? relayUrls : undefined
})
setContent('')
close()
} catch (error) {
@@ -92,11 +101,6 @@ export default function NormalPostContent({
})
}
const onAddClientTagChange = (checked: boolean) => {
setAddClientTag(checked)
window.localStorage.setItem(StorageKey.ADD_CLIENT_TAG, checked.toString())
}
return (
<div className="space-y-4">
<TextareaWithMentions
@@ -150,21 +154,11 @@ export default function NormalPostContent({
</div>
</div>
</div>
{showMoreOptions && (
<div className="space-y-2">
<div className="flex items-center space-x-2">
<Label htmlFor="add-client-tag">{t('Add client tag')}</Label>
<Switch
id="add-client-tag"
checked={addClientTag}
onCheckedChange={onAddClientTagChange}
/>
</div>
<div className="text-muted-foreground text-xs">
{t('Show others this was sent via Jumble')}
</div>
</div>
)}
<PostOptions
show={showMoreOptions}
postOptions={postOptions}
setPostOptions={setPostOptions}
/>
<div className="flex gap-2 items-center justify-around sm:hidden">
<Button
className="w-full"

View File

@@ -1,34 +1,32 @@
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { StorageKey } from '@/constants'
import { useToast } from '@/hooks/use-toast'
import { createPictureNoteDraftEvent } from '@/lib/draft-event'
import { cn } from '@/lib/utils'
import { useFeed } from '@/providers/FeedProvider.tsx'
import { useNostr } from '@/providers/NostrProvider'
import client from '@/services/client.service'
import { ChevronDown, Loader, LoaderCircle, Plus, X } from 'lucide-react'
import { Dispatch, SetStateAction, useEffect, useState } from 'react'
import { Dispatch, SetStateAction, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Image from '../Image'
import TextareaWithMentions from '../TextareaWithMentions.tsx'
import Mentions from './Mentions'
import PostOptions from './PostOptions.tsx'
import { TPostOptions } from './types.ts'
import Uploader from './Uploader'
export default function PicturePostContent({ close }: { close: () => void }) {
const { t } = useTranslation()
const { toast } = useToast()
const { publish, checkLogin } = useNostr()
const { relayUrls } = useFeed()
const [content, setContent] = useState('')
const [pictureInfos, setPictureInfos] = useState<{ url: string; tags: string[][] }[]>([])
const [posting, setPosting] = useState(false)
const [showMoreOptions, setShowMoreOptions] = useState(false)
const [addClientTag, setAddClientTag] = useState(false)
const [postOptions, setPostOptions] = useState<TPostOptions>({})
const canPost = !!content && !posting && pictureInfos.length > 0
useEffect(() => {
setAddClientTag(window.localStorage.getItem(StorageKey.ADD_CLIENT_TAG) === 'true')
}, [])
const post = async (e: React.MouseEvent) => {
e.stopPropagation()
checkLogin(async () => {
@@ -42,10 +40,18 @@ export default function PicturePostContent({ close }: { close: () => void }) {
if (!pictureInfos.length) {
throw new Error(t('Picture note requires images'))
}
let protectedEvent = false
if (postOptions.sendOnlyToCurrentRelays) {
const relayInfos = await client.fetchRelayInfos(relayUrls)
protectedEvent = relayInfos.every((info) => info?.supported_nips?.includes(70))
}
const draftEvent = await createPictureNoteDraftEvent(content, pictureInfos, {
addClientTag
addClientTag: postOptions.addClientTag,
protectedEvent
})
await publish(draftEvent, {
specifiedRelayUrls: postOptions.sendOnlyToCurrentRelays ? relayUrls : undefined
})
await publish(draftEvent)
setContent('')
close()
} catch (error) {
@@ -76,11 +82,6 @@ export default function PicturePostContent({ close }: { close: () => void }) {
})
}
const onAddClientTagChange = (checked: boolean) => {
setAddClientTag(checked)
window.localStorage.setItem(StorageKey.ADD_CLIENT_TAG, checked.toString())
}
return (
<div className="space-y-4">
<div className="text-xs text-muted-foreground">
@@ -121,21 +122,11 @@ export default function PicturePostContent({ close }: { close: () => void }) {
</div>
</div>
</div>
{showMoreOptions && (
<div className="space-y-2">
<div className="flex items-center space-x-2">
<Label htmlFor="add-client-tag">{t('Add client tag')}</Label>
<Switch
id="add-client-tag"
checked={addClientTag}
onCheckedChange={onAddClientTagChange}
/>
</div>
<div className="text-muted-foreground text-xs">
{t('Show others this was sent via Jumble')}
</div>
</div>
)}
<PostOptions
show={showMoreOptions}
postOptions={postOptions}
setPostOptions={setPostOptions}
/>
<div className="flex gap-2 items-center justify-around sm:hidden">
<Button
className="w-full"

View File

@@ -0,0 +1,82 @@
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Switch } from '@/components/ui/switch'
import { StorageKey } from '@/constants'
import { simplifyUrl } from '@/lib/url'
import { useFeed } from '@/providers/FeedProvider'
import { Info } from 'lucide-react'
import { Dispatch, SetStateAction, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { TPostOptions } from './types'
export default function PostOptions({
show,
postOptions,
setPostOptions
}: {
show: boolean
postOptions: TPostOptions
setPostOptions: Dispatch<SetStateAction<TPostOptions>>
}) {
const { t } = useTranslation()
const { relayUrls } = useFeed()
useEffect(() => {
setPostOptions({
addClientTag: window.localStorage.getItem(StorageKey.ADD_CLIENT_TAG) === 'true',
sendOnlyToCurrentRelays: false
})
}, [])
if (!show) return null
const onAddClientTagChange = (checked: boolean) => {
setPostOptions((prev) => ({ ...prev, addClientTag: checked }))
window.localStorage.setItem(StorageKey.ADD_CLIENT_TAG, checked.toString())
}
return (
<div className="space-y-2">
<div className="flex items-center space-x-2">
<Label htmlFor="add-client-tag">{t('Add client tag')}</Label>
<Switch
id="add-client-tag"
checked={postOptions.addClientTag}
onCheckedChange={onAddClientTagChange}
/>
</div>
<div className="text-muted-foreground text-xs">
{t('Show others this was sent via Jumble')}
</div>
<div className="flex items-center gap-2">
<div className="flex items-center gap-1">
<Label htmlFor="send-only-to-current-relays" className="truncate">
{relayUrls.length === 1
? t('Send only to r', { r: simplifyUrl(relayUrls[0]) })
: t('Send only to current relays')}
</Label>
{relayUrls.length > 1 && (
<Popover>
<PopoverTrigger>
<Info size={14} />
</PopoverTrigger>
<PopoverContent className="w-fit text-sm">
{relayUrls.map((url) => (
<div key={url}>{simplifyUrl(url)}</div>
))}
</PopoverContent>
</Popover>
)}
</div>
<Switch
className="shrink-0"
id="send-only-to-current-relays"
checked={postOptions.sendOnlyToCurrentRelays}
onCheckedChange={(checked) =>
setPostOptions((prev) => ({ ...prev, sendOnlyToCurrentRelays: checked }))
}
/>
</div>
</div>
)
}

View File

@@ -0,0 +1,4 @@
export type TPostOptions = {
addClientTag?: boolean
sendOnlyToCurrentRelays?: boolean
}

View File

@@ -162,6 +162,8 @@ export default {
'calculating...': 'calculating...',
'Calculate optimal read relays': 'Calculate optimal read relays',
'Login to set': 'Login to set',
'Please login to view following feed': 'Please login to view following feed'
'Please login to view following feed': 'Please login to view following feed',
'Send only to r': 'Send only to {{r}}',
'Send only to current relays': 'Send only to current relays'
}
}

View File

@@ -163,6 +163,8 @@ export default {
'calculating...': '计算中...',
'Calculate optimal read relays': '计算最佳读服务器',
'Login to set': '登录后设置',
'Please login to view following feed': '请登录以查看关注动态'
'Please login to view following feed': '请登录以查看关注动态',
'Send only to r': '只发送到 {{r}}',
'Send only to current relays': '只发送到当前服务器'
}
}

View File

@@ -51,6 +51,7 @@ export async function createShortTextNoteDraftEvent(
options: {
parentEvent?: Event
addClientTag?: boolean
protectedEvent?: boolean
} = {}
): Promise<TDraftEvent> {
const { pubkeys, otherRelatedEventIds, quoteEventIds, rootEventId, parentEventId } =
@@ -80,6 +81,10 @@ export async function createShortTextNoteDraftEvent(
tags.push(['client', 'jumble'])
}
if (options.protectedEvent) {
tags.push(['-'])
}
return {
kind: kinds.ShortTextNote,
content,
@@ -107,6 +112,7 @@ export async function createPictureNoteDraftEvent(
pictureInfos: { url: string; tags: string[][] }[],
options: {
addClientTag?: boolean
protectedEvent?: boolean
} = {}
): Promise<TDraftEvent> {
const { pubkeys, quoteEventIds } = await extractMentions(content)
@@ -125,6 +131,10 @@ export async function createPictureNoteDraftEvent(
tags.push(['client', 'jumble'])
}
if (options.protectedEvent) {
tags.push(['-'])
}
return {
kind: PICTURE_EVENT_KIND,
content,
@@ -139,6 +149,7 @@ export async function createCommentDraftEvent(
pictureInfos: { url: string; tags: string[][] }[],
options: {
addClientTag?: boolean
protectedEvent?: boolean
} = {}
): Promise<TDraftEvent> {
const {
@@ -174,6 +185,10 @@ export async function createCommentDraftEvent(
tags.push(['client', 'jumble'])
}
if (options.protectedEvent) {
tags.push(['-'])
}
return {
kind: COMMENT_EVENT_KIND,
content,

View File

@@ -7,7 +7,7 @@ import client from '@/services/client.service'
import storage from '@/services/storage.service'
import { ISigner, TAccount, TAccountPointer, TDraftEvent, TProfile, TRelayList } from '@/types'
import dayjs from 'dayjs'
import { Event, kinds } from 'nostr-tools'
import { Event, kinds, VerifiedEvent } from 'nostr-tools'
import * as nip19 from 'nostr-tools/nip19'
import * as nip49 from 'nostr-tools/nip49'
import { createContext, useContext, useEffect, useState } from 'react'
@@ -34,7 +34,10 @@ type TNostrContext = {
/**
* Default publish the event to current relays, user's write relays and additional relays
*/
publish: (draftEvent: TDraftEvent, additionalRelayUrls?: string[]) => Promise<Event>
publish: (
draftEvent: TDraftEvent,
options?: { additionalRelayUrls?: string[]; specifiedRelayUrls?: string[] }
) => Promise<Event>
signHttpAuth: (url: string, method: string) => Promise<string>
signEvent: (draftEvent: TDraftEvent) => Promise<Event>
nip04Encrypt: (pubkey: string, plainText: string) => Promise<string>
@@ -316,12 +319,26 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
if (!event) {
throw new Error('sign event failed')
}
return event
return event as VerifiedEvent
}
const publish = async (draftEvent: TDraftEvent, additionalRelayUrls: string[] = []) => {
const publish = async (
draftEvent: TDraftEvent,
{
additionalRelayUrls,
specifiedRelayUrls
}: { additionalRelayUrls?: string[]; specifiedRelayUrls?: string[] } = {}
) => {
const event = await signEvent(draftEvent)
await client.publishEvent((relayList?.write ?? []).concat(additionalRelayUrls), event)
await client.publishEvent(
specifiedRelayUrls?.length
? specifiedRelayUrls
: (relayList?.write ?? [])
.concat(additionalRelayUrls ?? [])
.concat(client.getDefaultRelayUrls()),
event,
{ signer: signEvent }
)
return event
}

View File

@@ -105,9 +105,26 @@ class ClientService extends EventTarget {
return this.defaultRelayUrls
}
async publishEvent(relayUrls: string[], event: NEvent) {
async publishEvent(
relayUrls: string[],
event: NEvent,
{
signer
}: {
signer?: (evt: TDraftEvent) => Promise<VerifiedEvent>
} = {}
) {
const result = await Promise.any(
this.pool.publish(relayUrls.concat(this.defaultRelayUrls), event)
relayUrls.map(async (url) => {
const relay = await this.pool.ensureRelay(url)
return relay.publish(event).catch((error) => {
if (error instanceof Error && error.message.startsWith('auth-required:') && signer) {
relay.auth((authEvt: EventTemplate) => signer(authEvt)).then(() => relay.publish(event))
} else {
throw error
}
})
})
)
this.dispatchEvent(new CustomEvent('eventPublished', { detail: event }))
return result