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
//! [NIP-38] User Statuses.
//!
//! `kind: 30315` ("User Status") is an **addressable**, optionally
//! **expiring** event. The `d` tag — the addressable identifier —
//! also doubles as the *status type*: NIP-38 standardises `general`
//! and `music` but leaves every other value open. The event body is
//! the human-readable status text; an empty body is a spec-level
//! signal to clear the status.
//!
//! Optional content:
//!
//! - a single link via an `r` / `p` / `e` / `a` tag (NIP-38 accepts
//! any of the four — this module exposes all four through
//! [`StatusLink`]);
//! - a NIP-40 `expiration` tag (handled by the existing builder
//! helper and re-used here).
//!
//! # Authoring and reading
//!
//! Use [`EventBuilder::user_status`] to author, and [`UserStatus::from_event`]
//! to parse an existing event back into the typed bundle. The
//! builder guarantees:
//!
//! - `kind = 30315`;
//! - exactly one `d` tag with the status-type identifier;
//! - at most one link tag (the last `with_link` call wins);
//! - the NIP-40 `expiration` tag when [`UserStatus::expires_at`] is
//! set.
//!
//! [NIP-38]: https://github.com/nostr-protocol/nips/blob/master/38.md
use thiserror::Error;
use crate::event::{
Alphabet, Coordinate, Event, EventBuilder, EventId, Kind, SingleLetterTag, Tag, TagKind,
};
use crate::key::PublicKey;
use crate::types::Timestamp;
/// `kind: 30315` — user status addressable event.
pub const KIND_USER_STATUS: Kind = Kind::new(30_315);
/// `d`-tag identifier for the "general" status type.
pub const STATUS_TYPE_GENERAL: &str = "general";
/// `d`-tag identifier for the "music" status type.
pub const STATUS_TYPE_MUSIC: &str = "music";
/// Status *type* (the `d`-tag identifier, doubling as the
/// addressable coordinate).
///
/// NIP-38 standardises `general` and `music` but explicitly leaves
/// room for other values through [`Self::Custom`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StatusType {
/// `general` — freeform status such as "Working", "Hiking".
General,
/// `music` — live-listening status; usually paired with an
/// `expiration` tag set to the track's end time.
Music,
/// Any other status type.
Custom(String),
}
impl StatusType {
/// Parse a `d`-tag identifier.
#[must_use]
pub fn parse(identifier: &str) -> Self {
match identifier {
STATUS_TYPE_GENERAL => Self::General,
STATUS_TYPE_MUSIC => Self::Music,
other => Self::Custom(other.to_owned()),
}
}
/// Render back to the wire identifier.
#[must_use]
pub const fn as_str(&self) -> &str {
match self {
Self::General => STATUS_TYPE_GENERAL,
Self::Music => STATUS_TYPE_MUSIC,
Self::Custom(s) => s.as_str(),
}
}
}
impl std::fmt::Display for StatusType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// Optional link attached to a user status.
///
/// NIP-38 mentions an `r`, `p`, `e`, or `a` tag; we surface all four
/// via this enum so the builder and reader keep the semantics
/// round-trippable.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatusLink {
/// `r` tag — external URI. NIP-38 explicitly shows non-HTTP
/// schemes such as `spotify:search:…` in its examples, so the
/// variant carries a plain [`String`] rather than a
/// [`Url`](crate::types::Url) (which is strict about absolute
/// HTTP-family URLs).
Web(String),
/// `p` tag — referenced profile.
Profile(PublicKey),
/// `e` tag — referenced regular event id.
Event(EventId),
/// `a` tag — referenced addressable coordinate.
Addressable(Coordinate),
}
impl StatusLink {
/// Convert this link into the corresponding [`Tag`].
#[must_use]
pub fn to_tag(&self) -> Tag {
match self {
Self::Web(uri) => {
let head = TagKind::single_letter(SingleLetterTag::lowercase(Alphabet::R));
Tag::with(&head, [uri.clone()])
}
Self::Profile(pk) => Tag::p(*pk),
Self::Event(id) => Tag::e(*id),
Self::Addressable(coord) => {
let head = TagKind::single_letter(SingleLetterTag::lowercase(Alphabet::A));
Tag::with(&head, [coord.to_wire()])
}
}
}
}
/// A parsed or freshly constructed user status.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserStatus {
/// Status type (maps to the addressable `d` tag).
pub status_type: StatusType,
/// Status text. An empty string is a spec-level clear signal.
pub content: String,
/// Optional link (at most one; see [`StatusLink`]).
pub link: Option<StatusLink>,
/// Optional NIP-40 expiration.
pub expires_at: Option<Timestamp>,
}
impl UserStatus {
/// Construct a new status with only the two required pieces.
#[must_use]
pub fn new(status_type: StatusType, content: impl Into<String>) -> Self {
Self {
status_type,
content: content.into(),
link: None,
expires_at: None,
}
}
/// Attach a link. At most one link is carried; subsequent calls
/// replace the previous value (matches the builder's behaviour).
#[must_use]
pub fn with_link(mut self, link: StatusLink) -> Self {
self.link = Some(link);
self
}
/// Attach an NIP-40 expiration.
#[must_use]
pub const fn with_expiration(mut self, ts: Timestamp) -> Self {
self.expires_at = Some(ts);
self
}
/// `true` when [`Self::content`] is empty — the spec's clear
/// signal.
#[must_use]
pub const fn is_clear(&self) -> bool {
self.content.is_empty()
}
/// Parse a NIP-38 event back into the typed bundle.
///
/// # Errors
///
/// - [`UserStatusError::WrongKind`] for any kind other than
/// [`KIND_USER_STATUS`].
/// - [`UserStatusError::MissingDTag`] when the addressable
/// `d`-identifier is absent.
pub fn from_event(event: &Event) -> Result<Self, UserStatusError> {
if event.kind != KIND_USER_STATUS {
return Err(UserStatusError::WrongKind(event.kind));
}
let d = find_d_tag(event).ok_or(UserStatusError::MissingDTag)?;
let status_type = StatusType::parse(d);
let link = parse_link(event);
let expires_at = event.expiration().ok().flatten();
Ok(Self {
status_type,
content: event.content.clone(),
link,
expires_at,
})
}
}
/// Errors raised when reading a [`UserStatus`] off an [`Event`].
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum UserStatusError {
/// The event was not `kind: 30315`.
#[error("expected kind 30315 (user status), got kind {}", .0.as_u16())]
WrongKind(Kind),
/// The required `d` tag was absent.
#[error("NIP-38 event must carry exactly one `d` tag")]
MissingDTag,
}
fn find_d_tag(event: &Event) -> Option<&str> {
let head = TagKind::single_letter(SingleLetterTag::lowercase(Alphabet::D));
event.tags.find_first(&head).and_then(|tag| tag.get(1))
}
fn parse_link(event: &Event) -> Option<StatusLink> {
for tag in &event.tags {
let TagKind::SingleLetter(letter) = tag.kind() else {
continue;
};
if letter.uppercase {
continue;
}
let Some(value) = tag.get(1) else {
continue;
};
let link = match letter.character {
Alphabet::R => Some(StatusLink::Web(value.to_owned())),
Alphabet::P => PublicKey::parse(value).ok().map(StatusLink::Profile),
Alphabet::E => EventId::parse(value).ok().map(StatusLink::Event),
Alphabet::A => Coordinate::parse(value).ok().map(StatusLink::Addressable),
_ => None,
};
if let Some(link) = link {
return Some(link);
}
}
None
}
impl EventBuilder {
/// Author a NIP-38 user-status event.
///
/// The builder pins `kind = 30315` and always emits the `d` tag
/// carrying the status-type identifier. The NIP-40 expiration
/// tag is attached through the existing
/// [`EventBuilder::expiration`] path when
/// [`UserStatus::expires_at`] is set, so callers that also
/// chain `.expiration(ts)` manually will get a single
/// consolidated tag.
#[must_use]
pub fn user_status(status: UserStatus) -> Self {
let mut builder =
Self::new(KIND_USER_STATUS, status.content).tag(Tag::d(status.status_type.as_str()));
if let Some(link) = status.link {
builder = builder.tag(link.to_tag());
}
if let Some(ts) = status.expires_at {
builder = builder.expiration(ts);
}
builder
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Keys;
fn keys() -> Keys {
Keys::parse("0000000000000000000000000000000000000000000000000000000000000003").unwrap()
}
#[test]
fn status_type_round_trips_through_parse_and_as_str() {
for (s, v) in [
("general", StatusType::General),
("music", StatusType::Music),
("lunar-phase", StatusType::Custom("lunar-phase".into())),
] {
let parsed = StatusType::parse(s);
assert_eq!(parsed, v);
assert_eq!(parsed.as_str(), s);
}
}
#[test]
fn builder_emits_kind_and_d_tag() {
let status = UserStatus::new(StatusType::General, "Working");
let event = EventBuilder::user_status(status)
.sign_with_keys(&keys())
.unwrap();
assert_eq!(event.kind, KIND_USER_STATUS);
assert_eq!(event.content, "Working");
let d = find_d_tag(&event).unwrap();
assert_eq!(d, STATUS_TYPE_GENERAL);
}
#[test]
fn builder_attaches_web_link_and_expiration() {
let uri = "spotify:search:Intergalatic".to_owned();
let status = UserStatus::new(StatusType::Music, "Intergalatic - Beastie Boys")
.with_link(StatusLink::Web(uri.clone()))
.with_expiration(Timestamp::from_secs(1_692_845_589));
let event = EventBuilder::user_status(status)
.sign_with_keys(&keys())
.unwrap();
let parsed = UserStatus::from_event(&event).unwrap();
assert_eq!(parsed.status_type, StatusType::Music);
assert_eq!(parsed.content, "Intergalatic - Beastie Boys");
assert_eq!(parsed.link, Some(StatusLink::Web(uri)));
assert_eq!(parsed.expires_at, Some(Timestamp::from_secs(1_692_845_589)));
}
#[test]
fn from_event_round_trips_profile_link() {
let pk = *keys().public_key();
let status =
UserStatus::new(StatusType::General, "mentoring").with_link(StatusLink::Profile(pk));
let event = EventBuilder::user_status(status)
.sign_with_keys(&keys())
.unwrap();
let parsed = UserStatus::from_event(&event).unwrap();
assert_eq!(parsed.link, Some(StatusLink::Profile(pk)));
}
#[test]
fn from_event_rejects_wrong_kind() {
let event = EventBuilder::text_note("not a status")
.sign_with_keys(&keys())
.unwrap();
assert!(matches!(
UserStatus::from_event(&event),
Err(UserStatusError::WrongKind(_))
));
}
#[test]
fn empty_content_signals_a_clear() {
let status = UserStatus::new(StatusType::General, "");
assert!(status.is_clear());
}
#[test]
fn custom_status_type_round_trips_on_d_tag() {
let status = UserStatus::new(StatusType::Custom("focus".into()), "heads-down");
let event = EventBuilder::user_status(status)
.sign_with_keys(&keys())
.unwrap();
let parsed = UserStatus::from_event(&event).unwrap();
assert_eq!(parsed.status_type, StatusType::Custom("focus".into()));
}
}