jensmemesclient/cli/src/commands/up.rs

90 lines
2.3 KiB
Rust

use crate::util;
use anyhow::{bail, Result};
use indicatif::{ProgressBar, ProgressStyle};
use libjens::{api::UpResp, JMClient};
use log::info;
use reqwest::{
multipart::{Form, Part},
Body,
};
use tokio::fs::File;
use tokio_util::codec::{BytesCodec, FramedRead};
pub async fn run(
client: &JMClient,
token: String,
path: String,
name: String,
category: String,
open: bool,
) -> Result<()> {
util::assert_category_exists(client, &category).await?;
let spinner = ProgressBar::new_spinner();
spinner.enable_steady_tick(50);
spinner.set_style(ProgressStyle::default_spinner().tick_strings(&[
"🗎 JM",
" 🗎 JM",
" 🗎 JM",
" 🗎 JM",
" 🗎 JM",
" 🗎 JM",
" 🗎 JM",
" 🗎JM",
"▪▪▪▪▪▪▪▪▪▪",
]));
spinner.set_message("Uploading...");
let res = client
.http
.post("https://api.tilera.xyz/jensmemes/v1/upload")
.multipart(
Form::new()
.text("category", category)
.text("token", token)
.part(
"file",
Part::stream(Body::wrap_stream(FramedRead::new(
{
info!("Opening file {}", &path);
File::open(path).await?
},
BytesCodec::new(),
)))
.file_name(name),
),
)
.send()
.await?;
let status = res.status();
// TODO move into JMClient
let bytes = &res.bytes().await?;
spinner.finish_with_message("Done!");
let res = if let Ok(res) = serde_json::from_slice::<UpResp>(bytes) {
res
} else if let Ok(s) = std::str::from_utf8(bytes) {
bail!("Server responded with unexpected response: {}", s);
} else {
bail!("Server responded with invalid utf8 bytes: {:?}", bytes);
};
println!("Server responded with code {}", status);
if !open {
println!();
}
for f in res.files {
if open {
util::open_link(&f).await?;
} else {
println!("{}", f);
}
}
Ok(())
}