1use std::collections::BTreeMap;
5use std::sync::Arc;
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{json, Value};
10
11use crate::auth::SlotGrant;
12use crate::engine::Ctx;
13use crate::error::{Error, Result};
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17pub struct SpaceInfo {
18 pub id: String,
19 #[serde(default)]
20 pub name: String,
21 #[serde(default)]
22 pub slug: String,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub icon: Option<String>,
25 #[serde(default)]
27 pub role: String,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub reason: Option<String>,
30 #[serde(default)]
31 pub workspace_id: String,
32 #[serde(default)]
33 pub head_seq: i64,
34}
35
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct SpaceList {
39 pub spaces: Vec<SpaceInfo>,
40 #[serde(default)]
42 pub requestable: u32,
43 #[serde(default)]
44 pub can_create: bool,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub create_blocked: Option<Value>,
47 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
51 pub offline: bool,
52}
53
54const CACHE_KEY: &str = "spaces";
55
56fn unreachable(e: &Error) -> bool {
58 e.code == "network" || e.code == "timeout"
59}
60
61fn cached(ctx: &Ctx) -> Option<SpaceList> {
62 let s = ctx.meta.meta_get(CACHE_KEY).ok().flatten()?;
63 let mut l: SpaceList = serde_json::from_str(&s).ok()?;
64 l.offline = true;
65 Some(l)
66}
67
68fn remember(ctx: &Ctx, l: &SpaceList) {
69 if let Ok(s) = serde_json::to_string(l) {
70 let _ = ctx.meta.meta_set(CACHE_KEY, &s);
71 }
72}
73
74pub(crate) fn forget(ctx: &Ctx) -> Result<()> {
76 ctx.meta.meta_set(CACHE_KEY, "")
77}
78
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81pub struct Ask {
82 pub role: String,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub slot: Option<String>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub space_id: Option<String>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub suggested_name: Option<String>,
90}
91
92impl Ask {
93 pub fn editor() -> Ask {
94 Ask { role: "editor".into(), slot: None, space_id: None, suggested_name: None }
95 }
96}
97
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
100pub struct Granted {
101 pub space_id: String,
102 #[serde(default)]
103 pub name: String,
104 #[serde(default)]
105 pub role: String,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub slot: Option<String>,
108 #[serde(default)]
109 pub created: bool,
110}
111
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct GrantResult {
115 pub status: String,
117 #[serde(default)]
118 pub spaces: Vec<Granted>,
119}
120
121#[derive(Clone)]
123pub struct Spaces {
124 pub(crate) ctx: Arc<Ctx>,
125 pub(crate) wait: bool,
126}
127
128impl Spaces {
129 pub fn no_wait(mut self) -> Spaces {
133 self.wait = false;
134 self
135 }
136
137 fn api(&self) -> crate::api::Api {
138 self.ctx.api.waiting(self.wait)
139 }
140
141 pub async fn list(&self) -> Result<SpaceList> {
147 let api = self.api();
148 let r = self
149 .ctx
150 .handle
151 .spawn(async move { api.json("GET", "/v1/spaces", None).await })
152 .await
153 .map_err(Error::network)?;
154 match r {
155 Ok(v) => {
156 let l: SpaceList = serde_json::from_value(v)?;
157 remember(&self.ctx, &l);
158 Ok(l)
159 }
160 Err(e) if unreachable(&e) => cached(&self.ctx).ok_or(e),
161 Err(e) => Err(e),
162 }
163 }
164
165 pub async fn create(&self, name: &str, slug: Option<&str>) -> Result<SpaceInfo> {
168 let mut body = json!({ "name": name });
169 if let Some(s) = slug {
170 body["slug"] = json!(s);
171 }
172 let api = self.api();
173 let v = self
174 .ctx
175 .handle
176 .spawn(async move { api.json("POST", "/v1/spaces", Some(&body)).await })
177 .await
178 .map_err(Error::network)??;
179 let space: SpaceInfo = serde_json::from_value(v.get("space").cloned().unwrap_or(v))?;
180 if let Some(mut l) = cached(&self.ctx) {
181 l.offline = false;
182 l.spaces.retain(|s| s.id != space.id);
183 l.spaces.push(space.clone());
184 remember(&self.ctx, &l);
185 }
186 Ok(space)
187 }
188
189 pub async fn find_or_create(&self, name: &str) -> Result<SpaceInfo> {
193 let list = self.list().await?;
194 let offline = list.offline;
195 if let Some(s) = list.spaces.into_iter().find(|s| s.name == name && !s.role.is_empty()) {
196 return Ok(s);
197 }
198 if offline {
199 return Err(Error::new(
200 "network",
201 format!("the server can't be reached, and no space named {name:?} is known yet"),
202 )
203 .with_hint(
204 "Retry once the device is online: the first sign-in needs the network to find or create the space.",
205 ));
206 }
207 let slug = slugify(name);
208 match self.create(name, Some(&slug)).await {
209 Err(e) if e.code == "slug_taken" => {
210 let list = self.list().await?;
213 match list.spaces.into_iter().find(|s| s.name == name && !s.role.is_empty()) {
214 Some(s) => Ok(s),
215 None => self.create(name, None).await,
216 }
217 }
218 r => r,
219 }
220 }
221
222 pub async fn request_access(
226 &self,
227 asks: Vec<Ask>,
228 on_approve_url: impl Fn(&str) + Send + Sync + 'static,
229 ) -> Result<GrantResult> {
230 let ctx = self.ctx.clone();
231 let api = self.api();
232 self.ctx
233 .handle
234 .spawn(async move {
235 let created = api.json("POST", "/v1/grant-requests", Some(&json!({ "asks": asks }))).await?;
236 let id = created.get("request").and_then(Value::as_str).unwrap_or_default().to_string();
237 let url = created.get("approve_url").and_then(Value::as_str).unwrap_or_default().to_string();
238 on_approve_url(&url);
239 let interval = Duration::from_secs(created.get("interval").and_then(Value::as_u64).unwrap_or(2).max(1));
240 let deadline = tokio::time::Instant::now()
241 + Duration::from_secs(created.get("expires_in").and_then(Value::as_u64).unwrap_or(600))
242 + interval;
243 while tokio::time::Instant::now() < deadline {
244 tokio::time::sleep(interval).await;
245 let st = match api.json("GET", &format!("/v1/grant-requests/{}", crate::api::seg(&id)), None).await
246 {
247 Ok(v) => v,
248 Err(e) if e.is_transient() => continue,
249 Err(e) => return Err(e),
250 };
251 let r: GrantResult = serde_json::from_value(st)?;
252 if r.status == "pending" {
253 continue;
254 }
255 let slots: BTreeMap<String, SlotGrant> = r
256 .spaces
257 .iter()
258 .filter_map(|g| {
259 g.slot
260 .clone()
261 .map(|s| (s, SlotGrant { space_id: g.space_id.clone(), role: g.role.clone() }))
262 })
263 .collect();
264 if !slots.is_empty() {
265 ctx.auth.merge_slots(slots)?;
266 }
267 return Ok(r);
268 }
269 Ok(GrantResult { status: "expired".into(), spaces: vec![] })
270 })
271 .await
272 .map_err(Error::network)?
273 }
274}
275
276fn slugify(name: &str) -> String {
277 let mut s = String::new();
278 for c in name.chars().flat_map(char::to_lowercase) {
279 if c.is_ascii_alphanumeric() {
280 s.push(c);
281 } else if !s.ends_with('-') && !s.is_empty() {
282 s.push('-');
283 }
284 }
285 let s = s.trim_end_matches('-').to_string();
286 if s.is_empty() {
287 "space".into()
288 } else {
289 s.chars().take(48).collect()
290 }
291}