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
//! This crate exports some GitHub API bindings through [`GitHub`].

use std::collections::HashSet;
use std::ops::{Deref, DerefMut};

use octorust::auth::Credentials;
use octorust::Client;
use tracing::{info, instrument, Level};

type Result<T> = std::result::Result<T, octorust::ClientError>;

/// Asynchronous GitHub API bindings that wraps [`octorust::Client`] internally.
///
/// # Examples
///
/// ```rust
/// use gfas_api::GitHub;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let github = GitHub::new(String::from("<TOKEN>"))?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
#[repr(transparent)]
pub struct GitHub(Client);

impl Deref for GitHub {
    type Target = Client;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for GitHub {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl GitHub {
    /// Create a new GitHub API client.
    pub fn new(token: String) -> Result<Self> {
        Ok(Self(Client::new("gfas", Credentials::Token(token))?))
    }

    /// Paginates through the given user profile link and returns
    /// discovered followings/followers collected in [`HashSet`].
    ///
    /// # Errors
    ///
    /// Fails if an error occurs during sending requests.
    #[instrument(skip(self), ret(level = Level::TRACE), err)]
    pub async fn explore(&self, user: &str, following: bool) -> Result<HashSet<String>> {
        let mut res = HashSet::new();

        const PER_PAGE: i64 = 100;

        let users = self.users();

        for page in 1.. {
            let response = if following {
                users.list_following_for_user(user, PER_PAGE, page).await
            } else {
                users.list_followers_for_user(user, PER_PAGE, page).await
            }?;

            let explored = response.body.into_iter().map(|u| u.login);

            let len = explored.len() as i64;

            res.extend(explored);

            info!("{}(+{len})", res.len());

            if len < PER_PAGE {
                break;
            }
        }

        Ok(res)
    }
}