1 module jmap.api;
2 import jmap.types;
3 static import jmap.types;
4 
5 version (SIL) {
6     void registerHandlersJmap(Handlers)(ref Handlers handlers) {
7         import kaleidic.sil.lang.typing.types : Variable, Function;
8         import std.meta : AliasSeq;
9         handlers.openModule("jmap");
10         scope (exit) handlers.closeModule();
11 
12         static foreach (T; AliasSeq!(Credentials, JmapSessionParams, Session, Mailbox, MailboxRights, MailboxSortProperty, Filter, FilterOperator, FilterOperatorKind, FilterCondition, Comparator, Account, AccountParams, AccountCapabilities, SessionCoreCapabilities, Contact, ContactGroup, ContactInformation, JmapFile, EmailAddress, Envelope, ContactAddress, ResultReference, JmapResponseError, EmailProperty, EmailBodyProperty))
13             handlers.registerType!T;
14 
15         static foreach (F; AliasSeq!(getSession, getSessionJson, wellKnownJmap, operatorAsFilter, filterCondition, addQuotes, uniqBy, mailboxPath, allMailboxPaths,
16                                      findMailboxPath))
17             handlers.registerHandler!F;
18     }
19 }
20 
21 version (SIL) :
22 
23     Variable[] uniqBy(Variable[] input, Function f) {
24         import std.algorithm : uniq;
25         import std.array : array;
26         return input.uniq!((a, b) => f(a, b).get!bool).array;
27     }
28 
29 string addQuotes(string s) {
30     if (s.length < 2 || s[0] == '"' || s[$ - 1] == '"')
31         return s;
32     return '"' ~ s ~ '"';
33 }
34 
35 struct JmapSessionParams {
36     Credentials credentials;
37     string uri;
38 }
39 
40 auto wellKnownJmap(string baseURI) {
41     import std.format : format;
42     import std.algorithm : endsWith;
43     return baseURI.endsWith(".well-known/jmap") ? baseURI : format!"%s/.well-known/jmap"(baseURI);
44 }
45 
46 string getSessionJson(JmapSessionParams params) {
47     return getSessionJson(params.uri, params.credentials);
48 }
49 
50 private string getSessionJson(string uri, Credentials credentials) {
51     import requests : Request, BasicAuthentication;
52     auto req = Request();
53     req.authenticator = new BasicAuthentication(credentials.user, credentials.pass);
54     auto result = cast(string) req.get(uri.wellKnownJmap).responseBody.data.idup;
55     return result;
56 }
57 
58 Session getSession(JmapSessionParams params) {
59     import mir.ion.deser.json : deserializeJson;
60     import std.string : strip;
61     import std.exception : enforce;
62     import std.algorithm : startsWith;
63     import std.stdio : writeln;
64 
65     auto json = getSessionJson(params).strip;
66     writeln(json);
67     enforce(json.startsWith("{") || json.startsWith("["), "invalid json response: \n" ~ json);
68     auto ret = json.deserializeJson!Session;
69     ret.credentials = params.credentials;
70     return ret;
71 }