rocket-pinboard/src/models/list.rs

86 lines
2.7 KiB
Rust
Raw Normal View History

use comrak;
use glob::glob;
use inflector::Inflector;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use std::time::SystemTime;
2017-12-27 22:02:55 +01:00
/// Converts raw string data (in Markdown format) to HTML
pub fn data_to_html(data: &String) -> String {
let mut options = comrak::ComrakOptions::default();
options.ext_strikethrough = true;
options.ext_tagfilter = true;
options.ext_autolink = true;
options.ext_tasklist = true;
comrak::markdown_to_html(data, &options)
}
#[derive(Clone, Debug, Serialize, Deserialize)]
2017-12-27 22:02:55 +01:00
/// Structure for representing a wish list
pub struct List {
2017-12-27 22:02:55 +01:00
/// The ID of the list (unique string)
pub id: String,
2017-12-27 22:02:55 +01:00
/// The index of the list (unique number)
pub index: i8,
2017-12-27 22:02:55 +01:00
/// The raw list data
pub data: String,
2017-12-27 22:02:55 +01:00
/// The time the list was last modified
pub mtime: SystemTime,
2017-12-27 22:02:55 +01:00
/// The name of the list, i.e. the person it is for
pub name: String,
2017-12-27 22:02:55 +01:00
/// The path to the list file
path: PathBuf
}
impl List {
pub fn to_html(&self) -> String {
data_to_html(&self.data)
}
pub fn update_data(&mut self, data : &String) {
let mut file = File::create(&self.path)
.expect(&format!("Cannot open list file {}",
self.path.to_str().unwrap()));
file.write_all(data.as_bytes())
.expect(&format!("Cannot write list file {}",
self.path.to_str().unwrap()));
self.data = data.clone();
let metadata = file.metadata().unwrap();
self.mtime = metadata.modified().unwrap();
}
pub fn load_all() -> Vec<Self> {
let mut lists : Vec<List> = vec![];
let mut index = 0;
for entry in glob("lists/*.list").unwrap().filter_map(Result::ok) {
let file_name = entry.file_name().unwrap().to_str().unwrap();
let name = match file_name.find('.') {
Some(index) => &file_name[0..index],
None => "unknown"
};
let mut data = String::new();
let mut file = File::open(&entry)
.expect(&format!("Cannot open list file {}", file_name));
file.read_to_string(&mut data)
.expect(&format!("Cannot read list file {}", file_name));
let metadata = file.metadata()
.expect(&format!("Cannot get metadata of list file {}", file_name));
let mut list = List {
id: String::from(name),
index : index,
data: data,
mtime: metadata.modified().unwrap(),
name: String::from(name).to_title_case(),
path: entry.clone()
};
lists.push(list);
index += 1;
}
lists
}
}