Browse Source

Saving attachments to disk too!

master
Julio Biason 6 years ago
parent
commit
9a7c35436c
  1. 1
      Cargo.lock
  2. 1
      Cargo.toml
  3. 33
      src/main.rs

1
Cargo.lock generated

@ -277,7 +277,6 @@ dependencies = [
"elefren 0.19.4 (registry+https://github.com/rust-lang/crates.io-index)", "elefren 0.19.4 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
"html2md 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)", "html2md 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)",
"hyper 0.12.28 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"reqwest 0.9.17 (registry+https://github.com/rust-lang/crates.io-index)", "reqwest 0.9.17 (registry+https://github.com/rust-lang/crates.io-index)",
] ]

1
Cargo.toml

@ -8,6 +8,5 @@ edition = "2018"
elefren = { version = "0.19", features = ["toml"] } elefren = { version = "0.19", features = ["toml"] }
html2md = "0.2.9" html2md = "0.2.9"
reqwest = "0.9.17" reqwest = "0.9.17"
hyper = "*"
log = "0.4.6" log = "0.4.6"
env_logger = "0.6.1" env_logger = "0.6.1"

33
src/main.rs

@ -11,8 +11,6 @@ use elefren::prelude::*;
use reqwest; use reqwest;
use hyper::Uri;
use log; use log;
use env_logger; use env_logger;
@ -76,14 +74,29 @@ fn save_attachments(record: &Status) -> () {
fn save_attachment(attachment: &Attachment, base_path: &PathBuf) -> () { fn save_attachment(attachment: &Attachment, base_path: &PathBuf) -> () {
log::debug!("Saving attachment {}", attachment.url); log::debug!("Saving attachment {}", attachment.url);
let uri: Uri = attachment.url.parse().expect("Invalid URL"); let filename = base_path.join(get_attachment_filename(&attachment.url));
let body = reqwest::get(&attachment.url) log::debug!("Saving attachment to {:?}", filename);
.expect("Failed to connect to server") if let Ok(mut fp) = File::create(filename) {
.text() reqwest::get(&attachment.url)
.expect("Failed to retrieve attachment"); .expect("Failed to connect to server")
.copy_to(&mut fp)
.expect("Failed to save attachment");
}
}
if let Ok(mut fp) = File::create(base_path.join(uri.path())) { fn get_attachment_filename(url: &str) -> String {
fp.write_all(body.as_bytes()) let mut frags = url.rsplitn(2, '/');
.expect("Failed to save the attachment"); log::debug!("URL fragments: {:?}", frags);
if let Some(path_part) = frags.next() {
log::debug!("Found path in the attachment URL: {:?}", path_part);
path_part
.split('?')
.next()
.unwrap_or(url)
.to_string()
} else {
// this is, most of the time, bad (due special characters -- like '?' -- and path)
log::debug!("No path in attachment, using full URL");
url.to_string()
} }
} }

Loading…
Cancel
Save