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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
|
use std::{str::FromStr, sync::Arc};
use axum::{Extension, body::Body, extract::Multipart, http::StatusCode, response::Response};
use somethings::auth::Session;
use wikarden::Wikarden;
use super::PageFrontmatter;
use crate::{
Query, RuntimeError,
config::Settings,
extractor::Wrap,
handler::{quark::open_template_path, see_other},
};
/// POST /quark/api/create
pub async fn create(
Extension(wikarden): Extension<Arc<Wikarden>>,
Extension(settings): Extension<Settings>,
Wrap(_session): Wrap<Session>,
mut multipart: Multipart,
) -> Result<Response, RuntimeError> {
let data = MultipartFields::from_multipart(&mut multipart).await?;
let operation = data.operation()?;
match operation {
Operation::Preview => match data.content {
None => Err(RuntimeError::incomplete_form("content")),
Some(content) => super::markup::preview(&content, &settings).await,
},
Operation::Create => {
let CreateForm { name, content }: CreateForm = data.try_into()?;
let redirect = api_redirect(&settings, &name, format!("../{name}"));
let wikres = wikarden
.create(&name, content, format!("Create page '{name}'"))
.await;
match wikres {
Err(e) => api_error(&settings, e).await,
Ok(_) => redirect.await,
}
}
_ => Err(RuntimeError::bad_request("usupported operation")),
}
}
/// POST /quark/api/create/section
pub async fn create_section(
Extension(wikarden): Extension<Arc<Wikarden>>,
Extension(settings): Extension<Settings>,
Wrap(_session): Wrap<Session>,
body: String,
) -> Result<Response, RuntimeError> {
let query: Query = body.parse()?;
match query.get_first_value("name") {
None => Err(RuntimeError::incomplete_form("name")),
Some(name) => match wikarden.create_section(name, None).await {
Err(e) => return api_error(&settings, e).await,
Ok(_) => super::markup::preview(&format!("created section {name}"), &settings).await,
},
}
}
/// POST /quark/api/edit
pub async fn edit(
Extension(wikarden): Extension<Arc<Wikarden>>,
Extension(settings): Extension<Settings>,
Wrap(_session): Wrap<Session>,
mut multipart: Multipart,
) -> Result<Response, RuntimeError> {
let data = MultipartFields::from_multipart(&mut multipart).await?;
let operation = data.operation()?;
match operation {
Operation::Preview => match data.content {
None => Err(RuntimeError::incomplete_form("content")),
Some(content) => super::markup::preview(&content, &settings).await,
},
Operation::Edit => {
let EditForm {
name,
content,
commit,
frontmatter,
}: EditForm = data.try_into()?;
let redirect = api_redirect(&settings, &name, format!("../{name}"));
let commit = match commit {
Some(commit) => commit,
None => {
let time = timeparse::format::human_with_time(&timeparse::whichever_now());
format!("edited '{name}' {time}")
}
};
tracing::trace!("editing with commit='{commit}'");
let source = format!("{frontmatter}\n{content}");
match wikarden.modify(&name, source, commit).await {
Err(e) => api_error(&settings, e).await,
Ok(_) => redirect.await,
}
}
_ => Err(RuntimeError::bad_request("usupported operation")),
}
}
/// POST /quark/api/edit/section
pub async fn edit_section(
Extension(wikarden): Extension<Arc<Wikarden>>,
Extension(settings): Extension<Settings>,
Wrap(_session): Wrap<Session>,
body: String,
) -> Result<Response, RuntimeError> {
let query: Query = body.parse()?;
let name = query
.get_first_value("name")
.ok_or(RuntimeError::incomplete_form("name"))?;
match query.get_first_value("home") {
None => Err(RuntimeError::incomplete_form("home")),
Some(home) => {
if home.is_empty() {
return Err(RuntimeError::incomplete_form("home"));
}
let full_path = format!("{name}/{home}");
match wikarden.page_exists(&full_path).await {
Ok(true) => (),
_ => {
return api_error(&settings, format!("page '{full_path}' does not exist"))
.await;
}
}
let res = wikarden
.modify_section_data(name, None, |sd| sd.set_home(Some(&full_path)))
.await;
match res {
Err(e) => api_error(&settings, e).await,
Ok(_) => api_success(&settings, format!("set redirection to '{full_path}'")).await,
}
}
}
}
/// POST /quark/api/move
pub async fn move_page(
Extension(wikarden): Extension<Arc<Wikarden>>,
Extension(settings): Extension<Settings>,
Wrap(_session): Wrap<Session>,
body: String,
) -> Result<Response, RuntimeError> {
let query: Query = body.parse()?;
let from = query
.get_first_value("from")
.ok_or(RuntimeError::incomplete_form("from"))?;
let to = query
.get_first_value("to")
.ok_or(RuntimeError::incomplete_form("to"))?;
match wikarden.move_page(from, to).await {
Err(e) => api_error(&settings, e).await,
Ok(()) => api_success(&settings, format!("moved '{from}' to '{to}'")).await,
}
}
/// POST /quark/api/delete
pub async fn delete(
Extension(wikarden): Extension<Arc<Wikarden>>,
Extension(settings): Extension<Settings>,
Wrap(_session): Wrap<Session>,
body: String,
) -> Result<Response, RuntimeError> {
let query = Query::from_str(&body)?;
let page = query
.get_first_value("name")
.ok_or(RuntimeError::incomplete_form("name"))?;
let page_path = format!("../{page}");
if query.has("rejection") || !query.has("confirmation") {
return see_other(page_path).await;
}
if page == settings.wikarden_index() {
//FIXME: Return an error here explaining that the index cannot be deleted
return see_other(page_path).await;
}
match wikarden.delete(page).await {
Err(e) => api_error(&settings, e).await,
Ok(_) => see_other(format!("../")).await,
}
}
/// redirect for API paths
///
/// reads the `api_redirect.html` template and returns a constructed `Response`
///
/// The `api_redirct.html` template has javascript within it that allows
/// the `<iframe>` to navigate the top-level window (`window.top.location`)
async fn api_redirect(
settings: &Settings,
page_name: &str,
page_location: String,
) -> Result<Response, RuntimeError> {
let path = settings.quark_template_dir().join("api_redirect.html");
let mut doc = open_template_path(path, settings).await?;
doc.set("page-name", page_name);
doc.set("page-location", page_location);
Response::builder()
.status(StatusCode::OK)
.body(Body::from(doc.compile()))
.map_err(|_| RuntimeError::Unknown)
}
async fn api_error<E: std::fmt::Display>(
settings: &Settings,
error: E,
) -> Result<Response, RuntimeError> {
let content = format!("# |Error|%red\n{error}");
super::markup::preview(&content, settings).await
}
async fn api_success<D: std::fmt::Display>(
settings: &Settings,
message: D,
) -> Result<Response, RuntimeError> {
let content = format!("# |Success|%green\n{message}");
super::markup::preview(&content, settings).await
}
/// page creation form
#[derive(Debug, PartialEq)]
struct CreateForm {
name: String,
content: String,
}
/// page editing form
#[derive(Debug)]
struct EditForm {
name: String,
content: String,
commit: Option<String>,
frontmatter: PageFrontmatter<'static>,
}
/// what an endpoint does; mutually exclusive
#[derive(Debug, PartialEq)]
enum Operation {
Create,
Edit,
Preview,
}
/// data read from axum's `Multipart` structure
///
/// This struct is meant to be turned into forms, like [`CreateForm`] and
/// [`EditForm`], with the `TryInto` trait.
struct MultipartFields {
name: Option<String>,
content: Option<String>,
commit: Option<String>,
og_description: Option<String>,
create: bool,
edit: bool,
preview: bool,
}
impl MultipartFields {
pub async fn from_multipart(multipart: &mut Multipart) -> Result<Self, RuntimeError> {
let mut name = None;
let mut content = None;
let mut commit = None;
let mut og_description = None;
let mut create = false;
let mut edit = false;
let mut preview = false;
macro_rules! field_text {
($field:ident $fieldname:literal) => {
Some($field.text().await.map_err(|_| {
RuntimeError::bad_request(format!("failed to decode field '{}'", $fieldname))
})?)
.map(|s| if s.is_empty() { None } else { Some(s) })
.flatten()
};
}
while let Some(field) = multipart
.next_field()
.await
.map_err(|_| RuntimeError::bad_request("multipart decode failed"))?
{
match field.name() {
Some("create") => create = true,
Some("edit") => edit = true,
Some("preview") => preview = true,
Some("name") => name = field_text!(field "name"),
Some("content") => content = field_text!(field "content"),
Some("commit") => commit = field_text!(field "commit"),
Some("og-description") => og_description = field_text!(field "og_description"),
_ => (),
}
}
Ok(MultipartFields {
name,
content,
commit,
og_description,
create,
edit,
preview,
})
}
fn operation(&self) -> Result<Operation, RuntimeError> {
match (self.create, self.edit, self.preview) {
(true, false, false) => Ok(Operation::Create),
(false, true, false) => Ok(Operation::Edit),
(false, false, true) => Ok(Operation::Preview),
_ => Err(RuntimeError::bad_request("too many operations")),
}
}
fn frontmatter(&mut self) -> PageFrontmatter<'static> {
let mut pf = PageFrontmatter::default();
if let Some(description) = self.og_description.take() {
pf.set_description(description);
}
pf
}
}
impl TryInto<CreateForm> for MultipartFields {
type Error = RuntimeError;
fn try_into(self) -> Result<CreateForm, RuntimeError> {
match (self.name, self.content) {
(Some(name), Some(content)) => Ok(CreateForm { name, content }),
_ => Err(RuntimeError::bad_request("create request missing fields")),
}
}
}
impl TryInto<EditForm> for MultipartFields {
type Error = RuntimeError;
fn try_into(mut self) -> Result<EditForm, RuntimeError> {
let pf = self.frontmatter();
match (self.name, self.content) {
(Some(name), Some(content)) => Ok(EditForm {
name,
content,
commit: self.commit,
frontmatter: pf,
}),
_ => Err(RuntimeError::bad_request("edit request missing fields")),
}
}
}
|