1use std::fs;
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
13#[serde(default)]
14pub struct SharingPolicy {
15 pub share_display_name: bool,
16 pub share_public_did: bool,
17 pub share_active_model: bool,
18 pub share_llm_outcomes: bool,
20 pub share_ontology_scope: bool,
21 pub share_installed_qapps: bool,
22 pub share_daemon_status: bool,
23 pub allow_group_chat_invites: bool,
24 pub allow_directory_lookup: bool,
25 pub allow_email_invites: bool,
26}
27
28impl Default for SharingPolicy {
29 fn default() -> Self {
30 Self {
31 share_display_name: true,
32 share_public_did: true,
33 share_active_model: false,
34 share_llm_outcomes: false,
35 share_ontology_scope: false,
36 share_installed_qapps: false,
37 share_daemon_status: false,
38 allow_group_chat_invites: true,
39 allow_directory_lookup: true,
40 allow_email_invites: true,
41 }
42 }
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct UserProfile {
47 pub display_name: String,
48 pub bio: Option<String>,
49 pub public_did: String,
50 pub active_front_door_id: Option<String>,
51 #[serde(default)]
52 pub relay_base_url: Option<String>,
53 #[serde(default)]
54 pub nym_address: Option<String>,
55 pub sharing: SharingPolicy,
56 pub updated_at: u64,
57}
58
59impl Default for UserProfile {
60 fn default() -> Self {
61 Self {
62 display_name: "Qualia User".to_string(),
63 bio: None,
64 public_did: String::new(),
65 active_front_door_id: None,
66 relay_base_url: None,
67 nym_address: None,
68 sharing: SharingPolicy::default(),
69 updated_at: 0,
70 }
71 }
72}
73
74pub fn profile_path() -> PathBuf {
76 crate::state::app_meta_dir().join("profile.json")
77}
78
79pub fn load_profile() -> UserProfile {
81 let path = profile_path();
82 if let Ok(text) = fs::read_to_string(&path) {
83 if let Ok(mut p) = serde_json::from_str::<UserProfile>(&text) {
84 if p.public_did.is_empty() {
85 p.public_did = resolve_public_did(&p);
86 }
87 return p;
88 }
89 }
90 let mut profile = UserProfile::default();
91 profile.public_did = resolve_public_did(&profile);
92 profile.updated_at = unix_now();
93 let _ = save_profile(&profile);
94 profile
95}
96
97pub fn save_profile(profile: &UserProfile) -> Result<(), String> {
99 let path = profile_path();
100 if let Some(parent) = path.parent() {
101 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
102 }
103 let mut p = profile.clone();
104 p.updated_at = unix_now();
105 if p.public_did.is_empty() {
106 p.public_did = resolve_public_did(&p);
107 }
108 let text = serde_json::to_string_pretty(&p).map_err(|e| e.to_string())?;
109 fs::write(path, text).map_err(|e| e.to_string())
110}
111
112pub fn apply_profile_patch(
118 base: &UserProfile,
119 patch: &serde_json::Value,
120) -> Result<UserProfile, String> {
121 if !patch.is_object() {
122 return Err("profile patch must be a JSON object".into());
123 }
124 let mut out = base.clone();
125
126 if let Some(v) = patch.get("display_name") {
127 out.display_name = v
128 .as_str()
129 .ok_or_else(|| "display_name must be a string".to_string())?
130 .to_string();
131 }
132 if let Some(v) = patch.get("bio") {
133 out.bio = match v {
134 serde_json::Value::Null => None,
135 serde_json::Value::String(s) => Some(s.clone()),
136 _ => return Err("bio must be a string or null".into()),
137 };
138 }
139 if let Some(v) = patch.get("public_did") {
140 if let Some(s) = v.as_str() {
141 if !s.is_empty() {
142 out.public_did = s.to_string();
143 }
144 } else if !v.is_null() {
145 return Err("public_did must be a string".into());
146 }
147 }
148 if let Some(v) = patch.get("active_front_door_id") {
149 out.active_front_door_id = match v {
150 serde_json::Value::Null => None,
151 serde_json::Value::String(s) => Some(s.clone()),
152 _ => return Err("active_front_door_id must be a string or null".into()),
153 };
154 }
155 if let Some(v) = patch.get("relay_base_url") {
156 out.relay_base_url = match v {
157 serde_json::Value::Null => None,
158 serde_json::Value::String(s) => Some(s.clone()),
159 _ => return Err("relay_base_url must be a string or null".into()),
160 };
161 }
162 if let Some(sharing) = patch.get("sharing") {
163 apply_sharing_patch(&mut out.sharing, sharing)?;
164 }
165
166 Ok(out)
167}
168
169fn apply_sharing_patch(
170 policy: &mut SharingPolicy,
171 patch: &serde_json::Value,
172) -> Result<(), String> {
173 let obj = patch
174 .as_object()
175 .ok_or_else(|| "sharing must be a JSON object".to_string())?;
176 for (key, value) in obj {
177 let Some(flag) = value.as_bool() else {
178 return Err(format!("sharing.{key} must be a boolean"));
179 };
180 match key.as_str() {
181 "share_display_name" => policy.share_display_name = flag,
182 "share_public_did" => policy.share_public_did = flag,
183 "share_active_model" => policy.share_active_model = flag,
184 "share_llm_outcomes" => policy.share_llm_outcomes = flag,
185 "share_ontology_scope" => policy.share_ontology_scope = flag,
186 "share_installed_qapps" => policy.share_installed_qapps = flag,
187 "share_daemon_status" => policy.share_daemon_status = flag,
188 "allow_group_chat_invites" => policy.allow_group_chat_invites = flag,
189 "allow_directory_lookup" => policy.allow_directory_lookup = flag,
190 "allow_email_invites" => policy.allow_email_invites = flag,
191 _ => {}
193 }
194 }
195 Ok(())
196}
197
198pub fn resolve_public_did(profile: &UserProfile) -> String {
200 let state = match crate::state::APP_STATE.get() {
201 Some(s) => s,
202 None => return format!("did:qualia:local:{}", unix_now()),
203 };
204
205 if let Some(ref fd_id) = profile.active_front_door_id {
206 let doors = state.front_doors.lock().unwrap();
207 if let Some(door) = doors.iter().find(|d| d.id == *fd_id) {
208 return door.did_uri.clone();
209 }
210 }
211
212 let doors = state.front_doors.lock().unwrap();
213 if let Some(door) = doors.first() {
214 return door.did_uri.clone();
215 }
216
217 let vault = state.key_vault.lock().unwrap();
218 let key = vault.derive_key("profile-root");
219 let pub_hex = hex::encode(ed25519_dalek::VerifyingKey::from(&key).as_bytes());
220 format!("did:qualia:root:{pub_hex}")
221}
222
223pub fn public_profile_card(profile: &UserProfile) -> serde_json::Value {
225 let mut card = serde_json::json!({
226 "version": 1,
227 "updated_at": profile.updated_at,
228 });
229
230 if profile.sharing.share_display_name {
231 card["display_name"] = serde_json::Value::String(profile.display_name.clone());
232 }
233 if profile.sharing.share_public_did {
234 card["public_did"] = serde_json::Value::String(profile.public_did.clone());
235 }
236 if let Some(ref bio) = profile.bio {
237 if profile.sharing.share_display_name {
238 card["bio"] = serde_json::Value::String(bio.clone());
239 }
240 }
241
242 card
243}
244
245fn unix_now() -> u64 {
246 std::time::SystemTime::now()
247 .duration_since(std::time::UNIX_EPOCH)
248 .unwrap_or_default()
249 .as_secs()
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use serde_json::json;
256
257 #[test]
258 fn partial_people_tab_patch_enables_invites_without_wiping_fields() {
259 let base = UserProfile {
260 display_name: "Old Name".into(),
261 bio: Some("keeps bio".into()),
262 public_did: "did:qualia:test:abc".into(),
263 active_front_door_id: Some("door-1".into()),
264 relay_base_url: Some("https://relay.example".into()),
265 nym_address: None,
266 sharing: SharingPolicy {
267 allow_group_chat_invites: false,
268 share_active_model: true, ..SharingPolicy::default()
270 },
271 updated_at: 1,
272 };
273 let patch = json!({
276 "display_name": "Timothy",
277 "sharing": { "allow_group_chat_invites": true }
278 });
279 let out = apply_profile_patch(&base, &patch).expect("partial patch must apply");
280 assert_eq!(out.display_name, "Timothy");
281 assert!(out.sharing.allow_group_chat_invites);
282 assert!(
283 out.sharing.share_active_model,
284 "unmentioned sharing flags must be preserved"
285 );
286 assert_eq!(out.bio.as_deref(), Some("keeps bio"));
287 assert_eq!(out.public_did, "did:qualia:test:abc");
288 assert_eq!(out.active_front_door_id.as_deref(), Some("door-1"));
289 assert_eq!(out.relay_base_url.as_deref(), Some("https://relay.example"));
290 }
291
292 #[test]
293 fn sharing_policy_deserializes_when_fields_are_omitted() {
294 let p: SharingPolicy = serde_json::from_str(r#"{"allow_group_chat_invites":false}"#)
295 .expect("#[serde(default)] must fill omitted SharingPolicy fields");
296 assert!(!p.allow_group_chat_invites);
297 assert!(p.share_display_name);
298 assert!(p.share_public_did);
299 }
300}