aboutsummaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: 3d40e7cd6940ef70ec49b54d75971f3c3ed11dda (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
// Copyleft (ɔ) 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,
};

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(),
  )
}

pub async fn filter_languages() -> Vec<String> {
  let mut languages = vec![];

  for i in github_api().await.unwrap().tree {
    if i._type == "tree" {
      languages.push(i.path);
    }
  }

  languages
}

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
}