// This file is part of api-worker . // Copyright (C) 2022-2022 Fuwn // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // // Copyright (C) 2022-2022 Fuwn // SPDX-License-Identifier: GPL-3.0-only use worker::Cors; use crate::{constants, structures::GitHubAPIResponse}; /// # Errors /// if GitHub API is unresponsive pub async fn github_api( ) -> Result> { let mut client = reqwest::Client::new() .get(constants::GITHUB_API_ENDPOINT) .header( "User-Agent", format!("senpy-club/api-worker - {}", env!("GIT_COMMIT_HASH")), ); 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 .send() .await? .json::() .await .unwrap_or_default(), ) } /// # Panics /// if GitHub API is unresponsive pub async fn filter_languages() -> Vec { let mut languages = vec![]; for i in github_api().await.unwrap().tree { if i.r#type == "tree" { languages.push(i.path); } } languages } /// # Panics /// if GitHub API is unresponsive pub async fn filter_images_by_language(language: &str) -> Vec { let mut images = vec![]; // URL (percent) encoding of pound symbol to pound symbol let language = language.replace("%23", "#"); for item in github_api().await.unwrap().tree { if item.path.split('/').collect::>()[0] == language && item.path.contains('/') { images.push(format!( "{}{}", constants::GITHUB_USER_CONTENT, // Pound symbols to URL (percent) encoding of pound symbol because we // are pushing a URL, not a string item.path.replace('#', "%23") )); } } images } pub fn cors() -> Cors { Cors::default() .with_origins(vec!["*"]) .with_methods(vec![worker::Method::Get]) }