Echo Writes Code

content.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use crate::errors::{ Error, Result };
use password_hash::{ PasswordHash, PasswordVerifier };
use pulldown_cmark::{ Parser as MarkdownParser };
use pulldown_cmark::html::{ push_html };
use scrypt::{ Scrypt };
use serde::{ Deserialize, Serialize };
use std::collections::{ HashMap, HashSet };
use std::path::{ Path, PathBuf };

#[derive(Debug)]
pub struct ContentDatabase {
  _content_path: PathBuf,
  pages_path: PathBuf,
  metadata_path: PathBuf,
  metadata: Metadata,
}

impl ContentDatabase {
  pub fn new(content_path: &Path, metadata_path: &Path) -> Result<ContentDatabase> {
    let metadata = std::fs::read_to_string(metadata_path)
      .map_err(Error::from)
      .and_then(|metadata_text| {
        let metadata = serde_json::from_str(&metadata_text)?;
        Ok(metadata)
      })
      .or_else(|e1| match e1 {
        Error::FromStdIo(ref e2) => match e2.kind() {
          std::io::ErrorKind::NotFound => Ok(Metadata::default()),
          _ => Err(e1),
        },
        _ => Err(e1),
      })?;

    let pages_path = content_path.join("pages");

    if !pages_path.is_dir() {
      std::fs::create_dir_all(&pages_path)?;
    }

    let mut database = ContentDatabase {
      _content_path: content_path.to_path_buf(),
      pages_path,
      metadata_path: metadata_path.to_path_buf(),
      metadata,
    };

    if database.find_page("_index").is_none() {
      database
        .save_page_content("_index", "## Welcome to your new Limetree CMS instance!\n\nFeel free to edit this page and replace the content.")?
        .create_page_metadata("_index", "Home", &[])?;
    }

    Ok(database)
  }

  pub fn save_metadata(&mut self) -> Result<()> {
    let metadata_text = serde_json::to_string(&self.metadata)?;
    std::fs::write(&self.metadata_path, &metadata_text)?;
    Ok(())
  }

  pub fn anonymous_permissions(&self) -> Option<Vec<Permission>> {
    self.metadata.users_by_username
      .get("anonymous")
      .and_then(|index| self.metadata.users.get(*index))
      .map(|user| user.permissions.clone())
  }

  pub fn authenticate(&self, username: &str, password: &str) -> Result<Vec<Permission>> {
    self.metadata.users_by_username
      .get(username)
      .and_then(|index| self.metadata.users.get(*index))
      .ok_or(Error::AuthenticationFailed)
      .and_then(|user| user.authenticate(username, password))
  }

  pub fn find_all_tags(&self) -> HashSet<String> {
    let mut tags = HashSet::new();

    for page in &self.metadata.pages {
      for tag in &page.tags {
        tags.insert(tag.to_string());
      }
    }

    tags
  }

  pub fn find_page<'a>(&'a self, slug: &str) -> Option<&'a Page> {
    self.metadata.pages_by_slug
      .get(slug)
      .and_then(|index| self.metadata.pages.get(*index))
  }

  pub fn iter_pages_tagged<'a>(&'a self, tags: &[String]) -> impl Iterator<Item = &'a Page> {
    self.metadata.pages
      .iter()
      .filter(move |page| page.tags
        .iter()
        .any(|t| tags.contains(t))) // Workaround for a known issue in Vec::contains()
  }

  pub fn load_page_content_html(&self, slug: &str) -> Result<String> {
    let markdown_content = self.load_page_content_markdown(slug)?;
    let mut html_content = String::new();

    {
      let parser = MarkdownParser::new(&markdown_content);
      push_html(&mut html_content, parser);
    }

    Ok(html_content)
  }

  pub fn load_page_content_markdown(&self, slug: &str) -> Result<String> {
    let disk_path = self.pages_path
      .join(slug)
      .with_added_extension("md");

    let markdown_content = std::fs::read_to_string(disk_path)?;
    Ok(markdown_content)
  }

  pub fn save_page_content(&mut self, slug: &str, content: &str) -> Result<&mut ContentDatabase> {
    let disk_path = self.pages_path
      .join(slug)
      .with_added_extension("md");

    std::fs::write(disk_path, content)?;
    Ok(self)
  }

  pub fn create_page_metadata(&mut self, slug: &str, title: &str, tags: &[String]) -> Result<&mut ContentDatabase> {
    if self.metadata.pages_by_slug.contains_key(slug) {
      return Err(Error::PageAlreadyExists(slug.to_string()));
    }

    self.metadata.pages_by_slug
      .insert(slug.to_string(), self.metadata.pages.len());

    self.metadata.pages.push(Page {
      slug: slug.to_string(),
      title: title.to_string(),
      tags: tags.to_vec(),
    });

    self.save_metadata()?;
    Ok(self)
  }

  pub fn update_page_metadata(&mut self, old_slug: &str, new_slug: &str, title: &str, tags: &[String]) -> Result<&mut ContentDatabase> {
    if old_slug != new_slug {
      if self.metadata.pages_by_slug.contains_key(new_slug) {
        return Err(Error::PageAlreadyExists(new_slug.to_string()));
      }

      let index = self.metadata.pages_by_slug
        .remove(old_slug)
        .ok_or_else(|| Error::PageNotFound(old_slug.to_string()))?;

      self.metadata.pages_by_slug
        .insert(new_slug.to_string(), index);
    }

    let index = *self.metadata.pages_by_slug
      .get(new_slug)
      .ok_or_else(|| Error::PageNotFound(new_slug.to_string()))?;

    let page = self.metadata.pages
      .get_mut(index)
      .expect("Slug lookup table should only contain valid indices");

    page.slug = new_slug.to_string();
    page.title = title.to_string();
    page.tags = tags.to_vec();

    Ok(self)
  }
}

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Metadata {
  pages: Vec<Page>,
  pages_by_slug: HashMap<String, usize>,
  users: Vec<User>,
  users_by_username: HashMap<String, usize>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Page {
  slug: String,
  title: String,
  tags: Vec<String>,
}

impl Page {
  pub fn slug(&self) -> &str {
    &self.slug
  }

  pub fn title(&self) -> &str {
    &self.title
  }

  pub fn tags(&self) -> &[String] {
    &self.tags
  }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct User {
  username: String,
  password: String,
  permissions: Vec<Permission>,
}

impl User {
  pub fn authenticate(&self, username: &str, password: &str) -> Result<Vec<Permission>> {
    if username != self.username {
      return Err(Error::AuthenticationFailed);
    }

    let hash = PasswordHash::new(&self.password)?;

    match Scrypt.verify_password(password.as_bytes(), &hash) {
      Ok(_) => Ok(self.permissions.clone()),
      Err(password_hash::Error::Password) => Err(Error::AuthenticationFailed),
      Err(e) => Err(e.into()),
    }
  }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum Permission {
  Read,
  Write,
}