Compare commits

..

No commits in common. "main" and "yaserde" have entirely different histories.

6 changed files with 62 additions and 249 deletions

3
.gitignore vendored
View file

@ -1,5 +1,4 @@
/target
.env
Cargo.lock
scratchpad/
*.bak
example*.xml

77
Cargo.lock generated
View file

@ -11,12 +11,6 @@ dependencies = [
"memchr",
]
[[package]]
name = "array_tool"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f8cb5d814eb646a863c4f24978cff2880c4be96ad8cde2c0f0678732902e271"
[[package]]
name = "atty"
version = "0.2.14"
@ -86,26 +80,6 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
[[package]]
name = "dirs"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03d86534ed367a67548dc68113a0f5db55432fdfbb6e6f9d77704397d95d5780"
dependencies = [
"libc",
"redox_users",
"winapi",
]
[[package]]
name = "dotenv"
version = "0.15.0"
@ -600,16 +574,11 @@ dependencies = [
name = "publicise-rs"
version = "0.1.0"
dependencies = [
"array_tool",
"dotenv",
"env_logger",
"log",
"reqwest",
"serde",
"tokio",
"toml",
"url",
"xdg",
"yaserde",
"yaserde_derive",
]
@ -672,16 +641,6 @@ dependencies = [
"bitflags",
]
[[package]]
name = "redox_users"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "528532f3d801c87aec9def2add9ca802fe569e44a544afe633765267840abe64"
dependencies = [
"getrandom",
"redox_syscall",
]
[[package]]
name = "regex"
version = "1.5.4"
@ -790,23 +749,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.136"
version = "1.0.131"
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",
]
checksum = "b4ad69dfbd3e45369132cc64e6748c2d65cdfb001a2b1c232d128b4ad60561c1"
[[package]]
name = "serde_json"
@ -966,15 +911,6 @@ dependencies = [
"tokio",
]
[[package]]
name = "toml"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa"
dependencies = [
"serde",
]
[[package]]
name = "tower-service"
version = "0.3.1"
@ -1184,15 +1120,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "xdg"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c4583db5cbd4c4c0303df2d15af80f0539db703fa1c68802d4cbbd2dd0f88f6"
dependencies = [
"dirs",
]
[[package]]
name = "xml-rs"
version = "0.8.4"

View file

@ -6,15 +6,10 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
array_tool = "1.0.3"
dotenv = "0.15.0"
env_logger = "0.8.4"
log = "0.4.0"
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0.136" , features = ["derive"] }
tokio = { version = "1", features = ["full"] }
toml = "0.5.8"
url = "2.2.2"
xdg = "2.4.1"
yaserde = "0.7.1"
yaserde_derive = "0.7.1"

13
LICENSE
View file

@ -1,13 +0,0 @@
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.

View file

@ -1,5 +0,0 @@
### publicise-rs
_Publicise_ is an application which traverses a Nextcloud folder and creates a public share for each file.
The application was originally devised as a way to share photos with people without Instagram accounts, and as an exploration of Rust.

View file

@ -1,36 +1,15 @@
extern crate xdg;
use env_logger::Env;
use log::debug;
#[allow(unused)]
use env_logger::{Env, Target};
#[allow(unused)]
use log::{debug, error, info, log_enabled, warn};
use reqwest;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::process::Command;
use std::str;
use toml;
use url::Url;
use yaserde_derive::YaDeserialize;
use yaserde::de::from_str;
#[allow(unused)]
use std::io::{self, BufReader, Write};
#[allow(unused)]
use yaserde_derive::{YaDeserialize, YaSerialize};
#[derive(Debug, Deserialize)]
pub struct Config {
credentials: Credentials,
paths: NextcloudPaths,
}
#[derive(Debug, Deserialize)]
pub struct Credentials {
username: String,
password: Option<String>,
password_script: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct NextcloudPaths {
root: String,
target: String,
}
#[allow(unused)]
fn publicise() {}
#[derive(Default, PartialEq, Debug, YaDeserialize)]
#[yaserde(
@ -39,7 +18,7 @@ pub struct NextcloudPaths {
namespace = "d: DAV:",
namespace = "nc: http://nextcloud.org/ns",
namespace = "oc: http://owncloud.org/ns",
namespace = "s: http://sabredav.org/ns"
namespace = "s: http://sabredav.org/ns",
)]
pub struct Multistatus {
#[yaserde(prefix = "d")]
@ -50,7 +29,7 @@ pub struct Multistatus {
#[yaserde(rename = "response", prefix = "d", namespace = "d: DAV:")]
pub struct NextcloudResponse {
#[yaserde(prefix = "d")]
href: String,
href: Option<String>,
#[yaserde(prefix = "d")]
propstat: Vec<Propstat>,
}
@ -59,30 +38,26 @@ pub struct NextcloudResponse {
#[yaserde(rename = "propstat", prefix = "d", namespace = "d: DAV:")]
pub struct Propstat {
#[yaserde(prefix = "d")]
prop: Prop,
prop: Option<Prop>,
#[yaserde(prefix = "d")]
status: String,
status: Option<String>,
}
#[derive(Default, PartialEq, Debug, YaDeserialize)]
#[yaserde(
rename = "prop",
namespace = "d: DAV:",
namespace = "oc: http://owncloud.org/ns"
)]
#[yaserde(rename = "prop", namespace = "d: DAV:", namespace = "oc: http://owncloud.org/ns")]
pub struct Prop {
#[yaserde(prefix = "d", rename = "getlastmodified")]
get_last_modified: String,
get_last_modified: Option<String>,
#[yaserde(prefix = "oc")]
permissions: String,
permissions: Option<String>,
#[yaserde(prefix = "d", rename = "resourcetype")]
resource_type: ResourceType,
resource_type: Option<ResourceType>,
#[yaserde(prefix = "d", rename = "getetag")]
get_etag: String,
get_etag: Option<String>,
#[yaserde(prefix = "d", rename = "getcontentlength")]
get_content_length: u32,
get_content_length: Option<u32>,
#[yaserde(prefix = "d", rename = "getcontenttype")]
get_content_type: String,
get_content_type: Option<String>,
#[yaserde(prefix = "oc", rename = "share-types")]
share_types: Vec<ShareType>,
}
@ -105,26 +80,19 @@ pub struct ResourceType {
#[yaserde(rename = "collection", namespace = "d: DAV:")]
pub struct Collection {
#[yaserde(prefix = "d")]
collection: String,
collection: Option<String>,
}
fn init() -> Result<Config, Box<dyn std::error::Error>> {
debug!("[init] Entering function...");
let xdg_dirs = xdg::BaseDirectories::with_prefix("publicise-rs").unwrap();
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();
debug!("[init] config: {:?}", config);
return Ok(config);
}
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(&config.paths.root)?;
async fn get_folder_contents(
password: String,
url_tail: &str,
) -> Result<String, Box<dyn std::error::Error>> {
debug!("Entering: get_folder_contents()");
let root_url = "https://theadamcooper.com";
let method = reqwest::Method::from_bytes(b"PROPFIND").unwrap();
let client = reqwest::Client::new();
let url = root_url.join(url_tail)?;
debug!("[get_folder_contents] url: {}", url);
let url = format!("{}{}", root_url, url_tail);
debug!("url: {}", url);
let body = String::from(
r#"<?xml version="1.0" encoding="UTF-8"?>
<d:propfind xmlns:d="DAV:">
@ -141,111 +109,53 @@ async fn get_folder_contents(url_tail: &str, config: &Config) -> Result<String,
);
let response_text = client
.request(method, url)
.basic_auth(config.credentials.username.as_str(), config.credentials.password.as_ref())
.basic_auth("adam", Some(password))
.body(body)
.send()
.await?
.text()
.await?;
debug!("[get_folder_contents] response_text: {:?}", response_text);
debug!("{:?}", response_text);
Ok(response_text)
}
async fn publicise_it(path: &str, config: &Config) -> Result<bool, Box<dyn std::error::Error>> {
debug!("[publicise_it] Entering function...");
let base_url = Url::parse(config.paths.root.as_str())?;
let url = base_url.join("ocs/v2.php/apps/files_sharing/api/v1/shares")?;
let method = reqwest::Method::POST;
let client = reqwest::Client::new();
let params = [("path", path), ("shareType", "3")];
debug!("[publicise_it] url: {}", url);
debug!("[publicise_it] params: {:?}", params);
let response_text = client
.request(method, url)
.basic_auth(config.credentials.username.as_str(), config.credentials.password.as_ref())
.header("OCS-APIRequest", "true")
.form(&params)
.send()
.await?
.text()
.await?;
debug!("[publicise_it] response_text: {:?}", response_text);
Ok(true)
fn get_password() -> Result<String, std::io::Error> {
print!("Nextcloud password: ");
io::stdout().flush().unwrap();
let mut buffer = String::new();
let stdin = io::stdin();
match stdin.read_line(&mut buffer) {
Ok(_) => Ok(buffer),
Err(error) => Err(error),
}
}
async fn traverse(mut result: Multistatus, config: &Config) -> Result<bool, Box<dyn std::error::Error>> {
debug!("[traverse] Entering function...");
let mut current_index: usize = 0;
let mut visited_items = HashMap::new();
let href_key = (&mut result.response[current_index].href).clone();
visited_items.insert(href_key, true);
current_index += 1;
while current_index < (&mut result.response).len() {
debug!("[traverse] current_index: {:?}", current_index);
debug!("[traverse] current href: {}", &result.response[current_index].href);
let href_key = (&mut result.response[current_index].href).clone();
if !visited_items.contains_key(&href_key) {
debug!("[traverse] Fresh item...");
if !(&mut result.response[current_index].propstat[0].prop.resource_type.collection).is_empty() {
debug!("[traverse] Collection...");
let folder_contents: String = get_folder_contents(
&result.response[current_index].href,
config,
)
.await
.unwrap();
let mut new_result: Multistatus = from_str(&String::from(folder_contents)).unwrap();
debug!("[traverse] Parsed:\n{:?}", new_result);
result.response.append(&mut new_result.response);
debug!("[traverse] new vector length: {}", &result.response.len());
} else {
debug!("[traverse] Node...");
if !(&mut result.response[current_index].propstat[0].prop.share_types).contains(&ShareType{ share_type: 3 }) {
debug!("[traverse] it's not public");
let username = config.credentials.username.as_str();
let username_seg_string = format!("/{}/", username);
let username_seg = username_seg_string.as_str();
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, config).await.unwrap();
} else {
debug!("[traverse] it's already public");
}
}
visited_items.insert(href_key, true);
debug!("[traverse] visited items: {:?}", visited_items);
} else {
debug!("[traverse] Already-visited item.");
}
current_index += 1;
}
Ok(true)
#[allow(unused)]
fn indent(size: usize) -> String {
const INDENT: &'static str = " ";
(0..size)
.map(|_| INDENT)
.fold(String::with_capacity(size * INDENT.len()), |r, s| r + s)
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
env_logger::Builder::from_env(Env::default()).init();
println!("Publicise it!\n\n");
use yaserde::de::from_str;
let mut config = init().unwrap();
if config.credentials.password == None {
let output = Command::new(&config.credentials.password_script.as_ref().unwrap()).output().unwrap();
if output.stdout.len() == 0 {
panic!("[main] Failed to acquire password from provided script.");
}
config.credentials.password = Some(String::from_utf8(output.stdout).unwrap());
}
debug!("[main] {:?}", &config);
env_logger::Builder::from_env(Env::default().default_filter_or("trace"))
.target(Target::Stdout)
.init();
println!("Publicise it!");
let password = get_password().unwrap().trim().to_string();
debug!("Received password: {}[END]", password);
let full_path = &(String::from("/remote.php/dav/files/") + &config.credentials.username + "/" + &config.paths.target);
let folder_contents: String =
get_folder_contents(full_path, &config)
let folder_contents =
get_folder_contents(password, "/nextcloud/remote.php/dav/files/adam/test_public/2019_test_public")
.await
.unwrap();
debug!("{:?}", folder_contents);
let result: Multistatus = from_str(&folder_contents).unwrap();
debug!("[main] {:?}", result);
let _ = traverse(result, &config).await.unwrap();
println!("{:?}", result);
Ok(())
}