Skip to content

Commit 2349421

Browse files
wesbillmanBrainPinkytlongwell-block
authored
feat: custom emoji — user-owned NIP-30 sets with a client-side union (#816)
Signed-off-by: Wes <[email protected]> Signed-off-by: tlongwell-block <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co> Co-authored-by: tlongwell-block <[email protected]>
1 parent 7a12e50 commit 2349421

48 files changed

Lines changed: 2563 additions & 62 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
use crate::client::{normalize_write_response, SproutClient};
2+
use crate::error::CliError;
3+
use sprout_sdk::CustomEmoji;
4+
5+
/// d-tag for a member's own custom emoji set (kind:30030). Mirrors the SDK
6+
/// constant; the workspace palette is the union of every member's own set.
7+
const CUSTOM_EMOJI_SET_D_TAG: &str = sprout_sdk::CUSTOM_EMOJI_SET_D_TAG;
8+
9+
/// Custom emoji entry in CLI output.
10+
#[derive(Debug, serde::Serialize)]
11+
struct EmojiEntry {
12+
shortcode: String,
13+
url: String,
14+
}
15+
16+
/// Parse `["emoji", shortcode, url]` tags from one event into entries.
17+
fn emoji_tags_of(event: &serde_json::Value) -> Vec<EmojiEntry> {
18+
let Some(tags) = event.get("tags").and_then(|v| v.as_array()) else {
19+
return vec![];
20+
};
21+
let mut out = Vec::new();
22+
for tag in tags {
23+
let Some(parts) = tag.as_array() else {
24+
continue;
25+
};
26+
if parts.first().and_then(|v| v.as_str()) != Some("emoji") {
27+
continue;
28+
}
29+
let (Some(shortcode), Some(url)) = (
30+
parts.get(1).and_then(|v| v.as_str()),
31+
parts.get(2).and_then(|v| v.as_str()),
32+
) else {
33+
continue;
34+
};
35+
out.push(EmojiEntry {
36+
shortcode: shortcode.to_string(),
37+
url: url.to_string(),
38+
});
39+
}
40+
out
41+
}
42+
43+
/// Union every member's kind:30030 set, deduped by `(shortcode, url)`.
44+
/// Stable, sorted by shortcode then url, so identical input yields identical output.
45+
fn union_custom_emoji(events: &[serde_json::Value]) -> Vec<EmojiEntry> {
46+
let mut seen = std::collections::HashSet::new();
47+
let mut out: Vec<EmojiEntry> = Vec::new();
48+
for event in events {
49+
for entry in emoji_tags_of(event) {
50+
if seen.insert((entry.shortcode.clone(), entry.url.clone())) {
51+
out.push(entry);
52+
}
53+
}
54+
}
55+
out.sort_by(|a, b| a.shortcode.cmp(&b.shortcode).then(a.url.cmp(&b.url)));
56+
out
57+
}
58+
59+
/// List the workspace custom emoji palette: the union of every member's
60+
/// own kind:30030 set (d=`sprout:custom-emoji`).
61+
async fn cmd_list(client: &SproutClient) -> Result<(), CliError> {
62+
let filter = serde_json::json!({
63+
"kinds": [sprout_sdk::kind::KIND_EMOJI_SET],
64+
"#d": [CUSTOM_EMOJI_SET_D_TAG],
65+
});
66+
let raw = client.query(&filter).await?;
67+
let events: Vec<serde_json::Value> = serde_json::from_str(&raw)
68+
.map_err(|e| CliError::Other(format!("failed to parse emoji set query: {e}")))?;
69+
let emojis = union_custom_emoji(&events);
70+
let output = serde_json::json!({ "emojis": emojis });
71+
println!("{}", serde_json::to_string(&output).unwrap_or_default());
72+
Ok(())
73+
}
74+
75+
/// Fetch the caller's own current custom emoji set (latest kind:30030 under
76+
/// the d-tag, authored by the caller). Empty when none published yet.
77+
async fn fetch_own_emoji(client: &SproutClient) -> Result<Vec<CustomEmoji>, CliError> {
78+
let me = client.keys().public_key().to_hex();
79+
let filter = serde_json::json!({
80+
"kinds": [sprout_sdk::kind::KIND_EMOJI_SET],
81+
"#d": [CUSTOM_EMOJI_SET_D_TAG],
82+
"authors": [me],
83+
"limit": 1,
84+
});
85+
let raw = client.query(&filter).await?;
86+
let events: Vec<serde_json::Value> = serde_json::from_str(&raw)
87+
.map_err(|e| CliError::Other(format!("failed to parse own emoji set: {e}")))?;
88+
// The relay keeps only the latest per (pubkey, d_tag), but be defensive.
89+
let Some(event) = events.last() else {
90+
return Ok(vec![]);
91+
};
92+
Ok(emoji_tags_of(event)
93+
.into_iter()
94+
.map(|e| CustomEmoji {
95+
shortcode: e.shortcode,
96+
url: e.url,
97+
})
98+
.collect())
99+
}
100+
101+
/// Publish the caller's own (replaced) kind:30030 set, signed as the caller.
102+
async fn publish_own_set(client: &SproutClient, emojis: &[CustomEmoji]) -> Result<(), CliError> {
103+
let builder = sprout_sdk::build_custom_emoji_set(emojis)
104+
.map_err(|e| CliError::Other(format!("build_custom_emoji_set failed: {e}")))?;
105+
let event = client.sign_event(builder)?;
106+
let resp = client.submit_event(event).await?;
107+
println!("{}", normalize_write_response(&resp));
108+
Ok(())
109+
}
110+
111+
/// Add/update a shortcode in the caller's own set (read-modify-write).
112+
async fn cmd_set(client: &SproutClient, shortcode: &str, url: &str) -> Result<(), CliError> {
113+
let normalized = sprout_sdk::normalize_custom_emoji_shortcode(shortcode)
114+
.map_err(|e| CliError::Other(format!("invalid shortcode: {e}")))?;
115+
let mut emojis = fetch_own_emoji(client).await?;
116+
emojis.retain(|e| e.shortcode != normalized);
117+
emojis.push(CustomEmoji {
118+
shortcode: normalized,
119+
url: url.to_string(),
120+
});
121+
publish_own_set(client, &emojis).await
122+
}
123+
124+
/// Remove a shortcode from the caller's own set (read-modify-write).
125+
async fn cmd_rm(client: &SproutClient, shortcode: &str) -> Result<(), CliError> {
126+
let normalized = sprout_sdk::normalize_custom_emoji_shortcode(shortcode)
127+
.map_err(|e| CliError::Other(format!("invalid shortcode: {e}")))?;
128+
let mut emojis = fetch_own_emoji(client).await?;
129+
let before = emojis.len();
130+
emojis.retain(|e| e.shortcode != normalized);
131+
if emojis.len() == before {
132+
// Nothing to remove; avoid republishing an unchanged set.
133+
println!(
134+
"{}",
135+
serde_json::json!({"accepted": true, "message": "not present"})
136+
);
137+
return Ok(());
138+
}
139+
publish_own_set(client, &emojis).await
140+
}
141+
142+
// ---------------------------------------------------------------------------
143+
// Dispatch
144+
// ---------------------------------------------------------------------------
145+
146+
pub async fn dispatch(cmd: crate::EmojiCmd, client: &SproutClient) -> Result<(), CliError> {
147+
use crate::EmojiCmd;
148+
match cmd {
149+
EmojiCmd::List => cmd_list(client).await,
150+
EmojiCmd::Set { shortcode, url } => cmd_set(client, &shortcode, &url).await,
151+
EmojiCmd::Rm { shortcode } => cmd_rm(client, &shortcode).await,
152+
}
153+
}
154+
155+
#[cfg(test)]
156+
mod tests {
157+
use super::*;
158+
159+
#[test]
160+
fn union_dedups_by_shortcode_and_url_across_members() {
161+
let events = vec![
162+
serde_json::json!({
163+
"tags": [
164+
["d", "sprout:custom-emoji"],
165+
["emoji", "zort", "https://example.com/zort.png"],
166+
["emoji", "narf", "https://example.com/narf.png"]
167+
]
168+
}),
169+
serde_json::json!({
170+
"tags": [
171+
["d", "sprout:custom-emoji"],
172+
// exact duplicate (same shortcode+url) — collapses
173+
["emoji", "narf", "https://example.com/narf.png"],
174+
// same shortcode, different url — both kept (distinct pair)
175+
["emoji", "zort", "https://example.com/zort2.png"]
176+
]
177+
}),
178+
];
179+
let emojis = union_custom_emoji(&events);
180+
let pairs: Vec<(&str, &str)> = emojis
181+
.iter()
182+
.map(|e| (e.shortcode.as_str(), e.url.as_str()))
183+
.collect();
184+
assert_eq!(
185+
pairs,
186+
vec![
187+
("narf", "https://example.com/narf.png"),
188+
("zort", "https://example.com/zort.png"),
189+
("zort", "https://example.com/zort2.png"),
190+
]
191+
);
192+
}
193+
}

‎crates/sprout-cli/src/commands/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pub mod channels;
22
pub mod dms;
3+
pub mod emoji;
34
pub mod feed;
45
pub mod mem;
56
pub mod messages;

‎crates/sprout-cli/src/commands/reactions.rs‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,19 @@ pub async fn cmd_add_reaction(
1010
client: &SproutClient,
1111
event_id: &str,
1212
emoji: &str,
13+
emoji_url: Option<&str>,
1314
) -> Result<(), CliError> {
1415
validate_hex64(event_id)?;
1516
let target_eid =
1617
EventId::parse(event_id).map_err(|e| CliError::Usage(format!("invalid event ID: {e}")))?;
1718

18-
let builder = sprout_sdk::build_reaction(target_eid, emoji)
19-
.map_err(|e| CliError::Other(format!("build_reaction failed: {e}")))?;
19+
let builder = if let Some(url) = emoji_url {
20+
sprout_sdk::build_custom_emoji_reaction(target_eid, emoji, url)
21+
.map_err(|e| CliError::Other(format!("build_custom_emoji_reaction failed: {e}")))?
22+
} else {
23+
sprout_sdk::build_reaction(target_eid, emoji)
24+
.map_err(|e| CliError::Other(format!("build_reaction failed: {e}")))?
25+
};
2026

2127
let event = client.sign_event(builder)?;
2228

@@ -125,7 +131,11 @@ pub async fn cmd_get_reactions(client: &SproutClient, event_id: &str) -> Result<
125131
pub async fn dispatch(cmd: crate::ReactionsCmd, client: &SproutClient) -> Result<(), CliError> {
126132
use crate::ReactionsCmd;
127133
match cmd {
128-
ReactionsCmd::Add { event, emoji } => cmd_add_reaction(client, &event, &emoji).await,
134+
ReactionsCmd::Add {
135+
event,
136+
emoji,
137+
emoji_url,
138+
} => cmd_add_reaction(client, &event, &emoji, emoji_url.as_deref()).await,
129139
ReactionsCmd::Remove { event, emoji } => cmd_remove_reaction(client, &event, &emoji).await,
130140
ReactionsCmd::Get { event } => cmd_get_reactions(client, &event).await,
131141
}

‎crates/sprout-cli/src/lib.rs‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,9 @@ enum Cmd {
179179
/// Add, remove, and list emoji reactions
180180
#[command(subcommand)]
181181
Reactions(ReactionsCmd),
182+
/// Manage your custom emoji set (workspace palette is the union of all members' sets)
183+
#[command(subcommand)]
184+
Emoji(EmojiCmd),
182185
/// List, open, and manage direct messages
183186
#[command(subcommand)]
184187
Dms(DmsCmd),
@@ -539,9 +542,12 @@ pub enum ReactionsCmd {
539542
/// Event ID (64-char hex)
540543
#[arg(long)]
541544
event: String,
542-
/// Emoji character (e.g. '👍')
545+
/// Emoji character (e.g. '👍') or custom emoji shortcode
543546
#[arg(long)]
544547
emoji: String,
548+
/// Image URL for a custom emoji reaction; when set, content becomes `:shortcode:`
549+
#[arg(long = "emoji-url")]
550+
emoji_url: Option<String>,
545551
},
546552
/// Remove an emoji reaction from a message
547553
Remove {
@@ -560,6 +566,31 @@ pub enum ReactionsCmd {
560566
},
561567
}
562568

569+
// ---------------------------------------------------------------------------
570+
// Custom emoji subcommands
571+
// ---------------------------------------------------------------------------
572+
573+
#[derive(Subcommand)]
574+
pub enum EmojiCmd {
575+
/// List the workspace custom emoji palette (union of every member's set)
576+
List,
577+
/// Add or update a custom emoji in your own set
578+
Set {
579+
/// Emoji shortcode, without surrounding colons
580+
#[arg(long)]
581+
shortcode: String,
582+
/// Image URL for the emoji
583+
#[arg(long)]
584+
url: String,
585+
},
586+
/// Remove a custom emoji from your own set
587+
Rm {
588+
/// Emoji shortcode, without surrounding colons
589+
#[arg(long)]
590+
shortcode: String,
591+
},
592+
}
593+
563594
// ---------------------------------------------------------------------------
564595
// DMs subcommands
565596
// ---------------------------------------------------------------------------
@@ -1104,6 +1135,7 @@ async fn run(cli: Cli) -> Result<(), CliError> {
11041135
Cmd::Channels(sub) => commands::channels::dispatch(sub, &client, &cli.format).await,
11051136
Cmd::Canvas(sub) => commands::channels::dispatch_canvas(sub, &client).await,
11061137
Cmd::Reactions(sub) => commands::reactions::dispatch(sub, &client).await,
1138+
Cmd::Emoji(sub) => commands::emoji::dispatch(sub, &client).await,
11071139
Cmd::Dms(sub) => commands::dms::dispatch(sub, &client).await,
11081140
Cmd::Users(sub) => commands::users::dispatch(sub, &client, &cli.format).await,
11091141
Cmd::Workflows(sub) => commands::workflows::dispatch(sub, &client).await,
@@ -1138,6 +1170,7 @@ mod tests {
11381170
"canvas",
11391171
"channels",
11401172
"dms",
1173+
"emoji",
11411174
"feed",
11421175
"mem",
11431176
"messages",
@@ -1217,13 +1250,15 @@ mod tests {
12171250
"members",
12181251
"purpose",
12191252
"remove-member",
1253+
"search",
12201254
"topic",
12211255
"unarchive",
12221256
"update"
12231257
]
12241258
);
12251259
assert_eq!(names(&cmd, "canvas"), vec!["get", "set"]);
12261260
assert_eq!(names(&cmd, "reactions"), vec!["add", "get", "remove"]);
1261+
assert_eq!(names(&cmd, "emoji"), vec!["list", "rm", "set"]);
12271262
assert_eq!(names(&cmd, "dms"), vec!["add-member", "list", "open"]);
12281263
assert_eq!(
12291264
names(&cmd, "users"),
@@ -1255,8 +1290,9 @@ mod tests {
12551290
fn subcommand_counts_are_stable() {
12561291
let expected: Vec<(&str, usize)> = vec![
12571292
("canvas", 2),
1258-
("channels", 14),
1293+
("channels", 15),
12591294
("dms", 3),
1295+
("emoji", 3),
12601296
("feed", 1),
12611297
("messages", 8),
12621298
("pack", 2),

‎crates/sprout-core/src/kind.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ pub const KIND_NIP65_RELAY_LIST_METADATA: u32 = 10002;
3030
/// User-owned global state, keyed by `(pubkey, kind)`. References content but is not itself
3131
/// channel-scoped content.
3232
pub const KIND_BOOKMARK_LIST: u32 = 10003;
33+
/// NIP-51: Emoji list (replaceable) — user preferred emojis and pointers to emoji sets.
34+
pub const KIND_EMOJI_LIST: u32 = 10030;
3335
/// NIP-51: Follow set (parameterized replaceable, 30000–39999 range) — named curated lists of pubkeys.
3436
///
3537
/// User-owned, keyed by `(pubkey, kind, d_tag)`. Allows multiple named follow lists on top of
@@ -39,6 +41,15 @@ pub const KIND_FOLLOW_SET: u32 = 30000;
3941
///
4042
/// User-owned, keyed by `(pubkey, kind, d_tag)`.
4143
pub const KIND_BOOKMARK_SET: u32 = 30003;
44+
/// NIP-51 / NIP-30: Emoji set (parameterized replaceable).
45+
///
46+
/// User-owned, keyed by `(pubkey, kind, d_tag)`. Each member publishes their own
47+
/// kind:30030 set (signed as themselves); the workspace emoji "palette" is the
48+
/// client-side union of everyone's sets — a view computed on read, not stored
49+
/// state. Ingest allowlists member-authored kind:30030/10030 (see
50+
/// `required_scope_for_kind`), and the generic NIP-33 replace path keeps only the
51+
/// latest per `(pubkey, d_tag)`.
52+
pub const KIND_EMOJI_SET: u32 = 30030;
4253
/// NIP-01: Channel metadata (replaceable). Not used by Sprout today.
4354
pub const KIND_CHANNEL_METADATA: u32 = 41;
4455
/// NIP-09: Event deletion request.
@@ -107,7 +118,6 @@ pub const RELAY_ADMIN_ADD_MEMBER: u32 = 9030;
107118
pub const RELAY_ADMIN_REMOVE_MEMBER: u32 = 9031;
108119
/// NIP-43: Change the role of an existing relay member.
109120
pub const RELAY_ADMIN_CHANGE_ROLE: u32 = 9032;
110-
111121
// NIP-43 relay membership announcement events (relay-signed)
112122
/// NIP-43: Relay membership list snapshot (relay-signed, replaceable by convention).
113123
pub const KIND_NIP43_MEMBERSHIP_LIST: u32 = 13534;
@@ -324,8 +334,10 @@ pub const ALL_KINDS: &[u32] = &[
324334
KIND_PIN_LIST,
325335
KIND_NIP65_RELAY_LIST_METADATA,
326336
KIND_BOOKMARK_LIST,
337+
KIND_EMOJI_LIST,
327338
KIND_FOLLOW_SET,
328339
KIND_BOOKMARK_SET,
340+
KIND_EMOJI_SET,
329341
KIND_CHANNEL_METADATA,
330342
KIND_DELETION,
331343
KIND_REACTION,

0 commit comments

Comments
 (0)