|
| 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 | +} |
0 commit comments