use super::structs::{
CatalogResponse,
CatalogThread,
ThreadResponse,
Thread,
};
use reqwest::header::COOKIE;
use std::result::Result;
pub struct Fetch;
impl Fetch {
const COOKIE_BODY: &'static str = "usercode_auth=1d1262ef030bfb23499773c8a3ab01cb";
pub fn catalog(board: &str) -> Result<Vec<CatalogThread>, String> {
let catalog_link = Links::catalog(&board, "json");
let client = reqwest::Client::new();
let response: CatalogResponse<CatalogThread> = client.get(&catalog_link)
.header(COOKIE, Fetch::COOKIE_BODY)
.send()
.map_err(|err| {
format!("Ошибка получения раздела {} ({})", &board, err)
})?
.json()
.map_err(|err| {
format!("Ошибка преобразования раздела {} ({})", &board, err)
})?;
Ok(response.threads.clone())
}
pub fn thread(board: &str, thread: &CatalogThread) -> Result<Thread, String> {
let thread_link = Links::thread(&board, &thread.num, "json");
let client = reqwest::Client::new();
let response: ThreadResponse<Thread> = client.get(&thread_link)
.header(COOKIE, Fetch::COOKIE_BODY)
.send()
.map_err(|err| {
format!("Ошибка получения треда {} ({})", &thread.num, err)
})?
.json()
.map_err(|err| {
format!("Ошибка преобразования треда {} ({})", &thread.num, err)
})?;
Ok(response.threads[0].clone())
}
}
pub struct Links;
#[allow(dead_code)]
impl Links {
pub fn catalog(board: &str, format: &str) -> String {
let url = format!("https://2ch.hk/{}/threads.{}", board, format);
url
}
pub fn board(board: &str, page: i32, format: &str) -> String {
let page_id: String = match page {
0 => "index".to_string(),
_ => page.to_string(),
};
let url = format!("https://2ch.hk/{}/{}.{}", board, page_id, format);
url
}
pub fn thread(board: &str, thread_num: &str, format: &str) -> String {
let url = format!("https://2ch.hk/{}/res/{}.{}", board, thread_num, format);
url
}
}