vector-core 0.3.0

Core library for Vector — the single source of truth for all Vector clients, SDKs, and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Flat Event Storage Module
//!
//! This module provides the generic event storage layer aligned with Nostr's protocol model.
//! All events (messages, reactions, attachments, etc.) are stored as flat rows in the database,
//! with relationships computed at query/render time.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ STORAGE LAYER (this module)                                    │
//! │ - Stores raw events as-is, including unknown types             │
//! │ - Schema: id, kind, content, tags, timestamp, pubkey, etc.     │
//! │ - Can sync/store events Vector doesn't understand yet          │
//! └─────────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │ PROCESSING LAYER (rumor.rs)                                    │
//! │ - Transforms raw events → typed structs                        │
//! │ - Unknown kind? → UnknownEvent (renders as placeholder)        │
//! │ - New event type = add enum variant + processing logic         │
//! └─────────────────────────────────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │ DISPLAY LAYER (message.rs - unchanged)                         │
//! │ - Message, Reaction, Attachment, etc.                          │
//! │ - Standardized interface for UI rendering                      │
//! │ - Materialized views: compose events → Message with reactions  │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Benefits
//!
//! - **Protocol alignment**: Matches Nostr's event-centric model
//! - **Future-proof**: Unknown event types are stored, not dropped
//! - **Easy extensibility**: New event types need no schema changes
//! - **Uniform storage**: DMs, community channels, and public events all stored the same way

use serde::{Deserialize, Serialize};

/// Nostr event kinds used in Vector
///
/// These are the standard Nostr kinds plus Vector-specific extensions.
/// Unknown kinds are stored but rendered as placeholders.
pub mod event_kind {
    /// Chat message text content (Kind 9). The internal storage kind for every
    /// text message — DMs and community channels alike.
    pub const CHAT_MESSAGE: u16 = 9;
    /// NIP-14: Private Direct Message (text content)
    pub const PRIVATE_DIRECT_MESSAGE: u16 = 14;
    /// Vector-specific: File attachment with encryption metadata
    pub const FILE_ATTACHMENT: u16 = 15;
    /// Vector-specific: Message edit (references original message, contains new content)
    pub const MESSAGE_EDIT: u16 = 16;
    /// NIP-25: Emoji reaction
    pub const REACTION: u16 = 7;
    /// NIP-78: Application-specific data (typing indicators, peer ads, etc.)
    pub const APPLICATION_SPECIFIC: u16 = 30078;

    // Community protocol append-plane kinds (GROUP_PROTOCOL.md). Vector-claimed
    // block 3300-3399 in the verified-empty 3000-3999 regular range. One kind per
    // event type so relays can slice by type with a pure `kinds` filter. The inner
    // signed event mirrors the outer kind (binding triad).
    pub const COMMUNITY_MESSAGE: u16 = 3300;
    pub const COMMUNITY_REACTION: u16 = 3301;
    pub const COMMUNITY_EDIT: u16 = 3302;
    pub const COMMUNITY_REKEY: u16 = 3303;
    pub const COMMUNITY_INVITE_BUNDLE: u16 = 3304;
    /// Cooperative delete: an inner control event referencing a target message's inner
    /// id, honored only when its signer is the target's author. Lets a member tombstone their
    /// own message in-app on peers WITHOUT the original per-message ephemeral key (multi-device
    /// or pre-retention sends), where a relay-side NIP-09 nuke is impossible.
    pub const COMMUNITY_DELETE: u16 = 3305;
    /// Presence (join/leave) announcement: an inner event signed by the joining/leaving member's
    /// identity, content "join" or "leave", posted to the primary channel. A client best-practice
    /// (not enforced) so honest clients announce arrival/departure; feeds the observed member list
    /// even before the member posts. A silent join is still possible by simply not sending this.
    pub const COMMUNITY_PRESENCE: u16 = 3306;
    // 3307 is RETIRED. Never reuse the number.
    /// Cooperative kick: an inner directive signed by a `KICK`-permissioned member, naming a
    /// target member (content = target hex) and carrying the actor's `vac` authority citation. NOT a
    /// rekey and NOT folded — soft removal. On receipt the TARGET self-removes (drops the community keys
    /// + wipes local chat data, like a leave); peers drop the target from their observed member list. A
    /// target that ignores it (malicious) is escalated to a BAN (the cryptographic rekey).
    pub const COMMUNITY_KICK: u16 = 3309;
    /// Control-plane authority entity (keyless/real-npub model): a per-entity append
    /// edition (RoleMetadata / Grant / RoleOrder / Banlist / ChannelMetadata / GroupRoot /
    /// OwnerAttestation, distinguished by the `vsk` tag), signed INSIDE the encryption by the
    /// actor's REAL npub and folded by its per-entity version chain.
    pub const COMMUNITY_CONTROL: u16 = 3308;
    /// WebXDC realtime peer signal: an inner event signed by the playing member's identity,
    /// JSON content `{"op":"ad","topic":...,"addr":...}` (Iroh node advertisement) or
    /// `{"op":"left","topic":...}` (stopped playing). The Community-transport twin of the
    /// NIP-17 `peer-advertisement` / `peer-left` DM rumors: persisted on receipt (kind-30078
    /// row keyed by topic) so a member who reopens Vector mid-session still discovers the
    /// active players, exactly like the DM path.
    pub const COMMUNITY_WEBXDC: u16 = 3310;
    /// Typing indicator: an inner event signed by the typing member, content "typing", sealed under
    /// the channel epoch key like presence. Ephemeral and never persisted/folded — the Community-transport
    /// twin of the NIP-17 typing rumor. Receivers show the typer for a short window, then it expires.
    pub const COMMUNITY_TYPING: u16 = 3311;
}

/// System event types for group member changes (stored as integers).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum SystemEventType {
    MemberLeft = 0,
    MemberJoined = 1,
    MemberRemoved = 2,
    WallpaperChanged = 3,
    WallpaperRemoved = 4,
}

impl SystemEventType {
    pub fn display_message(&self, display_name: &str) -> String {
        match self {
            SystemEventType::MemberLeft => format!("{} has left", display_name),
            SystemEventType::MemberJoined => format!("{} has joined", display_name),
            SystemEventType::MemberRemoved => format!("{} was removed", display_name),
            SystemEventType::WallpaperChanged => format!("{} changed the wallpaper", display_name),
            SystemEventType::WallpaperRemoved => format!("{} removed the wallpaper", display_name),
        }
    }

    pub fn as_u8(&self) -> u8 {
        *self as u8
    }
}

/// A stored event - the flat, protocol-aligned storage format
///
/// This struct represents any Nostr event after unwrapping/decryption.
/// It's designed to store events generically, allowing Vector to:
/// - Store unknown event types for future compatibility
/// - Query events efficiently with parsed fields
/// - Reconstruct typed display objects (Message, Reaction) at render time
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredEvent {
    /// Event ID (hex string, 64 chars)
    pub id: String,

    /// Nostr event kind (14=DM, 7=reaction, 15=file, etc.)
    pub kind: u16,

    /// Database chat ID (foreign key)
    pub chat_id: i64,

    /// Database user ID of sender (foreign key, optional)
    pub user_id: Option<i64>,

    /// Event content (encrypted for messages, emoji for reactions, URL for files)
    pub content: String,

    /// Nostr-style tags as JSON array
    /// Example: [["e", "abc123", "", "reply"], ["p", "pubkey"]]
    pub tags: Vec<Vec<String>>,

    /// Parsed reference ID for quick lookups
    /// - For reactions: the message ID being reacted to
    /// - For attachments: the message ID they belong to (if separate)
    /// - For messages: None
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reference_id: Option<String>,

    /// Event creation timestamp (Unix seconds)
    pub created_at: u64,

    /// When we received this event (Unix milliseconds)
    pub received_at: u64,

    /// Whether this event is from the current user
    pub mine: bool,

    /// Whether this event is pending confirmation (outgoing only)
    #[serde(default)]
    pub pending: bool,

    /// Whether sending this event failed (outgoing only)
    #[serde(default)]
    pub failed: bool,

    /// Outer giftwrap event ID for deduplication during sync
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wrapper_event_id: Option<String>,

    /// Sender's npub (for group chats where sender varies)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub npub: Option<String>,

    /// Cached link preview metadata (JSON serialized SiteMetadata)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preview_metadata: Option<String>,
}

impl StoredEvent {
    /// Create a new StoredEvent with required fields
    pub fn new(id: String, kind: u16, chat_id: i64, content: String, created_at: u64) -> Self {
        Self {
            id,
            kind,
            chat_id,
            user_id: None,
            content,
            tags: Vec::new(),
            reference_id: None,
            created_at,
            received_at: current_timestamp_ms(),
            mine: false,
            pending: false,
            failed: false,
            wrapper_event_id: None,
            npub: None,
            preview_metadata: None,
        }
    }

    /// Check if this is a message event (text or file)
    pub fn is_message(&self) -> bool {
        self.kind == event_kind::PRIVATE_DIRECT_MESSAGE
            || self.kind == event_kind::FILE_ATTACHMENT
    }

    /// Check if this is a reaction event
    pub fn is_reaction(&self) -> bool {
        self.kind == event_kind::REACTION
    }

    /// Check if this is a known event type
    pub fn is_known_kind(&self) -> bool {
        matches!(
            self.kind,
            event_kind::PRIVATE_DIRECT_MESSAGE
                | event_kind::FILE_ATTACHMENT
                | event_kind::REACTION
                | event_kind::APPLICATION_SPECIFIC
        )
    }

    /// Get a tag value by key (first match)
    pub fn get_tag(&self, key: &str) -> Option<&str> {
        self.tags
            .iter()
            .find(|tag| tag.first().map(|s| s.as_str()) == Some(key))
            .and_then(|tag| tag.get(1))
            .map(|s| s.as_str())
    }

    /// Get all tag values for a key
    pub fn get_tags(&self, key: &str) -> Vec<&str> {
        self.tags
            .iter()
            .filter(|tag| tag.first().map(|s| s.as_str()) == Some(key))
            .filter_map(|tag| tag.get(1))
            .map(|s| s.as_str())
            .collect()
    }

    /// Get the reply reference (e tag with "reply" marker)
    pub fn get_reply_reference(&self) -> Option<&str> {
        self.tags
            .iter()
            .find(|tag| {
                tag.first().map(|s| s.as_str()) == Some("e")
                    && tag.get(3).map(|s| s.as_str()) == Some("reply")
            })
            .and_then(|tag| tag.get(1))
            .map(|s| s.as_str())
    }

    /// Get millisecond-precision timestamp
    /// Combines created_at (seconds) with "ms" tag if present
    pub fn timestamp_ms(&self) -> u64 {
        if let Some(ms_str) = self.get_tag("ms") {
            if let Ok(ms) = ms_str.parse::<u64>() {
                if ms <= 999 {
                    return self.created_at * 1000 + ms;
                }
            }
        }
        self.created_at * 1000
    }
}

/// Get current timestamp in milliseconds
fn current_timestamp_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

/// Builder for creating StoredEvent from rumor processing
#[derive(Debug, Default)]
pub struct StoredEventBuilder {
    id: String,
    kind: u16,
    chat_id: i64,
    user_id: Option<i64>,
    content: String,
    tags: Vec<Vec<String>>,
    reference_id: Option<String>,
    created_at: u64,
    mine: bool,
    pending: bool,
    failed: bool,
    wrapper_event_id: Option<String>,
    npub: Option<String>,
}

impl StoredEventBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = id.into();
        self
    }

    pub fn kind(mut self, kind: u16) -> Self {
        self.kind = kind;
        self
    }

    pub fn chat_id(mut self, chat_id: i64) -> Self {
        self.chat_id = chat_id;
        self
    }

    pub fn user_id(mut self, user_id: Option<i64>) -> Self {
        self.user_id = user_id;
        self
    }

    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = content.into();
        self
    }

    pub fn tags(mut self, tags: Vec<Vec<String>>) -> Self {
        self.tags = tags;
        self
    }

    pub fn reference_id(mut self, reference_id: Option<String>) -> Self {
        self.reference_id = reference_id;
        self
    }

    pub fn created_at(mut self, created_at: u64) -> Self {
        self.created_at = created_at;
        self
    }

    pub fn mine(mut self, mine: bool) -> Self {
        self.mine = mine;
        self
    }

    pub fn pending(mut self, pending: bool) -> Self {
        self.pending = pending;
        self
    }

    pub fn failed(mut self, failed: bool) -> Self {
        self.failed = failed;
        self
    }

    pub fn wrapper_event_id(mut self, wrapper_event_id: Option<String>) -> Self {
        self.wrapper_event_id = wrapper_event_id;
        self
    }

    pub fn npub(mut self, npub: Option<String>) -> Self {
        self.npub = npub;
        self
    }

    pub fn build(self) -> StoredEvent {
        StoredEvent {
            id: self.id,
            kind: self.kind,
            chat_id: self.chat_id,
            user_id: self.user_id,
            content: self.content,
            tags: self.tags,
            reference_id: self.reference_id,
            created_at: self.created_at,
            received_at: current_timestamp_ms(),
            mine: self.mine,
            pending: self.pending,
            failed: self.failed,
            wrapper_event_id: self.wrapper_event_id,
            npub: self.npub,
            preview_metadata: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_stored_event_new() {
        let event = StoredEvent::new(
            "abc123".to_string(),
            event_kind::PRIVATE_DIRECT_MESSAGE,
            1,
            "Hello world".to_string(),
            1234567890,
        );

        assert_eq!(event.id, "abc123");
        assert_eq!(event.kind, 14);
        assert!(event.is_message());
        assert!(!event.is_reaction());
        assert!(event.is_known_kind());
    }

    #[test]
    fn test_get_tag() {
        let mut event = StoredEvent::new(
            "abc123".to_string(),
            event_kind::PRIVATE_DIRECT_MESSAGE,
            1,
            "Hello".to_string(),
            1234567890,
        );
        event.tags = vec![
            vec!["e".to_string(), "ref123".to_string(), "".to_string(), "reply".to_string()],
            vec!["ms".to_string(), "500".to_string()],
        ];

        assert_eq!(event.get_tag("ms"), Some("500"));
        assert_eq!(event.get_reply_reference(), Some("ref123"));
    }

    #[test]
    fn test_timestamp_ms() {
        let mut event = StoredEvent::new(
            "abc123".to_string(),
            event_kind::PRIVATE_DIRECT_MESSAGE,
            1,
            "Hello".to_string(),
            1234567890,
        );

        // Without ms tag
        assert_eq!(event.timestamp_ms(), 1234567890000);

        // With ms tag
        event.tags = vec![vec!["ms".to_string(), "456".to_string()]];
        assert_eq!(event.timestamp_ms(), 1234567890456);
    }

    #[test]
    fn test_unknown_kind() {
        let event = StoredEvent::new(
            "abc123".to_string(),
            65535, // Unknown kind (max u16 value)
            1,
            "Unknown content".to_string(),
            1234567890,
        );

        assert!(!event.is_message());
        assert!(!event.is_reaction());
        assert!(!event.is_known_kind());
    }

    #[test]
    fn test_builder() {
        let event = StoredEventBuilder::new()
            .id("abc123")
            .kind(event_kind::REACTION)
            .chat_id(1)
            .content("👍")
            .reference_id(Some("msg456".to_string()))
            .mine(true)
            .build();

        assert_eq!(event.id, "abc123");
        assert!(event.is_reaction());
        assert_eq!(event.reference_id, Some("msg456".to_string()));
        assert!(event.mine);
    }
}