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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
|
// -*- coding: utf-8 -*-
//
// Simple CMS
//
// Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT
use anyhow::{self as ah, format_err as err, Context as _};
use cms_ident::{CheckedIdent, CheckedIdentElem, Ident, Strip, Tail};
use inotify::{WatchMask, Watches};
use std::path::{Path, PathBuf};
use tokio::{
fs::{read_dir, File, OpenOptions},
io::AsyncReadExt as _,
};
fn elem(e: &'static str) -> CheckedIdentElem {
// Panic, if the string contains invalid characters.
let ident = e.parse::<Ident>().unwrap();
ident.into_checked_element().unwrap()
}
fn syselem(e: &'static str) -> CheckedIdentElem {
// Panic, if the string contains invalid characters.
let ident = e.parse::<Ident>().unwrap();
ident.into_checked_sys_element().unwrap()
}
lazy_static::lazy_static! {
static ref TAIL_CONTENT_HTML: Tail = Tail::One(elem("content.html"));
static ref TAIL_HEADER_HTML: Tail = Tail::One(elem("header.html"));
static ref TAIL_REDIRECT: Tail = Tail::One(elem("redirect"));
static ref TAIL_TITLE: Tail = Tail::One(elem("title"));
static ref TAIL_PRIORITY: Tail = Tail::One(elem("priority"));
static ref TAIL_NAV_STOP: Tail = Tail::One(elem("nav_stop"));
static ref TAIL_NAV_LABEL: Tail = Tail::One(elem("nav_label"));
static ref ELEM_MACROS: CheckedIdentElem = syselem("__macros");
static ref WATCH_MASK: WatchMask =
WatchMask::CREATE
| WatchMask::DELETE
| WatchMask::DELETE_SELF
| WatchMask::MODIFY
| WatchMask::MOVE_SELF
| WatchMask::MOVE
| WatchMask::ATTRIB;
}
#[inline]
async fn fs_add_dir_watch(path: &Path, watches: &mut Watches) {
if path.is_dir() {
let _ = watches.add(path, *WATCH_MASK);
}
}
#[inline]
async fn fs_add_file_watch(path: &Path, watches: &mut Watches) {
if path.is_file() {
let _ = watches.add(path, *WATCH_MASK);
}
}
#[inline]
async fn fs_file_open_r(path: &Path, watches: &mut Watches) -> ah::Result<File> {
let file = OpenOptions::new()
.read(true)
.open(path)
.await
.context("Open database file")?;
fs_add_file_watch(path, watches).await;
if let Some(parent_dir) = path.parent() {
fs_add_dir_watch(parent_dir, watches).await;
}
Ok(file)
}
#[inline]
async fn fs_file_mtime(path: &Path, watches: &mut Watches) -> ah::Result<u64> {
let fd = fs_file_open_r(path, watches).await?;
let mtime = fd
.metadata()
.await
.context("Get database file metadata")?
.modified()
.context("Get database file mtime")?;
let mtime = mtime
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.context("Convert mtime to unix time")?;
Ok(mtime.as_secs())
}
#[inline]
async fn fs_file_read(path: &Path, watches: &mut Watches) -> ah::Result<Vec<u8>> {
let mut fd = fs_file_open_r(path, watches).await?;
let mut buf = vec![]; // read_to_end will allocate before read.
fd.read_to_end(&mut buf)
.await
.context("Read database file")?;
Ok(buf)
}
#[inline]
async fn fs_file_is_empty(path: &Path, watches: &mut Watches) -> ah::Result<bool> {
Ok(fs_file_read(path, watches).await?.is_empty())
}
#[inline]
async fn fs_file_read_string(path: &Path, watches: &mut Watches) -> ah::Result<String> {
let data = fs_file_read(path, watches).await?;
String::from_utf8(data).context("Database file UTF-8 encoding")
}
#[inline]
async fn fs_file_read_u64(path: &Path, watches: &mut Watches) -> ah::Result<u64> {
fs_file_read_string(path, watches)
.await?
.trim()
.parse::<u64>()
.context("Database parse u64 value")
}
#[inline]
async fn fs_file_read_bool(path: &Path, watches: &mut Watches) -> ah::Result<bool> {
let value = fs_file_read_u64(path, watches).await?;
Ok(value != 0)
}
#[derive(Clone, Debug)]
pub struct PageInfo {
pub name: Vec<u8>,
pub nav_label: Vec<u8>,
pub nav_stop: bool,
pub stamp: u64,
pub prio: u64,
}
pub struct DbFsIntf {
db_pages: PathBuf,
db_macros: PathBuf,
db_images: PathBuf,
db_strings: PathBuf,
}
impl DbFsIntf {
const DEFAULT_PRIO: u64 = 500;
const DEFAULT_MTIME: u64 = 0;
pub fn new(path: &Path) -> ah::Result<Self> {
if !path.is_dir() {
return Err(err!("DB: {:?} is not a directory.", path));
}
let db_pages = path.join("pages");
if !db_pages.is_dir() {
return Err(err!("DB: {:?} is not a directory.", db_pages));
}
let db_macros = path.join("macros");
if !db_macros.is_dir() {
return Err(err!("DB: {:?} is not a directory.", db_macros));
}
let db_images = path.join("images");
if !db_images.is_dir() {
return Err(err!("DB: {:?} is not a directory.", db_images));
}
let db_strings = path.join("strings");
if !db_strings.is_dir() {
return Err(err!("DB: {:?} is not a directory.", db_strings));
}
Ok(Self {
db_pages,
db_macros,
db_images,
db_strings,
})
}
pub async fn get_page(&self, page: &CheckedIdent, watches: &mut Watches) -> Vec<u8> {
let path = page.to_fs_path(&self.db_pages, &TAIL_CONTENT_HTML);
fs_file_read(&path, watches)
.await
.unwrap_or_else(|_| vec![])
}
pub async fn get_page_redirect(&self, page: &CheckedIdent, watches: &mut Watches) -> Vec<u8> {
let path = page.to_fs_path(&self.db_pages, &TAIL_REDIRECT);
fs_file_read(&path, watches)
.await
.unwrap_or_else(|_| vec![])
}
pub async fn get_page_title(&self, page: &CheckedIdent, watches: &mut Watches) -> Vec<u8> {
let path = page.to_fs_path(&self.db_pages, &TAIL_TITLE);
if let Ok(title) = fs_file_read(&path, watches).await {
title
} else {
self.get_nav_label(page, watches).await
}
}
pub async fn get_page_stamp(&self, page: &CheckedIdent, watches: &mut Watches) -> u64 {
let path = page.to_fs_path(&self.db_pages, &TAIL_CONTENT_HTML);
fs_file_mtime(&path, watches)
.await
.unwrap_or(Self::DEFAULT_MTIME)
}
pub async fn get_page_prio(&self, page: &CheckedIdent, watches: &mut Watches) -> u64 {
let path = page.to_fs_path(&self.db_pages, &TAIL_PRIORITY);
fs_file_read_u64(&path, watches)
.await
.unwrap_or(Self::DEFAULT_PRIO)
}
pub async fn get_subpages(&self, page: &CheckedIdent, watches: &mut Watches) -> Vec<PageInfo> {
let path = page.to_fs_path(&self.db_pages, &Tail::None);
let mut subpages = Vec::with_capacity(64);
fs_add_dir_watch(&path, watches).await;
if let Ok(mut dir_reader) = read_dir(path).await {
while let Ok(Some(entry)) = dir_reader.next_entry().await {
let epath = entry.path();
let ename = entry.file_name();
if ename.as_encoded_bytes().starts_with(b".") {
continue; // No . and ..
}
if ename.as_encoded_bytes().starts_with(b"__") {
continue; // No system folders and files.
}
if !epath.is_dir() {
continue; // Not a directory.
}
if epath.join("hidden").exists() {
continue; // This entry is hidden.
}
if !fs_file_is_empty(&epath.join("redirect"), watches)
.await
.unwrap_or(true)
{
continue; // This entry is redirected to somewhere else.
}
let Some(ename_str) = ename.to_str() else {
continue; // Entry name is not a valid str.
};
let Ok(subpage_ident) = page.clone_append(ename_str).into_checked() else {
continue; // Entry name is not a valid CheckedIdent element.
};
let nav_label = self.get_nav_label(&subpage_ident, watches).await;
let nav_stop = self.get_nav_stop(&subpage_ident, watches).await;
let stamp = self.get_page_stamp(&subpage_ident, watches).await;
let prio = self.get_page_prio(&subpage_ident, watches).await;
let info = PageInfo {
name: ename.into_encoded_bytes(),
nav_label,
nav_stop,
stamp,
prio,
};
subpages.push(info);
fs_add_dir_watch(&epath, watches).await;
}
}
subpages
}
pub async fn get_nav_stop(&self, page: &CheckedIdent, watches: &mut Watches) -> bool {
let path = page.to_fs_path(&self.db_pages, &TAIL_NAV_STOP);
fs_file_read_bool(&path, watches).await.unwrap_or(false)
}
pub async fn get_nav_label(&self, page: &CheckedIdent, watches: &mut Watches) -> Vec<u8> {
let path = page.to_fs_path(&self.db_pages, &TAIL_NAV_LABEL);
fs_file_read(&path, watches)
.await
.unwrap_or_else(|_| vec![])
}
pub async fn get_macro(
&self,
page: &CheckedIdent,
name: &CheckedIdentElem,
watches: &mut Watches,
) -> Vec<u8> {
// Try to get the page specific macro.
// Traverse the path backwards.
let tail = Tail::Two(ELEM_MACROS.clone(), name.clone());
let mut rstrip = 0;
while let Ok(path) = page.to_stripped_fs_path(&self.db_pages, Strip::Right(rstrip), &tail) {
if let Ok(data) = fs_file_read(&path, watches).await {
return data;
}
rstrip += 1;
}
// Try to get the global macro.
let path = name.to_fs_path(&self.db_macros, &Tail::None);
fs_file_read(&path, watches)
.await
.unwrap_or_else(|_| vec![])
}
pub async fn get_string(&self, name: &CheckedIdentElem, watches: &mut Watches) -> Vec<u8> {
let path = name.to_fs_path(&self.db_strings, &Tail::None);
fs_file_read(&path, watches)
.await
.unwrap_or_else(|_| vec![])
}
pub async fn get_image(&self, name: &CheckedIdentElem, watches: &mut Watches) -> Vec<u8> {
let path = name.to_fs_path(&self.db_images, &Tail::None);
fs_file_read(&path, watches)
.await
.unwrap_or_else(|_| vec![])
}
pub async fn get_headers(&self, page: &CheckedIdent, watches: &mut Watches) -> Vec<u8> {
let mut ret = Vec::with_capacity(4096);
let mut rstrip = 0;
while let Ok(path) =
page.to_stripped_fs_path(&self.db_pages, Strip::Right(rstrip), &TAIL_HEADER_HTML)
{
if let Ok(data) = fs_file_read(&path, watches).await {
ret.extend_from_slice(&data);
}
rstrip += 1;
}
ret
}
}
// vim: ts=4 sw=4 expandtab
|