jensmemesclient/cli/src/commands/up.rs

71 lines
1.6 KiB
Rust
Raw Normal View History

2021-05-27 18:01:30 +02:00
use crate::util;
use anyhow::{Result, bail};
2021-05-27 18:01:30 +02:00
use jm_client_core::{api::UpResp, JMClient};
2020-12-06 14:57:14 +01:00
use log::info;
2020-12-05 12:08:24 +01:00
use reqwest::{
multipart::{Form, Part},
Body,
};
use tokio::{fs::File, io::reader_stream};
pub async fn run(
2021-05-27 18:01:30 +02:00
client: &JMClient,
2020-12-05 12:08:24 +01:00
token: String,
path: String,
name: String,
category: String,
open: bool,
) -> Result<()> {
2021-05-27 18:01:30 +02:00
util::assert_category_exists(client, &category).await?;
2020-12-05 12:08:24 +01:00
2021-05-27 18:01:30 +02:00
let res = client
.http
2020-12-05 12:08:24 +01:00
.post("https://data.tilera.xyz/api/jensmemes/upload")
.multipart(
Form::new()
.text("category", category)
.text("token", token)
.part(
"file",
2020-12-06 14:57:14 +01:00
Part::stream(Body::wrap_stream(reader_stream({
info!("Opening file {}", &path);
File::open(path).await?
})))
.file_name(name),
2020-12-05 12:08:24 +01:00
),
)
.send()
.await?;
let status = res.status();
2021-05-27 18:01:30 +02:00
// TODO move into JMClient
let bytes = &res.bytes().await?;
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);
}
};
2020-12-05 12:08:24 +01:00
println!("Server responded with code {}", status);
2020-12-05 12:32:01 +01:00
2020-12-05 12:08:24 +01:00
if !open {
println!();
}
for f in res.files {
if open {
2021-05-27 18:01:30 +02:00
util::open_link(&f).await?;
2020-12-05 12:08:24 +01:00
} else {
println!("{}", f);
}
}
Ok(())
}