diff --git a/Cargo.lock b/Cargo.lock index 8a92b9d..a5bda72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1177,6 +1177,7 @@ dependencies = [ "futures-util", "log", "petname", + "rand 0.8.4", "serde 1.0.126", ] diff --git a/Cargo.toml b/Cargo.toml index a56410c..baec813 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ serde = "1.0.126" futures-util = "0.3.15" config = "0.11.0" petname = "1.1.0" +rand = "0.8.4" [dependencies.byte-unit] version = "4.0.12" diff --git a/config.toml b/config.toml index 0f09af6..b749b52 100644 --- a/config.toml +++ b/config.toml @@ -7,4 +7,5 @@ upload_path="./upload" [paste] pet_names = true +random = { enabled = false, length = 8 } default_extension = "txt" diff --git a/src/config.rs b/src/config.rs index 874628f..a91bdb0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -31,10 +31,21 @@ pub struct ServerConfig { pub struct PasteConfig { /// Use pet names instead of original file names. pub pet_names: bool, + /// Random string configuration. + pub random: RandomConfig, /// Default file extension. pub default_extension: String, } +/// Random string configuration. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RandomConfig { + /// Use random strings instead of original file names. + pub enabled: bool, + /// Length of the random string to generate. + pub length: Option, +} + impl Config { /// Parses the config file and returns the values. pub fn parse(file_name: &str) -> Result { diff --git a/src/file.rs b/src/file.rs index f10053e..730a544 100644 --- a/src/file.rs +++ b/src/file.rs @@ -1,4 +1,5 @@ use crate::config::Config; +use rand::{distributions::Alphanumeric, Rng}; use std::fs::File; use std::io::{Result as IoResult, Write}; @@ -7,9 +8,11 @@ use std::io::{Result as IoResult, Write}; /// - If `file_name` does not have an extension, it is replaced with [`default_extension`]. /// - If `file_name` is "-", it is replaced with "stdin". /// - If [`pet_names`] is `true`, `file_name` is replaced with a pet name. +/// - If [`random.enabled`] is `true`, `file_name` is replaced with a random string. /// /// [`default_extension`]: crate::config::PasteConfig::default_extension /// [`pet_names`]: crate::config::PasteConfig::pet_names +/// [`random.enabled`]: crate::config::RandomConfig::enabled pub fn save(mut file_name: &str, bytes: &[u8], config: &Config) -> IoResult { if file_name == "-" { file_name = "stdin"; @@ -20,11 +23,28 @@ pub fn save(mut file_name: &str, bytes: &[u8], config: &Config) -> IoResult(), + ); + path.set_extension(extension); } } None => { if config.paste.pet_names { path.set_file_name(petname::petname(2, "-")); + } else if config.paste.random.enabled { + path.set_file_name( + rand::thread_rng() + .sample_iter(&Alphanumeric) + .take(config.paste.random.length.unwrap_or(8)) + .map(char::from) + .collect::(), + ); } path.set_extension(&config.paste.default_extension); }