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
//! Notifications interface
extern crate serde_json;

use std::collections::HashMap;

use futures::future;
use hyper::client::connect::Connect;
use url::form_urlencoded;

use users::User;
use Future;
use Github;

/// Provides access to notifications.
/// See the [github docs](https://developer.github.com/v3/activity/notifications/)
/// for more information.
pub struct Notifications<C>
where
    C: Clone + Connect + 'static,
{
    github: Github<C>,
}

impl<C: Clone + Connect + 'static> Notifications<C> {
    #[doc(hidden)]
    pub fn new(github: Github<C>) -> Self {
        Self { github }
    }

    /// List the authenticated user's notifications.
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#list-your-notifications)
    /// for more information.
    pub fn list(&self, options: &ThreadListOptions) -> Future<Vec<Thread>> {
        let mut uri = vec!["/notifications".into()];
        if let Some(query) = options.serialize() {
            uri.push(query);
        }
        self.github.get(&uri.join("?"))
    }

    /// List the authenticated user's notifications for a repository.
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#list-your-notifications-in-a-repository)
    /// for more information.
    pub fn list_for_repo<O, R>(
        &self,
        owner: O,
        repo: R,
        options: &ThreadListOptions,
    ) -> Future<Vec<Thread>>
    where
        O: Into<String>,
        R: Into<String>,
    {
        let mut uri = vec![format!(
            "/repos/{}/{}/notifications",
            owner.into(),
            repo.into()
        )];
        if let Some(query) = options.serialize() {
            uri.push(query);
        }
        self.github.get(&uri.join("?"))
    }

    /// Mark notifications as read. Default: `now`
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#mark-as-read)
    /// for more information.
    pub fn mark_as_read<S>(&self, last_read_at: S) -> Future<()>
    where
        S: Into<Option<String>>,
    {
        let url = match last_read_at.into() {
            Some(last_read_at) => format!(
                "/notifications?{}",
                form_urlencoded::Serializer::new(String::new())
                    .append_pair("last_read_at", &last_read_at)
                    .finish()
            ),
            None => String::from("/notifications"),
        };
        self.github.put_no_response(&url, Vec::new())
    }

    /// Mark notifications as read in a repository. Default: `now`
    ///
    /// See [github docs](https://developer.github.com/v3/activity/notifications/#mark-notifications-as-read-in-a-repository)
    /// for more information.
    pub fn mark_as_read_for_repo<O, R, S>(&self, owner: O, repo: R, last_read_at: S) -> Future<()>
    where
        O: Into<String>,
        R: Into<String>,
        S: Into<Option<String>>,
    {
        let path = match last_read_at.into() {
            Some(last_read_at) => format!(
                "/notifications?{}",
                form_urlencoded::Serializer::new(String::new())
                    .append_pair("last_read_at", &last_read_at)
                    .finish()
            ),
            None => String::from("/notifications"),
        };
        self.github.put_no_response(
            &format!("/repos/{}/{}{}", owner.into(), repo.into(), path),
            Vec::new(),
        )
    }

    /// Return a single thread.
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#view-a-single-thread)
    /// for more information.
    pub fn get_thread<S>(&self, id: S) -> Future<Thread>
    where
        S: Into<String>,
    {
        self.github
            .get(&format!("/notifications/threads/{}", id.into()))
    }

    /// Mark a thread as read
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#mark-a-thread-as-read)
    /// for more information.
    pub fn mark_thread_as_read<S>(&self, id: S) -> Future<()>
    where
        S: Into<String>,
    {
        self.github
            .patch_no_response(&format!("/notifications/threads/{}", id.into()), Vec::new())
    }

    /// Return the subscription information for a thread.
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#get-a-thread-subscription)
    /// for more information.
    pub fn get_subscription<S>(&self, id: S) -> Future<Subscription>
    where
        S: Into<String>,
    {
        self.github.get(&format!(
            "/notifications/threads/{}/subscription",
            id.into(),
        ))
    }

    /// Subscribe to a thread and return the subscription information.
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#set-a-thread-subscription)
    /// for more information.
    pub fn subscribe<S>(&self, id: S) -> Future<Subscription>
    where
        S: Into<String>,
    {
        let mut map = HashMap::new();
        map.insert("subscribed", true);

        self.github.put(
            &format!("/notifications/threads/{}/subscription", id.into()),
            json!(map),
        )
    }

    /// Unsubscribe to a thread and return the subscription information.
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#set-a-thread-subscription)
    /// for more information.
    pub fn unsubscribe<S>(&self, id: S) -> Future<Subscription>
    where
        S: Into<String>,
    {
        let mut map = HashMap::new();
        map.insert("ignored", true);

        self.github.put(
            &format!("/notifications/threads/{}/subscription", id.into()),
            json!(map),
        )
    }

    /// Delete the thread subscription.
    ///
    /// See the [github docs](https://developer.github.com/v3/activity/notifications/#delete-a-thread-subscription)
    /// for more information.
    pub fn delete_subscription<S>(&self, id: S) -> Future<()>
    where
        S: Into<String>,
    {
        self.github.delete(&format!(
            "/notifications/threads/{}/subscription",
            id.into()
        ))
    }
}

// representations

#[derive(Debug, Deserialize)]
pub struct Thread {
    pub id: String,
    pub unread: bool,
    pub updated_at: String,
    pub last_read_at: Option<String>,
    pub reason: String,
    pub subject: Subject,
    pub repository: Repository,
    pub url: String,
    pub subscription_url: String,
}

#[derive(Default)]
pub struct ThreadListOptions {
    params: HashMap<&'static str, String>,
}

impl ThreadListOptions {
    pub fn builder() -> ThreadListOptionsBuilder {
        ThreadListOptionsBuilder::default()
    }

    /// serialize options as a string. returns None if no options are defined
    pub fn serialize(&self) -> Option<String> {
        if self.params.is_empty() {
            None
        } else {
            let encoded: String = form_urlencoded::Serializer::new(String::new())
                .extend_pairs(&self.params)
                .finish();
            Some(encoded)
        }
    }
}

#[derive(Default)]
pub struct ThreadListOptionsBuilder(ThreadListOptions);

impl ThreadListOptionsBuilder {
    /// if `true`, show notifications marked as read. Default: `false`
    pub fn all(&mut self, all: bool) -> &mut Self {
        self.0.params.insert("all", all.to_string());
        self
    }

    /// if `true`, only shows notifications in which the user is directly participating or
    /// mentioned. Default: `false`
    pub fn participating(&mut self, val: bool) -> &mut Self {
        self.0.params.insert("participating", val.to_string());
        self
    }

    /// Only show notifications updated after the given time.
    pub fn since<T>(&mut self, since: T) -> &mut Self
    where
        T: Into<String>,
    {
        self.0.params.insert("since", since.into());
        self
    }

    /// Only show notifications updated before a given time.
    pub fn before<T>(&mut self, before: T) -> &mut Self
    where
        T: Into<String>,
    {
        self.0.params.insert("before", before.into());
        self
    }

    pub fn build(&self) -> ThreadListOptions {
        ThreadListOptions {
            params: self.0.params.clone(),
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct Subject {
    title: String,
    url: String,
    latest_comment_url: String,
    #[serde(rename = "type")]
    kind: String,
}

#[derive(Debug, Deserialize)]
pub struct Repository {
    pub id: u32,
    pub node_id: String,
    pub name: String,
    pub full_name: String,
    pub owner: User,
    pub html_url: String,
}

#[derive(Debug, Deserialize)]
pub struct Subscription {
    pub subscribed: bool,
    pub ignored: bool,
    pub reason: String,
    pub created_at: String,
    pub url: String,
    pub thread_url: String,
}