jensmemesclient/cli/src/util.rs
2020-12-06 14:57:14 +01:00

65 lines
1.8 KiB
Rust

use std::unreachable;
use anyhow::Result;
use log::info;
use once_cell::sync::OnceCell;
use reqwest::Client;
use term_table::{Table, TableBuilder, TableStyle};
use tokio::process::Command;
use crate::api::{CatsResp, Meme, MemesResp};
// cached api responses
static CATS: OnceCell<Vec<String>> = OnceCell::new();
static MEMES: OnceCell<Vec<Meme>> = OnceCell::new();
pub async fn open_link(url: &str) -> anyhow::Result<()> {
match std::env::var_os("BROWSER") {
Some(browser) => {
Command::new(&browser).arg(url).status().await?;
},
None => opener::open(&url)?,
}
Ok(())
}
pub async fn cats(http: &Client) -> Result<&Vec<String>> {
if CATS.get().is_none() {
info!("Requesting categories from server");
let res = http
.get("https://data.tilera.xyz/api/jensmemes/categories")
.send()
.await?;
let cats = serde_json::from_slice::<CatsResp>(&res.bytes().await?)?;
Ok(CATS.get_or_init(|| cats.categories.into_iter().map(|c| c.id).collect()))
} else {
unreachable!();
}
}
pub async fn memes(http: &Client) -> Result<&Vec<Meme>> {
if MEMES.get().is_none() {
info!("Requesting memes from server");
let res = http
.get("https://data.tilera.xyz/api/jensmemes/memes")
.send()
.await?;
let memes = serde_json::from_slice::<MemesResp>(&res.bytes().await?)?;
Ok(MEMES.get_or_init(|| memes.memes))
} else {
unreachable!();
}
}
/// returns an empty table with the correct format settings for lists
pub fn list_table<'a>() -> Table<'a> {
TableBuilder::new()
.style(TableStyle::simple())
.separate_rows(false)
.has_top_boarder(false)
.has_bottom_boarder(false)
.build()
}