summaryrefslogtreecommitdiff
path: root/src/session.rs
blob: b9e508e67d1a3673cccd4ece27ad07f812cc14fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::BTreeMap;
use std::collections::btree_map::{Iter, Keys};

use crate::capabilities::{AccountCapabilities, CapabilityRegistry, ServerCapabilities};
use crate::*;

// 2: JMAP Session Resource {{{

/// Intermediate Serde-Powered Account Struct
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ISessionAccount {
    pub name: String,
    pub isPersonal: bool,
    pub isReadOnly: bool,
    pub accountCapabilities: JObj<String, JObject>,
}

/// Intermediate Serde-Powered Session Struct
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct ISession {
    pub capabilities: JObj<String, JObject>,
    pub accounts: JObj<JMAPId, ISessionAccount>,
    pub primaryAccounts: JObj<String, JMAPId>,
    pub username: String,
    pub apiUrl: String,
    pub downloadUrl: String,
    pub eventSourceUrl: String,
    pub state: String,
}
//}}}
// 2.a Library specifics for the Session Resource {{{
/// Fully evaluated jmap account
#[derive(Debug)]
pub struct JMAPAccount {
    pub base: ISessionAccount,
    pub capabilities: AccountCapabilities,
}

/// Evaluated session (the accounts are evaluated lazily)
#[derive(Debug)]
pub struct JMAPSession {
    base: ISession,
    capabilities: ServerCapabilities,
    accounts: BTreeMap<JMAPId, Option<JMAPAccount>>,
}

impl JMAPSession {
    /// Get session from the json
    pub fn from_json(json: &str, parsers: CapabilityRegistry) -> Result<Self, serde_json::Error> {
        let session: ISession = serde_json::from_str(json)?;
        Ok(Self::from_intermediate(session, parsers))
    }

    /// Get session from the ISession object
    pub fn from_intermediate(session: ISession, parsers: CapabilityRegistry) -> Self {
        let mut accounts = BTreeMap::new();
        for acc in session.accounts.keys() {
            accounts.insert(acc.clone(), None);
        }
        Self {
            capabilities: parsers.server_capabilities(&session),
            base: session,
            accounts,
        }
    }

    /// Show all the available accounts
    pub fn list_accounts(&self) -> Keys<'_, JMAPId, Option<JMAPAccount>> {
        self.accounts.keys()
    }

    /// Get all the json-based account intermediate structs in an iterator
    pub fn intermediate_accounts(&self) -> Iter<'_, JMAPId, ISessionAccount> {
        self.base.accounts.iter()
    }

    /// Get a singular json-base account intermediate
    pub fn get_intermediate_account(&self, account_id: &JMAPId) -> Option<&ISessionAccount> {
        self.base.accounts.get(account_id)
    }

    /// Get the fully evaluated account if it was initialized
    pub fn get_account(&self, account_id: &JMAPId) -> Option<&JMAPAccount> {
        if let Some(acc) = self.accounts.get(account_id) {
            acc.as_ref()
        } else {
            None
        }
    }

    /// Get the fully evaluated account if it was initialized, mutable
    pub fn get_account_mut(&mut self, account_id: &JMAPId) -> Option<&mut JMAPAccount> {
        if let Some(acc) = self.accounts.get_mut(account_id) {
            acc.as_mut()
        } else {
            None
        }
    }

    /// Evaluate account
    fn eval_account(&mut self, account_id: &JMAPId) -> Option<bool> {
        let evaluated_account = self.accounts.get(account_id).is_some_and(|x| x.is_some());
        if evaluated_account {
            return Some(false);
        }

        if let Some(capabilities) = self
            .capabilities
            .account_capabilities(account_id, &self.base)
        {
            let base = self
                .get_intermediate_account(account_id)
                .expect("Already checked")
                .clone();
            let acc = self
                .accounts
                .get_mut(account_id)
                .expect("Accounts and intermediateAccounts have the same keys");
            *acc = Some(JMAPAccount { base, capabilities });
            Some(true)
        } else {
            None
        }
    }

    /// get_account that evaluates the account if necessary
    pub fn eval_get_account(&mut self, account_id: &JMAPId) -> Option<&JMAPAccount> {
        if self.eval_account(account_id).is_some() {
            Some(
                self.get_account(account_id)
                    .expect("We should have made this account just now"),
            )
        } else {
            None
        }
    }

    /// get_account_mut that evaluates the account if necessary
    pub fn eval_get_account_mut(&mut self, account_id: &JMAPId) -> Option<&mut JMAPAccount> {
        if self.eval_account(account_id).is_some() {
            Some(
                self.get_account_mut(account_id)
                    .expect("We should have made this account just now"),
            )
        } else {
            None
        }
    }
}
// }}}
// Appendix A: tests {{{
#[cfg(test)]
mod test {
    use serde::{Deserialize, Serialize};
    use serde_json::Value;

    use crate::capabilities::{
        AccountCapabilities, Capability, CapabilityCollection, CapabilityDyn, JMAPCoreCapability,
    };
    use crate::{JArr, JDate, JMAPId, JNumber, JObj, JUTCDate, JUnknown, from_junknown};
    use std::assert_matches;

    enum DeserializeTestCapability {
        Session(DTC_Session),
        Account(DTC_Session, DTC_Account),
    }

    #[derive(Serialize, Deserialize, Clone)]
    struct DTC_Session {
        num: JNumber,
        numArr: JArr<JNumber>,
        bool: bool,
        str: String,
        boolObj: JObj<JMAPId, bool>,
        date: JDate,
    }

    #[derive(Serialize, Deserialize, Clone)]
    struct DTC_Account {
        #[serde(skip)]
        account_id: Option<JMAPId>,
        utc_date: JUTCDate,
    }

    impl Capability for DeserializeTestCapability {
        const URN: &str = "urn:xyz:wilkuu:deser_test";

        fn from_object(obj: &crate::JObject) -> Self {
            Self::Session(from_junknown(obj.clone()).unwrap())
        }

        fn account_cap(&self, account_id: JMAPId, obj: &crate::JObject) -> Self {
            let session_cap = (match self {
                Self::Session(s) => s,
                Self::Account(s, _) => s,
            })
            .clone();
            let mut acc: DTC_Account = from_junknown(obj.clone()).unwrap();
            acc.account_id = Some(account_id);
            Self::Account(session_cap, acc)
        }

        fn account(&self) -> Option<JMAPId> {
            match self {
                Self::Session(_) => None,
                Self::Account(_, a) => Some(a.account_id.clone().expect("This should always be Some, considering that we create it with the account_id in account_cap")),
            }
        }
    }

    #[test]
    fn intermediate_parse_test() {
        let in1 = r#"
                {
                  "capabilities": {
                    "urn:ietf:params:jmap:core": {
                      "maxSizeUpload": 50000000,
                      "maxConcurrentUpload": 8,
                      "maxSizeRequest": 10000000,
                      "maxConcurrentRequests": 8,
                      "maxCallsInRequest": 32,
                      "maxObjectsInGet": 256,
                      "maxObjectsInSet": 128,
                      "collationAlgorithms": [
                        "i;ascii-numeric",
                        "i;ascii-casemap",
                        "i;unicode-casemap"
                      ]
                    },
                    "urn:ietf:params:jmap:mail": {},
                    "urn:ietf:params:jmap:contacts": {},
                    "https://example.com/apis/foobar": {
                      "maxFoosFinangled": 42
                    }
                  },
                  "accounts": {
                    "A13824": {
                      "name": "john@example.com",
                      "isPersonal": true,
                      "isReadOnly": false,
                      "accountCapabilities": {
                        "urn:ietf:params:jmap:mail": {
                          "maxMailboxesPerEmail": null,
                          "maxMailboxDepth": 10
                        },
                        "urn:ietf:params:jmap:contacts": {
                        }
                      }
                    },
                    "A97813": {
                      "name": "jane@example.com",
                      "isPersonal": false,
                      "isReadOnly": true,
                      "accountCapabilities": {
                        "urn:ietf:params:jmap:mail": {
                          "maxMailboxesPerEmail": 1,
                          "maxMailboxDepth": 10
                        }
                      }
                    }
                  },
                  "primaryAccounts": {
                    "urn:ietf:params:jmap:mail": "A13824",
                    "urn:ietf:params:jmap:contacts": "A13824"
                  },
                  "username": "john@example.com",
                  "apiUrl": "https://jmap.example.com/api/",
                  "downloadUrl": "https://jmap.example.com/download/{accountId}/{blobId}/{name}?accept={type}",
                  "uploadUrl": "https://jmap.example.com/upload/{accountId}/",
                  "eventSourceUrl": "https://jmap.example.com/eventsource/?types={types}&closeafter={closeafter}&ping={ping}",
                  "state": "75128aab4b1b"
}
        "#;

        let intermediate: Result<crate::session::ISession, serde_json::Error> =
            serde_json::from_str(in1);
        assert_matches!(intermediate, Ok(_));
        println!("{:?}", intermediate);
    }

    #[test]
    fn basic_init() {
        let in1 = r#"
                {
                  "capabilities": {
                    "urn:ietf:params:jmap:core": {
                      "maxSizeUpload": 50000000,
                      "maxConcurrentUpload": 8,
                      "maxSizeRequest": 10000000,
                      "maxConcurrentRequests": 8,
                      "maxCallsInRequest": 32,
                      "maxObjectsInGet": 256,
                      "maxObjectsInSet": 128,
                      "collationAlgorithms": [
                        "i;ascii-numeric",
                        "i;ascii-casemap",
                        "i;unicode-casemap"
                      ]
                    },
                    "urn:ietf:params:jmap:mail": {},
                    "urn:ietf:params:jmap:contacts": {},
                    "https://example.com/apis/foobar": {
                      "maxFoosFinangled": 42
                    },
                    "urn:xyz:wilkuu:deser_test": {
                         "num": 12.0, 
                         "numArr": [1,2.0,3.0],
                         "bool": true, 
                         "str": "string", 
                         "boolObj": { "a": true, "b": false }, 
                         "date": "2026-08-10T10:00:00+02:00"
                    }
                  },
                  "accounts": {
                    "A13824": {
                      "name": "john@example.com",
                      "isPersonal": true,
                      "isReadOnly": false,
                      "accountCapabilities": {
                        "urn:ietf:params:jmap:mail": {
                          "maxMailboxesPerEmail": null,
                          "maxMailboxDepth": 10
                        },
                        "urn:ietf:params:jmap:contacts": {
                        },
                        "urn:xyz:wilkuu:deser_test": {
                            "utc_date": "2026-08-10T12:00:00Z"
                        }  
                      }
                    }
                },
                  "primaryAccounts": {
                    "urn:ietf:params:jmap:mail": "A13824",
                    "urn:ietf:params:jmap:contacts": "A13824",
                    "urn:xyz:wilkuu_deser_test": "A13824"
                  },
                  "username": "john@example.com",
                  "apiUrl": "https://jmap.example.com/api/",
                  "downloadUrl": "https://jmap.example.com/download/{accountId}/{blobId}/{name}?accept={type}",
                  "uploadUrl": "https://jmap.example.com/upload/{accountId}/",
                  "eventSourceUrl": "https://jmap.example.com/eventsource/?types={types}&closeafter={closeafter}&ping={ping}",
                  "state": "75128aab4b1b"
}
        "#;

        let mut parsers = crate::session::CapabilityRegistry::default();
        parsers.add_capability::<DeserializeTestCapability>();

        let mut session = match crate::session::JMAPSession::from_json(in1, parsers) {
            Ok(i) => i,
            Err(e) => unreachable!("Error in parsing json {:?}", e),
        };
        print!("{:?}", session);

        let list: Vec<JMAPId> = session.list_accounts().map(Clone::clone).collect();
        assert_eq!(list, vec![JMAPId("A13824".to_string())]);
        assert!(
            session
                .capabilities
                .get_capability::<JMAPCoreCapability>()
                .is_some()
        );
        let account = session.get_account(&crate::JMAPId("A13824".to_string()));
        assert!(account.is_none());
        let account_opt = session.eval_get_account(&crate::JMAPId("A13824".to_string()));
        assert!(account_opt.is_some());
        let account_opt = session.eval_get_account_mut(&crate::JMAPId("A13824".to_string()));
        let account = account_opt.unwrap();
        assert_eq!(
            account
                .capabilities
                .0
                .keys()
                .map(Clone::clone)
                .collect::<Vec<String>>(),
            vec![JMAPCoreCapability::URN, DeserializeTestCapability::URN]
        );
        let cap: &mut JMAPCoreCapability = account.capabilities.get_capability_mut().unwrap();
        assert_eq!(cap.account(), Some(JMAPId("A13824".to_string())));

        let deser_cap: &mut DeserializeTestCapability =
            account.capabilities.get_capability_mut().unwrap();
        assert_eq!(deser_cap.account(), Some(JMAPId("A13824".to_string())));
        match deser_cap {
            DeserializeTestCapability::Session(_) => unreachable!("This should be an account cap"),
            DeserializeTestCapability::Account(s, _a) => {
                assert_eq!(s.num, 12.0);
                assert_eq!(s.numArr, vec![1.0, 2.0, 3.0]);
                assert!(s.bool);
                assert_eq!(s.str, "string");
                assert_eq!(s.boolObj.get(&JMAPId("a".to_string())), Some(true).as_ref());
                assert_eq!(
                    s.boolObj.get(&JMAPId("b".to_string())),
                    Some(false).as_ref()
                );
                // TODO: Test dates
            }
        }
    }
}
// }}}

// vim: set foldmethod=marker