jensmemesclient/cli/src/util.rs

85 lines
2.6 KiB
Rust
Raw Normal View History

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-19 19:43:23 +01:00
#[macro_export]
macro_rules! init_once_cell {
($cell:ident, $init_fn:expr) => {
match $cell.get() {
Some(x) => x,
None => {
let x = $init_fn;
$cell.get_or_init(|| x)
}
}
2020-12-05 12:08:24 +01:00
}
}
2020-12-05 12:32:01 +01:00
2020-12-19 19:43:23 +01:00
/// ways to communicyte with the JM API
pub mod api {
use once_cell::sync::OnceCell;
use log::info;
use crate::api::{Meme, CatsResp, MemesResp, User, UsersResp};
use reqwest::Client;
use anyhow::Result;
// cached api responses
static CATS: OnceCell<Vec<String>> = OnceCell::new();
static MEMES: OnceCell<Vec<Meme>> = OnceCell::new();
static USERS: OnceCell<Vec<User>> = OnceCell::new();
pub async fn cats(http: &Client) -> Result<&Vec<String>> {
Ok(init_once_cell!(CATS, {
2020-12-18 16:58:53 +01:00
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-19 19:43:23 +01:00
cats.categories.into_iter().map(|c| c.id).collect()
}))
}
2020-12-05 12:32:01 +01:00
2020-12-19 19:43:23 +01:00
pub async fn memes(http: &Client) -> Result<&Vec<Meme>> {
Ok(init_once_cell!(MEMES, {
2020-12-18 16:58:53 +01:00
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-19 19:43:23 +01:00
memes.memes
}))
}
2020-12-05 22:20:08 +01:00
2020-12-19 19:43:23 +01:00
pub async fn users(http: &Client) -> Result<&Vec<User>> {
Ok(init_once_cell!(USERS, {
info!("Requesting users from server");
let res = http.get("https://data.tilera.xyz/api/jensmemes/users").send().await?;
let users = serde_json::from_slice::<UsersResp>(&res.bytes().await?)?;
users.users
}))
}
}
pub async fn open_link(url: &str) -> anyhow::Result<()> {
match std::env::var_os("BROWSER") {
Some(browser) => {
Command::new(&browser).arg(url).status().await?;
2020-12-18 16:58:53 +01:00
},
2020-12-19 19:43:23 +01:00
None => opener::open(&url)?,
}
Ok(())
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()
}