mirror of
https://github.com/YGGverse/titanit.git
synced 2026-03-31 17:15:30 +00:00
implement from_url method
This commit is contained in:
parent
a5e345eaa8
commit
580dbdb4a7
1 changed files with 32 additions and 4 deletions
|
|
@ -1,4 +1,4 @@
|
||||||
use anyhow::{anyhow, Error, Result};
|
use anyhow::{anyhow, bail, Error, Result};
|
||||||
use std::{
|
use std::{
|
||||||
fs::{create_dir_all, remove_file, rename, File},
|
fs::{create_dir_all, remove_file, rename, File},
|
||||||
path::{PathBuf, MAIN_SEPARATOR},
|
path::{PathBuf, MAIN_SEPARATOR},
|
||||||
|
|
@ -18,6 +18,35 @@ pub struct Item {
|
||||||
impl Item {
|
impl Item {
|
||||||
// Constructors
|
// Constructors
|
||||||
|
|
||||||
|
/// Build new `Self` from URL (request)
|
||||||
|
/// * e.g. 123 -> /directory/1/2/3
|
||||||
|
pub fn from_url(url: &str, directory: &str) -> Result<Self> {
|
||||||
|
let s = match url.rfind('/') {
|
||||||
|
Some(pos) => match url.get(pos + 1..) {
|
||||||
|
Some(u) => u.parse::<u64>()?,
|
||||||
|
None => bail!("Invalid request"),
|
||||||
|
},
|
||||||
|
None => bail!("ID not found"),
|
||||||
|
}
|
||||||
|
.to_string();
|
||||||
|
let mut p = String::with_capacity(s.len());
|
||||||
|
for (i, d) in s.chars().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
p.push(MAIN_SEPARATOR)
|
||||||
|
}
|
||||||
|
p.push(d)
|
||||||
|
}
|
||||||
|
let path = PathBuf::from_str(&format!(
|
||||||
|
"{}{MAIN_SEPARATOR}{p}",
|
||||||
|
directory.trim_end_matches(MAIN_SEPARATOR),
|
||||||
|
))?;
|
||||||
|
Ok(Self {
|
||||||
|
file: File::open(&path)?,
|
||||||
|
path,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create new `Self` with unique pathname in the root `directory`
|
||||||
pub fn create(directory: &str) -> Result<Self> {
|
pub fn create(directory: &str) -> Result<Self> {
|
||||||
loop {
|
loop {
|
||||||
// generate file id from current unix time
|
// generate file id from current unix time
|
||||||
|
|
@ -83,12 +112,14 @@ impl Item {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Delete `Self`, cleanup FS
|
||||||
pub fn delete(self) -> Result<()> {
|
pub fn delete(self) -> Result<()> {
|
||||||
Ok(remove_file(self.path)?)
|
Ok(remove_file(self.path)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
|
|
||||||
|
/// Shared helper to build public URI
|
||||||
pub fn to_uri(&self, directory: &str) -> String {
|
pub fn to_uri(&self, directory: &str) -> String {
|
||||||
self.path
|
self.path
|
||||||
.to_str()
|
.to_str()
|
||||||
|
|
@ -96,7 +127,4 @@ impl Item {
|
||||||
.replace(directory, "")
|
.replace(directory, "")
|
||||||
.replace("/", "")
|
.replace("/", "")
|
||||||
}
|
}
|
||||||
|
|
||||||
/* @TODO implement short links handle without slash
|
|
||||||
pub fn alias(&self, relative: &str) -> String {} */
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue