1 module pastemyst.user;
2 
3 import std.typecons;
4 import std.uri;
5 import vibe.d;
6 import pastemyst.info;
7 
8 /++
9  + represents a single pastemyst user
10  +/
11 public struct User
12 {
13     /++
14      + id of the user
15      +/
16     @name("_id")
17     public string id;
18 
19     /++
20      + username of the user
21      +/
22     public string username;
23 
24     /++
25      + url of their avatar image
26      +/
27     public string avatarUrl;
28 
29     /++
30      + their default language
31      +/
32     public string defaultLang;
33 
34     /++
35      + if they have a public profile
36      +/
37     public bool publicProfile;
38 
39     /++
40      + how long has the user been a supporter for, 0 if not a supporter
41      +/
42     public uint supporterLength;
43 
44     /++
45      + if the user is a contributor to pastemyst
46      +/
47     public bool contributor;
48 }
49 
50 /++
51  + checks if a user exists
52  +/
53 public bool userExists(string username)
54 {
55     bool exists = false;
56 
57     const reqstring = USER_ENDPOINT ~ encodeComponent(username) ~ "/exists";
58 
59     requestHTTP(reqstring,
60         (scope req)
61         {
62             req.method = HTTPMethod.GET;
63         },
64         (scope res)
65         {
66             if (res.statusCode == HTTPStatus.ok)
67             {
68                 exists = true;
69             }
70         }
71     );
72 
73     return exists;
74 }
75 
76 /++
77  + finds a user by their username, returns null if not found or if the user doesnt have a public profile set.
78  +/
79 public Nullable!User getUser(string username)
80 {
81     Nullable!User user = Nullable!User.init;
82 
83     const reqstring = USER_ENDPOINT ~ encodeComponent(username);
84 
85     requestHTTP(reqstring,
86         (scope req)
87         {
88             req.method = HTTPMethod.GET;
89         },
90         (scope res)
91         {
92             if (res.statusCode != HTTPStatus.notFound)
93             {
94                 user = nullable(deserializeJson!User(res.bodyReader.readAllUTF8()));
95             }
96         }
97     );
98 
99     return user;
100 }
101 
102 @("user exists")
103 unittest
104 {
105     assert(userExists("codemyst"));
106 }
107 
108 @("getting a user")
109 unittest
110 {
111     assert(getUser("codemyst").get().publicProfile);
112 }