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
//! This module contains functions which interface with the GitHub API.
//!
//! Every function in this module needs an instance of `AppTokens`, wherein the `discord` field does *not* need to be set.
//!
//! The GitHub authentication is used just to get a bigger rate limit,
//! so if you don't need to make a lot of requests just pass an empty string.


use hyper::header::{Authorization, IfNoneMatch, EntityTag, UserAgent, Bearer, ETag};
use self::super::super::util::GITHUB_USER_AGENT;
use hyper::status::StatusCode;
use self::super::super::Error;
use self::super::AppTokens;
use self::headers::*;
use hyper::Client;
use std::io::Read;


mod headers {
    header! {
        (XPollInterval, "X-Poll-Interval") => [u64]
    }
}


/// Check whether a user with the specified name exists.
///
/// # Examples
///
/// ```
/// # use dishub::ops::AppTokens;
/// # use dishub::ops::github::user_exists;
/// # let tokens = AppTokens {
/// #     github: "".to_string(),
/// #     discord: "".to_string(),
/// # };
/// let response = user_exists("nabijaczleweli", &tokens);
/// assert_eq!(response, Ok(true));
/// ```
pub fn user_exists(uname: &str, tokens: &AppTokens) -> Result<bool, Error> {
    exists(format!("https://api.github.com/users/{}", uname), tokens, "GitHub user information")
}

/// Check whether a repository with the specified slug exists.
///
/// # Examples
///
/// ```
/// # use dishub::ops::AppTokens;
/// # use dishub::ops::github::repo_exists;
/// # let tokens = AppTokens {
/// #     github: "".to_string(),
/// #     discord: "".to_string(),
/// # };
/// let response = repo_exists("nabijaczleweli/dishub", &tokens);
/// assert_eq!(response, Ok(true));
/// ```
pub fn repo_exists(slug: &str, tokens: &AppTokens) -> Result<bool, Error> {
    exists(format!("https://api.github.com/repos/{}", slug), tokens, "GitHub repository")
}

/// Get the events for a user when you don't have an ETag (which is to say - for the first time).
///
/// The returned tuple contains:
///
///   * The raw JSON response,
///   * The event bundle's ETag,
///   * The next minimum amount of milliseconds polling the same event queue is permitted.
///
/// You should use this only once and use `poll_user_events_update()` afterwards.
///
/// # Examples
///
/// ```no_run
/// # use dishub::ops::AppTokens;
/// # use dishub::ops::github::poll_user_events_new;
/// # let tokens = AppTokens {
/// #     github: "".to_string(),
/// #     discord: "".to_string(),
/// # };
/// let (response, etag, next) = poll_user_events_new("nabijaczleweli", &tokens).unwrap();
/// ```
pub fn poll_user_events_new(uname: &str, tokens: &AppTokens) -> Result<(String, String, u64), Error> {
    poll_events_new(format!("https://api.github.com/users/{}/events", uname), tokens, "GitHub user events")
}

/// Get the events for a repository when you don't have an ETag (which is to say - for the first time).
///
/// The returned tuple contains:
///
///   * The raw JSON response,
///   * The event bundle's ETag,
///   * The next minimum amount of milliseconds polling the same event queue is permitted.
///
/// You should use this only once and use `poll_repo_events_update()` afterwards.
///
/// # Examples
///
/// ```no_run
/// # use dishub::ops::AppTokens;
/// # use dishub::ops::github::poll_repo_events_new;
/// # let tokens = AppTokens {
/// #     github: "".to_string(),
/// #     discord: "".to_string(),
/// # };
/// let (response, etag, next) = poll_repo_events_new("nabijaczleweli/dishub", &tokens).unwrap();
/// ```
pub fn poll_repo_events_new(slug: &str, tokens: &AppTokens) -> Result<(String, String, u64), Error> {
    poll_events_new(format!("https://api.github.com/repos/{}/events", slug), tokens, "GitHub repo events")
}

/// Get the events for a user when you already have an ETag (which is to say - after the first time).
///
/// If the event list hasn't changed the first element of the returned tuple will be `None`,
/// otherwise it's a tuple of:
///
///   * The raw JSON response,
///   * The event bundle's new ETag.
///
/// The second element always constains the next minimum amount of milliseconds polling the same event queue is permitted.
///
/// # Examples
///
/// ```no_run
/// # use dishub::ops::AppTokens;
/// # use dishub::ops::github::poll_user_events_update;
/// # let tokens = AppTokens {
/// #     github: "".to_string(),
/// #     discord: "".to_string(),
/// # };
/// # let prev_etag = "9c1bac04e0735a8cba6a7b277b70c19f";
/// let (changed, next) = poll_user_events_update("nabijaczleweli", prev_etag, &tokens).unwrap();
/// if let Some((response, etag)) = changed {
///     // The feed changed
/// }
/// ```
pub fn poll_user_events_update(uname: &str, e_tag: &str, tokens: &AppTokens) -> Result<(Option<(String, String)>, u64), Error> {
    poll_events_update(format!("https://api.github.com/users/{}/events", uname), e_tag, tokens, "GitHub user events")
}

/// Get the events for a repository when you already have an ETag (which is to say - after the first time).
///
/// If the event list hasn't changed the first element of the returned tuple will be `None`,
/// otherwise it's a tuple of:
///
///   * The raw JSON response,
///   * The event bundle's new ETag.
///
/// The second element always constains the next minimum amount of milliseconds polling the same event queue is permitted.
///
/// # Examples
///
/// ```no_run
/// # use dishub::ops::AppTokens;
/// # use dishub::ops::github::poll_repo_events_update;
/// # let tokens = AppTokens {
/// #     github: "".to_string(),
/// #     discord: "".to_string(),
/// # };
/// # let prev_etag = "4797f0ad2ee145181045fe69c61676e6";
/// let (changed, next) = poll_repo_events_update("nabijaczleweli/dishub", prev_etag, &tokens).unwrap();
/// if let Some((response, etag)) = changed {
///     // The feed changed
/// }
/// ```
pub fn poll_repo_events_update(slug: &str, e_tag: &str, tokens: &AppTokens) -> Result<(Option<(String, String)>, u64), Error> {
    poll_events_update(format!("https://api.github.com/repos/{}/events", slug), e_tag, tokens, "GitHub user events")
}

fn exists(url: String, tokens: &AppTokens, desc: &'static str) -> Result<bool, Error> {
    Client::new()
        .get(&url)
        .header(Authorization(Bearer { token: tokens.github.clone() }))
        .header(UserAgent(GITHUB_USER_AGENT.to_string()))
        .send()
        .map_err(|_| {
            Error::Io {
                desc: desc,
                op: "get",
            }
        })
        .map(|r| r.status != StatusCode::NotFound)
}

fn poll_events_new(url: String, tokens: &AppTokens, desc: &'static str) -> Result<(String, String, u64), Error> {
    Client::new()
        .get(&url)
        .header(Authorization(Bearer { token: tokens.github.clone() }))
        .header(UserAgent(GITHUB_USER_AGENT.to_string()))
        .send()
        .map_err(|_| {
            Error::Io {
                desc: desc,
                op: "poll",
            }
        })
        .map(|mut r| {
            let mut buf = String::new();
            r.read_to_string(&mut buf).unwrap();

            let etag: &ETag = r.headers.get().unwrap();
            let poll_interval: &XPollInterval = r.headers.get().unwrap();
            (buf, etag.tag().to_string(), **poll_interval)
        })
}

fn poll_events_update(url: String, etag: &str, tokens: &AppTokens, desc: &'static str) -> Result<(Option<(String, String)>, u64), Error> {
    Client::new()
        .get(&url)
        .header(Authorization(Bearer { token: tokens.github.clone() }))
        .header(UserAgent(GITHUB_USER_AGENT.to_string()))
        .header(IfNoneMatch::Items(vec![EntityTag::new(false, etag.to_string())]))
        .send()
        .map_err(|_| {
            Error::Io {
                desc: desc,
                op: "poll",
            }
        })
        .map(|mut r| {
            (if r.status == StatusCode::NotModified {
                None
            } else {
                let mut buf = String::new();
                r.read_to_string(&mut buf).unwrap();

                let etag: &ETag = r.headers.get().unwrap();
                Some((buf, etag.tag().to_string()))
            },
             r.headers.get::<XPollInterval>().map(|r| **r).unwrap_or(60))
        })
}