use crate::structs; use std::fs::write; use std::path::Path; extern crate reqwest; extern crate serde_json; pub fn generate_slug(text: &str) -> String { text.to_lowercase().trim().replace(|c: char| !c.is_alphanumeric(), "-") } pub async fn get_manga(client: reqwest::Client, id: i32) -> Result, structs::Error> { let resp = client.get(&format!("https://mangadex.org/api/v2/manga/{}?include=chapters", &id)) .send() .await?; if resp.status() == 404 { return Ok(None); } resp.error_for_status_ref()?; Ok(Some(serde_json::from_str(&resp.text().await?)?)) } pub async fn get_chapter(client: reqwest::Client, chapter: i32) -> Result, structs::Error> { let resp = client.get(&format!("https://mangadex.org/api/v2/chapter/{}", &chapter)) .send() .await?; if resp.status() == 404 { return Ok(None); } resp.error_for_status_ref()?; Ok(Some(serde_json::from_str(&resp.text().await?)?)) } pub async fn download_page(client: reqwest::Client, server: &str, server_fallback: &str, hash: &str, server_file: &str, local_file: &Path) -> Result { let res = download(client.clone(), &format!("{}{}/{}", &server, &hash, &server_file), &local_file).await; if server_fallback.is_empty() { return res; } match res { Ok(true) => Ok(true), _ => download(client.clone(), &format!("{}{}/{}", &server_fallback, &hash, &server_file), &local_file).await } } async fn download(client: reqwest::Client, url: &str, file: &Path) -> Result { let resp = client.get(url) .send() .await?; if resp.status() == 404 { return Ok(false); } resp.error_for_status_ref()?; let bytes = resp.bytes().await?; write(&file, bytes)?; Ok(true) }