1use serde::ser::{SerializeMap, SerializeSeq};
11use serde::{Serialize, Serializer};
12use serde_json::{Map, Value};
13
14use crate::chat::SerializableChat;
15use crate::profile::SlimProfile;
16
17const RELATIVE: char = '~';
19
20#[derive(Serialize)]
21pub struct BootPayload<'a> {
22 profiles: CompactProfiles<'a>,
23 chats: Vec<Value>,
24 templates: Templates,
25 cache_root: &'a str,
26}
27
28#[derive(Serialize)]
29struct Templates {
30 profile: Value,
31 chat: Map<String, Value>,
32 message: Map<String, Value>,
33}
34
35pub fn boot_payload<'a>(profiles: &'a [SlimProfile], chats: &[SerializableChat], cache_root: Option<&'a str>) -> BootPayload<'a> {
36 let root = cache_root.filter(|r| !r.is_empty());
37
38 let mut chats = to_items(chats);
39 let chat = template(&chats, &["messages"]);
40 prune(&mut chats, &chat);
41 let mut messages: Vec<&mut Value> = chats
42 .iter_mut()
43 .filter_map(|c| c.get_mut("messages").and_then(Value::as_array_mut))
44 .flat_map(|m| m.iter_mut())
45 .collect();
46 let message = template_refs(&messages, &[]);
47 for m in messages.iter_mut() {
48 prune_one(m, &message);
49 }
50
51 BootPayload {
52 profiles: CompactProfiles { items: profiles, root },
53 chats,
54 templates: Templates {
55 profile: serde_json::to_value(SlimProfile::default()).unwrap_or_default(),
56 chat,
57 message,
58 },
59 cache_root: root.unwrap_or(""),
60 }
61}
62
63struct CompactProfiles<'a> {
66 items: &'a [SlimProfile],
67 root: Option<&'a str>,
68}
69
70impl Serialize for CompactProfiles<'_> {
71 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
72 let empty = SlimProfile::default();
73 let mut seq = s.serialize_seq(Some(self.items.len()))?;
74 for p in self.items {
75 seq.serialize_element(&CompactProfile { p, empty: &empty, root: self.root })?;
76 }
77 seq.end()
78 }
79}
80
81struct CompactProfile<'a> {
82 p: &'a SlimProfile,
83 empty: &'a SlimProfile,
84 root: Option<&'a str>,
85}
86
87impl Serialize for CompactProfile<'_> {
88 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
89 let (p, d) = (self.p, self.empty);
90 let mut m = s.serialize_map(None)?;
91 macro_rules! changed {
92 ($($f:ident),*) => {$(
93 if p.$f != d.$f {
94 m.serialize_entry(stringify!($f), &p.$f)?;
95 }
96 )*};
97 }
98 changed!(id, name, display_name, nickname, lud06, lud16, banner, avatar, about, website, nip05, status, last_updated, mine, bot, is_blocked);
99 for (key, path) in [("avatar_cached", &p.avatar_cached), ("banner_cached", &p.banner_cached)] {
100 match self.root.and_then(|r| path.strip_prefix(r)) {
101 Some(rel) => m.serialize_entry(&format_args!("{key}{RELATIVE}"), rel)?,
102 None if !path.is_empty() => m.serialize_entry(key, path)?,
103 None => {}
104 }
105 }
106 changed!(stream_consent);
107 m.end()
108 }
109}
110
111fn to_items<T: serde::Serialize>(items: &[T]) -> Vec<Value> {
112 items.iter().filter_map(|i| serde_json::to_value(i).ok()).collect()
113}
114
115fn template(items: &[Value], skip: &[&str]) -> Map<String, Value> {
116 template_refs(&items.iter().collect::<Vec<_>>(), skip)
117}
118
119fn template_refs<V: std::ops::Deref<Target = Value>>(items: &[V], skip: &[&str]) -> Map<String, Value> {
121 let mut out = Map::new();
122 let Some(first) = items.first().and_then(|v| v.as_object()) else { return out };
123 'keys: for key in first.keys() {
124 if skip.contains(&key.as_str()) {
125 continue;
126 }
127 let mut seen: Vec<(&Value, usize)> = Vec::new();
128 for item in items {
129 let Some(v) = item.get(key) else { continue 'keys };
130 if let Some(entry) = seen.iter_mut().find(|(c, _)| *c == v) {
131 entry.1 += 1;
132 } else if candidate(v) {
133 seen.push((v, 1));
134 }
135 }
136 if let Some((v, n)) = seen.into_iter().max_by_key(|(_, n)| *n) {
137 if n > 1 {
138 out.insert(key.clone(), v.clone());
139 }
140 }
141 }
142 out
143}
144
145fn candidate(v: &Value) -> bool {
147 match v {
148 Value::String(s) => s.len() <= 16,
149 Value::Array(a) => a.is_empty(),
150 Value::Object(o) => o.values().all(default_like),
151 _ => true,
152 }
153}
154
155fn default_like(v: &Value) -> bool {
156 match v {
157 Value::Null => true,
158 Value::Bool(b) => !b,
159 Value::Number(n) => n.as_f64() == Some(0.0),
160 Value::String(s) => s.is_empty(),
161 Value::Array(a) => a.is_empty(),
162 Value::Object(o) => o.values().all(default_like),
163 }
164}
165
166fn prune(items: &mut [Value], tpl: &Map<String, Value>) {
167 for item in items {
168 prune_one(item, tpl);
169 }
170}
171
172fn prune_one(item: &mut Value, tpl: &Map<String, Value>) {
173 if let Some(obj) = item.as_object_mut() {
174 obj.retain(|k, v| tpl.get(k) != Some(v));
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 fn expand(payload: &Value) -> (Vec<Value>, Vec<Value>) {
184 let root = payload["cache_root"].as_str().unwrap();
185 let fill = |items: &Value, tpl: &Value| -> Vec<Value> {
186 items
187 .as_array()
188 .unwrap()
189 .iter()
190 .map(|p| {
191 let mut o = tpl.as_object().unwrap().clone();
192 for (k, v) in p.as_object().unwrap() {
193 match k.strip_suffix(RELATIVE) {
194 Some(k) => o.insert(k.to_string(), Value::String(format!("{root}{}", v.as_str().unwrap()))),
195 None => o.insert(k.clone(), v.clone()),
196 };
197 }
198 Value::Object(o)
199 })
200 .collect()
201 };
202 let mut chats = fill(&payload["chats"], &payload["templates"]["chat"]);
203 for c in &mut chats {
204 let m = fill(&c["messages"], &payload["templates"]["message"]);
205 c["messages"] = Value::Array(m);
206 }
207 (fill(&payload["profiles"], &payload["templates"]["profile"]), chats)
208 }
209
210 fn profile(id: &str, name: &str, avatar_cached: &str) -> SlimProfile {
211 SlimProfile { id: id.into(), name: name.into(), avatar_cached: avatar_cached.into(), ..Default::default() }
212 }
213
214 fn chat(id: &str, messages: Vec<crate::types::Message>) -> SerializableChat {
215 let mut interner = crate::compact::NpubInterner::new();
216 let mut c = crate::chat::Chat::new_dm(id.to_string(), &mut interner);
217 for m in messages {
218 c.internal_add_message(m, &mut interner);
219 }
220 c.to_serializable(&interner)
221 }
222
223 #[test]
224 fn expanding_the_payload_gives_back_exactly_what_was_compacted() {
225 let root = "/data/io.vectorapp/cache/";
226 let profiles = vec![
227 profile("npub1a", "", ""),
228 profile("npub1b", "", ""),
229 profile("npub1c", "Cat", "/data/io.vectorapp/cache/avatars/c.png"),
230 profile("npub1d", "Dog", "/elsewhere/d.png"),
231 SlimProfile { id: "npub1e".into(), mine: true, last_updated: 7, ..Default::default() },
232 ];
233 let msg = |id: &str, content: &str, npub: Option<&str>| crate::types::Message {
234 id: id.repeat(64 / id.len()),
235 content: content.into(),
236 at: 1_700_000_000_000,
237 npub: npub.map(str::to_string),
238 ..Default::default()
239 };
240 let chats = vec![
241 chat("npub1a", vec![msg("a1", "hi", Some("npub1a")), msg("a2", "", None)]),
242 chat("npub1b", vec![]),
243 chat("npub1c", vec![msg("c1", "yo", Some("npub1c"))]),
244 ];
245
246 let payload = serde_json::to_value(boot_payload(&profiles, &chats, Some(root))).unwrap();
247 let (p, c) = expand(&payload);
248 assert_eq!(p, to_items(&profiles), "profiles round-trip");
249 assert_eq!(c, to_items(&chats), "chats and their messages round-trip");
250
251 let sent = &payload["profiles"];
252 assert_eq!(sent[0].as_object().unwrap().len(), 1, "a bare profile is just its id: {}", sent[0]);
253 assert_eq!(sent[2]["avatar_cached~"], "avatars/c.png", "a cached path rides relative to the root");
254 assert_eq!(sent[3]["avatar_cached"], "/elsewhere/d.png", "a path outside the root is sent whole");
255 let missing_npub = payload["chats"][0]["messages"][1].as_object().unwrap();
256 assert!(!missing_npub.contains_key("npub"), "an omitted optional key stays omitted");
257 }
258
259 #[test]
260 fn expanding_without_a_root_or_items_is_a_no_op() {
261 let payload = serde_json::to_value(boot_payload(&[], &[], None)).unwrap();
262 let (p, c) = expand(&payload);
263 assert!(p.is_empty() && c.is_empty());
264 let profiles = vec![profile("npub1a", "", "/x/a.png"), profile("npub1b", "", "/x/a.png")];
265 let payload = serde_json::to_value(boot_payload(&profiles, &[], None)).unwrap();
266 assert_eq!(expand(&payload).0, to_items(&profiles));
267 }
268
269 #[test]
270 fn every_profile_field_survives_the_compact_form() {
271 let mut full = serde_json::to_value(SlimProfile::default()).unwrap();
273 for (_, v) in full.as_object_mut().unwrap() {
274 *v = match &*v {
275 Value::String(_) => Value::String("x".into()),
276 Value::Bool(_) => Value::Bool(true),
277 Value::Number(_) => Value::from(7),
278 Value::Object(o) => {
279 let mut o = o.clone();
280 for (_, f) in o.iter_mut() {
281 if f.is_string() {
282 *f = Value::String("y".into());
283 }
284 }
285 Value::Object(o)
286 }
287 other => other.clone(),
288 };
289 }
290 let profile: SlimProfile = serde_json::from_value(full).unwrap();
291 let profiles = [profile];
292 let payload = serde_json::to_value(boot_payload(&profiles, &[], Some("/root/"))).unwrap();
293 assert_eq!(expand(&payload).0, to_items(&profiles));
294 }
295}