jensmemesclient/cli/src/util.rs

66 lines
1.8 KiB
Rust
Raw Normal View History

2020-12-05 12:32:01 +01:00
use anyhow::Result;
2020-12-06 14:57:14 +01:00
use log::info;
2020-12-05 12:32:01 +01:00
use once_cell::sync::OnceCell;
use reqwest::Client;
2020-12-05 22:20:08 +01:00
use term_table::{Table, TableBuilder, TableStyle};
2020-12-05 12:08:24 +01:00
use tokio::process::Command;
2020-12-05 22:20:08 +01:00
use crate::api::{CatsResp, Meme, MemesResp};
2020-12-05 12:32:01 +01:00
2020-12-05 22:20:08 +01:00
// cached api responses
2020-12-05 12:32:01 +01:00
static CATS: OnceCell<Vec<String>> = OnceCell::new();
2020-12-05 22:20:08 +01:00
static MEMES: OnceCell<Vec<Meme>> = OnceCell::new();
2020-12-05 12:32:01 +01:00
2020-12-05 12:08:24 +01:00
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(())
}
2020-12-05 12:32:01 +01:00
pub async fn cats(http: &Client) -> Result<&Vec<String>> {
2020-12-18 16:58:53 +01:00
Ok(match CATS.get() {
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?)?;
2020-12-05 12:32:01 +01:00
2020-12-18 16:58:53 +01:00
CATS.get_or_init(|| cats.categories.into_iter().map(|c| c.id).collect())
},
Some(x) => x,
})
2020-12-05 12:32:01 +01:00
}
2020-12-05 22:20:08 +01:00
pub async fn memes(http: &Client) -> Result<&Vec<Meme>> {
2020-12-18 16:58:53 +01:00
Ok(match MEMES.get() {
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?)?;
2020-12-05 22:20:08 +01:00
2020-12-18 16:58:53 +01:00
MEMES.get_or_init(|| memes.memes)
},
Some(x) => x,
})
2020-12-05 22:20:08 +01:00
}
/// 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()
}