aboutsummaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: a55ddc68856a9e268fc6193fa9d1e49f284e0a05 (plain) (blame)
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
// Copyright (C) 2021-2021 the senpy club
// SPDX-License-Identifier: GPL-3.0-only

use crate::{
  constants::{GITHUB_API_ENDPOINT, GITHUB_USER_CONTENT, USER_AGENT},
  structures::GitHubAPIResponse,
};

/// # Errors
/// if GitHub API is unresponsive
pub async fn github_api() -> Result<GitHubAPIResponse, Box<dyn std::error::Error>> {
  let mut client = actix_web::client::Client::new()
    .get(GITHUB_API_ENDPOINT)
    .header("User-Agent", USER_AGENT);

  if std::env::var("GITHUB_TOKEN").is_ok() {
    client = client.header(
      "Authorization",
      format!(
        "token {}",
        std::env::var("GITHUB_TOKEN").unwrap_or_else(|_| "Null".to_string())
      ),
    );
  }

  Ok(
    client
      .timeout(std::time::Duration::from_secs(60))
      .send()
      .await?
      .json::<GitHubAPIResponse>()
      .limit(20_000_000)
      .await
      .unwrap_or_default(),
  )
}

/// # Panics
/// if GitHub API is unresponsive
pub async fn filter_languages() -> Vec<String> {
  let mut languages = vec![];

  for i in github_api().await.unwrap().tree {
    #[allow(clippy::used_underscore_binding)]
    if i._type == "tree" {
      languages.push(i.path);
    }
  }

  languages
}

/// # Panics
/// if GitHub API is unresponsive
pub async fn filter_images_by_language(language: &str) -> Vec<String> {
  let mut images = vec![];

  for i in github_api().await.unwrap().tree {
    // Example:
    //  "Language/Image.png" would become ["Language", "Image.png"]

    // TODO: Fix this with type_ascription
    let x: Vec<&str> = i.path.split('/').collect();
    if x[0] == language && i.path.contains('/') {
      images.push(format!("{}{}", GITHUB_USER_CONTENT, i.path));
    }
  }

  images
}