switch to Results and some cleanup

This commit is contained in:
2025-03-23 21:27:29 +01:00
parent de0cebb3b5
commit 82d0d5bf4a

View File

@ -1,6 +1,7 @@
use postgres::{Client, NoTls}; use postgres::{Client, NoTls};
use std::{ use std::{
env::args, env::args,
error::Error,
fs::{self, File}, fs::{self, File},
io::{self, BufRead, BufReader, Write}, io::{self, BufRead, BufReader, Write},
}; };
@ -15,250 +16,218 @@ fn show_usage() {
println!("add_custom_name"); println!("add_custom_name");
} }
fn run_as_cli() -> i32 { fn run_as_cli(client: &mut postgres::Client) -> Result<(), Box<dyn Error>> {
let mut result: i32;
let mut client = Client::connect("host=192.168.0.10 port=28945 user=hentai password=h99nqaNPhpfbuuhCDwQXLpZAnoVTjSQP7taoqmQhpzc2rPLVC4JUAKxAHfuuhuU9", NoTls).unwrap();
let mut option: String = String::new();
show_usage(); show_usage();
println!("Please input any of these options or type \'exit\' to leave"); println!("Please input any of these options or type \'exit\' to leave\n");
loop { loop {
result = 0; let mut option = String::new();
io::stdin() io::stdin().read_line(&mut option)?;
.read_line(&mut option)
.expect("Failed to read input");
let option: &str = option.trim_end(); // to get rid of '\n' match option.trim_end() {
match option {
"usage" => show_usage(), "usage" => show_usage(),
"generate" => result = generate_file(&mut client, None), "generate" => generate_file(client, None)?,
"convert" => result = convert_folders(&mut client, None), "convert" => convert_folders(client, None)?,
"import" => result = import_file(&mut client, None), "import" => import_file(client, None)?,
"add_url" => result = add_url(&mut client, None), "add_url" => add_url(client, None)?,
"add_custom_name" => result = add_artist_with_custom_name(&mut client, None), "add_custom_name" => add_artist_with_custom_name(client, None)?,
"exit" => break, "exit" => {
return Ok(());
}
_ => { _ => {
eprintln!("Invalid option!"); eprintln!("Invalid option!");
} }
} };
if result != 0 { println!("Done!");
return result;
} }
} }
result fn run_with_input(
} client: &mut postgres::Client,
arguments: Vec<String>,
fn run_with_input(arguments: Vec<String>) -> i32 { ) -> Result<(), Box<dyn Error>> {
let mut result: i32 = 0;
if arguments[1] == "usage" { if arguments[1] == "usage" {
show_usage(); show_usage();
return result; return Ok(());
} }
let mut client = Client::connect("host=192.168.0.10 port=28945 user=hentai password=h99nqaNPhpfbuuhCDwQXLpZAnoVTjSQP7taoqmQhpzc2rPLVC4JUAKxAHfuuhuU9", NoTls).unwrap();
let value: String = arguments[2].clone(); let value: String = arguments[2].clone();
match arguments[1].as_str() { match arguments[1].as_str() {
"generate" => result = generate_file(&mut client, Option::Some(value)), "generate" => generate_file(client, Option::Some(value))?,
"convert" => result = convert_folders(&mut client, Option::Some(value)), "convert" => convert_folders(client, Option::Some(value))?,
"import" => result = import_file(&mut client, Option::Some(value)), "import" => import_file(client, Option::Some(value))?,
"add_url" => result = add_url(&mut client, Option::Some(value)), "add_url" => add_url(client, Option::Some(value))?,
"add_custom_name" => { "add_custom_name" => {
let values: Vec<String> = vec![arguments[2].clone(), arguments[3].clone()]; let values: Vec<String> = vec![arguments[2].clone(), arguments[3].clone()];
result = add_artist_with_custom_name(&mut client, Option::Some(values)); add_artist_with_custom_name(client, Option::Some(values))?
} }
_ => { _ => {
eprintln!("Invalid argument"); return Err(Box::new(io::Error::new(
result = 1; io::ErrorKind::InvalidInput,
"Invalid argument",
)));
} }
};
println!("Done!");
Ok(())
} }
result fn generate_file(
} client: &mut postgres::Client,
website: Option<String>,
fn generate_file(client: &mut postgres::Client, website: Option<String>) -> i32 { ) -> Result<(), Box<dyn Error>> {
let mut website_name: String = String::new(); let mut website_name = String::new();
match website { match website {
Some(val) => website_name = val, Some(val) => website_name = val,
None => { None => {
io::stdin() println!(
.read_line(&mut website_name) "Please input the desired website name. Options currently are (Rule34, Iwara)"
.expect("Failed to read input"); );
io::stdin().read_line(&mut website_name)?;
} }
}; };
let output = client let website_name = website_name.trim();
.query_one("SELECT website_exists($1);", &[&website_name])
.unwrap(); let output = client.query_one("SELECT website_exists($1);", &[&website_name])?;
let found: bool = output.get(0); let found: bool = output.get(0);
if !found { if !found {
eprintln!("Invalid website_name"); return Err(Box::new(io::Error::new(
return 1; io::ErrorKind::InvalidInput,
"Invalid website_name",
)));
} }
let filename = format!("{website_name}_generated.txt"); let filename = format!("{website_name}_generated.txt");
let mut file = match File::create_new(filename) { let mut file = File::create_new(filename)?;
Ok(file) => file,
Err(error) => {
let message = error.to_string();
eprintln!("Problem creating the file: {message}");
return 1;
}
};
let output = client let output = client.query("SELECT * FROM get_urls_and_paths($1);", &[&website_name])?;
.query("SELECT * FROM get_urls_and_paths($1);", &[&website_name])
.unwrap();
for row in output { for row in output {
let url: String = row.get(0); let url: String = row.get(0);
let folder_path: String = row.get(1); let folder_path: String = row.get(1);
writeln!(file, "{} # {}", url, folder_path).unwrap(); writeln!(file, "{} # {}", url, folder_path)?;
} }
0 Ok(())
} }
fn convert_folders(client: &mut postgres::Client, path: Option<String>) -> i32 { fn convert_folders(
let mut root_folder: String = String::new(); client: &mut postgres::Client,
path: Option<String>,
) -> Result<(), Box<dyn Error>> {
let mut root_folder = String::new();
match path { match path {
Some(val) => root_folder = val, Some(val) => root_folder = val,
None => { None => {
io::stdin() println!("Please input the desired path to where your files live");
.read_line(&mut root_folder) io::stdin().read_line(&mut root_folder)?;
.expect("Failed to read input");
} }
}; };
let filename: &str = "convert_folders.log"; let root_folder = root_folder.trim();
let mut log_file = match File::create_new(filename) {
Ok(file) => file,
Err(error) => {
let message = error.to_string();
eprintln!("Problem creating the file: {message}");
return 1;
}
};
let output = client let filename = "convert_folders.log";
.query("SELECT * FROM get_all_convertable_paths();", &[]) let mut log_file = File::create_new(filename)?;
.unwrap();
let output = client.query("SELECT * FROM get_all_convertable_paths();", &[])?;
for row in output { for row in output {
let old_path: String = row.get(0); let old_path: String = row.get(0);
let new_path: String = row.get(1); let new_path: String = row.get(1);
let old_path = format!("{}/{}", root_folder, old_path); let old_path = format!("{}/{}", root_folder, old_path);
let new_path = format!("{}/{}", root_folder, new_path); let new_path = format!("{}/{}", root_folder, new_path);
let old_path = urlencoding::decode(&old_path).unwrap().to_string(); let old_path = urlencoding::decode(&old_path)?.to_string();
dbg!(&old_path); dbg!(&old_path);
dbg!(&new_path); dbg!(&new_path);
if !fs::exists(&old_path).unwrap() { if fs::exists(&old_path)? {
continue; fs::rename(&old_path, &new_path)?;
writeln!(log_file, "Converted {} => {}", old_path, new_path)?;
}
} }
fs::rename(&old_path, &new_path).unwrap(); Ok(())
writeln!(log_file, "Converted {} => {}", old_path, new_path).unwrap();
} }
0 fn import_file(client: &mut postgres::Client, file: Option<String>) -> Result<(), Box<dyn Error>> {
} let mut filename = String::new();
fn import_file(client: &mut postgres::Client, file: Option<String>) -> i32 {
let mut filename: String = String::new();
match file { match file {
Some(val) => filename = val, Some(val) => filename = val,
None => { None => {
io::stdin() println!("Please input the name of the desired file");
.read_line(&mut filename) io::stdin().read_line(&mut filename)?;
.expect("Failed to read input");
} }
}; };
let input_file = File::open(filename).unwrap(); let filename = filename.trim();
let input_file = File::open(filename)?;
let reader_iter = BufReader::new(input_file).lines(); let reader_iter = BufReader::new(input_file).lines();
if File::open("Fucked.txt").is_ok() { if File::open("Fucked.txt").is_ok() {
if File::open("Fucked.txt.bak").is_ok() { if File::open("Fucked.txt.bak").is_ok() {
fs::remove_file("Fucked.txt.bak").unwrap(); fs::remove_file("Fucked.txt.bak")?;
} }
fs::rename("Fucked.txt", "Fucked.txt.bak").unwrap(); fs::rename("Fucked.txt", "Fucked.txt.bak")?;
} }
let mut fucked_file = match File::create_new("Fucked.txt") { let mut fucked_file = File::create_new("Fucked.txt")?;
Ok(file) => file, writeln!(fucked_file, "Them are hella fucked")?;
Err(err) => {
eprintln!("Problem creating the file: {}", err);
return 1;
}
};
writeln!(fucked_file, "Them are hella fucked").unwrap();
for line in reader_iter { for line in reader_iter {
let line = line.unwrap(); let line = line?;
if line.contains("#") { if line.contains("#") {
writeln!(fucked_file, "{}", line).unwrap(); writeln!(fucked_file, "{}", line)?;
continue; continue;
} }
match client.query_one("SELECT insert_url($1);", &[&line]) { client.query_one("SELECT insert_url($1);", &[&line])?;
Ok(_) => (),
Err(_) => {
writeln!(fucked_file, "{}", line).unwrap();
}
};
} }
0 Ok(())
} }
fn add_url(client: &mut postgres::Client, uri: Option<String>) -> i32 { fn add_url(client: &mut postgres::Client, uri: Option<String>) -> Result<(), Box<dyn Error>> {
let mut url: String = String::new(); let mut url = String::new();
match uri { match uri {
Some(val) => url = val, Some(val) => url = val,
None => { None => {
io::stdin() println!("Please input the desired url");
.read_line(&mut url) io::stdin().read_line(&mut url)?;
.expect("Failed to read input");
} }
}; };
let url: &str = url.trim(); let url = url.trim();
let output = match client.query_one("SELECT insert_url($1);", &[&url]) { let output = client.query_one("SELECT insert_url($1);", &[&url])?;
Ok(val) => val,
Err(val) => {
eprintln!("{}", val);
return 1;
}
};
let something: String = output.get(0); let something: String = output.get(0);
println!("{}", something); println!("{something}");
0 Ok(())
} }
fn add_artist_with_custom_name( fn add_artist_with_custom_name(
client: &mut postgres::Client, client: &mut postgres::Client,
uri_and_artist: Option<Vec<String>>, uri_and_artist: Option<Vec<String>>,
) -> i32 { ) -> Result<(), Box<dyn Error>> {
let mut url: String = String::new(); let mut url: String = String::new();
let mut artist_name: String = String::new(); let mut artist_name: String = String::new();
@ -268,47 +237,33 @@ fn add_artist_with_custom_name(
artist_name = vec[1].clone(); artist_name = vec[1].clone();
} }
None => { None => {
io::stdin() io::stdin().read_line(&mut url)?;
.read_line(&mut url) io::stdin().read_line(&mut artist_name)?;
.expect("Failed to read input");
io::stdin()
.read_line(&mut artist_name)
.expect("Failed to read input");
} }
}; };
let url: &str = url.trim(); let url: &str = url.trim();
let artist_name: &str = artist_name.trim(); let artist_name: &str = artist_name.trim();
let output = match client.query_one( let output = client.query_one(
"SELECT insert_url_with_custom_artist($1, $2);", "SELECT insert_url_with_custom_artist($1, $2);",
&[&url, &artist_name], &[&url, &artist_name],
) { )?;
Ok(val) => val,
Err(val) => {
eprintln!("{}", val);
return 1;
}
};
let something: String = output.get(0); let something: String = output.get(0);
println!("{}", something); println!("{something}");
0 Ok(())
} }
fn main() -> Result<(), i32> { fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = args().collect(); let args: Vec<String> = args().collect();
let result = if args.len() == 1 { let mut client = Client::connect("host=192.168.0.10 port=28945 user=hentai password=h99nqaNPhpfbuuhCDwQXLpZAnoVTjSQP7taoqmQhpzc2rPLVC4JUAKxAHfuuhuU9", NoTls)?;
run_as_cli()
} else {
run_with_input(args)
};
if result != 0 { match args.len() {
return Err(result); 1 => run_as_cli(&mut client)?,
_ => run_with_input(&mut client, args)?,
} }
Ok(()) Ok(())