-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.rs
67 lines (61 loc) · 2.24 KB
/
upload.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use std::{error::Error, fmt::Write};
use anyhow::{anyhow, bail, Result};
use multipart::client::lazy::Multipart;
use ureq::Transport;
use crate::types::{FinishUploadResult, InitUploadResult};
fn transport_error(api_name: &str, e: Transport) -> Result<()> {
let mut msg = format!("{api_name}: {}", e.kind());
if let Some(message) = e.message() {
write!(msg, ": {message}")?;
}
if let Some(source) = e.source() {
write!(msg, ": {source}")?;
}
Err(anyhow!(msg))
}
pub fn upload_mod(mod_name: &str, api_key: &str, file: &[u8]) -> Result<()> {
let upload_url = match ureq::post("https://mods.factorio.com/api/v2/mods/releases/init_upload")
.set("authorization", &format!("Bearer {api_key}"))
.send_form(&[("mod", mod_name)])
{
Err(ureq::Error::Status(code, res)) => {
return Err(anyhow!("init_upload: status code {code}").context(
match res.into_json()? {
InitUploadResult::Err(e) => e.to_string(),
_ => String::from("Unknown error"),
},
))
}
Err(ureq::Error::Transport(e)) => return transport_error("init_upload", e),
Ok(res) => match res.into_json()? {
InitUploadResult::Err(e) => bail!(e),
InitUploadResult::Ok { upload_url } => upload_url,
},
};
let parts = Multipart::new()
.add_stream(
"file",
file,
Some(format!("{mod_name}.zip")),
Some("application/x-zip-compressed".parse()?),
)
.prepare()?;
match ureq::post(&upload_url)
.set(
"Content-Type",
&format!("multipart/form-data; boundary={}", parts.boundary()),
)
.send(parts)
{
Err(ureq::Error::Status(code, res)) => Err(anyhow!("finish_upload: status code {code}")
.context(match res.into_json()? {
FinishUploadResult::Err(e) => e.to_string(),
_ => String::from("Unknown error"),
})),
Err(ureq::Error::Transport(e)) => transport_error("finish_upload", e),
Ok(res) => match res.into_json()? {
FinishUploadResult::Err(e) => Err(e.into()),
_ => Ok(()),
},
}
}