Configuration struct (#6)

Configuration struct stores username, password or password script, Nextcloud root, and target path
This commit is contained in:
Adam Cooper 2022-03-20 04:04:24 -04:00
parent a7d5962d30
commit 703a7c4810
3 changed files with 49 additions and 19 deletions

14
Cargo.lock generated
View File

@ -793,6 +793,20 @@ name = "serde"
version = "1.0.136"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.136"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"

View File

@ -11,7 +11,7 @@ dotenv = "0.15.0"
env_logger = "0.8.4"
log = "0.4.0"
reqwest = { version = "0.11", features = ["json"] }
serde = "1.0.136"
serde = { version = "1.0.136" , features = ["derive"] }
tokio = { version = "1", features = ["full"] }
toml = "0.5.8"
url = "2.2.2"

View File

@ -7,28 +7,33 @@ use log::{debug, error, info, log_enabled, warn};
use reqwest;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::io::{self, Write};
#[allow(unused)]
use std::process::Command;
use std::str;
use toml;
use url::Url;
#[allow(unused)]
use yaserde_derive::{YaDeserialize, YaSerialize};
use yaserde::de::from_str;
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
pub struct Config {
credentials: Credentials,
paths: NextcloudPaths,
}
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
pub struct Credentials {
username: String,
password: String,
password: Option<String>,
password_script: Option<String>,
}
#[derive(Deserialize)]
#[derive(Debug, Deserialize)]
pub struct NextcloudPaths {
root: Url,
root: String,
target: String,
}
@ -111,13 +116,16 @@ pub struct Collection {
fn init() -> Result<Config, Box<dyn std::error::Error>> {
let xdg_dirs = xdg::BaseDirectories::with_prefix("publicise-rs").unwrap();
let config_file = xdg_dirs.find_config_file("config.toml").unwrap();
return Error{};
let config_path = xdg_dirs.find_config_file("config.toml").unwrap();
let config_file_contents = fs::read_to_string(config_path).unwrap();
let config: Config = toml::from_str(&config_file_contents).unwrap();
return Ok(config);
}
async fn get_folder_contents(url_tail: &str, password: &str) -> Result<String, Box<dyn std::error::Error>> {
#[allow(unused)]
async fn get_folder_contents(url_tail: &str, config: &Config) -> Result<String, Box<dyn std::error::Error>> {
debug!("[get_folder_contents] Entering function...");
let root_url = Url::parse("https://cloud.theadamcooper.com")?;
let root_url = Url::parse(&config.paths.root)?;
let method = reqwest::Method::from_bytes(b"PROPFIND").unwrap();
let client = reqwest::Client::new();
let url = root_url.join(url_tail)?;
@ -138,7 +146,7 @@ async fn get_folder_contents(url_tail: &str, password: &str) -> Result<String, B
);
let response_text = client
.request(method, url)
.basic_auth("adam", Some(password))
.basic_auth("adam", config.credentials.password.as_ref())
.body(body)
.send()
.await?
@ -148,6 +156,7 @@ async fn get_folder_contents(url_tail: &str, password: &str) -> Result<String, B
Ok(response_text)
}
#[allow(unused)]
async fn publicise_it(path: &str, password: &str) -> Result<bool, Box<dyn std::error::Error>> {
debug!("[publicise_it] Entering function...");
let url = "https://cloud.theadamcooper.com/ocs/v2.php/apps/files_sharing/api/v1/shares";
@ -169,7 +178,8 @@ async fn publicise_it(path: &str, password: &str) -> Result<bool, Box<dyn std::e
Ok(true)
}
async fn traverse(mut result: Multistatus, password: &str) -> Result<bool, Box<dyn std::error::Error>> {
#[allow(unused)]
async fn traverse(mut result: Multistatus, config: &Config) -> Result<bool, Box<dyn std::error::Error>> {
debug!("[traverse] Entering function...");
// Initialize the indexed "pointer"
let mut current_index: usize = 0;
@ -193,7 +203,7 @@ async fn traverse(mut result: Multistatus, password: &str) -> Result<bool, Box<d
// Get the contents XML
let folder_contents: String = get_folder_contents(
&result.response[current_index].href, // change to mutable borrow if necessary
password,
config,
)
.await
.unwrap();
@ -215,7 +225,7 @@ async fn traverse(mut result: Multistatus, password: &str) -> Result<bool, Box<d
let index = &result.response[current_index].href.find(username_seg).unwrap_or(0);
let new_index = index + username.len() + 2;
let new_href = &result.response[current_index].href[new_index..];
publicise_it(new_href, password).await.unwrap();
publicise_it(new_href, config.credentials.password.as_ref().unwrap()).await.unwrap();
} else {
debug!("[traverse] it's already public");
}
@ -230,6 +240,7 @@ async fn traverse(mut result: Multistatus, password: &str) -> Result<bool, Box<d
Ok(true)
}
#[allow(unused)]
fn get_password() -> Result<String, std::io::Error> {
print!("Nextcloud password: ");
io::stdout().flush().unwrap();
@ -257,16 +268,21 @@ async fn main() -> std::io::Result<()> {
.init();
println!("Publicise it!\n\n");
let config = init().unwrap();
let password: String = get_password().unwrap().trim().to_string();
let mut config = init().unwrap();
if config.credentials.password == None {
let output = Command::new(&config.credentials.password_script.as_ref().unwrap()).output().unwrap();
config.credentials.password = Some(String::from_utf8(output.stdout).unwrap());
}
debug!("{:?}", &config);
let full_path = &(String::from("/remote.php/dav/files/") + &config.credentials.username + "/" + &config.paths.target);
let folder_contents: String =
get_folder_contents("/remote.php/dav/files/adam/test_public", &password)
get_folder_contents(full_path, &config)
.await
.unwrap();
let result: Multistatus = from_str(&folder_contents).unwrap();
debug!("{:?}", result);
let _ = traverse(result, &password).await.unwrap();
let _ = traverse(result, &config).await.unwrap();
Ok(())
}