5 Commits

Author SHA1 Message Date
woikos
158f3d77d3 Bump version to v0.3.0
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 10:55:53 +01:00
woikos
f54c73f0eb Update og:image to use smesh branding
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 17:11:14 +01:00
woikos
1d58162890 Release v0.2.5
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 17:07:38 +01:00
woikos
9820a1c6c0 Move DM conversations to secondary panel with improvements
- Open DM conversations in secondary panel (dual-pane) or overlay (mobile)
- Add relay selection toggles in message composer
- Add background DM subscriptions for real-time updates
- Add close buttons on conversation items and message view header
- Replace conversation view instead of stacking when switching

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 17:04:30 +01:00
woikos
ad5f9cccf9 Fix refresh to merge data instead of wiping cache
- Remove clearAllDMCaches() call from manual refresh
- Merge new conversations with existing instead of replacing
- Cache clearing now only happens on logout

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 13:35:29 +01:00
12 changed files with 293 additions and 75 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "smesh", "name": "smesh",
"version": "0.2.4", "version": "0.3.0",
"description": "A user-friendly Nostr client for exploring relay feeds", "description": "A user-friendly Nostr client for exploring relay feeds",
"private": true, "private": true,
"type": "module", "type": "module",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

@@ -3,7 +3,7 @@ import { formatTimestamp } from '@/lib/timestamp'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import client from '@/services/client.service' import client from '@/services/client.service'
import { TConversation, TProfile } from '@/types' import { TConversation, TProfile } from '@/types'
import { Lock, Users } from 'lucide-react' import { Lock, Users, X } from 'lucide-react'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
interface ConversationItemProps { interface ConversationItemProps {
@@ -11,13 +11,15 @@ interface ConversationItemProps {
isActive: boolean isActive: boolean
isFollowing: boolean isFollowing: boolean
onClick: () => void onClick: () => void
onClose?: () => void
} }
export default function ConversationItem({ export default function ConversationItem({
conversation, conversation,
isActive, isActive,
isFollowing, isFollowing,
onClick onClick,
onClose
}: ConversationItemProps) { }: ConversationItemProps) {
const [profile, setProfile] = useState<TProfile | null>(null) const [profile, setProfile] = useState<TProfile | null>(null)
@@ -58,7 +60,21 @@ export default function ConversationItem({
</span> </span>
)} )}
</div> </div>
<span className="text-xs text-muted-foreground flex-shrink-0">{formattedTime}</span> <div className="flex items-center gap-1 flex-shrink-0">
<span className="text-xs text-muted-foreground">{formattedTime}</span>
{isActive && onClose && (
<button
onClick={(e) => {
e.stopPropagation()
onClose()
}}
className="p-0.5 rounded hover:bg-muted-foreground/20 transition-colors"
title="Close conversation"
>
<X className="size-4 text-muted-foreground" />
</button>
)}
</div>
</div> </div>
<div className="flex items-center gap-1.5 mt-0.5"> <div className="flex items-center gap-1.5 mt-0.5">

View File

@@ -1,3 +1,5 @@
import { toDMConversation } from '@/lib/link'
import { useSecondaryPage } from '@/PageManager'
import { useDM } from '@/providers/DMProvider' import { useDM } from '@/providers/DMProvider'
import { useFollowList } from '@/providers/FollowListProvider' import { useFollowList } from '@/providers/FollowListProvider'
import { useMuteList } from '@/providers/MuteListProvider' import { useMuteList } from '@/providers/MuteListProvider'
@@ -17,6 +19,7 @@ import ConversationItem from './ConversationItem'
export default function ConversationList() { export default function ConversationList() {
const { t } = useTranslation() const { t } = useTranslation()
const { push, pop } = useSecondaryPage()
const { const {
conversations, conversations,
currentConversation, currentConversation,
@@ -128,7 +131,17 @@ export default function ConversationList() {
conversation={conversation} conversation={conversation}
isActive={currentConversation === conversation.partnerPubkey} isActive={currentConversation === conversation.partnerPubkey}
isFollowing={followingSet.has(conversation.partnerPubkey)} isFollowing={followingSet.has(conversation.partnerPubkey)}
onClick={() => selectConversation(conversation.partnerPubkey)} onClick={() => {
// If already viewing a different conversation, pop first to replace
if (currentConversation && currentConversation !== conversation.partnerPubkey) {
pop()
}
push(toDMConversation(conversation.partnerPubkey))
}}
onClose={() => {
selectConversation(null)
pop()
}}
/> />
))} ))}
{/* Sentinel element for infinite scroll */} {/* Sentinel element for infinite scroll */}

View File

@@ -1,27 +1,14 @@
import { useDM } from '@/providers/DMProvider' import { useDM } from '@/providers/DMProvider'
import { Loader2, RefreshCw } from 'lucide-react' import { Loader2, RefreshCw } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import ConversationList from './ConversationList' import ConversationList from './ConversationList'
import MessageView from './MessageView'
import { Button } from '../ui/button' import { Button } from '../ui/button'
export default function InboxContent() { export default function InboxContent() {
const { t } = useTranslation() const { t } = useTranslation()
const { isLoading, error, refreshConversations, currentConversation, selectConversation } = const { isLoading, error, refreshConversations } = useDM()
useDM()
const [isMobileView, setIsMobileView] = useState(false)
useEffect(() => { if (isLoading) {
const checkMobile = () => {
setIsMobileView(window.innerWidth < 768)
}
checkMobile()
window.addEventListener('resize', checkMobile)
return () => window.removeEventListener('resize', checkMobile)
}, [])
if (isLoading && !currentConversation) {
return ( return (
<div className="flex items-center justify-center h-64"> <div className="flex items-center justify-center h-64">
<div className="flex flex-col items-center gap-2 text-muted-foreground"> <div className="flex flex-col items-center gap-2 text-muted-foreground">
@@ -44,37 +31,10 @@ export default function InboxContent() {
) )
} }
// Mobile view: show either list or conversation // Conversations list - clicking opens in secondary panel (or overlay on mobile)
if (isMobileView) {
if (currentConversation) {
return (
<div className="h-[calc(100vh-8rem)]">
<MessageView onBack={() => selectConversation(null)} />
</div>
)
}
return (
<div className="h-[calc(100vh-8rem)]">
<ConversationList />
</div>
)
}
// Desktop view: split pane
return ( return (
<div className="flex h-[calc(100vh-8rem)]"> <div className="h-[calc(100vh-8rem)]">
<div className="w-80 border-r flex-shrink-0 overflow-hidden"> <ConversationList />
<ConversationList />
</div>
<div className="flex-1 overflow-hidden">
{currentConversation ? (
<MessageView />
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
<p>{t('Select a conversation to view messages')}</p>
</div>
)}
</div>
</div> </div>
) )
} }

View File

@@ -1,6 +1,8 @@
import { cn } from '@/lib/utils'
import { useDM } from '@/providers/DMProvider' import { useDM } from '@/providers/DMProvider'
import { AlertCircle, Loader2, Send } from 'lucide-react' import { useNostr } from '@/providers/NostrProvider'
import { useRef, useState } from 'react' import { AlertCircle, ChevronDown, ChevronUp, Loader2, Send } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Button } from '../ui/button' import { Button } from '../ui/button'
import { Textarea } from '../ui/textarea' import { Textarea } from '../ui/textarea'
@@ -8,18 +10,47 @@ import { Textarea } from '../ui/textarea'
export default function MessageComposer() { export default function MessageComposer() {
const { t } = useTranslation() const { t } = useTranslation()
const { sendMessage, currentConversation } = useDM() const { sendMessage, currentConversation } = useDM()
const { relayList } = useNostr()
const [message, setMessage] = useState('') const [message, setMessage] = useState('')
const [isSending, setIsSending] = useState(false) const [isSending, setIsSending] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [showRelays, setShowRelays] = useState(false)
const [selectedRelays, setSelectedRelays] = useState<Set<string>>(new Set())
const textareaRef = useRef<HTMLTextAreaElement>(null) const textareaRef = useRef<HTMLTextAreaElement>(null)
// Get user's write relays
const writeRelays = useMemo(() => relayList?.write || [], [relayList])
// Initialize selected relays when write relays change
useEffect(() => {
if (writeRelays.length > 0 && selectedRelays.size === 0) {
setSelectedRelays(new Set(writeRelays))
}
}, [writeRelays])
const toggleRelay = (url: string) => {
setSelectedRelays((prev) => {
const next = new Set(prev)
if (next.has(url)) {
// Don't allow deselecting all relays
if (next.size > 1) {
next.delete(url)
}
} else {
next.add(url)
}
return next
})
}
const handleSend = async () => { const handleSend = async () => {
if (!message.trim() || !currentConversation || isSending) return if (!message.trim() || !currentConversation || isSending) return
setIsSending(true) setIsSending(true)
setError(null) setError(null)
try { try {
await sendMessage(message.trim()) const relaysToUse = Array.from(selectedRelays)
await sendMessage(message.trim(), relaysToUse.length > 0 ? relaysToUse : undefined)
setMessage('') setMessage('')
// Return focus to input after sending // Return focus to input after sending
textareaRef.current?.focus() textareaRef.current?.focus()
@@ -38,6 +69,11 @@ export default function MessageComposer() {
} }
} }
// Format relay URL for display
const formatRelayUrl = (url: string) => {
return url.replace(/^wss?:\/\//, '').replace(/\/$/, '')
}
return ( return (
<div className="p-3 space-y-2"> <div className="p-3 space-y-2">
{error && ( {error && (
@@ -46,6 +82,41 @@ export default function MessageComposer() {
<span>{error}</span> <span>{error}</span>
</div> </div>
)} )}
{/* Relay selector */}
{writeRelays.length > 0 && (
<div className="space-y-1">
<button
onClick={() => setShowRelays(!showRelays)}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{showRelays ? <ChevronUp className="size-3" /> : <ChevronDown className="size-3" />}
<span>
{t('Relays')} ({selectedRelays.size}/{writeRelays.length})
</span>
</button>
{showRelays && (
<div className="flex flex-wrap gap-1">
{writeRelays.map((url) => (
<button
key={url}
onClick={() => toggleRelay(url)}
className={cn(
'text-xs px-2 py-0.5 rounded-full border transition-colors',
selectedRelays.has(url)
? 'bg-primary text-primary-foreground border-primary'
: 'bg-muted text-muted-foreground border-muted hover:border-primary/50'
)}
title={url}
>
{formatRelayUrl(url)}
</button>
))}
</div>
)}
</div>
)}
<div className="flex items-end gap-2"> <div className="flex items-end gap-2">
<Textarea <Textarea
ref={textareaRef} ref={textareaRef}

View File

@@ -6,7 +6,7 @@ import { useNostr } from '@/providers/NostrProvider'
import client from '@/services/client.service' import client from '@/services/client.service'
import indexedDb from '@/services/indexed-db.service' import indexedDb from '@/services/indexed-db.service'
import { TDirectMessage, TProfile } from '@/types' import { TDirectMessage, TProfile } from '@/types'
import { ArrowLeft, ChevronDown, ChevronUp, Loader2, MoreVertical, RefreshCw, Settings, Trash2, Undo2, Users, X } from 'lucide-react' import { ChevronDown, ChevronUp, Loader2, MoreVertical, RefreshCw, Settings, Trash2, Undo2, Users, X } from 'lucide-react'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Button } from '../ui/button' import { Button } from '../ui/button'
@@ -232,11 +232,6 @@ export default function MessageView({ onBack }: MessageViewProps) {
) : ( ) : (
// Normal header // Normal header
<> <>
{onBack && (
<Button variant="ghost" size="icon" onClick={onBack} className="size-8">
<ArrowLeft className="size-4" />
</Button>
)}
<UserAvatar userId={currentConversation} className="size-8" /> <UserAvatar userId={currentConversation} className="size-8" />
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
@@ -291,6 +286,17 @@ export default function MessageView({ onBack }: MessageViewProps) {
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
{onBack && (
<Button
variant="ghost"
size="icon"
className="size-8"
title={t('Close conversation')}
onClick={onBack}
>
<X className="size-4" />
</Button>
)}
</> </>
)} )}
</div> </div>

View File

@@ -92,3 +92,7 @@ export const toUserAggregationDetail = (feedId: string, pubkey: string) => {
} }
export const toLogin = () => '/login' export const toLogin = () => '/login'
export const toLogout = () => '/logout' export const toLogout = () => '/logout'
export const toDMConversation = (pubkey: string) => {
const npub = pubkey.startsWith('npub') ? pubkey : nip19.npubEncode(pubkey)
return `/dm/${npub}`
}

View File

@@ -0,0 +1,66 @@
import MessageView from '@/components/Inbox/MessageView'
import SecondaryPageLayout from '@/layouts/SecondaryPageLayout'
import { useSecondaryPage } from '@/PageManager'
import { useDM } from '@/providers/DMProvider'
import { TPageRef } from '@/types'
import { nip19 } from 'nostr-tools'
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
interface DMConversationPageProps {
pubkey?: string
index?: number
}
const DMConversationPage = forwardRef<TPageRef, DMConversationPageProps>(({ pubkey, index }, ref) => {
const { t } = useTranslation()
const layoutRef = useRef<TPageRef>(null)
const { selectConversation, currentConversation } = useDM()
const { pop } = useSecondaryPage()
// Decode npub to hex if needed
const hexPubkey = useMemo(() => {
if (!pubkey) return null
if (pubkey.startsWith('npub')) {
try {
const decoded = nip19.decode(pubkey)
return decoded.type === 'npub' ? decoded.data : null
} catch {
return null
}
}
return pubkey
}, [pubkey])
useImperativeHandle(ref, () => layoutRef.current as TPageRef)
// Select the conversation when this page mounts
useEffect(() => {
if (hexPubkey && hexPubkey !== currentConversation) {
selectConversation(hexPubkey)
}
}, [hexPubkey, selectConversation, currentConversation])
// Clear conversation when page unmounts
useEffect(() => {
return () => {
selectConversation(null)
}
}, [])
const handleBack = () => {
selectConversation(null)
pop()
}
return (
<SecondaryPageLayout ref={layoutRef} index={index} title={t('Conversation')}>
<div className="h-full">
<MessageView onBack={handleBack} />
</div>
</SecondaryPageLayout>
)
})
DMConversationPage.displayName = 'DMConversationPage'
export default DMConversationPage

View File

@@ -24,7 +24,7 @@ type TDMContext = {
error: string | null error: string | null
selectConversation: (partnerPubkey: string | null) => void selectConversation: (partnerPubkey: string | null) => void
startConversation: (partnerPubkey: string) => void startConversation: (partnerPubkey: string) => void
sendMessage: (content: string) => Promise<void> sendMessage: (content: string, customRelayUrls?: string[]) => Promise<void>
refreshConversations: () => Promise<void> refreshConversations: () => Promise<void>
reloadConversation: () => void reloadConversation: () => void
loadMoreConversations: () => Promise<void> loadMoreConversations: () => Promise<void>
@@ -98,6 +98,10 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
// Track if we've already initialized to avoid reloading on navigation // Track if we've already initialized to avoid reloading on navigation
const hasInitializedRef = useRef(false) const hasInitializedRef = useRef(false)
const lastPubkeyRef = useRef<string | null>(null) const lastPubkeyRef = useRef<string | null>(null)
// Background subscription for real-time DM updates
const dmSubscriptionRef = useRef<{ close: () => void } | null>(null)
// Track newest message timestamp from subscription (to update hasNewMessages)
const [newestIncomingTimestamp, setNewestIncomingTimestamp] = useState(0)
// Create encryption wrapper object for dm.service // Create encryption wrapper object for dm.service
const encryption: IDMEncryption | null = useMemo(() => { const encryption: IDMEncryption | null = useMemo(() => {
@@ -180,6 +184,16 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
// Step 4: Background refresh from network (don't clear existing data) // Step 4: Background refresh from network (don't clear existing data)
backgroundRefreshConversations() backgroundRefreshConversations()
// Step 5: Start real-time subscription for new DMs
if (dmSubscriptionRef.current) {
dmSubscriptionRef.current.close()
}
const relayUrls = relayList?.read || []
dmSubscriptionRef.current = dmService.subscribeToDMs(pubkey, relayUrls, (event) => {
// New DM event received - update timestamp to trigger hasNewMessages
setNewestIncomingTimestamp(event.created_at)
})
} }
loadDeletedStateAndConversations() loadDeletedStateAndConversations()
@@ -196,11 +210,16 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
setIsSelectionMode(false) setIsSelectionMode(false)
// Clear in-memory plaintext cache // Clear in-memory plaintext cache
clearPlaintextCache() clearPlaintextCache()
// Stop DM subscription
if (dmSubscriptionRef.current) {
dmSubscriptionRef.current.close()
dmSubscriptionRef.current = null
}
// Reset initialization flag so we reload on next login // Reset initialization flag so we reload on next login
hasInitializedRef.current = false hasInitializedRef.current = false
lastPubkeyRef.current = null lastPubkeyRef.current = null
} }
}, [pubkey, encryption]) }, [pubkey, encryption, relayList])
// Load full conversation when selected // Load full conversation when selected
useEffect(() => { useEffect(() => {
@@ -428,7 +447,7 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
} }
}, [pubkey, encryption, relayList, deletedState, allConversations]) }, [pubkey, encryption, relayList, deletedState, allConversations])
// Full refresh - clears caches and reloads everything (manual action) // Full refresh - fetches fresh data from network (manual action)
const refreshConversations = useCallback(async () => { const refreshConversations = useCallback(async () => {
if (!pubkey || !encryption) return if (!pubkey || !encryption) return
@@ -436,11 +455,6 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
setError(null) setError(null)
try { try {
// Clear caches for fresh start (only on manual refresh)
await indexedDb.clearAllDMCaches()
setConversationMessages(new Map())
setLoadedConversations(new Set())
// Get relay URLs // Get relay URLs
const relayUrls = relayList?.read || [] const relayUrls = relayList?.read || []
@@ -451,8 +465,18 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
const nip04Events = events.filter((e) => e.kind === 4) const nip04Events = events.filter((e) => e.kind === 4)
const giftWraps = events.filter((e) => e.kind === 1059) const giftWraps = events.filter((e) => e.kind === 1059)
// Build conversation list from NIP-04 events immediately (no decryption needed) // Build conversation map from existing conversations (merge, don't replace)
const conversationMap = dmService.groupEventsIntoConversations(nip04Events, pubkey) const conversationMap = new Map<string, TConversation>()
allConversations.forEach((c) => conversationMap.set(c.partnerPubkey, c))
// Add NIP-04 conversations
const nip04Convs = dmService.groupEventsIntoConversations(nip04Events, pubkey)
nip04Convs.forEach((conv, key) => {
const existing = conversationMap.get(key)
if (!existing || conv.lastMessageAt > existing.lastMessageAt) {
conversationMap.set(key, conv)
}
})
// Show NIP-04 conversations immediately (filtered by deleted state) // Show NIP-04 conversations immediately (filtered by deleted state)
const updateAndShowConversations = () => { const updateAndShowConversations = () => {
@@ -530,7 +554,7 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
setError('Failed to load conversations') setError('Failed to load conversations')
setIsLoading(false) setIsLoading(false)
} }
}, [pubkey, encryption, relayList, deletedState]) }, [pubkey, encryption, relayList, deletedState, allConversations])
const loadMoreConversations = useCallback(async () => { const loadMoreConversations = useCallback(async () => {
if (!hasMoreConversations) return if (!hasMoreConversations) return
@@ -593,12 +617,15 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
}, [currentConversation]) }, [currentConversation])
const sendMessage = useCallback( const sendMessage = useCallback(
async (content: string) => { async (content: string, customRelayUrls?: string[]) => {
if (!pubkey || !encryption || !currentConversation) { if (!pubkey || !encryption || !currentConversation) {
throw new Error('Cannot send message: not logged in or no conversation selected') throw new Error('Cannot send message: not logged in or no conversation selected')
} }
const relayUrls = relayList?.write || [] // Use custom relays if provided, otherwise fall back to user's write relays
const relayUrls = customRelayUrls && customRelayUrls.length > 0
? customRelayUrls
: (relayList?.write || [])
// Find existing encryption type for this conversation // Find existing encryption type for this conversation
const conversation = conversations.find((c) => c.partnerPubkey === currentConversation) const conversation = conversations.find((c) => c.partnerPubkey === currentConversation)
@@ -862,9 +889,12 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
// Check if there are new messages since last seen // Check if there are new messages since last seen
const newestMessageTimestamp = useMemo(() => { const newestMessageTimestamp = useMemo(() => {
if (filteredConversations.length === 0) return 0 const fromConversations = filteredConversations.length === 0
return Math.max(...filteredConversations.map((c) => c.lastMessageAt)) ? 0
}, [filteredConversations]) : Math.max(...filteredConversations.map((c) => c.lastMessageAt))
// Also consider real-time incoming messages
return Math.max(fromConversations, newestIncomingTimestamp)
}, [filteredConversations, newestIncomingTimestamp])
const hasNewMessages = newestMessageTimestamp > lastSeenTimestamp const hasNewMessages = newestMessageTimestamp > lastSeenTimestamp
@@ -873,6 +903,8 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
if (!pubkey || newestMessageTimestamp === 0) return if (!pubkey || newestMessageTimestamp === 0) return
setLastSeenTimestamp(newestMessageTimestamp) setLastSeenTimestamp(newestMessageTimestamp)
storage.setDMLastSeenTimestamp(pubkey, newestMessageTimestamp) storage.setDMLastSeenTimestamp(pubkey, newestMessageTimestamp)
// Reset incoming timestamp so indicator clears
setNewestIncomingTimestamp(0)
}, [pubkey, newestMessageTimestamp]) }, [pubkey, newestMessageTimestamp])
return ( return (

View File

@@ -1,5 +1,6 @@
import AppearanceSettingsPage from '@/pages/secondary/AppearanceSettingsPage' import AppearanceSettingsPage from '@/pages/secondary/AppearanceSettingsPage'
import BookmarkPage from '@/pages/secondary/BookmarkPage' import BookmarkPage from '@/pages/secondary/BookmarkPage'
import DMConversationPage from '@/pages/secondary/DMConversationPage'
import EmojiPackSettingsPage from '@/pages/secondary/EmojiPackSettingsPage' import EmojiPackSettingsPage from '@/pages/secondary/EmojiPackSettingsPage'
import ExternalContentPage from '@/pages/secondary/ExternalContentPage' import ExternalContentPage from '@/pages/secondary/ExternalContentPage'
import FollowingListPage from '@/pages/secondary/FollowingListPage' import FollowingListPage from '@/pages/secondary/FollowingListPage'
@@ -53,6 +54,7 @@ const SECONDARY_ROUTE_CONFIGS = [
{ path: '/mutes', element: <MuteListPage /> }, { path: '/mutes', element: <MuteListPage /> },
{ path: '/rizful', element: <RizfulPage /> }, { path: '/rizful', element: <RizfulPage /> },
{ path: '/bookmarks', element: <BookmarkPage /> }, { path: '/bookmarks', element: <BookmarkPage /> },
{ path: '/dm/:pubkey', element: <DMConversationPage /> },
{ path: '/follow-packs/:id', element: <FollowPackPage /> }, { path: '/follow-packs/:id', element: <FollowPackPage /> },
{ path: '/user-aggregation/:feedId/:npub', element: <UserAggregationDetailPage /> } { path: '/user-aggregation/:feedId/:npub', element: <UserAggregationDetailPage /> }
] ]

View File

@@ -877,6 +877,54 @@ class DMService {
const pTag = tags.find((t) => t[0] === 'p') const pTag = tags.find((t) => t[0] === 'p')
return pTag ? pTag[1] : null return pTag ? pTag[1] : null
} }
/**
* Subscribe to incoming DMs in real-time
* Returns a close function to stop the subscription
*/
subscribeToDMs(
pubkey: string,
relayUrls: string[],
onEvent: (event: Event) => void
): { close: () => void } {
const allRelays = [...new Set([...relayUrls, ...BIG_RELAY_URLS])]
const since = Math.floor(Date.now() / 1000) - 60 // Start from 1 minute ago to catch recent
// Subscribe to NIP-04 DMs (kind 4) addressed to user
const nip04Sub = client.subscribe(
allRelays,
[
{ kinds: [KIND_ENCRYPTED_DM], '#p': [pubkey], since },
{ kinds: [KIND_ENCRYPTED_DM], authors: [pubkey], since }
],
{
onevent: (event) => {
indexedDb.putDMEvent(event).catch(() => {})
onEvent(event)
}
}
)
// Subscribe to NIP-17 gift wraps (kind 1059) addressed to user
const giftWrapSub = client.subscribe(
allRelays,
{ kinds: [KIND_GIFT_WRAP], '#p': [pubkey], since },
{
onevent: (event) => {
indexedDb.putDMEvent(event).catch(() => {})
onEvent(event)
}
}
)
return {
close: async () => {
const [nip04, giftWrap] = await Promise.all([nip04Sub, giftWrapSub])
nip04.close()
giftWrap.close()
}
}
}
} }
const dmService = new DMService() const dmService = new DMService()