-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathsocial.rs
More file actions
280 lines (246 loc) · 8.21 KB
/
Copy pathsocial.rs
File metadata and controls
280 lines (246 loc) · 8.21 KB
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
use nostr::{EventBuilder, Kind, Tag};
use serde::Deserialize;
use sprout_sdk::kind::{
KIND_BOOKMARK_LIST, KIND_BOOKMARK_SET, KIND_FOLLOW_SET, KIND_MUTE_LIST,
KIND_NIP65_RELAY_LIST_METADATA, KIND_PIN_LIST,
};
use crate::client::SproutClient;
use crate::error::CliError;
use crate::validate::{parse_event_id, validate_hex64};
/// A single contact entry (CLI-local, not from sprout-sdk).
#[derive(Debug, Deserialize)]
pub struct ContactEntry {
pub pubkey: String,
#[serde(default)]
pub relay_url: Option<String>,
#[serde(default)]
pub petname: Option<String>,
}
pub async fn cmd_publish_note(
client: &SproutClient,
content: &str,
reply_to: Option<&str>,
) -> Result<(), CliError> {
if let Some(r) = reply_to {
validate_hex64(r)?;
}
let reply_id = reply_to.map(parse_event_id).transpose()?;
let builder = sprout_sdk::build_note(content, reply_id)
.map_err(|e| CliError::Other(format!("build error: {e}")))?;
let event = client.sign_event(builder)?;
let resp = client.submit_event(event).await?;
println!("{resp}");
Ok(())
}
pub async fn cmd_set_contact_list(
client: &SproutClient,
contacts_json: &str,
) -> Result<(), CliError> {
let entries: Vec<ContactEntry> = serde_json::from_str(contacts_json)
.map_err(|e| CliError::Usage(format!("invalid contacts JSON: {e}")))?;
let contacts: Vec<(&str, Option<&str>, Option<&str>)> = entries
.iter()
.map(|c| {
(
c.pubkey.as_str(),
c.relay_url.as_deref(),
c.petname.as_deref(),
)
})
.collect();
let builder = sprout_sdk::build_contact_list(&contacts)
.map_err(|e| CliError::Other(format!("build error: {e}")))?;
let event = client.sign_event(builder)?;
let resp = client.submit_event(event).await?;
println!("{resp}");
Ok(())
}
/// Get a single event by ID via POST /query.
pub async fn cmd_get_event(client: &SproutClient, event_id: &str) -> Result<(), CliError> {
validate_hex64(event_id)?;
let filter = serde_json::json!({
"ids": [event_id]
});
let resp = client.query(&filter).await?;
println!("{resp}");
Ok(())
}
/// Get user notes (kind:1) by author pubkey.
pub async fn cmd_get_user_notes(
client: &SproutClient,
pubkey: &str,
limit: Option<u32>,
before: Option<i64>,
) -> Result<(), CliError> {
validate_hex64(pubkey)?;
let limit = limit.unwrap_or(50).min(100);
let mut filter = serde_json::json!({
"kinds": [1],
"authors": [pubkey],
"limit": limit
});
if let Some(b) = before {
filter["until"] = serde_json::json!(b);
}
let resp = client.query(&filter).await?;
println!("{resp}");
Ok(())
}
/// Get a user's contact list (kind:3) by pubkey.
pub async fn cmd_get_contact_list(client: &SproutClient, pubkey: &str) -> Result<(), CliError> {
validate_hex64(pubkey)?;
let filter = serde_json::json!({
"kinds": [3],
"authors": [pubkey],
"limit": 1
});
let resp = client.query(&filter).await?;
println!("{resp}");
Ok(())
}
fn validate_social_list_kind(kind: u32) -> Result<(), CliError> {
match kind {
KIND_MUTE_LIST
| KIND_PIN_LIST
| KIND_NIP65_RELAY_LIST_METADATA
| KIND_BOOKMARK_LIST
| KIND_FOLLOW_SET
| KIND_BOOKMARK_SET => Ok(()),
_ => Err(CliError::Usage(format!(
"unsupported social list kind {kind}; supported kinds: 10000, 10001, 10002, 10003, 30000, 30003"
))),
}
}
fn is_parameterized_social_list_kind(kind: u32) -> bool {
matches!(kind, KIND_FOLLOW_SET | KIND_BOOKMARK_SET)
}
fn parse_tags_json(tags_json: &str) -> Result<Vec<Tag>, CliError> {
let raw_tags: Vec<Vec<String>> = serde_json::from_str(tags_json)
.map_err(|e| CliError::Usage(format!("invalid tags JSON: {e}")))?;
raw_tags
.iter()
.map(|parts| {
let refs: Vec<&str> = parts.iter().map(String::as_str).collect();
Tag::parse(&refs).map_err(|e| CliError::Usage(format!("invalid tag {parts:?}: {e}")))
})
.collect::<Result<_, _>>()
}
fn has_d_tag(tags: &[Tag]) -> bool {
tags.iter()
.any(|t| t.as_slice().first().map(|s| s.as_str()) == Some("d"))
}
pub async fn cmd_set_list(
client: &SproutClient,
kind: u16,
tags_json: &str,
content: &str,
) -> Result<(), CliError> {
let kind_u32 = u32::from(kind);
validate_social_list_kind(kind_u32)?;
let tags = parse_tags_json(tags_json)?;
if is_parameterized_social_list_kind(kind_u32) && !has_d_tag(&tags) {
return Err(CliError::Usage(format!(
"kind {kind} is parameterized replaceable and requires a d tag"
)));
}
let builder = EventBuilder::new(Kind::Custom(kind), content, tags);
let event = client.sign_event(builder)?;
let resp = client.submit_event(event).await?;
println!("{resp}");
Ok(())
}
pub async fn cmd_get_list(
client: &SproutClient,
pubkey: &str,
kind: u32,
d_tag: Option<&str>,
) -> Result<(), CliError> {
validate_hex64(pubkey)?;
validate_social_list_kind(kind)?;
if !is_parameterized_social_list_kind(kind) && d_tag.is_some() {
return Err(CliError::Usage(format!(
"kind {kind} is not parameterized; omit --d-tag"
)));
}
let mut filter = serde_json::json!({
"kinds": [kind],
"authors": [pubkey],
"limit": 10
});
if let Some(d) = d_tag {
filter["#d"] = serde_json::json!([d]);
}
let resp = client.query(&filter).await?;
println!("{resp}");
Ok(())
}
// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------
pub async fn dispatch(cmd: crate::SocialCmd, client: &SproutClient) -> Result<(), CliError> {
use crate::SocialCmd;
match cmd {
SocialCmd::PublishNote { content, reply_to } => {
cmd_publish_note(client, &content, reply_to.as_deref()).await
}
SocialCmd::SetContactList { contacts } => cmd_set_contact_list(client, &contacts).await,
SocialCmd::GetEvent { event } => cmd_get_event(client, &event).await,
SocialCmd::GetUserNotes {
pubkey,
limit,
before,
} => cmd_get_user_notes(client, &pubkey, limit, before).await,
SocialCmd::GetContactList { pubkey } => cmd_get_contact_list(client, &pubkey).await,
SocialCmd::SetList {
kind,
tags,
content,
} => cmd_set_list(client, kind, &tags, &content).await,
SocialCmd::GetList {
pubkey,
kind,
d_tag,
} => cmd_get_list(client, &pubkey, kind, d_tag.as_deref()).await,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn social_list_kind_validation_accepts_supported_kinds() {
for kind in [
KIND_MUTE_LIST,
KIND_PIN_LIST,
KIND_NIP65_RELAY_LIST_METADATA,
KIND_BOOKMARK_LIST,
KIND_FOLLOW_SET,
KIND_BOOKMARK_SET,
] {
assert!(validate_social_list_kind(kind).is_ok(), "kind {kind}");
}
}
#[test]
fn social_list_kind_validation_rejects_unsupported_kinds() {
let err = validate_social_list_kind(30002).unwrap_err();
assert!(
matches!(err, CliError::Usage(msg) if msg.contains("unsupported social list kind 30002"))
);
}
#[test]
fn parses_tags_json_and_detects_d_tag() {
let tags = parse_tags_json(r#"[["d","friends"],["p","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]]"#)
.expect("tags parse");
assert!(has_d_tag(&tags));
}
#[test]
fn malformed_tags_json_is_usage_error() {
let err = parse_tags_json("not json").unwrap_err();
assert!(matches!(err, CliError::Usage(msg) if msg.contains("invalid tags JSON")));
}
#[test]
fn parameterized_social_list_kind_detection() {
assert!(is_parameterized_social_list_kind(KIND_FOLLOW_SET));
assert!(is_parameterized_social_list_kind(KIND_BOOKMARK_SET));
assert!(!is_parameterized_social_list_kind(KIND_MUTE_LIST));
}
}