Compare commits

..

No commits in common. "master" and "proper_html_handling" have entirely different histories.

81 changed files with 1851 additions and 9473 deletions

View file

@ -14,10 +14,25 @@ before_install:
script: script:
- rustup target add x86_64-unknown-linux-musl - rustup target add x86_64-unknown-linux-musl
- cargo test --target=x86_64-unknown-linux-musl
- cargo build --release --target=x86_64-unknown-linux-musl - cargo build --release --target=x86_64-unknown-linux-musl
- cargo test --release --target=x86_64-unknown-linux-musl
- strip -s target/x86_64-unknown-linux-musl/release/sausagewiki - strip -s target/x86_64-unknown-linux-musl/release/sausagewiki
- XZ_OPT=-9 tar Jcf sausagewiki.tar.xz -C target/x86_64-unknown-linux-musl/release/ sausagewiki - xz -9 < target/x86_64-unknown-linux-musl/release/sausagewiki > sausagewiki.xz
deploy:
provider: releases
api_key:
secure: NmM+uk4ijbv5wFF3O7w9KLTrGYbe1mxWAzJDR8cD9rimgORWNQKlHOZtthAQxVgtvmhKAMkzwglgQSX3p0w4yGK5oaV3oO1aA21dzlf0BXL7/BOxgYSTjV+x8O1uIu57ERnf4k2WATCpLSx4r4LpfxMgjdEtIl6LDAnV/zX+HKu7pZAzXvmkS22m5CJbEY4M6DpCAIfpP99dolnyU7h5/AR1njMmzSqGB/naVe5O2j0sBveInsjC+4gPSh9QT/VHZBxbOctcy+kSzwN4iDktkFdYIGe9Z2sDjXsiI39ihXntyOHXA2iVpdkgpIGeLIYBOo+DobgMdS45CzZQ2y9zLnwXwODCgrh8qexxnRpC8RG7uKuVe50R6v4HDPgkjwCJoHicxaEUDiPIsg5qCxEfMYd5qUt21OwEwBN9N8K/RZD0fmgKLE5lQiyxubufeSB4wjpWrXct2M46t25qPFobbZ0kzLCXtZHtKk1mkkk+EWv8UOhRvJ8ih0Fb9ivSOrN6YA1/eRd9/SRntkJriMYmfAW50W3DnyFnPHqdV+x+jHJgcB+DnaDvQnPamk93ZDF/UyUDjVuPJFd0BAFxoRUy6HGaF/yajH4r9g3EdlfSu2IrGDo4vIA9qawBYpHyaSGvYwdCDx4/oUPIAf8sLBS01WOaDJgcmmFey7A/OqSEt6Q=
file: sausagewiki.xz
skip_cleanup: true
on:
repo: maghoff/sausagewiki
branch: master
rust: stable
cache: cargo
before_cache:
- chmod -R a+r $HOME/.cargo
branches: branches:
except: except:

View file

@ -4,5 +4,3 @@ This is a list of people who have contributed to this project.
- Magnus Hoff (maghoff@gmail.com) - Magnus Hoff (maghoff@gmail.com)
- Johannes Hoff (johanneshoff@gmail.com) - Johannes Hoff (johanneshoff@gmail.com)
- Konstantin Yegupov (kyegupov4@gmail.com)
- cmal (paul@cmal.info)

1593
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,93 +1,67 @@
[package] [package]
authors = ["Magnus Hoff <maghoff@gmail.com>"]
description = "A wiki engine"
license = "GPL-3.0"
name = "sausagewiki" name = "sausagewiki"
version = "0.1.0-dev" version = "0.1.0"
edition = "2018" authors = ["Magnus Hoff <maghoff@gmail.com>"]
license = "GPL-3.0"
[build-dependencies] [profile.release]
quote = "1.0.17" panic = "abort"
walkdir = "1"
[build-dependencies.diesel]
default-features = false
features = ["sqlite", "chrono"]
version = "1.4.8"
[build-dependencies.diesel_migrations]
default-features = false
features = ["sqlite"]
version = "1.4.0"
[dependencies] [dependencies]
bart = "0.1.6" bart = "0.1.4"
bart_derive = "0.1.6" bart_derive = "0.1.4"
chrono = "0.4" chrono = "0.4"
clap = "2.31" clap = "2.26"
diff = "0.1"
futures = "0.1" futures = "0.1"
futures-cpupool = "0.1" futures-cpupool = "0.1"
hyper = "0.11" hyper = "0.11"
lazy_static = "1.4.0" lazy_static = "0.2"
maplit = "1" percent-encoding = "1.0.0"
percent-encoding = "1.0" r2d2 = "0.7"
r2d2 = "0.8" r2d2-diesel = "0.16"
r2d2-diesel = "1.0.0"
regex = "0.2" regex = "0.2"
seahash = "3.0.5"
serde = "1.0.0" serde = "1.0.0"
serde_derive = "1.0.0" serde_derive = "1.0.0"
serde_json = "1.0" serde_json = "1.0"
serde_urlencoded = "0.5.3" serde_urlencoded = "0.5.0"
slug = "0.1" slug = "0.1"
titlecase = "0.10" titlecase = "0.10"
tokio-io = "0.1" tokio-io = "0.1"
tokio-proto = "0.1" tokio-proto = "0.1"
tokio-service = "0.1" tokio-service = "0.1"
serde_plain = "0.3.0"
rand = "0.5.5"
[dependencies.codegen] [dependencies.libsqlite3-sys]
path = "libs/codegen" features = ["bundled"]
version = "*"
[dependencies.diesel] [dependencies.diesel]
default-features = false default-features = false
features = ["sqlite", "chrono"] features = ["sqlite", "chrono"]
version = "1.4.8" version = "0.16"
[dependencies.diesel_infer_schema] [dependencies.diesel_codegen]
default-features = false default-features = false
features = ["sqlite"] features = ["sqlite"]
version = "1.4.0" version = "0.16"
[dependencies.diesel_migrations]
default-features = false
features = ["sqlite"]
version = "1.4.0"
[dependencies.libsqlite3-sys]
features = ["bundled"]
version = "<0.23.0"
[dependencies.num] [dependencies.num]
default-features = false default-features = false
version = "0.1" version = "0.1"
[dependencies.pulldown-cmark] [dependencies.pulldown-cmark]
default-features = false
git = "https://github.com/maghoff/pulldown-cmark.git" git = "https://github.com/maghoff/pulldown-cmark.git"
default-features = false
[dev-dependencies] [dependencies.static_resource_derive]
indoc = "1.0.4" path = "libs/static_resource_derive"
matches = "0.1"
[features] [build-dependencies]
dynamic-assets = [] quote = "0.3.10"
walkdir = "1"
[profile] [build-dependencies.diesel]
default-features = false
[profile.release] features = ["sqlite", "chrono"]
panic = "abort" version = "0.16.0"
[workspace] [workspace]

45
README.md Normal file
View file

@ -0,0 +1,45 @@
[![Build Status](https://travis-ci.org/maghoff/sausagewiki.svg?branch=master)](https://travis-ci.org/maghoff/sausagewiki)
Sausagewiki is a simple, self-contained wiki engine.
Copyright (C) 2017 Magnus Hovland Hoff <maghoff@gmail.com>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Install and run
===============
Sausagewiki aims to be simple to get up and running. It is distributed as a
single independent executable for Linux.
1. Download the latest build of `sausagewiki.xz` from <https://github.com/maghoff/sausagewiki/releases/latest>
2. Decompress: `xz -d sausagewiki.xz`
3. Set execution permission: `chmod a+x sausagewiki`
4. Run: `./sausagewiki wiki.db`
For other platforms you will presently have to build it yourself. Sausagewiki
is built like other Rust projects, with `cargo build`.
Command line arguments
----------------------
USAGE:
sausagewiki [FLAGS] [OPTIONS] <DATABASE>
FLAGS:
-h, --help Prints help information
--trust_identity Trust the value in the X-Identity header to be an authenticated username.
This only makes sense when Sausagewiki runs behind a reverse proxy which
sets this header.
-V, --version Prints version information
OPTIONS:
-p, --port <port> Sets the listening port
ARGS:
<DATABASE> Sets the database file to use
Sausagewiki will create an SQLite database file with the filename given in the
`DATABASE` parameter and open an HTTP server bound to `127.0.0.1` and the given
port number. The default port number is 8080.

View file

@ -1,5 +1,3 @@
"use strict";
function autosizeTextarea(textarea, shadow) { function autosizeTextarea(textarea, shadow) {
shadow.style.width = textarea.clientWidth + "px"; shadow.style.width = textarea.clientWidth + "px";
shadow.value = textarea.value; shadow.value = textarea.value;
@ -8,128 +6,46 @@ function autosizeTextarea(textarea, shadow) {
function queryArgsFromForm(form) { function queryArgsFromForm(form) {
const items = []; const items = [];
for (const {name, value, type, checked} of form.elements) { for (const {name, value} of form.elements) {
if (!name) continue; if (!name) continue;
if (type === "radio" && !checked) continue;
items.push(encodeURIComponent(name) + '=' + encodeURIComponent(value)); items.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
} }
return items.join('&'); return items.join('&');
} }
function isEdited(form) { let hasBeenOpen = false;
for (const {name, value, defaultValue, checked, defaultChecked} of form.elements) {
if (name && ((value !== defaultValue) || (checked !== defaultChecked))) return true;
}
return false;
}
function instantiate(templateId) {
return document.getElementById(templateId).firstElementChild.cloneNode(true);
}
function popup(dialog) {
document.body.appendChild(dialog);
dialog.querySelector(".primary").focus();
return new Promise((resolve, reject) => {
function handler(ev) {
document.body.removeChild(dialog);
resolve(ev.target.getAttribute("data-value"));
}
const buttons = dialog.querySelectorAll('.btn-row>*');
for (let i = 0; i < buttons.length; ++i)
buttons[i].addEventListener("click", handler);
});
}
function loginDialog(loginUrl) {
const dialog = instantiate("login");
dialog.querySelector("a").setAttribute("href", loginUrl);
return popup(dialog);
}
function alertAsync(message) {
const dialog = instantiate("alert");
dialog.querySelector(".message").textContent = message;
return popup(dialog);
}
function confirmDiscard() {
return popup(instantiate("confirm-discard"));
}
const state = {
hasBeenOpen: false,
saving: false,
editing: function () { return document.querySelector(".container").classList.contains('edit'); },
hasCancelUrl: function () { return document.querySelector("a.button-cancel").getAttribute('href') !== ""; }
};
function openEditor() { function openEditor() {
const bodyElement = document.querySelector("body");
const container = document.querySelector(".container"); const container = document.querySelector(".container");
const rendered = container.querySelector(".rendered"); const rendered = container.querySelector(".rendered");
const editor = container.querySelector(".editor"); const editor = container.querySelector(".editor");
const textarea = editor.querySelector('textarea[name="body"]'); const textarea = editor.querySelector('textarea[name="body"]');
const shadow = editor.querySelector('textarea.shadow-control'); const shadow = editor.querySelector('textarea.shadow-control');
const form = document.getElementById('article-editor'); const form = editor.querySelector("form");
const cancel = form.querySelector('.cancel'); const cancel = editor.querySelector('.cancel');
const cancelButton = form.querySelector('button.button-cancel');
const cancelInteractionGroup = form.querySelector(".cancel-interaction-group");
const footer = document.querySelector("footer"); const footer = document.querySelector("footer");
const lastUpdated = footer.querySelector(".last-updated"); const lastUpdated = footer.querySelector(".last-updated");
textarea.style.height = rendered.clientHeight + "px"; textarea.style.height = rendered.clientHeight + "px";
retainScrollRatio(() => {
container.classList.add('edit'); container.classList.add('edit');
autosizeTextarea(textarea, shadow);
});
updateFormEnabledState();
if (state.hasBeenOpen) return; autosizeTextarea(textarea, shadow);
state.hasBeenOpen = true;
textarea.focus();
if (hasBeenOpen) return;
hasBeenOpen = true;
textarea.addEventListener('input', () => autosizeTextarea(textarea, shadow)); textarea.addEventListener('input', () => autosizeTextarea(textarea, shadow));
window.addEventListener('resize', () => autosizeTextarea(textarea, shadow)); window.addEventListener('resize', () => autosizeTextarea(textarea, shadow));
function updateFormEnabledState() { form.addEventListener("submit", function (ev) {
const baseEnabled = !state.saving && state.editing(); ev.preventDefault();
const enabled = { ev.stopPropagation();
cancel: baseEnabled && state.hasCancelUrl(),
};
cancelInteractionGroup.classList.remove(!enabled.cancel ? "interaction-group--root--enabled" : "interaction-group--root--disabled");
cancelInteractionGroup.classList.add(enabled.cancel ? "interaction-group--root--enabled" : "interaction-group--root--disabled");
for (const el of form.elements) {
el.disabled = !baseEnabled;
}
cancelButton.disabled = true;
// TODO: edit-link in footer?
}
function retainScrollRatio(innerFunction) {
const scrollElement = document.body.parentElement;
const savedScrollRatio = scrollElement.scrollTop / (scrollElement.scrollHeight - scrollElement.clientHeight);
innerFunction();
scrollElement.scrollTop = (scrollElement.scrollHeight - scrollElement.clientHeight) * savedScrollRatio;
}
function closeEditor() {
retainScrollRatio(() => container.classList.remove('edit'));
document.activeElement && document.activeElement.blur();
}
function doSave() {
state.saving = true;
updateFormEnabledState();
const body = queryArgsFromForm(form); const body = queryArgsFromForm(form);
textarea.disabled = true;
fetch( fetch(
form.getAttribute("action"), form.getAttribute("action"),
@ -142,26 +58,12 @@ function openEditor() {
credentials: "same-origin", credentials: "same-origin",
} }
).then(response => { ).then(response => {
// I don't know how to more precisely determine that we hit a login redirect:
const probablyLoginRedirect = response.redirected &&
(response.headers.get("content-type") !== "application/json");
if (probablyLoginRedirect) {
return loginDialog(response.url)
.then(() => {
state.saving = false;
updateFormEnabledState();
});
}
if (!response.ok) throw new Error("Unexpected status code (" + response.status + ")"); if (!response.ok) throw new Error("Unexpected status code (" + response.status + ")");
return response.json() return response.json();
.then(result => { }).then(result => {
// Update url-bar, page title, footer and cancel link // Update url-bar, page title and footer
const url = result.slug == "" ? "." : result.slug; window.history.replaceState(null, result.title, result.slug == "" ? "." : result.slug);
window.history.replaceState(null, result.title, url);
cancel.setAttribute("href", url);
document.querySelector("title").textContent = result.title; document.querySelector("title").textContent = result.title;
lastUpdated.innerHTML = result.last_updated; lastUpdated.innerHTML = result.last_updated;
lastUpdated.classList.remove("missing"); lastUpdated.classList.remove("missing");
@ -169,110 +71,31 @@ function openEditor() {
// Update body: // Update body:
rendered.innerHTML = result.rendered; rendered.innerHTML = result.rendered;
form.elements.title.value = result.title;
shadow.value = textarea.value = result.body;
form.querySelector(`.theme-picker--option[value=${JSON.stringify(result.theme)}]`).checked = true;
bodyElement.className = `theme-${result.theme}`;
// Update form: // Update form:
form.elements.base_revision.value = result.revision; form.elements.base_revision.value = result.revision;
for (const element of form.elements) { for (const element of form.elements) {
element.defaultValue = element.value; element.defaultValue = element.value;
element.defaultChecked = element.checked;
} }
if (!result.conflict) { container.classList.remove('edit');
closeEditor();
}
state.saving = false; textarea.disabled = false;
updateFormEnabledState();
autosizeTextarea(textarea, shadow);
if (result.conflict) {
return alertAsync("Your edit came into conflict with another change " +
"and has not been saved.\n" +
"Please resolve the merge conflict and save again.");
}
});
}).catch(err => { }).catch(err => {
state.saving = false; textarea.disabled = false;
updateFormEnabledState();
console.error(err); console.error(err);
return alertAsync(err.toString()); alert(err);
}); });
}
function doCancel() {
Promise.resolve(!isEdited(form) || confirmDiscard())
.then(doReset => {
if (doReset) {
closeEditor();
updateFormEnabledState();
form.reset();
let selectedTheme = form.querySelector(`.theme-picker--option[checked]`).value;
bodyElement.className = `theme-${selectedTheme}`;
}
});
}
form.addEventListener("submit", function (ev) {
ev.preventDefault();
ev.stopPropagation();
doSave();
}); });
cancel.addEventListener('click', function (ev) { cancel.addEventListener('click', function (ev) {
ev.preventDefault(); ev.preventDefault();
ev.stopPropagation(); ev.stopPropagation();
doCancel();
container.classList.remove('edit');
form.reset();
}); });
window.addEventListener("beforeunload", function (ev) {
if (isEdited(form)) {
ev.preventDefault();
return ev.returnValue = "Discard changes?";
}
});
document.addEventListener("keypress", function (ev) {
const accel = ev.ctrlKey || ev.metaKey; // Imprecise, but works cross platform
if (ev.key === "Enter" && accel) {
if (!state.editing()) return;
ev.stopPropagation();
ev.preventDefault();
doSave();
}
});
const themeOptions = form.querySelectorAll(".theme-picker--option");
for (let themeOption of themeOptions) {
themeOption.addEventListener("click", function (ev) {
bodyElement.className = `theme-${ev.target.value}`;
});
}
} }
function initializeTheme() {
const form = document.getElementById('article-editor');
let preSelectedTheme = form.querySelector(`.theme-picker--option[checked]`);
if (preSelectedTheme) return;
let themes = form.querySelectorAll(`.theme-picker--option`);
let randomThemeId = (Math.random() * themes.length) | 0;
let theme = themes[randomThemeId];
theme.defaultChecked = theme.checked = true;
document.querySelector("body").className = `theme-${theme.value}`;
}
initializeTheme();
document document
.getElementById("openEditor") .getElementById("openEditor")
.addEventListener("click", function (ev) { .addEventListener("click", function (ev) {

View file

@ -18,17 +18,11 @@ function debouncer(interval, callback) {
const results = form.querySelector('.live-results'); const results = form.querySelector('.live-results');
const resultPrototype = document.getElementById('search-result-prototype').firstChild; const resultPrototype = document.getElementById('search-result-prototype').firstChild;
function clearChildren(element) {
while (element.lastChild) {
element.removeChild(results.lastChild);
}
}
let ongoing = false; let ongoing = false;
function submit() { function submit() {
if (input.value === "") { if (input.value === "") {
results.classList.remove("show"); results.classList.remove("show");
clearChildren(results); while (results.lastChild) results.removeChild(results.lastChild);
return; return;
} }
@ -37,7 +31,7 @@ function debouncer(interval, callback) {
const query = input.value; const query = input.value;
fetch( fetch(
"_search?snippet_size=14&limit=4&q=" + encodeURIComponent(query), "_search?snippet_size=4&limit=4&q=" + encodeURIComponent(query),
{ {
headers: { headers: {
"Accept": "application/json", "Accept": "application/json",
@ -49,14 +43,14 @@ function debouncer(interval, callback) {
return response.json(); return response.json();
}).then(result => { }).then(result => {
clearChildren(results); while (results.lastChild) results.removeChild(results.lastChild);
result.hits.forEach((hit, index) => { result.hits.forEach((hit, index) => {
const item = resultPrototype.cloneNode(true); const item = resultPrototype.cloneNode(true);
item.querySelector('.link').href = hit.slug || "."; item.querySelector('.link').href = hit.slug || ".";
item.querySelector('.link').setAttribute("data-focusindex", index + 1); item.querySelector('.link').setAttribute("data-focusindex", index + 1);
item.querySelector('.title').textContent = hit.title; item.querySelector('.title').textContent = hit.title;
item.querySelector('.snippet').innerHTML = hit.snippet; item.querySelector('.snippet').textContent = hit.snippet;
results.appendChild(item); results.appendChild(item);
}) })
@ -74,18 +68,9 @@ function debouncer(interval, callback) {
ongoing = false; ongoing = false;
}).catch(err => { }).catch(err => {
console.error(err);
clearChildren(results);
results.classList.add("show");
const item = document.createElement("li");
item.classList.add("search-result");
item.classList.add("error");
item.textContent = "Live search unavailable";
results.appendChild(item);
ongoing = false; ongoing = false;
console.error(err);
alert(err); // TODO Better interactive error reporting
}); });
} }
const submitter = debouncer(300, submit); const submitter = debouncer(300, submit);

View file

@ -1,9 +1,13 @@
.prototype { @font-face {
display: none; font-family: 'Amatic SC';
font-style: normal;
font-weight: 400;
src: local('Amatic SC Regular'), local('AmaticSC-Regular'),
url('amatic-sc-v9-latin-regular.woff') format('woff');
} }
input { .prototype {
margin: 0; /* reset for Safari */ display: none;
} }
html { html {
@ -13,6 +17,8 @@ html {
} }
h1 { h1 {
font-family: 'Amatic SC', sans-serif;
font-weight: normal; font-weight: normal;
font-style: normal; font-style: normal;
@ -25,7 +31,7 @@ article h1 {
margin-bottom: 0; margin-bottom: 0;
} }
h2, h3, h4, h5, h6 { h2, h3 {
font-family: inherit; font-family: inherit;
font-size: 18px; font-size: 18px;
line-height: 32px; line-height: 32px;
@ -43,31 +49,25 @@ h3 {
font-style: italic; font-style: italic;
} }
h4, h5, h6 {
font-weight: normal;
font-style: normal;
}
article ul, article ol { article ul, article ol {
padding-left: 32px; padding-left: 32px;
} }
h1+*, h2+*, h3+*, h4+*, h5+*, h6+* { h1+*, h2+*, h3+* {
margin-top: 0; margin-top: 0;
} }
article>hr { article>hr {
border: none; border: none;
border-top: 6px solid var(--theme-main); border-top: 1px solid black;
width: 40px; max-width: 400px;
width: 70%;
margin: 20px auto; margin: 20px auto;
} }
.notice { .notice {
background: var(--theme-main); background: lightyellow;
color: var(--theme-text); padding: 16px 48px;
padding: 1px 24px;
font-size: 18px; font-size: 18px;
line-height: 32px; line-height: 32px;
@ -76,22 +76,6 @@ article>hr {
width: 100%; width: 100%;
margin: 30px auto; margin: 30px auto;
} }
.notice a {
color: var(--theme-link);
}
.hero {
background: var(--theme-main);
color: var(--theme-text);
/* Hack to force containing the children instead of collapsing marigins */
border: 1px solid var(--theme-main);
}
.search-container {
background: var(--theme-main);
color: var(--theme-text);
}
header, article>*, .search { header, article>*, .search {
box-sizing: border-box; box-sizing: border-box;
@ -108,7 +92,7 @@ header {
} }
article { article {
margin: 50px auto 120px auto; margin: 0 auto 120px auto;
font-size: 18px; font-size: 18px;
line-height: 32px; line-height: 32px;
@ -159,19 +143,7 @@ pre {
} }
a { a {
color: #1976D2; color: #457796;
text-decoration: none;
}
a[href^="http"]::after {
display: inline-block;
padding: 0 0.1rem;
font-size: 75%;
content: "🔗";
line-height: 0;
}
a[href^="http"]:hover::after {
text-decoration: none; text-decoration: none;
} }
@ -205,10 +177,10 @@ body {
footer { footer {
padding: 16px 8px 16px 8px; padding: 0 8px;
background: var(--theme-main); background: #f8f8f8;
color: var(--theme-text); color: #444;
text-align: center; text-align: center;
font-family: -apple-system, BlinkMacSystemFont, font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", "Roboto", "Oxygen", "Segoe UI", "Roboto", "Oxygen",
@ -216,10 +188,6 @@ footer {
"Droid Sans", "Helvetica Neue", sans-serif; "Droid Sans", "Helvetica Neue", sans-serif;
} }
footer a {
color: var(--theme-link);
}
ul.dense { ul.dense {
list-style: none; list-style: none;
padding: 0; padding: 0;
@ -275,11 +243,6 @@ h1>input {
width: 100%; width: 100%;
} }
.hero input {
background: var(--theme-input);
color: var(--theme-text);
}
.shadow-control { .shadow-control {
visibility: hidden; visibility: hidden;
position: fixed; position: fixed;
@ -309,163 +272,18 @@ h1>input {
bottom: 0; bottom: 0;
left: 0; left: 0;
box-sizing: border-box; background: #91A238;
padding: 10px 20px;
text-align: right;
box-shadow: 0px 5px 20px rgba(0,0,0, 0.2);
background: white;
color: var(--theme-text);
padding: 10px 10px;
transform: translate(0, 65px);
transition: transform 100ms;
transition-timing-function: linear;
pointer-events: none;
} }
.edit .editor-controls { @media (min-width: 630px) {
transform: translate(0, 0);
transition-timing-function: cubic-bezier(.17,.84,.44,1);
pointer-events: unset;
}
.theme-picker {
position: absolute;
top: 0;
left: 0;
right: 0;
display: flex;
}
.theme-picker--option {
/* reset */
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
-ms-appearance: none;
appearance: none;
border: none;
border-radius: 0;
margin: 0;
padding: 0;
height: 20px;
background: var(--theme-main);
color: var(--theme-text);
flex-grow: 1;
position: relative;
}
.theme-picker--option:checked::after {
content: " ";
display: block;
background: white;
border-radius: 5px;
width: 10px;
height: 10px;
position: absolute;
top: calc(50% - 5px);
left: calc(50% - 5px);
}
.button {
border-radius: 2px;
display: inline-block;
width: 120px;
text-align: center;
border: none;
cursor: pointer;
font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans",
"Droid Sans", "Helvetica Neue", sans-serif;
font-size: 16px;
line-height: 20px;
padding: 10px 0px;
margin-left: 10px;
}
.button[disabled] {
opacity: 0.5;
cursor: default;
}
.button:hover {
text-decoration: none;
}
.button:not([disabled]):hover, .button:not([disabled]):active {
background: var(--button-alt);
}
.button-cancel {
background: white;
color: var(--theme-main);
--button-alt: #f0f0f0;
}
.button-default {
background: var(--theme-main);
color: var(--theme-text);
--button-alt: var(--theme-input);
}
.cancel-interaction-group {
display: inline;
}
.interaction-group--root--enabled .interaction-group--disabled {
display: none;
}
.interaction-group--root--disabled .interaction-group--enabled {
display: none;
}
@media (min-width: 960px) {
/* min-width is calculated like this:
body-width = width of the main text column
controls-width = width of .editor-controls element, including drop-shadow
min-width = body-width + 2*controls-width = 600 + 2 * 180 = 960
*/
.editor-controls { .editor-controls {
border-radius: 2px;
position: fixed; position: fixed;
left: calc(50% + 320px); left: auto;
width: 140px; right: 20px;
top: calc(50% - 55px); bottom: 20px;
height: 110px;
padding: 10px;
transform: translate(20px, 0); box-shadow: 2px 2px 8px rgba(0,0,0, 0.25);
opacity: 0;
transition: transform 100ms, opacity 100ms;
transition-timing-function: linear;
}
.edit .editor-controls {
transform: translate(0, 0);
transition-timing-function: cubic-bezier(.17,.84,.44,1);
opacity: 1;
}
.button {
margin: 0;
margin-bottom: 10px;
} }
} }
@ -482,6 +300,9 @@ article ul.search-results {
.search-result .title { .search-result .title {
font-weight: bold; font-weight: bold;
} }
.snippet {
white-space: pre-line;
}
.search-result p { .search-result p {
margin: 0; margin: 0;
} }
@ -490,18 +311,18 @@ article ul.search-results {
display: block; display: block;
color: inherit; color: inherit;
text-decoration: none; text-decoration: none;
padding: 8px 16px; border: 1px solid #ccc;
background: white; padding: 8px;
color: black;
} }
.search-result a:hover, .search-result a:focus { .search-result a:hover, .search-result a:focus {
background: var(--theme-main); background: #0074D9;
color: var(--theme-text); border-color: #0074D9;
color: white;
} }
.search { .search {
text-align: center; text-align: center;
margin-top: 45px; margin-top: 30px;
position: relative; position: relative;
} }
@ -510,18 +331,16 @@ input[type="search"]::-webkit-search-decoration {
} }
input[type="search"] { input[type="search"] {
-webkit-appearance: none; -webkit-appearance: textfield;
border-radius: 0;
box-sizing: border-box; box-sizing: border-box;
width: 100%; width: 100%;
max-width: 300px; max-width: 300px;
transition: max-width 200ms;
padding: 0 16px; padding: 0 16px;
margin: 0; margin: 0;
border: none; border: 1px solid #ccc;
background: var(--theme-input);
color: var(--theme-text);
font: inherit; font: inherit;
font-size: 18px; font-size: 18px;
@ -529,12 +348,13 @@ input[type="search"] {
line-height: 32px; line-height: 32px;
height: 34px; height: 34px;
border-radius: 18px;
text-overflow: ellipsis; text-overflow: ellipsis;
} }
input[type="search"]::placeholder, .hero input::placeholder { .search input:focus, .search.focus input {
color: var(--theme-text); max-width: 300px;
opacity: 0.6; border-color: #999;
} }
.search .live-results { .search .live-results {
@ -542,8 +362,9 @@ input[type="search"]::placeholder, .hero input::placeholder {
box-sizing: border-box; box-sizing: border-box;
width: 100%; width: 100%;
max-width: 300px; max-width: 266px; /* 300px - padding - border */
background: white;
padding: 0; padding: 0;
margin: 0 auto; margin: 0 auto;
@ -553,15 +374,6 @@ input[type="search"]::placeholder, .hero input::placeholder {
max-height: 0px; max-height: 0px;
} }
.search-widget-container {
border-radius: 2px;
overflow: hidden;
width: 100%;
max-width: 300px;
display: inline-block;
}
.live-results.show { .live-results.show {
max-height: 500px; max-height: 500px;
} }
@ -569,33 +381,23 @@ input[type="search"]::placeholder, .hero input::placeholder {
.live-results .search-result { .live-results .search-result {
margin: 0; margin: 0;
} }
.live-results a {
.live-results .search-result.error { border-top: none;
padding: 8px;
color: #888;
} }
@media (min-width: 630px) { @media (min-width: 630px) {
.search { .search {
text-align: right; text-align: right;
height: 38px;
position: relative;
} }
.search-widget-container { .search input {
position: absolute; max-width: 125px;
right: 8px;
width: 300px;
box-shadow: 0 0 0 rgba(0,0,0,0.2);
transition: all 0.2s ease-in-out;
}
.focus .search-widget-container {
box-shadow: 0 5px 20px rgba(0,0,0,0.2);
} }
.search .live-results { .search .live-results {
width: 100%; position: absolute;
right: 8px;
margin: 0 16px;
max-height: 0px; max-height: 0px;
} }
@ -603,146 +405,3 @@ input[type="search"]::placeholder, .hero input::placeholder {
max-height: 500px; max-height: 500px;
} }
} }
.diff {
background: none;
white-space: pre-wrap;
}
.removed {
color: #866;
background: #fdd;
text-decoration: line-through;
}
.added {
background: #ceb;
}
.modal-block {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
}
.popup {
display: flex;
flex-direction: column;
text-align: center;
background: #eee;
box-shadow: 0px 5px 20px rgba(0,0,0, 0.2);
}
.popup>.message {
margin: 16px 32px;
max-width: 600px;
}
.popup>.btn-row {
display: flex;
flex-direction: row;
font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans",
"Droid Sans", "Helvetica Neue", sans-serif;
}
.btn-row>* {
padding: 8px 16px;
margin: 0;
background: white;
color: black;
border: none;
border-radius: 0;
flex: 1;
font-family: inherit;
cursor: pointer;
}
.btn-row>*:hover {
text-decoration: underline;
}
.primary {
background: #337ab7;
color: white;
}
@media print {
@page {
margin: 25mm;
}
html, body {
height: unset;
}
body {
display: block;
}
.hero {
background: none;
color: initial;
/* Disable hack to force containing the children instead of collapsing marigins */
border: none;
}
h1, h2, h3, h4, h5, h6 {
/* This doesn't work at all, but it might start to! */
break-after: avoid;
page-break-after: avoid;
}
a, a:visited, a:hover, a:visited:hover {
text-decoration: none;
color: black !important;
font-weight: normal !important;
}
a[href^="http"]::after {
display: none;
}
article {
margin: 0 auto;
}
article>hr {
border-color: black;
}
h1 {
font-size: 22pt;
line-height: 33pt;
}
article, h2, h3, h4, h5, h6, .notice {
font-size: 12pt;
line-height: 18pt;
}
article p {
text-align: justify;
}
pre {
overflow: visible;
white-space: pre-wrap;
}
.search {
display: none;
}
footer {
display: none;
}
}

View file

@ -1,54 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Test themes &ndash; Sausagewiki</title>
<link href="themes.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">
<style>
.themed {
padding: 10px;
background: var(--theme-main);
color: var(--theme-text);
}
.link {
color: var(--theme-link);
}
.proto {
display: none;
}
#bar {
display: flex;
width: 100%;
}
#bar>div {
height: 30px;
flex-grow: 1;
}
</style>
</head>
<body>
<div id="bar"></div>
<div class="proto">
<div class="themed">The <span class="link">quick</span> brown <span class="link">dog</span> jumps over the lazy log <span class="theme-name"></span></div>
<div class="themed"><input type=search placeholder=placeholder> <input type=search value="Bacon"></div>
</div>
<script>
const themes = ["red", "pink", "purple", "deep-purple", "indigo", "blue", "light-blue", "cyan", "teal", "green", "light-green", "lime", "yellow", "amber", "orange", "deep-orange", "brown", "gray", "blue-gray"];
const body = document.querySelector("body");
const proto = document.querySelector(".proto");
for (theme of themes) {
const block = proto.cloneNode(true);
block.className = `theme-${theme}`;
block.querySelector(".theme-name").textContent = theme;
body.appendChild(block);
}
const bar = document.querySelector("#bar");
for (theme of themes) {
const block = document.createElement("div");
block.className = `theme-${theme} themed`;
bar.appendChild(block);
}
</script>
</body>
</html>

View file

@ -1,134 +0,0 @@
.theme-red {
--theme-main: #F44336;
--theme-text: white;
--theme-input: #E57373;
--theme-link: #FFF59D;
}
.theme-pink {
--theme-main: #E91E63;
--theme-text: white;
--theme-input: #F06292;
--theme-link: #FFF59D;
}
.theme-purple {
--theme-main: #9C27B0;
--theme-text: white;
--theme-input: #BA68C8;
--theme-link: #90CAF9;
}
.theme-deep-purple {
--theme-main: #673AB7;
--theme-text: white;
--theme-input: #9575CD;
--theme-link: #90CAF9;
}
.theme-indigo {
--theme-main: #3F51B5;
--theme-text: white;
--theme-input: #7986CB;
--theme-link: #90CAF9;
}
.theme-blue {
--theme-main: #2196F3;
--theme-text: white;
--theme-input: #64B5F6;
--theme-link: #90CAF9;
}
.theme-light-blue {
--theme-main: #03A9F4;
--theme-text: white;
--theme-input: #4FC3F7;
--theme-link: #90CAF9;
}
.theme-cyan {
--theme-main: #00ACC1;
--theme-text: white;
--theme-input: #26C6DA;
--theme-link: #90CAF9;
}
.theme-teal {
--theme-main: #009688;
--theme-text: white;
--theme-input: #4DB6AC;
--theme-link: #90CAF9;
}
.theme-green {
--theme-main: #4CAF50;
--theme-text: white;
--theme-input: #81C784;
--theme-link: #90CAF9;
}
.theme-light-green {
--theme-main: #7CB342;
--theme-text: white;
--theme-input: #9CCC65;
--theme-link: #90CAF9;
}
.theme-lime {
--theme-main: #C0CA33;
--theme-text: white;
--theme-input: #AFB42B;
--theme-link: #1976D2;
}
.theme-yellow {
--theme-main: #FDD835;
--theme-text: white;
--theme-input: #FBC02D;
--theme-link: #1976D2;
}
.theme-amber {
--theme-main: #FFB300;
--theme-text: white;
--theme-input: #FFA000;
--theme-link: #1976D2;
}
.theme-orange {
--theme-main: #FB8C00;
--theme-text: white;
--theme-input: #FFA726;
--theme-link: #FFF59D;
}
.theme-deep-orange {
--theme-main: #FF5722;
--theme-text: white;
--theme-input: #FF8A65;
--theme-link: #FFF59D;
}
.theme-brown {
--theme-main: #795548;
--theme-text: white;
--theme-input: #A1887F;
--theme-link: #FFF59D;
}
.theme-gray {
--theme-main: #9E9E9E;
--theme-text: white;
--theme-input: #E0E0E0;
--theme-link: #90CAF9;
}
.theme-blue-gray {
--theme-main: #607D8B;
--theme-text: white;
--theme-input: #90A4AE;
--theme-link: #90CAF9;
}

View file

@ -1,53 +1,36 @@
#[macro_use] #[macro_use] extern crate quote;
extern crate diesel; extern crate diesel;
extern crate walkdir;
use diesel::prelude::*;
use diesel::Connection; use diesel::Connection;
use quote::quote; use diesel::prelude::*;
use std::env; use std::env;
use std::fs::File; use std::fs::File;
use std::io::prelude::*; use std::io::prelude::*;
use std::path::Path; use std::path::Path;
use walkdir::WalkDir; use walkdir::WalkDir;
#[allow(dead_code)]
mod sqlfunc {
use diesel::sql_types::Text;
sql_function!(fn markdown_to_fts(text: Text) -> Text);
sql_function!(fn theme_from_str_hash(text: Text) -> Text);
}
fn main() { fn main() {
let out_dir = env::var("OUT_DIR").expect("cargo must set OUT_DIR"); let out_dir = env::var("OUT_DIR").expect("cargo must set OUT_DIR");
let db_path = Path::new(&out_dir).join("build.db"); let db_path = Path::new(&out_dir).join("build.db");
let db_path = db_path let db_path = db_path.to_str().expect("Will only work for Unicode-representable paths");
.to_str()
.expect("Will only work for Unicode-representable paths");
let _ignore_failure = std::fs::remove_file(db_path); let _ignore_failure = std::fs::remove_file(db_path);
let connection = SqliteConnection::establish(db_path) let connection = SqliteConnection::establish(db_path)
.unwrap_or_else(|_| panic!("Error esablishing a database connection to {}", db_path)); .expect(&format!("Error esablishing a database connection to {}", db_path));
// Integer is a dummy placeholder. Compiling fails when passing (). // Integer is a dummy placeholder. Compiling fails when passing ().
diesel::expression::sql_literal::sql::<diesel::sql_types::Integer>("PRAGMA foreign_keys = ON") diesel::expression::sql_literal::sql::<(diesel::types::Integer)>("PRAGMA foreign_keys = ON")
.execute(&connection) .execute(&connection)
.expect("Should be able to enable foreign keys"); .expect("Should be able to enable foreign keys");
sqlfunc::markdown_to_fts::register_impl(&connection, |_: String| -> String { unreachable!() }) diesel::migrations::run_pending_migrations(&connection).unwrap();
.unwrap();
sqlfunc::theme_from_str_hash::register_impl(&connection, |_: String| -> String {
unreachable!()
})
.unwrap();
diesel_migrations::run_pending_migrations(&connection).unwrap();
let infer_schema_path = Path::new(&out_dir).join("infer_schema.rs"); let infer_schema_path = Path::new(&out_dir).join("infer_schema.rs");
let mut file = File::create(infer_schema_path).expect("Unable to open file for writing"); let mut file = File::create(infer_schema_path).expect("Unable to open file for writing");
file.write_all( file.write_all(quote! {
quote! {
mod __diesel_infer_schema_articles { mod __diesel_infer_schema_articles {
infer_table_from_schema!(#db_path, "articles"); infer_table_from_schema!(#db_path, "articles");
} }
@ -57,21 +40,9 @@ fn main() {
infer_table_from_schema!(#db_path, "article_revisions"); infer_table_from_schema!(#db_path, "article_revisions");
} }
pub use self::__diesel_infer_schema_article_revisions::*; pub use self::__diesel_infer_schema_article_revisions::*;
} }.as_str().as_bytes()).expect("Unable to write to file");
.to_string()
.as_bytes(),
)
.expect("Unable to write to file");
for entry in WalkDir::new("migrations") for entry in WalkDir::new("migrations").into_iter().filter_map(|e| e.ok()) {
.into_iter()
.filter_map(|e| e.ok())
{
println!("cargo:rerun-if-changed={}", entry.path().display()); println!("cargo:rerun-if-changed={}", entry.path().display());
} }
// For build_config.rs
for env_var in &["CONTINUOUS_INTEGRATION", "TRAVIS_BRANCH", "TRAVIS_COMMIT"] {
println!("cargo:rerun-if-env-changed={}", env_var);
}
} }

View file

@ -1,4 +0,0 @@
Thank you for your interest in contributing to Sausagewiki!
The high level design of Sausagewiki is described in [DESIGN.md](DESIGN.md).
Please consider your contribution in light of this document.

View file

@ -1,16 +0,0 @@
class Sausagewiki < Formula
desc "A simple, self-contained Wiki engine"
homepage "https://github.com/maghoff/sausagewiki/"
head "https://github.com/maghoff/sausagewiki.git"
depends_on "rust" => :build
def install
system "cargo", "build", "--release"
bin.install "target/release/sausagewiki"
end
test do
system "#{bin}/sausagewiki", "--version"
end
end

View file

@ -1,42 +0,0 @@
Sausagewiki is a simple, self-contained wiki engine. This is not merely a
description, but in fact design goals. Let's look closer at them.
Sausagewiki is simple
=====================
Sausagewiki is somewhat feature sparse. Of course, implementing features takes
time and effort, but that is not all. Sausagewiki attempts to attain
simplicity in part by being very restrictive with which features to add. Which
features belong in Sausagewiki? That is hard to pin down. There are many
features that could be included in a simple wiki engine, but it is probably
true that including _all_ those features would make the engine no longer
simple. Because of this, Sausagewiki is extremely restrictive with which
features to add.
Sausagewiki is simple to use. The user interface is clean and simple. The wiki
language is small and easy to fully grasp. For example: In order to keep the
wiki syntax small and easy, the inline HTML feature of Markdown has been
excluded. It would make the wiki syntax too large.
The executable has few command line options. It is easy for the system
administrator to get up and running correctly. As a user you can also be sure
that Sausagewiki is the same when using it in different places.
Sausagewiki is self-contained
=============================
The binary does not have runtime dependencies. It does not dynamically link
with any library. (This is true for Linux. For other systems it needs to link
to the C standard library) It does not require any other program during
run time, and it does not require any resource file external to the
Sausagewiki binary.
Sausagewiki has no configuration file. This is sensible only as long as it
also has very few command line options.
The data for a given wiki instance is contained in one file only. This makes
a wiki instance easy to back up, copy and move.
Sausagewiki is a wiki engine
============================
The user experience is geared towards collaborative editing rather than a
division between editors and readers. Sausagewiki aims for a low barrier to
entry; new readers should feel invited to edit the text if appropriate.

View file

@ -1,27 +0,0 @@
#![recursion_limit = "128"]
#[macro_use]
extern crate quote;
#[macro_use]
extern crate serde_derive;
extern crate base64;
extern crate proc_macro;
extern crate serde;
extern crate serde_json;
extern crate sha2;
extern crate syn;
use proc_macro::TokenStream;
mod licenses;
mod static_resource;
#[proc_macro_derive(StaticResource, attributes(filename, mime))]
pub fn static_resource(input: TokenStream) -> TokenStream {
static_resource::static_resource(input)
}
#[proc_macro_derive(Licenses)]
pub fn licenses(input: TokenStream) -> TokenStream {
licenses::licenses(input)
}

View file

@ -1,105 +0,0 @@
use std::fs::File;
use proc_macro::TokenStream;
use quote;
use serde::de::IgnoredAny;
use serde_json;
const SOURCES: &[&str] = &["src/licenses/license-hound.json", "src/licenses/other.json"];
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum LicenseId {
Bsd3Clause,
Mit,
Mpl2,
Ofl11,
}
impl LicenseId {
fn include_notice(&self) -> bool {
use self::LicenseId::*;
match self {
Mpl2 => false,
_ => true,
}
}
}
impl quote::ToTokens for LicenseId {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
use self::LicenseId::*;
tokens.append(match self {
Bsd3Clause => "Bsd3Clause",
Mit => "Mit",
Mpl2 => "Mpl2",
Ofl11 => "Ofl11",
});
}
}
#[derive(Debug, Deserialize)]
struct LicenseDescription {
chosen_license: LicenseId,
copyright_notice: String,
link: Option<String>,
}
#[derive(Debug, Deserialize)]
struct LicenseReport {
package_name: String,
conclusion: Result<LicenseDescription, IgnoredAny>,
}
impl quote::ToTokens for LicenseReport {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
let c: &LicenseDescription = self.conclusion.as_ref().unwrap();
let (name, link, copyright, license) = (
&self.package_name,
&c.link,
&c.copyright_notice,
&c.chosen_license,
);
let link = match *link {
Some(ref link) => quote! { Some(#link) },
None => quote! { None },
};
let copyright = match license.include_notice() {
true => copyright,
false => "",
};
tokens.append(quote! {
LicenseInfo {
name: #name,
link: #link,
copyright: #copyright,
license: License::#license,
}
});
}
}
pub fn licenses(_input: TokenStream) -> TokenStream {
let mut license_infos = SOURCES
.iter()
.map(|x| -> Vec<LicenseReport> { serde_json::from_reader(File::open(x).unwrap()).unwrap() })
.map(|x| x.into_iter().filter(|x| x.conclusion.is_ok()))
.fold(vec![], |mut a, b| {
a.extend(b);
a
});
license_infos.sort_unstable_by_key(|x| x.package_name.to_lowercase());
let gen = quote! {
lazy_static! {
static ref LICENSE_INFOS: &'static [LicenseInfo] = &[
#(#license_infos,)*
];
}
};
gen.parse().unwrap()
}

View file

@ -1,17 +1,14 @@
[package] [package]
name = "codegen" name = "static_resource_derive"
version = "0.1.0" version = "0.1.0"
authors = ["Magnus Hoff <maghoff@gmail.com>"] authors = ["Magnus Hoff <maghoff@gmail.com>"]
license = "GPL-3.0" license = "GPL-3.0"
[dependencies] [dependencies]
base64 = "0.6"
quote = "0.3.10" quote = "0.3.10"
serde = "1.0.0"
serde_derive = "1.0.0"
serde_json = "1.0"
sha2 = "0.6"
syn = "0.10.5" syn = "0.10.5"
sha2 = "0.6"
base64 = "0.6"
[lib] [lib]
proc-macro = true proc-macro = true

View file

@ -1,64 +1,63 @@
use std; #![recursion_limit="128"]
#[macro_use] extern crate quote;
extern crate base64;
extern crate proc_macro;
extern crate sha2;
extern crate syn;
use proc_macro::TokenStream;
use std::fs::File; use std::fs::File;
use std::io::prelude::*; use std::io::prelude::*;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use proc_macro::TokenStream;
use syn;
fn user_crate_root() -> PathBuf { fn user_crate_root() -> PathBuf {
std::env::current_dir().expect("Unable to get current directory") std::env::current_dir().expect("Unable to get current directory")
} }
fn find_attr<'a>(attrs: &'a [syn::Attribute], name: &str) -> Option<&'a str> { fn find_attr<'a>(attrs: &'a Vec<syn::Attribute>, name: &str) -> Option<&'a str> {
attrs attrs.iter()
.iter()
.find(|&x| x.name() == name) .find(|&x| x.name() == name)
.and_then(|attr| match attr.value { .and_then(|ref attr| match &attr.value {
syn::MetaItem::NameValue(_, syn::Lit::Str(ref template, _)) => Some(template), &syn::MetaItem::NameValue(_, syn::Lit::Str(ref template, _)) => Some(template),
_ => None, _ => None
}) })
.map(|x| x.as_ref()) .map(|x| x.as_ref())
} }
fn buf_file<P: AsRef<Path>>(filename: P) -> Vec<u8> { fn buf_file<P: AsRef<Path>>(filename: P) -> Vec<u8> {
let mut f = File::open(filename).expect("Unable to open file for reading"); let mut f = File::open(filename)
.expect("Unable to open file for reading");
let mut buf = Vec::new(); let mut buf = Vec::new();
f.read_to_end(&mut buf).expect("Unable to read file"); f.read_to_end(&mut buf)
.expect("Unable to read file");
buf buf
} }
fn calculate_checksum<P: AsRef<Path>>(filename: P) -> String { fn calculate_checksum<P: AsRef<Path>>(filename: P) -> String {
use base64::*; use base64::*;
use sha2::{Digest, Sha256}; use sha2::{Sha256, Digest};
encode_config(&Sha256::digest(&buf_file(filename)), URL_SAFE) encode_config(&Sha256::digest(&buf_file(filename)), URL_SAFE)
} }
#[proc_macro_derive(StaticResource, attributes(filename, mime))]
pub fn static_resource(input: TokenStream) -> TokenStream { pub fn static_resource(input: TokenStream) -> TokenStream {
let s = input.to_string(); let s = input.to_string();
let ast = syn::parse_macro_input(&s).unwrap(); let ast = syn::parse_macro_input(&s).unwrap();
let filename = let filename = find_attr(&ast.attrs, "filename")
find_attr(&ast.attrs, "filename").expect("The `filename` attribute must be specified"); .expect("The `filename` attribute must be specified");
let abs_filename = user_crate_root().join(filename); let abs_filename = user_crate_root().join(filename);
let abs_filename = abs_filename let abs_filename = abs_filename.to_str().expect("Absolute file path must be valid Unicode");
.to_str()
.expect("Absolute file path must be valid Unicode");
let checksum = calculate_checksum(&abs_filename); let checksum = calculate_checksum(&abs_filename);
let path: &Path = filename.as_ref(); let mime = find_attr(&ast.attrs, "mime")
let resource_name = format!( .expect("The `mime` attribute must be specified");
"{}-{}.{}",
path.file_stem().unwrap().to_str().unwrap(),
checksum,
path.extension().unwrap().to_str().unwrap()
);
let mime = find_attr(&ast.attrs, "mime").expect("The `mime` attribute must be specified");
let name = &ast.ident; let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
@ -98,12 +97,12 @@ pub fn static_resource(input: TokenStream) -> TokenStream {
} }
impl #impl_generics #name #ty_generics #where_clause { impl #impl_generics #name #ty_generics #where_clause {
pub fn resource_name() -> &'static str { pub fn checksum() -> &'static str {
#resource_name #checksum
} }
pub fn etag() -> ::hyper::header::EntityTag { pub fn etag() -> ::hyper::header::EntityTag {
::hyper::header::EntityTag::new(false, #checksum.to_owned()) ::hyper::header::EntityTag::new(false, Self::checksum().to_owned())
} }
} }
}; };

View file

@ -1,24 +0,0 @@
DROP TRIGGER article_revisions_ai;
DROP TRIGGER article_revisions_ad;
DROP TRIGGER article_revisions_au_disable;
DROP TRIGGER article_revisions_au_enable;
CREATE TRIGGER article_revisions_ai AFTER INSERT ON article_revisions WHEN new.latest = 1 BEGIN
DELETE FROM article_search WHERE rowid = new.article_id;
INSERT INTO article_search(rowid, title, body, slug) VALUES (new.article_id, new.title, markdown_to_fts(new.body), new.slug);
END;
CREATE TRIGGER article_revisions_ad AFTER DELETE ON article_revisions WHEN old.latest = 1 BEGIN
DELETE FROM article_search WHERE rowid = old.article_id;
END;
-- Index unique_latest_revision_per_article_id makes sure the following is sufficient:
CREATE TRIGGER article_revisions_au_disable AFTER UPDATE ON article_revisions WHEN old.latest = 1 AND new.latest = 0 BEGIN
DELETE FROM article_search WHERE rowid = old.article_id;
END;
CREATE TRIGGER article_revisions_au_enable AFTER UPDATE ON article_revisions WHEN old.latest = 0 AND new.latest = 1 BEGIN
INSERT INTO article_search(rowid, title, body, slug) VALUES (new.article_id, new.title, markdown_to_fts(new.body), new.slug);
END;
DELETE FROM article_search;
INSERT INTO article_search(title, body, slug)
SELECT title, markdown_to_fts(body), slug FROM article_revisions WHERE latest = 1;

View file

@ -1,7 +0,0 @@
ALTER TABLE article_revisions ADD COLUMN theme TEXT NOT NULL CHECK (theme IN (
'red', 'pink', 'purple', 'deep-purple', 'indigo', 'blue', 'light-blue',
'cyan', 'teal', 'green', 'light-green', 'lime', 'yellow', 'amber',
'orange', 'deep-orange', 'brown', 'gray', 'blue-gray'
)) DEFAULT 'red';
UPDATE article_revisions SET theme=theme_from_str_hash(title);

View file

@ -1,75 +0,0 @@
[![Build Status](https://travis-ci.org/maghoff/sausagewiki.svg?branch=master)](https://travis-ci.org/maghoff/sausagewiki)
Sausagewiki is a simple, self-contained wiki engine.
Copyright (C) 2017 Magnus Hovland Hoff <maghoff@gmail.com>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Features
========
Some features of Sausagewiki, in no particular order:
* Simple to [install and run](#install-and-run), no runtime dependencies
* Reasonable to [back up](https://github.com/maghoff/sausagewiki/wiki/Backup),
there is only one data file
* Can be reverse proxied behind any path without configuration
* Snappy, light resource usage
* Markdown syntax
* Plus [table-support](https://help.github.com/articles/organizing-information-with-tables/)
* Without embedded HTML
* Full text search
* Responsive design: fits different screens as well as print
* Progressive enhancement: works with or without JavaScript
* Works with [external authentication](https://github.com/maghoff/sausagewiki/wiki/Enabling-authentication)
Install and run
===============
Sausagewiki aims to be simple to get up and running. It is distributed as a
single independent executable for Linux:
1. Download the latest build of `sausagewiki.tar.xz` from <https://github.com/maghoff/sausagewiki/releases/latest>
2. Decompress: `tar Jxf sausagewiki.tar.xz`, it decompresses to the single
Linux executable `sausagewiki`
3. Run: `./sausagewiki wiki.db`
For a more permanent installation, you could [install Sausagewiki as a systemd
service](https://github.com/maghoff/sausagewiki/wiki/System-wide-installation-with-systemd).
Alternative installation methods include the following:
**Build from source** with `cargo build --release`, producing the binary as
`target/release/sausagewiki`. This requires you to have a working installation
of [rust](https://www.rust-lang.org/en-US/).
**Install with [Homebrew](https://brew.sh/)** on OS X/macOS:
`brew install --HEAD https://raw.githubusercontent.com/maghoff/sausagewiki/master/deploy/sausagewiki.rb`
(Some users are hitting [rust issue #39870](https://github.com/rust-lang/rust/issues/39870)
with this brew formula, even though it is supposed to have been fixed)
Command line arguments
----------------------
USAGE:
sausagewiki [FLAGS] [OPTIONS] <DATABASE>
FLAGS:
-h, --help Prints help information
--trust-identity Trust the value in the X-Identity header to be an authenticated username.
This only makes sense when Sausagewiki runs behind a reverse proxy which
sets this header.
-V, --version Prints version information
OPTIONS:
-a, --address <address> Sets the IP address to bind to [default: 127.0.0.1]
-p, --port <port> Sets the listening port [default: 8080]
ARGS:
<DATABASE> Sets the database file to use
Sausagewiki will create an SQLite database file with the filename given in the
`DATABASE` parameter and open an HTTP server bound to the configured address,
`<address>:<port>`.

View file

@ -1,90 +1,24 @@
#[cfg(not(feature = "dynamic-assets"))] use futures::Future;
mod static_assets { use web::{Resource, ResponseFuture};
use crate::web::{Resource, ResponseFuture};
use futures::Future;
use std::collections::HashMap;
// The CSS should be built to a single CSS file at compile time #[derive(StaticResource)]
#[derive(StaticResource)] #[filename = "assets/style.css"]
#[filename = "assets/themes.css"] #[mime = "text/css"]
#[mime = "text/css"] pub struct StyleCss;
pub struct ThemesCss;
#[derive(StaticResource)] #[derive(StaticResource)]
#[filename = "assets/style.css"] #[filename = "assets/script.js"]
#[mime = "text/css"] #[mime = "application/javascript"]
pub struct StyleCss; pub struct ScriptJs;
#[derive(StaticResource)] #[derive(StaticResource)]
#[filename = "assets/script.js"] #[filename = "assets/search.js"]
#[mime = "application/javascript"] #[mime = "application/javascript"]
pub struct ScriptJs; pub struct SearchJs;
#[derive(StaticResource)] // SIL Open Font License 1.1: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL
#[filename = "assets/search.js"] // Copyright 2015 The Amatic SC Project Authors (contact@sansoxygen.com)
#[mime = "application/javascript"] #[derive(StaticResource)]
pub struct SearchJs; #[filename = "assets/amatic-sc-v9-latin-regular.woff"]
#[mime = "application/font-woff"]
// SIL Open Font License 1.1: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL pub struct AmaticFont;
// Copyright 2015 The Amatic SC Project Authors (contact@sansoxygen.com)
// #[derive(StaticResource)]
// #[filename = "assets/amatic-sc-v9-latin-regular.woff"]
// #[mime = "application/font-woff"]
// pub struct AmaticFont;
type BoxResource = Box<dyn Resource + Sync + Send>;
type ResourceFn = Box<dyn Fn() -> BoxResource + Sync + Send>;
lazy_static! {
pub static ref ASSETS_MAP: HashMap<&'static str, ResourceFn> = hashmap!{
// The CSS should be built to a single CSS file at compile time
ThemesCss::resource_name() =>
Box::new(|| Box::new(ThemesCss) as BoxResource) as ResourceFn,
StyleCss::resource_name() =>
Box::new(|| Box::new(StyleCss) as BoxResource) as ResourceFn,
ScriptJs::resource_name() =>
Box::new(|| Box::new(ScriptJs) as BoxResource) as ResourceFn,
SearchJs::resource_name() =>
Box::new(|| Box::new(SearchJs) as BoxResource) as ResourceFn,
};
}
}
#[cfg(not(feature = "dynamic-assets"))]
pub use self::static_assets::*;
#[cfg(feature = "dynamic-assets")]
mod dynamic_assets {
pub struct ThemesCss;
impl ThemesCss {
pub fn resource_name() -> &'static str {
"themes.css"
}
}
pub struct StyleCss;
impl StyleCss {
pub fn resource_name() -> &'static str {
"style.css"
}
}
pub struct ScriptJs;
impl ScriptJs {
pub fn resource_name() -> &'static str {
"script.js"
}
}
pub struct SearchJs;
impl SearchJs {
pub fn resource_name() -> &'static str {
"search.js"
}
}
}
#[cfg(feature = "dynamic-assets")]
pub use self::dynamic_assets::*;

View file

@ -1,53 +0,0 @@
#![allow(dead_code)]
// The non-CARGO env variables used here must be listed
// in build.rs to properly trigger rebuild on change
pub const PROJECT_NAME: &str = env!("CARGO_PKG_NAME");
const SOFT_HYPHEN: &str = "\u{00AD}";
#[cfg(all(not(debug_assertions), feature = "dynamic-assets"))]
compile_error!("dynamic-assets must not be used for production");
lazy_static! {
pub static ref VERSION: String = || -> String {
let mut components = vec![];
#[cfg(debug_assertions)]
components.push("debug".into());
#[cfg(test)]
components.push("test".into());
#[cfg(feature = "dynamic-assets")]
components.push("dynamic-assets".into());
if option_env!("CONTINUOUS_INTEGRATION").is_none() {
components.push("local-build".into());
}
if let Some(branch) = option_env!("TRAVIS_BRANCH") {
components.push(format!("branch:{}", branch));
}
if let Some(commit) = option_env!("TRAVIS_COMMIT") {
components.push(format!(
"commit:{}",
commit
.as_bytes()
.chunks(4)
.map(|x| String::from_utf8(x.to_owned()).unwrap_or_else(|_| String::new()))
.collect::<Vec<_>>()
.join(SOFT_HYPHEN)
));
}
if !components.is_empty() {
format!("{} ({})", env!("CARGO_PKG_VERSION"), components.join(" "))
} else {
env!("CARGO_PKG_VERSION").to_string()
}
}();
pub static ref HTTP_SERVER: String = format!("{}/{}", PROJECT_NAME, VERSION.as_str());
}

101
src/db.rs
View file

@ -1,109 +1,32 @@
use diesel::expression::sql_literal::sql;
use diesel::prelude::*; use diesel::prelude::*;
use diesel::sql_types::*; use diesel::expression::sql_literal::sql;
use r2d2::{CustomizeConnection, Pool}; use diesel::types::*;
use r2d2::{Config, CustomizeConnection, Pool};
use r2d2_diesel::{self, ConnectionManager}; use r2d2_diesel::{self, ConnectionManager};
use crate::rendering;
use crate::theme;
embed_migrations!(); embed_migrations!();
#[derive(Debug)] #[derive(Debug)]
struct SqliteInitializer; struct SqliteInitializer;
#[allow(dead_code)]
pub mod sqlfunc {
use diesel::sql_types::Text;
sql_function!(fn markdown_to_fts(text: Text) -> Text);
sql_function!(fn theme_from_str_hash(text: Text) -> Text);
}
impl CustomizeConnection<SqliteConnection, r2d2_diesel::Error> for SqliteInitializer { impl CustomizeConnection<SqliteConnection, r2d2_diesel::Error> for SqliteInitializer {
fn on_acquire(&self, conn: &mut SqliteConnection) -> Result<(), r2d2_diesel::Error> { fn on_acquire(&self, conn: &mut SqliteConnection) -> Result<(), r2d2_diesel::Error> {
sql::<Integer>("PRAGMA foreign_keys = ON") sql::<(Integer)>("PRAGMA foreign_keys = ON")
.execute(conn) .execute(conn)
.map_err(r2d2_diesel::Error::QueryError)?; .and(Ok(()))
.map_err(|x| r2d2_diesel::Error::QueryError(x))
sqlfunc::markdown_to_fts::register_impl(conn, |text: String| {
rendering::render_markdown_for_fts(&text)
})
.map_err(r2d2_diesel::Error::QueryError)?;
sqlfunc::theme_from_str_hash::register_impl(conn, |title: String| {
theme::theme_from_str_hash(&title)
})
.map_err(r2d2_diesel::Error::QueryError)?;
Ok(())
} }
} }
pub fn create_pool<S: Into<String>>( pub fn create_pool(connection_string: String) -> Result<Pool<ConnectionManager<SqliteConnection>>, Box<::std::error::Error>> {
connection_string: S, let config = Config::builder()
) -> Result<Pool<ConnectionManager<SqliteConnection>>, Box<dyn (::std::error::Error)>> {
let manager = ConnectionManager::<SqliteConnection>::new(connection_string);
let pool = Pool::builder()
.connection_customizer(Box::new(SqliteInitializer {})) .connection_customizer(Box::new(SqliteInitializer {}))
.build(manager)?; .build();
let manager = ConnectionManager::<SqliteConnection>::new(connection_string);
let pool = Pool::new(config, manager)?;
embedded_migrations::run(&*pool.get()?)?; embedded_migrations::run(&*pool.get()?)?;
Ok(pool) Ok(pool)
} }
#[cfg(test)]
pub fn test_connection() -> SqliteConnection {
let mut conn = SqliteConnection::establish(":memory:")
.expect("SQLite should be able to create an in-memory database");
SqliteInitializer.on_acquire(&mut conn).unwrap();
embedded_migrations::run(&conn).unwrap();
conn
}
#[cfg(test)]
mod test {
use super::*;
use diesel::sql_query;
#[test]
fn markdown_to_fts() {
let conn = test_connection();
#[derive(QueryableByName, PartialEq, Eq, Debug)]
struct Row {
#[sql_type = "Text"]
text: String,
}
let res = sql_query("SELECT markdown_to_fts('[link](url)') as text")
.load::<Row>(&conn)
.unwrap();
let expected = rendering::render_markdown_for_fts("[link](url)");
assert_eq!(expected, res[0].text);
}
#[test]
fn theme_from_str_hash() {
let conn = test_connection();
#[derive(QueryableByName, PartialEq, Eq, Debug)]
struct Row {
#[sql_type = "Text"]
theme: theme::Theme,
}
let res = sql_query("SELECT theme_from_str_hash('Bartefjes') as theme")
.load::<Row>(&conn)
.unwrap();
let expected = theme::theme_from_str_hash("Bartefjes");
assert_eq!(expected, res[0].theme);
}
}

View file

@ -1,71 +0,0 @@
#![allow(clippy::into_iter_on_ref)]
#![allow(clippy::vec_init_then_push)]
#![recursion_limit = "128"]
// for diesel's infer_schema!
#[cfg(test)]
#[macro_use]
extern crate matches;
#[macro_use]
extern crate bart_derive;
#[macro_use]
extern crate codegen;
#[macro_use]
#[allow(clippy::useless_attribute)]
#[allow(deprecated)]
extern crate diesel_infer_schema;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate hyper;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate maplit;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_plain;
use std::net::{IpAddr, SocketAddr};
mod assets;
mod build_config;
mod db;
mod merge;
mod mimes;
mod models;
mod rendering;
mod resources;
mod schema;
mod site;
mod state;
mod theme;
mod web;
mod wiki_lookup;
pub fn main(
db_file: String,
bind_host: IpAddr,
bind_port: u16,
trust_identity: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let db_pool = db::create_pool(db_file)?;
let cpu_pool = futures_cpupool::CpuPool::new_num_cpus();
let state = state::State::new(db_pool, cpu_pool);
let lookup = wiki_lookup::WikiLookup::new(state, trust_identity);
let server = hyper::server::Http::new()
.bind(&SocketAddr::new(bind_host, bind_port), move || {
Ok(site::Site::new(lookup.clone(), trust_identity))
})?;
println!("Listening on http://{}", server.local_addr().unwrap());
server.run()?;
Ok(())
}

View file

@ -1,9 +0,0 @@
<p>Copyright &lt;YEAR&gt; &lt;COPYRIGHT HOLDER&gt;<br /></p>
<p>Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</p>
<p>1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</p>
<p>2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.</p>
<p>3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.</p>
<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>

View file

@ -1,682 +0,0 @@
<p>Version 3, 29 June 2007</p>
<p>Copyright &copy; 2007 Free Software Foundation, Inc.
&lt;<a href="https://fsf.org/">https://fsf.org/</a>&gt;</p><p>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.</p>
<h2><a name="preamble"></a>Preamble</h3>
<p>The GNU General Public License is a free, copyleft license for
software and other kinds of works.</p>
<p>The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.</p>
<p>When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.</p>
<p>To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.</p>
<p>For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.</p>
<p>Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.</p>
<p>For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.</p>
<p>Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.</p>
<p>Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.</p>
<p>The precise terms and conditions for copying, distribution and
modification follow.</p>
<h2><a name="terms"></a>TERMS AND CONDITIONS</h3>
<h3><a name="section0"></a>0. Definitions.</h4>
<p>&ldquo;This License&rdquo; refers to version 3 of the GNU General Public License.</p>
<p>&ldquo;Copyright&rdquo; also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.</p>
<p>&ldquo;The Program&rdquo; refers to any copyrightable work licensed under this
License. Each licensee is addressed as &ldquo;you&rdquo;. &ldquo;Licensees&rdquo; and
&ldquo;recipients&rdquo; may be individuals or organizations.</p>
<p>To &ldquo;modify&rdquo; a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a &ldquo;modified version&rdquo; of the
earlier work or a work &ldquo;based on&rdquo; the earlier work.</p>
<p>A &ldquo;covered work&rdquo; means either the unmodified Program or a work based
on the Program.</p>
<p>To &ldquo;propagate&rdquo; a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.</p>
<p>To &ldquo;convey&rdquo; a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.</p>
<p>An interactive user interface displays &ldquo;Appropriate Legal Notices&rdquo;
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.</p>
<h3><a name="section1"></a>1. Source Code.</h4>
<p>The &ldquo;source code&rdquo; for a work means the preferred form of the work
for making modifications to it. &ldquo;Object code&rdquo; means any non-source
form of a work.</p>
<p>A &ldquo;Standard Interface&rdquo; means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.</p>
<p>The &ldquo;System Libraries&rdquo; of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
&ldquo;Major Component&rdquo;, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.</p>
<p>The &ldquo;Corresponding Source&rdquo; for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.</p>
<p>The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.</p>
<p>The Corresponding Source for a work in source code form is that
same work.</p>
<h3><a name="section2"></a>2. Basic Permissions.</h4>
<p>All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.</p>
<p>You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.</p>
<p>Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.</p>
<h3><a name="section3"></a>3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
<p>No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.</p>
<p>When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.</p>
<h3><a name="section4"></a>4. Conveying Verbatim Copies.</h4>
<p>You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.</p>
<p>You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.</p>
<h3><a name="section5"></a>5. Conveying Modified Source Versions.</h4>
<p>You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:</p>
<ul>
<li>a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.</li>
<li>b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
&ldquo;keep intact all notices&rdquo;.</li>
<li>c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.</li>
<li>d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.</li>
</ul>
<p>A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
&ldquo;aggregate&rdquo; if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.</p>
<h3><a name="section6"></a>6. Conveying Non-Source Forms.</h4>
<p>You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:</p>
<ul>
<li>a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.</li>
<li>b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.</li>
<li>c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.</li>
<li>d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.</li>
<li>e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.</li>
</ul>
<p>A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.</p>
<p>A &ldquo;User Product&rdquo; is either (1) a &ldquo;consumer product&rdquo;, which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, &ldquo;normally used&rdquo; refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.</p>
<p>&ldquo;Installation Information&rdquo; for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.</p>
<p>If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).</p>
<p>The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.</p>
<p>Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.</p>
<h3><a name="section7"></a>7. Additional Terms.</h4>
<p>&ldquo;Additional permissions&rdquo; are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.</p>
<p>When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.</p>
<p>Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:</p>
<ul>
<li>a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or</li>
<li>b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or</li>
<li>c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or</li>
<li>d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or</li>
<li>e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or</li>
<li>f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.</li>
</ul>
<p>All other non-permissive additional terms are considered &ldquo;further
restrictions&rdquo; within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.</p>
<p>If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.</p>
<p>Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.</p>
<h3><a name="section8"></a>8. Termination.</h4>
<p>You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).</p>
<p>However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.</p>
<p>Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.</p>
<p>Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.</p>
<h3><a name="section9"></a>9. Acceptance Not Required for Having Copies.</h4>
<p>You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.</p>
<h3><a name="section10"></a>10. Automatic Licensing of Downstream Recipients.</h4>
<p>Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.</p>
<p>An &ldquo;entity transaction&rdquo; is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.</p>
<p>You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.</p>
<h3><a name="section11"></a>11. Patents.</h4>
<p>A &ldquo;contributor&rdquo; is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's &ldquo;contributor version&rdquo;.</p>
<p>A contributor's &ldquo;essential patent claims&rdquo; are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, &ldquo;control&rdquo; includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.</p>
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.</p>
<p>In the following three paragraphs, a &ldquo;patent license&rdquo; is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To &ldquo;grant&rdquo; such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.</p>
<p>If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. &ldquo;Knowingly relying&rdquo; means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.</p>
<p>If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.</p>
<p>A patent license is &ldquo;discriminatory&rdquo; if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.</p>
<p>Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.</p>
<h3><a name="section12"></a>12. No Surrender of Others' Freedom.</h4>
<p>If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.</p>
<h3><a name="section13"></a>13. Use with the GNU Affero General Public License.</h4>
<p>Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.</p>
<h3><a name="section14"></a>14. Revised Versions of this License.</h4>
<p>The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.</p>
<p>Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License &ldquo;or any later version&rdquo; applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.</p>
<p>If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.</p>
<p>Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.</p>
<h3><a name="section15"></a>15. Disclaimer of Warranty.</h4>
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
<h3><a name="section16"></a>16. Limitation of Liability.</h4>
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.</p>
<h3><a name="section17"></a>17. Interpretation of Sections 15 and 16.</h4>
<p>If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.</p>
<p>END OF TERMS AND CONDITIONS</p>
<h2><a name="howto"></a>How to Apply These Terms to Your New Programs</h3>
<p>If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.</p>
<p>To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the &ldquo;copyright&rdquo; line and a pointer to where the full notice is found.</p>
<pre> &lt;one line to give the program's name and a brief idea of what it does.&gt;
Copyright (C) &lt;year&gt; &lt;name of author&gt;
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.
</pre>
<p>Also add information on how to contact you by electronic and paper mail.</p>
<p>If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:</p>
<pre> &lt;program&gt; Copyright (C) &lt;year&gt; &lt;name of author&gt;
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
</pre>
<p>The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an &ldquo;about box&rdquo;.</p>
<p>You should also get your employer (if you work as a programmer) or school,
if any, to sign a &ldquo;copyright disclaimer&rdquo; for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
&lt;<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>&gt;.</p>
<p>The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
&lt;<a href="https://www.gnu.org/licenses/why-not-lgpl.html">https://www.gnu.org/licenses/why-not-lgpl.html</a>&gt;.</p>

File diff suppressed because one or more lines are too long

View file

@ -1,19 +0,0 @@
<p>Copyright &lt;YEAR&gt; &lt;COPYRIGHT HOLDER&gt;</p>
<p>Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:</p>
<p>The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.</p>
<p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.</p>

View file

@ -1,126 +0,0 @@
<h2 id="definitions">1. Definitions</h2>
<dl>
<dt>1.1. “Contributor”</dt>
<dd><p>means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.</p>
</dd>
<dt>1.2. “Contributor Version”</dt>
<dd><p>means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributors Contribution.</p>
</dd>
<dt>1.3. “Contribution”</dt>
<dd><p>means Covered Software of a particular Contributor.</p>
</dd>
<dt>1.4. “Covered Software”</dt>
<dd><p>means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.</p>
</dd>
<dt>1.5. “Incompatible With Secondary Licenses”</dt>
<dd><p>means</p>
<ol type="a">
<li><p>that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or</p></li>
<li><p>that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.</p></li>
</ol>
</dd>
<dt>1.6. “Executable Form”</dt>
<dd><p>means any form of the work other than Source Code Form.</p>
</dd>
<dt>1.7. “Larger Work”</dt>
<dd><p>means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.</p>
</dd>
<dt>1.8. “License”</dt>
<dd><p>means this document.</p>
</dd>
<dt>1.9. “Licensable”</dt>
<dd><p>means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.</p>
</dd>
<dt>1.10. “Modifications”</dt>
<dd><p>means any of the following:</p>
<ol type="a">
<li><p>any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or</p></li>
<li><p>any new file in Source Code Form that contains any Covered Software.</p></li>
</ol>
</dd>
<dt>1.11. “Patent Claims” of a Contributor</dt>
<dd><p>means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.</p>
</dd>
<dt>1.12. “Secondary License”</dt>
<dd><p>means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.</p>
</dd>
<dt>1.13. “Source Code Form”</dt>
<dd><p>means the form of the work preferred for making modifications.</p>
</dd>
<dt>1.14. “You” (or “Your”)</dt>
<dd><p>means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.</p>
</dd>
</dl>
<h2 id="license-grants-and-conditions">2. License Grants and Conditions</h2>
<h3 id="grants">2.1. Grants</h3>
<p>Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:</p>
<ol type="a">
<li><p>under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and</p></li>
<li><p>under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.</p></li>
</ol>
<h3 id="effective-date">2.2. Effective Date</h3>
<p>The licenses granted in Section&nbsp;2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution.</p>
<h3 id="limitations-on-grant-scope">2.3. Limitations on Grant Scope</h3>
<p>The licenses granted in this Section&nbsp;2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section&nbsp;2.1(b) above, no patent license is granted by a Contributor:</p>
<ol type="a">
<li><p>for any code that a Contributor has removed from Covered Software; or</p></li>
<li><p>for infringements caused by: (i) Your and any other third partys modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or</p></li>
<li><p>under Patent Claims infringed by Covered Software in the absence of its Contributions.</p></li>
</ol>
<p>This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section&nbsp;3.4).</p>
<h3 id="subsequent-licenses">2.4. Subsequent Licenses</h3>
<p>No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section&nbsp;10.2) or under the terms of a Secondary License (if permitted under the terms of Section&nbsp;3.3).</p>
<h3 id="representation">2.5. Representation</h3>
<p>Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License.</p>
<h3 id="fair-use">2.6. Fair Use</h3>
<p>This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents.</p>
<h3 id="conditions">2.7. Conditions</h3>
<p>Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section&nbsp;2.1.</p>
<h2 id="responsibilities">3. Responsibilities</h2>
<h3 id="distribution-of-source-form">3.1. Distribution of Source Form</h3>
<p>All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients rights in the Source Code Form.</p>
<h3 id="distribution-of-executable-form">3.2. Distribution of Executable Form</h3>
<p>If You distribute Covered Software in Executable Form then:</p>
<ol type="a">
<li><p>such Covered Software must also be made available in Source Code Form, as described in Section&nbsp;3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and</p></li>
<li><p>You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients rights in the Source Code Form under this License.</p></li>
</ol>
<h3 id="distribution-of-a-larger-work">3.3. Distribution of a Larger Work</h3>
<p>You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).</p>
<h3 id="notices">3.4. Notices</h3>
<p>You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies.</p>
<h3 id="application-of-additional-terms">3.5. Application of Additional Terms</h3>
<p>You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.</p>
<h2 id="inability-to-comply-due-to-statute-or-regulation">4. Inability to Comply Due to Statute or Regulation</h2>
<p>If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.</p>
<h2 id="termination">5. Termination</h2>
<p>5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.</p>
<p>5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section&nbsp;2.1 of this License shall terminate.</p>
<p>5.3. In the event of termination under Sections&nbsp;5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.</p>
<h2 id="disclaimer-of-warranty">6. Disclaimer of Warranty</h2>
<p><em>Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.</em></p>
<h2 id="limitation-of-liability">7. Limitation of Liability</h2>
<p><em>Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such partys negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.</em></p>
<h2 id="litigation">8. Litigation</h2>
<p>Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a partys ability to bring cross-claims or counter-claims.</p>
<h2 id="miscellaneous">9. Miscellaneous</h2>
<p>This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.</p>
<h2 id="versions-of-the-license">10. Versions of the License</h2>
<h3 id="new-versions">10.1. New Versions</h3>
<p>Mozilla Foundation is the license steward. Except as provided in Section&nbsp;10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.</p>
<h3 id="effect-of-new-versions">10.2. Effect of New Versions</h3>
<p>You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.</p>
<h3 id="modified-versions">10.3. Modified Versions</h3>
<p>If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License).</p>
<h3 id="distributing-source-code-form-that-is-incompatible-with-secondary-licenses">10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses</h3>
<p>If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.</p>
<h2 id="exhibit-a---source-code-form-license-notice">Exhibit A - Source Code Form License Notice</h2>
<blockquote>
<p>This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.</p>
</blockquote>
<p>If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.</p>
<p>You may add additional accurate notices of copyright ownership.</p>
<h2 id="exhibit-b---incompatible-with-secondary-licenses-notice">Exhibit B - “Incompatible With Secondary Licenses” Notice</h2>
<blockquote>
<p>This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0.</p>
</blockquote>

View file

@ -1,49 +0,0 @@
[
{
"package_name": "Amatic SC",
"conclusion": {
"Ok": {
"chosen_license": "Ofl11",
"copyright_notice": "Copyright 2015 The Amatic SC Project Authors (contact@sansoxygen.com)"
}
}
},
{
"package_name": "magenta-sys",
"version": "0.1.1",
"conclusion": {
"Ok": {
"chosen_license": "Bsd3Clause",
"copyright_notice": "Copyright 2016 The Fuchsia Authors. All rights reserved."
}
}
},
{
"package_name": "diesel_codegen",
"version": "0.16.0",
"conclusion": {
"Ok": {
"chosen_license": "Mit",
"copyright_notice": "Copyright (c) 2015-2017 Sean Griffin",
"full_spdx_license": "MIT OR Apache-2.0",
"full_license_document": "The MIT License (MIT)\n\nCopyright (c) 2015-2017 Sean Griffin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n",
"license_source": {
"GitHubRepo": {
"url": "https://raw.githubusercontent.com/diesel-rs/diesel/master/LICENSE-MIT"
}
},
"link": "http://diesel.rs"
}
}
},
{
"package_name": "musl",
"conclusion": {
"Ok": {
"chosen_license": "Mit",
"copyright_notice": "Copyright © 2005-2014 Rich Felker, et al.",
"link": "https://www.musl-libc.org/"
}
}
}
]

View file

@ -1,78 +0,0 @@
<p>Version 1.1 - 26 February 2007</p>
<h2> PREAMBLE</h2>
<p>The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.</p>
<p>The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.</p>
<h2> DEFINITIONS</h2>
<p>"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.</p>
<p>"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).</p>
<p>"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).</p>
<p>"Modified Version" refers to any derivative made by adding to, deleting,
or substituting &mdash; in part or in whole &mdash; any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.</p>
<p>"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.</p>
<h2>PERMISSION &amp; CONDITIONS</h2>
<p>Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:</p>
<p>1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.</p>
<p>2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.</p>
<p>3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.</p>
<p>4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.</p>
<p>5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.</p>
<h2>TERMINATION</h2>
<p>This license becomes null and void if any of the above conditions are
not met.</p>
<h2>DISCLAIMER</h2>
<p>THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.</p>

View file

@ -1,77 +1,103 @@
#[macro_use] #![recursion_limit="128"] // for diesel's infer_schema!
extern crate lazy_static;
use std::net::IpAddr; #[macro_use] extern crate bart_derive;
#[macro_use] extern crate diesel;
#[macro_use] extern crate diesel_codegen;
#[macro_use] extern crate hyper;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate static_resource_derive;
mod build_config; extern crate chrono;
use crate::build_config::*; extern crate clap;
extern crate futures;
extern crate futures_cpupool;
extern crate percent_encoding;
extern crate pulldown_cmark;
extern crate r2d2;
extern crate r2d2_diesel;
extern crate serde;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate slug;
extern crate titlecase;
const DATABASE: &str = "DATABASE"; use std::net::SocketAddr;
const TRUST_IDENTITY: &str = "trust-identity";
const ADDRESS: &str = "address"; mod assets;
const PORT: &str = "port"; mod db;
mod mimes;
mod models;
mod rendering;
mod resources;
mod schema;
mod site;
mod state;
mod web;
mod wiki_lookup;
fn args<'a>() -> clap::ArgMatches<'a> { fn args<'a>() -> clap::ArgMatches<'a> {
use clap::{App, Arg}; use clap::{App, Arg};
App::new(PROJECT_NAME) App::new("sausagewiki")
.version(VERSION.as_str()) .about("A wiki engine")
.about(env!("CARGO_PKG_DESCRIPTION")) .arg(Arg::with_name("DATABASE")
.arg(
Arg::with_name(DATABASE)
.help("Sets the database file to use") .help("Sets the database file to use")
.required(true), .required(true))
) .arg(Arg::with_name("port")
.arg(
Arg::with_name(PORT)
.help("Sets the listening port") .help("Sets the listening port")
.short("p") .short("p")
.long(PORT) .long("port")
.default_value("8080")
.validator(|x| match x.parse::<u16>() { .validator(|x| match x.parse::<u16>() {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err("Must be an integer in the range [0, 65535]".into()), Err(_) => Err("Must be an integer in the range [0, 65535]".to_owned())
}) })
.takes_value(true), .takes_value(true))
) .arg(Arg::with_name("trust_identity")
.arg( .help("Trust the value in the X-Identity header to be an \
Arg::with_name(ADDRESS)
.help("Sets the IP address to bind to")
.short("a")
.long(ADDRESS)
.default_value("127.0.0.1")
.validator(|x| match x.parse::<IpAddr>() {
Ok(_) => Ok(()),
Err(_) => Err("Must be a valid IP address".into()),
})
.takes_value(true),
)
.arg(
Arg::with_name(TRUST_IDENTITY)
.help(
"Trust the value in the X-Identity header to be an \
authenticated username. This only makes sense when Sausagewiki \ authenticated username. This only makes sense when Sausagewiki \
runs behind a reverse proxy which sets this header.", runs behind a reverse proxy which sets this header.")
) .long("trust_identity"))
.long(TRUST_IDENTITY),
)
.get_matches() .get_matches()
} }
fn main() -> Result<(), Box<dyn std::error::Error>> { fn core_main() -> Result<(), Box<std::error::Error>> {
let args = args(); let args = args();
const CLAP: &str = "Guaranteed by clap"; let db_file = args.value_of("DATABASE").expect("Guaranteed by clap").to_owned();
const VALIDATOR: &str = "Guaranteed by clap validator"; let bind_host = "127.0.0.1".parse().unwrap();
let db_file = args.value_of(DATABASE).expect(CLAP).to_owned(); let bind_port = args.value_of("port")
let bind_host = args .map(|p| p.parse().expect("Guaranteed by validator"))
.value_of(ADDRESS) .unwrap_or(8080);
.expect(CLAP)
.parse()
.expect(VALIDATOR);
let bind_port = args.value_of(PORT).expect(CLAP).parse().expect(VALIDATOR);
let trust_identity = args.is_present(TRUST_IDENTITY); let trust_identity = args.is_present("trust_identity");
sausagewiki::main(db_file, bind_host, bind_port, trust_identity) let db_pool = db::create_pool(db_file)?;
let cpu_pool = futures_cpupool::CpuPool::new_num_cpus();
let state = state::State::new(db_pool, cpu_pool);
let lookup = wiki_lookup::WikiLookup::new(state);
let server =
hyper::server::Http::new()
.bind(
&SocketAddr::new(bind_host, bind_port),
move || Ok(site::Site::new(lookup.clone(), trust_identity))
)?;
println!("Listening on http://{}", server.local_addr().unwrap());
server.run()?;
Ok(())
}
fn main() {
match core_main() {
Ok(()) => (),
Err(err) => {
eprintln!("{:#?}", err);
std::process::exit(1)
}
}
} }

View file

@ -1,7 +0,0 @@
use std::fmt::Debug;
#[derive(Debug, PartialEq)]
pub struct Chunk<'a, Item: 'a + Debug + PartialEq + Copy>(
pub &'a [diff::Result<Item>],
pub &'a [diff::Result<Item>],
);

View file

@ -1,174 +0,0 @@
use std::fmt::Debug;
use diff::Result::*;
use super::chunk::Chunk;
pub struct ChunkIterator<'a, Item>
where
Item: 'a + Debug + PartialEq,
{
left: &'a [diff::Result<Item>],
right: &'a [diff::Result<Item>],
}
impl<'a, Item> ChunkIterator<'a, Item>
where
Item: 'a + Debug + PartialEq + Eq,
{
pub fn new(
left: &'a [diff::Result<Item>],
right: &'a [diff::Result<Item>],
) -> ChunkIterator<'a, Item> {
ChunkIterator { left, right }
}
}
impl<'a, Item> Iterator for ChunkIterator<'a, Item>
where
Item: 'a + Debug + PartialEq + Copy,
{
type Item = Chunk<'a, Item>;
fn next(&mut self) -> Option<Self::Item> {
let mut i = 0;
while let (Some(&Both(..)), Some(&Both(..))) = (self.left.get(i), self.right.get(i)) {
i += 1;
}
if i > 0 {
let chunk = Chunk(&self.left[..i], &self.right[..i]);
self.left = &self.left[i..];
self.right = &self.right[i..];
return Some(chunk);
}
let mut li = 0;
let mut ri = 0;
loop {
match (self.left.get(li), self.right.get(ri)) {
(Some(&Right(_)), _) => {
li += 1;
}
(_, Some(&Right(_))) => {
ri += 1;
}
(Some(&Left(_)), Some(_)) => {
li += 1;
ri += 1;
}
(Some(_), Some(&Left(_))) => {
li += 1;
ri += 1;
}
(Some(&Both(..)), Some(&Both(..))) => {
let chunk = Chunk(&self.left[..li], &self.right[..ri]);
self.left = &self.left[li..];
self.right = &self.right[ri..];
return Some(chunk);
}
_ => {
if !self.left.is_empty() || !self.right.is_empty() {
let chunk = Chunk(self.left, self.right);
self.left = &self.left[self.left.len()..];
self.right = &self.right[self.right.len()..];
return Some(chunk);
}
return None;
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn simple_case() {
let o = "aaabbbccc";
let a = "aaaxxxbbbccc";
let b = "aaabbbyyyccc";
let oa = diff::chars(o, a);
let ob = diff::chars(o, b);
let chunks = ChunkIterator::new(&oa, &ob).collect::<Vec<_>>();
assert_eq!(
vec![
Chunk(&oa[0..3], &ob[0..3]),
Chunk(&oa[3..6], &ob[3..3]),
Chunk(&oa[6..9], &ob[3..6]),
Chunk(&oa[9..9], &ob[6..9]),
Chunk(&oa[9..12], &ob[9..12]),
],
chunks
);
}
#[test]
fn real_conflict() {
let o = "aaabbbccc";
let a = "aaaxxxccc";
let b = "aaayyyccc";
let oa = diff::chars(o, a);
let ob = diff::chars(o, b);
let chunks = ChunkIterator::new(&oa, &ob).collect::<Vec<_>>();
assert_eq!(
vec![
Chunk(&oa[0..3], &ob[0..3]),
Chunk(&oa[3..9], &ob[3..9]),
Chunk(&oa[9..12], &ob[9..12]),
],
chunks
);
}
#[test]
fn additional_at_end() {
let o = "aaabbbccc";
let a = "aaabbbccc";
let b = "aaabbbcccddd";
let oa = diff::chars(o, a);
let ob = diff::chars(o, b);
let chunks = ChunkIterator::new(&oa, &ob).collect::<Vec<_>>();
assert_eq!(
vec![Chunk(&oa[0..9], &ob[0..9]), Chunk(&oa[9..9], &ob[9..12]),],
chunks
);
}
#[test]
fn additional_at_end_2() {
let o = "aaabbb";
let a = "aaabbbccc";
let b = "aaabbbcccddd";
let oa = diff::chars(o, a);
let ob = diff::chars(o, b);
let chunks = ChunkIterator::new(&oa, &ob).collect::<Vec<_>>();
assert_eq!(
vec![Chunk(&oa[0..6], &ob[0..6]), Chunk(&oa[6..9], &ob[6..12]),],
chunks
);
}
#[test]
fn completely_unrelated() {
let o = "aaa";
let a = "bbb";
let b = "ccc";
let oa = diff::chars(o, a);
let ob = diff::chars(o, b);
let chunks = ChunkIterator::new(&oa, &ob).collect::<Vec<_>>();
assert_eq!(vec![Chunk(&oa[0..6], &ob[0..6]),], chunks);
}
}

View file

@ -1,280 +0,0 @@
mod chunk;
mod chunk_iterator;
mod output;
use std::fmt::Debug;
use self::chunk_iterator::ChunkIterator;
use self::output::Output::Resolved;
use self::output::*;
pub use self::output::Output;
#[derive(Debug, PartialEq)]
pub enum MergeResult<Item: Debug + PartialEq> {
Clean(String),
Conflicted(Vec<Output<Item>>),
}
impl<'a> MergeResult<&'a str> {
pub fn into_strings(self) -> MergeResult<String> {
match self {
MergeResult::Clean(x) => MergeResult::Clean(x),
MergeResult::Conflicted(x) => {
MergeResult::Conflicted(x.into_iter().map(Output::into_strings).collect())
}
}
}
}
impl MergeResult<String> {
pub fn flatten(self) -> String {
match self {
MergeResult::Clean(x) => x,
MergeResult::Conflicted(x) => x
.into_iter()
.flat_map(|out| match out {
Output::Conflict(a, _o, b) => {
let mut x: Vec<String> = vec![];
x.push("<<<<<<< Your changes:\n".into());
x.extend(a.into_iter().map(|x| format!("{}\n", x)));
x.push("======= Their changes:\n".into());
x.extend(b.into_iter().map(|x| format!("{}\n", x)));
x.push(">>>>>>> Conflict ends here\n".into());
x
}
Output::Resolved(x) => x.into_iter().map(|x| format!("{}\n", x)).collect(),
})
.collect(),
}
}
}
impl MergeResult<char> {
pub fn flatten(self) -> String {
match self {
MergeResult::Clean(x) => x,
MergeResult::Conflicted(x) => x
.into_iter()
.flat_map(|out| match out {
Output::Conflict(a, _o, b) => {
let mut x: Vec<char> = vec![];
x.push('<');
x.extend(a);
x.push('|');
x.extend(b);
x.push('>');
x
}
Output::Resolved(x) => x,
})
.collect(),
}
}
}
pub fn merge_lines<'a>(a: &'a str, o: &'a str, b: &'a str) -> MergeResult<&'a str> {
let oa = diff::lines(o, a);
let ob = diff::lines(o, b);
let chunks = ChunkIterator::new(&oa, &ob);
let hunks: Vec<_> = chunks.map(resolve).collect();
let clean = hunks.iter().all(|x| matches!(x, Resolved(..)));
if clean {
MergeResult::Clean(
hunks
.into_iter()
.flat_map(|x| match x {
Resolved(y) => y.into_iter(),
_ => unreachable!(),
})
.collect::<Vec<_>>()
.join("\n"),
)
} else {
MergeResult::Conflicted(hunks)
}
}
pub fn merge_chars<'a>(a: &'a str, o: &'a str, b: &'a str) -> MergeResult<char> {
let oa = diff::chars(o, a);
let ob = diff::chars(o, b);
let chunks = ChunkIterator::new(&oa, &ob);
let hunks: Vec<_> = chunks.map(resolve).collect();
let clean = hunks.iter().all(|x| matches!(x, Resolved(..)));
if clean {
MergeResult::Clean(
hunks
.into_iter()
.flat_map(|x| match x {
Resolved(y) => y.into_iter(),
_ => unreachable!(),
})
.collect(),
)
} else {
MergeResult::Conflicted(hunks)
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
use super::output::Output::*;
use super::output::*;
use super::*;
#[test]
fn simple_case() {
fn merge_chars(a: &str, o: &str, b: &str) -> Vec<Output<char>> {
let oa = diff::chars(o, a);
let ob = diff::chars(o, b);
let chunks = super::chunk_iterator::ChunkIterator::new(&oa, &ob);
chunks.map(resolve).collect()
}
assert_eq!(
vec![
Resolved("aaa".chars().collect()),
Resolved("xxx".chars().collect()),
Resolved("bbb".chars().collect()),
Resolved("yyy".chars().collect()),
Resolved("ccc".chars().collect()),
],
merge_chars("aaaxxxbbbccc", "aaabbbccc", "aaabbbyyyccc",)
);
}
#[test]
fn clean_case() {
assert_eq!(
MergeResult::Clean(
indoc!(
"
aaa
xxx
bbb
yyy
ccc
"
)
.into()
),
merge_lines(
indoc!(
"
aaa
xxx
bbb
ccc
"
),
indoc!(
"
aaa
bbb
ccc
"
),
indoc!(
"
aaa
bbb
yyy
ccc
"
),
)
);
}
#[test]
fn clean_case_chars() {
assert_eq!(
MergeResult::Clean("Title".into()),
merge_chars("Titlle", "titlle", "title",)
);
}
#[test]
fn false_conflict() {
assert_eq!(
MergeResult::Clean(
indoc!(
"
aaa
xxx
ccc
"
)
.into()
),
merge_lines(
indoc!(
"
aaa
xxx
ccc
"
),
indoc!(
"
aaa
bbb
ccc
"
),
indoc!(
"
aaa
xxx
ccc
"
),
)
);
}
#[test]
fn true_conflict() {
assert_eq!(
MergeResult::Conflicted(vec![
Resolved(vec!["aaa"]),
Conflict(vec!["xxx"], vec![], vec!["yyy"]),
Resolved(vec!["bbb", "ccc", ""]),
]),
merge_lines(
indoc!(
"
aaa
xxx
bbb
ccc
"
),
indoc!(
"
aaa
bbb
ccc
"
),
indoc!(
"
aaa
yyy
bbb
ccc
"
),
)
);
}
}

View file

@ -1,113 +0,0 @@
use std::fmt::Debug;
use diff::Result::*;
use super::chunk::Chunk;
#[derive(Debug, PartialEq)]
pub enum Output<Item: Debug + PartialEq> {
Resolved(Vec<Item>),
Conflict(Vec<Item>, Vec<Item>, Vec<Item>),
}
impl<'a> Output<&'a str> {
pub fn into_strings(self) -> Output<String> {
match self {
Output::Resolved(x) => Output::Resolved(x.into_iter().map(str::to_string).collect()),
Output::Conflict(a, o, b) => Output::Conflict(
a.into_iter().map(str::to_string).collect(),
o.into_iter().map(str::to_string).collect(),
b.into_iter().map(str::to_string).collect(),
),
}
}
}
fn choose_left<Item: Copy>(operations: &[diff::Result<Item>]) -> Vec<Item> {
operations
.iter()
.filter_map(|x| match *x {
Both(y, _) => Some(y),
Left(y) => Some(y),
Right(_) => None,
})
.collect()
}
fn choose_right<Item: Copy>(operations: &[diff::Result<Item>]) -> Vec<Item> {
operations
.iter()
.filter_map(|x| match *x {
Both(_, y) => Some(y),
Left(_) => None,
Right(y) => Some(y),
})
.collect()
}
fn no_change<Item>(operations: &[diff::Result<Item>]) -> bool {
operations.iter().all(|x| matches!(x, Both(..)))
}
pub fn resolve<'a, Item: 'a + Debug + PartialEq + Copy>(chunk: Chunk<'a, Item>) -> Output<Item> {
if chunk.0 == chunk.1 {
// Either nothing changed or both sides made the same change
return Output::Resolved(choose_right(chunk.0));
}
if no_change(chunk.0) {
return Output::Resolved(choose_right(chunk.1));
}
if no_change(chunk.1) {
return Output::Resolved(choose_right(chunk.0));
}
Output::Conflict(
choose_right(chunk.0),
choose_left(chunk.0),
choose_right(chunk.1),
)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn empty() {
assert_eq!(Output::Resolved(vec![]), resolve::<i32>(Chunk(&[], &[])));
}
#[test]
fn same() {
assert_eq!(
Output::Resolved(vec![1]),
resolve::<i32>(Chunk(&[Both(1, 1)], &[Both(1, 1)]))
);
}
#[test]
fn only_left() {
assert_eq!(
Output::Resolved(vec![2]),
resolve::<i32>(Chunk(&[Left(1), Right(2)], &[]))
);
}
#[test]
fn false_conflict() {
assert_eq!(
Output::Resolved(vec![2]),
resolve::<i32>(Chunk(&[Left(1), Right(2)], &[Left(1), Right(2)],))
);
}
#[test]
fn real_conflict() {
assert_eq!(
Output::Conflict(vec![2], vec![1], vec![3],),
resolve::<i32>(Chunk(&[Left(1), Right(2)], &[Left(1), Right(3)],))
);
}
}

View file

@ -2,6 +2,5 @@ use hyper::mime;
lazy_static! { lazy_static! {
pub static ref TEXT_HTML: mime::Mime = "text/html;charset=utf-8".parse().unwrap(); pub static ref TEXT_HTML: mime::Mime = "text/html;charset=utf-8".parse().unwrap();
pub static ref TEXT_PLAIN: mime::Mime = "text/plain;charset=utf-8".parse().unwrap();
pub static ref APPLICATION_JSON: mime::Mime = "application/json".parse().unwrap(); pub static ref APPLICATION_JSON: mime::Mime = "application/json".parse().unwrap();
} }

View file

@ -1,12 +1,4 @@
use crate::theme::Theme; use chrono;
fn slug_link(slug: &str) -> &str {
if slug.is_empty() {
"."
} else {
slug
}
}
#[derive(Debug, Queryable)] #[derive(Debug, Queryable)]
pub struct ArticleRevision { pub struct ArticleRevision {
@ -23,17 +15,9 @@ pub struct ArticleRevision {
pub latest: bool, pub latest: bool,
pub author: Option<String>, pub author: Option<String>,
pub theme: Theme,
} }
impl ArticleRevision { #[derive(Debug, Queryable)]
pub fn link(&self) -> &str {
slug_link(&self.slug)
}
}
#[derive(Debug, PartialEq, Queryable)]
pub struct ArticleRevisionStub { pub struct ArticleRevisionStub {
pub sequence_number: i32, pub sequence_number: i32,
@ -47,31 +31,11 @@ pub struct ArticleRevisionStub {
pub latest: bool, pub latest: bool,
pub author: Option<String>, pub author: Option<String>,
pub theme: Theme,
} }
impl ArticleRevisionStub { #[derive(Debug, Queryable, Serialize)]
pub fn link(&self) -> &str {
slug_link(&self.slug)
}
}
use diesel::sql_types::Text;
#[derive(Debug, QueryableByName, Serialize)]
pub struct SearchResult { pub struct SearchResult {
#[sql_type = "Text"]
pub title: String, pub title: String,
#[sql_type = "Text"]
pub snippet: String, pub snippet: String,
#[sql_type = "Text"]
pub slug: String, pub slug: String,
} }
impl SearchResult {
pub fn link(&self) -> &str {
slug_link(&self.slug)
}
}

View file

@ -1,65 +1,9 @@
use pulldown_cmark::Event::{End, Text}; use pulldown_cmark::{Parser, html, OPTION_ENABLE_TABLES, OPTION_DISABLE_HTML};
use pulldown_cmark::{html, Parser, Tag, OPTION_DISABLE_HTML, OPTION_ENABLE_TABLES};
use slug::slugify;
fn slugify_link(text: &str, title: &str) -> Option<(String, String)> {
Some((slugify(text), title.to_owned()))
}
fn parser(src: &str) -> Parser {
let opts = OPTION_ENABLE_TABLES | OPTION_DISABLE_HTML;
Parser::new_with_broken_link_callback(src, opts, Some(&slugify_link))
}
pub fn render_markdown(src: &str) -> String { pub fn render_markdown(src: &str) -> String {
let p = parser(src); let opts = OPTION_ENABLE_TABLES | OPTION_DISABLE_HTML;
let p = Parser::new_ext(src, opts);
let mut buf = String::new(); let mut buf = String::new();
html::push_html(&mut buf, p); html::push_html(&mut buf, p);
buf buf
} }
fn is_html_special(c: char) -> bool {
c == '&' || c == '<' || c == '>'
}
pub fn render_markdown_for_fts(src: &str) -> String {
let p = parser(src);
let mut buf = String::new();
for event in p {
match event {
// As far as I understand this is a basic
// sanitizing to prevent HTML from
// appearing in page.
Text(text) => buf.push_str(&text.replace(is_html_special, " ")),
// Footnote links maybe?
End(Tag::Link(uri, _title)) => {
buf.push_str(" (");
buf.push_str(&uri.replace(is_html_special, " "));
buf.push_str(") ");
}
_ => buf.push(' '),
}
}
buf
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn slug_link() {
let actual = render_markdown("[Slug link]");
let expected = "<p><a href=\"slug-link\" title=\"Slug link\">Slug link</a></p>\n";
assert_eq!(actual, expected);
}
#[test]
fn footnote_links() {
let actual = render_markdown("[Link]\n\n[Link]: target");
let expected = "<p><a href=\"target\">Link</a></p>\n";
assert_eq!(actual, expected);
}
}

View file

@ -1,98 +0,0 @@
use futures::{self, Future};
use hyper::header::ContentType;
use hyper::server::*;
use crate::build_config;
use crate::mimes::*;
use crate::site::system_page;
use crate::web::{Resource, ResponseFuture};
#[derive(Licenses)]
pub struct AboutResource;
impl AboutResource {
pub fn new() -> Self {
AboutResource
}
}
enum License {
Bsd3Clause,
Mit,
Mpl2,
Ofl11,
}
impl License {
fn link(&self) -> &'static str {
use self::License::*;
match self {
Bsd3Clause => "bsd-3-clause",
Mit => "mit",
Mpl2 => "mpl2",
Ofl11 => "sil-ofl-1.1",
}
}
fn name(&self) -> &'static str {
use self::License::*;
match self {
Bsd3Clause => "BSD-3-Clause",
Mit => "MIT",
Mpl2 => "MPL2",
Ofl11 => "OFL-1.1",
}
}
}
struct LicenseInfo {
name: &'static str,
link: Option<&'static str>,
copyright: &'static str,
license: License,
}
#[derive(BartDisplay)]
#[template = "templates/about.html"]
struct Template<'a> {
deps: &'a [LicenseInfo],
}
impl<'a> Template<'a> {
fn version(&self) -> &str {
&build_config::VERSION
}
}
impl Resource for AboutResource {
fn allow(&self) -> Vec<hyper::Method> {
use hyper::Method::*;
vec![Options, Head, Get]
}
fn head(&self) -> ResponseFuture {
Box::new(futures::finished(
Response::new()
.with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone())),
))
}
fn get(self: Box<Self>) -> ResponseFuture {
let head = self.head();
Box::new(head.and_then(move |head| {
Ok(head.with_body(
system_page(
None, // Hmm, should perhaps accept `base` as argument
"About Sausagewiki",
Template {
deps: *LICENSE_INFOS,
},
)
.to_string(),
))
}))
}
}

View file

@ -0,0 +1,51 @@
use futures::{self, Future};
use hyper;
use hyper::header::Location;
use hyper::server::*;
use web::{Resource, ResponseFuture};
pub struct ArticleRedirectResource {
slug: String,
}
impl ArticleRedirectResource {
pub fn new(slug: String) -> Self {
// Hack to let redirects to "" work:
// TODO Calculate absolute Location URLs to conform to spec
// This would also remove the need for this hack
Self {
slug: if slug == "" { ".".to_owned() } else { slug }
}
}
}
impl Resource for ArticleRedirectResource {
fn allow(&self) -> Vec<hyper::Method> {
use hyper::Method::*;
vec![Options, Head, Get, Put]
}
fn head(&self) -> ResponseFuture {
Box::new(futures::finished(Response::new()
.with_status(hyper::StatusCode::TemporaryRedirect)
.with_header(Location::new(self.slug.clone()))
))
}
fn get(self: Box<Self>) -> ResponseFuture {
Box::new(self.head()
.and_then(move |head| {
Ok(head
.with_body(format!("Moved to {}", self.slug)))
}))
}
fn put(self: Box<Self>, _body: hyper::Body, _identity: Option<String>) -> ResponseFuture {
Box::new(self.head()
.and_then(move |head| {
Ok(head
.with_body(format!("Moved to {}", self.slug)))
}))
}
}

View file

@ -1,52 +1,20 @@
use chrono::{DateTime, Local, TimeZone}; use chrono::{TimeZone, DateTime, Local};
use futures::{self, Future}; use futures::{self, Future};
use hyper;
use hyper::header::{ContentType, Location}; use hyper::header::ContentType;
use hyper::server::*; use hyper::server::*;
use serde_json;
use serde_urlencoded;
use crate::assets::ScriptJs; use assets::ScriptJs;
use crate::mimes::*; use mimes::*;
use crate::rendering::render_markdown; use rendering::render_markdown;
use crate::site::Layout; use site::Layout;
use crate::state::{RebaseConflict, State, UpdateResult}; use state::State;
use crate::theme::{self, Theme}; use web::{Resource, ResponseFuture};
use crate::web::{Resource, ResponseFuture};
use super::changes_resource::QueryParameters; use super::changes_resource::QueryParameters;
struct SelectableTheme {
theme: Theme,
selected: bool,
}
#[derive(BartDisplay)]
#[template = "templates/article.html"]
struct Template<'a> {
revision: i32,
last_updated: Option<&'a str>,
edit: bool,
cancel_url: Option<&'a str>,
title: &'a str,
raw: &'a str,
rendered: String,
themes: &'a [SelectableTheme],
}
impl<'a> Template<'a> {
fn script_js(&self) -> &'static str {
ScriptJs::resource_name()
}
}
#[derive(Deserialize)]
struct UpdateArticle {
base_revision: i32,
title: String,
body: String,
theme: Option<Theme>,
}
pub struct ArticleResource { pub struct ArticleResource {
state: State, state: State,
article_id: i32, article_id: i32,
@ -56,12 +24,7 @@ pub struct ArticleResource {
impl ArticleResource { impl ArticleResource {
pub fn new(state: State, article_id: i32, revision: i32, edit: bool) -> Self { pub fn new(state: State, article_id: i32, revision: i32, edit: bool) -> Self {
Self { Self { state, article_id, revision, edit }
state,
article_id,
revision,
edit,
}
} }
} }
@ -81,75 +44,68 @@ pub fn last_updated(article_id: i32, created: &DateTime<Local>, author: Option<&
Template { Template {
created: &created.to_rfc2822(), created: &created.to_rfc2822(),
article_history: &format!( article_history: &format!("_changes{}", QueryParameters::default().article_id(Some(article_id)).into_link()),
"_changes{}",
QueryParameters::default()
.article_id(Some(article_id))
.into_link()
),
author: author.map(|author| Author { author: author.map(|author| Author {
author, author: &author,
history: format!( history: format!("_changes{}", QueryParameters::default().author(Some(author.to_owned())).into_link()),
"_changes{}",
QueryParameters::default()
.author(Some(author.to_owned()))
.into_link()
),
}), }),
} }.to_string()
.to_string()
} }
impl Resource for ArticleResource { impl Resource for ArticleResource {
fn allow(&self) -> Vec<hyper::Method> { fn allow(&self) -> Vec<hyper::Method> {
use hyper::Method::*; use hyper::Method::*;
vec![Options, Head, Get, Put, Post] vec![Options, Head, Get, Put]
} }
fn head(&self) -> ResponseFuture { fn head(&self) -> ResponseFuture {
Box::new(futures::finished( Box::new(futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::Ok) .with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone())), .with_header(ContentType(TEXT_HTML.clone()))
)) ))
} }
fn get(self: Box<Self>) -> ResponseFuture { fn get(self: Box<Self>) -> ResponseFuture {
let data = self #[derive(BartDisplay)]
.state #[template="templates/article.html"]
.get_article_revision(self.article_id, self.revision) struct Template<'a> {
revision: i32,
last_updated: Option<&'a str>,
edit: bool,
cancel_url: Option<&'a str>,
title: &'a str,
raw: &'a str,
rendered: String,
script_js_checksum: &'a str,
}
let data = self.state.get_article_revision(self.article_id, self.revision)
.map(|x| x.expect("Data model guarantees that this exists")); .map(|x| x.expect("Data model guarantees that this exists"));
let head = self.head(); let head = self.head();
Box::new(data.join(head).and_then(move |(data, head)| { Box::new(data.join(head)
Ok(head.with_body( .and_then(move |(data, head)| {
Layout { Ok(head
.with_body(Layout {
base: None, // Hmm, should perhaps accept `base` as argument base: None, // Hmm, should perhaps accept `base` as argument
title: &data.title, title: &data.title,
theme: data.theme,
body: &Template { body: &Template {
revision: data.revision, revision: data.revision,
last_updated: Some(&last_updated( last_updated: Some(&last_updated(
data.article_id, data.article_id,
&Local.from_utc_datetime(&data.created), &Local.from_utc_datetime(&data.created),
data.author.as_deref(), data.author.as_ref().map(|x| &**x)
)), )),
edit: self.edit, edit: self.edit,
cancel_url: Some(data.link()), cancel_url: Some(&data.slug),
title: &data.title, title: &data.title,
raw: &data.body, raw: &data.body,
rendered: render_markdown(&data.body), rendered: render_markdown(&data.body),
themes: &theme::THEMES script_js_checksum: ScriptJs::checksum(),
.iter()
.map(|&x| SelectableTheme {
theme: x,
selected: x == data.theme,
})
.collect::<Vec<_>>(),
}, },
} }.to_string()))
.to_string(),
))
})) }))
} }
@ -158,8 +114,15 @@ impl Resource for ArticleResource {
use futures::Stream; use futures::Stream;
#[derive(Deserialize)]
struct UpdateArticle {
base_revision: i32,
title: String,
body: String,
}
#[derive(BartDisplay)] #[derive(BartDisplay)]
#[template = "templates/article_contents.html"] #[template="templates/article_contents.html"]
struct Template<'a> { struct Template<'a> {
title: &'a str, title: &'a str,
rendered: String, rendered: String,
@ -167,158 +130,43 @@ impl Resource for ArticleResource {
#[derive(Serialize)] #[derive(Serialize)]
struct PutResponse<'a> { struct PutResponse<'a> {
conflict: bool,
slug: &'a str, slug: &'a str,
revision: i32, revision: i32,
title: &'a str, title: &'a str,
body: &'a str,
theme: Theme,
rendered: &'a str, rendered: &'a str,
last_updated: &'a str, last_updated: &'a str,
} }
Box::new( Box::new(body
body.concat2() .concat2()
.map_err(Into::into)
.and_then(|body| {
serde_urlencoded::from_bytes(&body)
.map_err(Into::into) .map_err(Into::into)
.and_then(|body| serde_urlencoded::from_bytes(&body).map_err(Into::into))
.and_then(move |update: UpdateArticle| {
self.state.update_article(
self.article_id,
update.base_revision,
update.title,
update.body,
identity,
update.theme,
)
}) })
.and_then(|updated| match updated { .and_then(move |update: UpdateArticle| {
UpdateResult::Success(updated) => Ok(Response::new() self.state.update_article(self.article_id, update.base_revision, update.title, update.body, identity)
})
.and_then(|updated| {
futures::finished(Response::new()
.with_status(hyper::StatusCode::Ok) .with_status(hyper::StatusCode::Ok)
.with_header(ContentType(APPLICATION_JSON.clone())) .with_header(ContentType(APPLICATION_JSON.clone()))
.with_body( .with_body(serde_json::to_string(&PutResponse {
serde_json::to_string(&PutResponse {
conflict: false,
slug: &updated.slug, slug: &updated.slug,
revision: updated.revision, revision: updated.revision,
title: &updated.title, title: &updated.title,
body: &updated.body,
theme: updated.theme,
rendered: &Template { rendered: &Template {
title: &updated.title, title: &updated.title,
rendered: render_markdown(&updated.body), rendered: render_markdown(&updated.body),
} }.to_string(),
.to_string(),
last_updated: &last_updated( last_updated: &last_updated(
updated.article_id, updated.article_id,
&Local.from_utc_datetime(&updated.created), &Local.from_utc_datetime(&updated.created),
updated.author.as_deref(), updated.author.as_ref().map(|x| &**x)
), ),
}) }).expect("Should never fail"))
.expect("Should never fail"),
)),
UpdateResult::RebaseConflict(RebaseConflict {
base_article,
title,
body,
theme,
}) => {
let title = title.flatten();
let body = body.flatten();
Ok(Response::new()
.with_status(hyper::StatusCode::Ok)
.with_header(ContentType(APPLICATION_JSON.clone()))
.with_body(
serde_json::to_string(&PutResponse {
conflict: true,
slug: &base_article.slug,
revision: base_article.revision,
title: &title,
body: &body,
theme,
rendered: &Template {
title: &title,
rendered: render_markdown(&body),
}
.to_string(),
last_updated: &last_updated(
base_article.article_id,
&Local.from_utc_datetime(&base_article.created),
base_article.author.as_deref(),
),
})
.expect("Should never fail"),
))
}
}),
)
}
fn post(self: Box<Self>, body: hyper::Body, identity: Option<String>) -> ResponseFuture {
// TODO Check incoming Content-Type
use futures::Stream;
Box::new(
body.concat2()
.map_err(Into::into)
.and_then(|body| serde_urlencoded::from_bytes(&body).map_err(Into::into))
.and_then(move |update: UpdateArticle| {
self.state.update_article(
self.article_id,
update.base_revision,
update.title,
update.body,
identity,
update.theme,
) )
}) })
.and_then(|updated| match updated {
UpdateResult::Success(updated) => Ok(Response::new()
.with_status(hyper::StatusCode::SeeOther)
.with_header(ContentType(TEXT_PLAIN.clone()))
.with_header(Location::new(updated.link().to_owned()))
.with_body("See other")),
UpdateResult::RebaseConflict(RebaseConflict {
base_article,
title,
body,
theme,
}) => {
let title = title.flatten();
let body = body.flatten();
Ok(Response::new()
.with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone()))
.with_body(
Layout {
base: None,
title: &title,
theme,
body: &Template {
revision: base_article.revision,
last_updated: Some(&last_updated(
base_article.article_id,
&Local.from_utc_datetime(&base_article.created),
base_article.author.as_deref(),
)),
edit: true,
cancel_url: Some(base_article.link()),
title: &title,
raw: &body,
rendered: render_markdown(&body),
themes: &theme::THEMES
.iter()
.map(|&x| SelectableTheme {
theme: x,
selected: x == theme,
})
.collect::<Vec<_>>(),
},
}
.to_string(),
))
}
}),
) )
} }
} }

View file

@ -1,17 +1,16 @@
use chrono::{DateTime, Local, TimeZone}; use chrono::{TimeZone, DateTime, Local};
use futures::{self, Future}; use futures::{self, Future};
use hyper;
use hyper::header::ContentType; use hyper::header::ContentType;
use hyper::server::*; use hyper::server::*;
use crate::mimes::*; use mimes::*;
use crate::models; use models;
use crate::rendering::render_markdown; use rendering::render_markdown;
use crate::site::system_page; use site::Layout;
use crate::web::{Resource, ResponseFuture}; use web::{Resource, ResponseFuture};
use super::changes_resource::QueryParameters; use super::changes_resource::QueryParameters;
use super::diff_resource;
use super::pagination::Pagination; use super::pagination::Pagination;
pub struct ArticleRevisionResource { pub struct ArticleRevisionResource {
@ -24,12 +23,7 @@ impl ArticleRevisionResource {
} }
} }
pub fn timestamp_and_author( pub fn timestamp_and_author(sequence_number: i32, article_id: i32, created: &DateTime<Local>, author: Option<&str>) -> String {
sequence_number: i32,
article_id: i32,
created: &DateTime<Local>,
author: Option<&str>,
) -> String {
struct Author<'a> { struct Author<'a> {
author: &'a str, author: &'a str,
history: String, history: String,
@ -47,17 +41,15 @@ pub fn timestamp_and_author(
Template { Template {
created: &created.to_rfc2822(), created: &created.to_rfc2822(),
article_history: &format!( article_history: &format!("_changes{}",
"_changes{}",
QueryParameters::default() QueryParameters::default()
.pagination(pagination) .pagination(pagination)
.article_id(Some(article_id)) .article_id(Some(article_id))
.into_link() .into_link()
), ),
author: author.map(|author| Author { author: author.map(|author| Author {
author, author: &author,
history: format!( history: format!("_changes{}",
"_changes{}",
QueryParameters::default() QueryParameters::default()
.pagination(pagination) .pagination(pagination)
.article_id(Some(article_id)) .article_id(Some(article_id))
@ -65,8 +57,7 @@ pub fn timestamp_and_author(
.into_link() .into_link()
), ),
}), }),
} }.to_string()
.to_string()
} }
impl Resource for ArticleRevisionResource { impl Resource for ArticleRevisionResource {
@ -76,56 +67,44 @@ impl Resource for ArticleRevisionResource {
} }
fn head(&self) -> ResponseFuture { fn head(&self) -> ResponseFuture {
Box::new(futures::finished( Box::new(futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::Ok) .with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone())), .with_header(ContentType(TEXT_HTML.clone()))
)) ))
} }
fn get(self: Box<Self>) -> ResponseFuture { fn get(self: Box<Self>) -> ResponseFuture {
#[derive(BartDisplay)] #[derive(BartDisplay)]
#[template = "templates/article_revision.html"] #[template="templates/article_revision.html"]
struct Template<'a> { struct Template<'a> {
link_current: &'a str, link_current: &'a str,
timestamp_and_author: &'a str, timestamp_and_author: &'a str,
diff_link: Option<String>,
title: &'a str,
rendered: String, rendered: String,
} }
let head = self.head(); let head = self.head();
let data = self.data; let data = self.data;
Box::new(head.and_then(move |head| { Box::new(head
Ok(head.with_body( .and_then(move |head|
system_page( Ok(head
Some("../../"), // Hmm, should perhaps accept `base` as argument .with_body(Layout {
&data.title, base: Some("../../"), // Hmm, should perhaps accept `base` as argument
&Template { title: &data.title,
body: &Template {
link_current: &format!("_by_id/{}", data.article_id), link_current: &format!("_by_id/{}", data.article_id),
timestamp_and_author: &timestamp_and_author( timestamp_and_author: &timestamp_and_author(
data.sequence_number, data.sequence_number,
data.article_id, data.article_id,
&Local.from_utc_datetime(&data.created), &Local.from_utc_datetime(&data.created),
data.author.as_deref(), data.author.as_ref().map(|x| &**x)
), ),
diff_link: if data.revision > 1 { title: &data.title,
Some(format!(
"_diff/{}?{}",
data.article_id,
diff_resource::QueryParameters::new(
data.revision as u32 - 1,
data.revision as u32,
)
))
} else {
None
},
rendered: render_markdown(&data.body), rendered: render_markdown(&data.body),
}, },
) }.to_string()))
.to_string(),
)) ))
}))
} }
} }

View file

@ -1,27 +1,27 @@
use futures::future::{done, finished}; use diesel;
use futures::{self, Future}; use futures::{self, Future};
use futures::future::{done, finished};
use hyper;
use hyper::header::ContentType; use hyper::header::ContentType;
use hyper::server::*; use hyper::server::*;
use serde_urlencoded;
use crate::mimes::*; use mimes::*;
use crate::schema::article_revisions; use schema::article_revisions;
use crate::site::system_page; use site::Layout;
use crate::state::State; use state::State;
use crate::web::{Resource, ResponseFuture}; use web::{Resource, ResponseFuture};
use super::diff_resource;
use super::pagination::Pagination; use super::pagination::Pagination;
use super::TemporaryRedirectResource; use super::TemporaryRedirectResource;
const DEFAULT_LIMIT: i32 = 30; const DEFAULT_LIMIT: i32 = 30;
type BoxResource = Box<dyn Resource + Sync + Send>; type BoxResource = Box<Resource + Sync + Send>;
#[derive(Clone)] #[derive(Clone)]
pub struct ChangesLookup { pub struct ChangesLookup {
state: State, state: State,
show_authors: bool,
} }
#[derive(Serialize, Deserialize, Default)] #[derive(Serialize, Deserialize, Default)]
@ -38,16 +38,8 @@ pub struct QueryParameters {
impl QueryParameters { impl QueryParameters {
pub fn pagination(self, pagination: Pagination<i32>) -> Self { pub fn pagination(self, pagination: Pagination<i32>) -> Self {
Self { Self {
after: if let Pagination::After(x) = pagination { after: if let Pagination::After(x) = pagination { Some(x) } else { None },
Some(x) before: if let Pagination::Before(x) = pagination { Some(x) } else { None },
} else {
None
},
before: if let Pagination::Before(x) = pagination {
Some(x)
} else {
None
},
..self ..self
} }
} }
@ -62,18 +54,14 @@ impl QueryParameters {
pub fn limit(self, limit: i32) -> Self { pub fn limit(self, limit: i32) -> Self {
Self { Self {
limit: if limit != DEFAULT_LIMIT { limit: if limit != DEFAULT_LIMIT { Some(limit) } else { None },
Some(limit)
} else {
None
},
..self ..self
} }
} }
pub fn into_link(self) -> String { pub fn into_link(self) -> String {
let args = serde_urlencoded::to_string(self).expect("Serializing to String cannot fail"); let args = serde_urlencoded::to_string(self).expect("Serializing to String cannot fail");
if !args.is_empty() { if args.len() > 0 {
format!("?{}", args) format!("?{}", args)
} else { } else {
"_changes".to_owned() "_changes".to_owned()
@ -81,12 +69,14 @@ impl QueryParameters {
} }
} }
fn apply_query_config( fn apply_query_config<'a>(
mut query: article_revisions::BoxedQuery<diesel::sqlite::Sqlite>, mut query: article_revisions::BoxedQuery<'a, diesel::sqlite::Sqlite>,
article_id: Option<i32>, article_id: Option<i32>,
author: Option<String>, author: Option<String>,
limit: i32, limit: i32,
) -> article_revisions::BoxedQuery<diesel::sqlite::Sqlite> { )
-> article_revisions::BoxedQuery<'a, diesel::sqlite::Sqlite>
{
use diesel::prelude::*; use diesel::prelude::*;
if let Some(article_id) = article_id { if let Some(article_id) = article_id {
@ -101,21 +91,14 @@ fn apply_query_config(
} }
impl ChangesLookup { impl ChangesLookup {
pub fn new(state: State, show_authors: bool) -> ChangesLookup { pub fn new(state: State) -> ChangesLookup {
Self { Self { state }
state,
show_authors,
}
} }
pub fn lookup( pub fn lookup(&self, query: Option<&str>) -> Box<Future<Item=Option<BoxResource>, Error=::web::Error>> {
&self,
query: Option<&str>,
) -> Box<dyn Future<Item = Option<BoxResource>, Error = crate::web::Error>> {
use super::pagination; use super::pagination;
let state = self.state.clone(); let state = self.state.clone();
let show_authors = self.show_authors;
Box::new( Box::new(
done((|| { done((|| {
@ -125,34 +108,31 @@ impl ChangesLookup {
let limit = match params.limit { let limit = match params.limit {
None => Ok(DEFAULT_LIMIT), None => Ok(DEFAULT_LIMIT),
Some(x) if (1..=100).contains(&x) => Ok(x), Some(x) if 1 <= x && x <= 100 => Ok(x),
_ => Err("`limit` argument must be in range [1, 100]"), _ => Err("`limit` argument must be in range [1, 100]"),
}?; }?;
Ok((pagination, params.article_id, params.author, limit)) Ok((pagination, params.article_id, params.author, limit))
})()) })())
.and_then(move |(pagination, article_id, author, limit)| { .and_then(move |(pagination, article_id, author, limit)| match pagination {
match pagination {
Pagination::After(x) => { Pagination::After(x) => {
let author2 = author.clone(); let author2 = author.clone();
Box::new( Box::new(state.query_article_revision_stubs(move |query| {
state
.query_article_revision_stubs(move |query| {
use diesel::prelude::*; use diesel::prelude::*;
apply_query_config(query, article_id, author2, limit) apply_query_config(query, article_id, author2, limit)
.filter(article_revisions::sequence_number.gt(x)) .filter(article_revisions::sequence_number.gt(x))
.order(article_revisions::sequence_number.asc()) .order(article_revisions::sequence_number.asc())
}) }).and_then(move |mut data| {
.and_then(move |mut data| {
let extra_element = if data.len() > limit as usize { let extra_element = if data.len() > limit as usize {
data.pop() data.pop()
} else { } else {
None None
}; };
let args = QueryParameters { let args =
QueryParameters {
after: None, after: None,
before: None, before: None,
article_id, article_id,
@ -163,49 +143,25 @@ impl ChangesLookup {
Ok(Some(match extra_element { Ok(Some(match extra_element {
Some(x) => Box::new(TemporaryRedirectResource::new( Some(x) => Box::new(TemporaryRedirectResource::new(
args.pagination(Pagination::Before(x.sequence_number)) args
.into_link(), .pagination(Pagination::Before(x.sequence_number))
)) .into_link()
as BoxResource, )) as BoxResource,
None => Box::new(TemporaryRedirectResource::new( None => Box::new(TemporaryRedirectResource::new(
args.into_link(), args.into_link()
)) )) as BoxResource,
as BoxResource,
})) }))
}), })) as Box<Future<Item=Option<BoxResource>, Error=::web::Error>>
) },
as Box< Pagination::Before(x) => Box::new(finished(Some(Box::new(ChangesResource::new(state, Some(x), article_id, author, limit)) as BoxResource))),
dyn Future<Item = Option<BoxResource>, Error = crate::web::Error>, Pagination::None => Box::new(finished(Some(Box::new(ChangesResource::new(state, None, article_id, author, limit)) as BoxResource))),
> })
}
Pagination::Before(x) => {
Box::new(finished(Some(Box::new(ChangesResource::new(
state,
show_authors,
Some(x),
article_id,
author,
limit,
)) as BoxResource)))
}
Pagination::None => Box::new(finished(Some(Box::new(ChangesResource::new(
state,
show_authors,
None,
article_id,
author,
limit,
))
as BoxResource))),
}
}),
) )
} }
} }
pub struct ChangesResource { pub struct ChangesResource {
state: State, state: State,
show_authors: bool,
before: Option<i32>, before: Option<i32>,
article_id: Option<i32>, article_id: Option<i32>,
author: Option<String>, author: Option<String>,
@ -213,22 +169,8 @@ pub struct ChangesResource {
} }
impl ChangesResource { impl ChangesResource {
pub fn new( pub fn new(state: State, before: Option<i32>, article_id: Option<i32>, author: Option<String>, limit: i32) -> Self {
state: State, Self { state, before, article_id, author, limit }
show_authors: bool,
before: Option<i32>,
article_id: Option<i32>,
author: Option<String>,
limit: i32,
) -> Self {
Self {
state,
show_authors,
before,
article_id,
author,
limit,
}
} }
fn query_args(&self) -> QueryParameters { fn query_args(&self) -> QueryParameters {
@ -250,15 +192,14 @@ impl Resource for ChangesResource {
} }
fn head(&self) -> ResponseFuture { fn head(&self) -> ResponseFuture {
Box::new(futures::finished( Box::new(futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::Ok) .with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone())), .with_header(ContentType(TEXT_HTML.clone()))
)) ))
} }
fn get(self: Box<Self>) -> ResponseFuture { fn get(self: Box<Self>) -> ResponseFuture {
use chrono::{Local, TimeZone}; use chrono::{TimeZone, Local};
struct Row<'a> { struct Row<'a> {
resource: &'a ChangesResource, resource: &'a ChangesResource,
@ -273,14 +214,11 @@ impl Resource for ChangesResource {
title: String, title: String,
_latest: bool, _latest: bool,
diff_link: Option<String>,
} }
impl<'a> Row<'a> { impl<'a> Row<'a> {
fn author_link(&self) -> String { fn author_link(&self) -> String {
self.resource self.resource.query_args()
.query_args()
.pagination(Pagination::After(self.sequence_number)) .pagination(Pagination::After(self.sequence_number))
.author(self.author.clone()) .author(self.author.clone())
.into_link() .into_link()
@ -293,11 +231,10 @@ impl Resource for ChangesResource {
} }
#[derive(BartDisplay)] #[derive(BartDisplay)]
#[template = "templates/changes.html"] #[template="templates/changes.html"]
struct Template<'a> { struct Template<'a> {
resource: &'a ChangesResource, resource: &'a ChangesResource,
show_authors: bool,
newer: Option<NavLinks>, newer: Option<NavLinks>,
older: Option<NavLinks>, older: Option<NavLinks>,
changes: &'a [Row<'a>], changes: &'a [Row<'a>],
@ -307,7 +244,7 @@ impl Resource for ChangesResource {
fn subject_clause(&self) -> String { fn subject_clause(&self) -> String {
match self.resource.article_id { match self.resource.article_id {
Some(x) => format!(" <a href=\"_by_id/{}\">this article</a>", x), Some(x) => format!(" <a href=\"_by_id/{}\">this article</a>", x),
None => " the wiki".to_string(), None => format!(" the wiki"),
} }
} }
@ -316,25 +253,24 @@ impl Resource for ChangesResource {
} }
fn all_articles_link(&self) -> Option<String> { fn all_articles_link(&self) -> Option<String> {
self.resource self.resource.article_id.map(|_| {
.article_id self.resource.query_args()
.map(|_| self.resource.query_args().article_id(None).into_link()) .article_id(None)
.into_link()
})
} }
fn all_authors_link(&self) -> Option<String> { fn all_authors_link(&self) -> Option<String> {
self.resource self.resource.author.as_ref().map(|_| {
.author self.resource.query_args()
.as_ref() .author(None)
.map(|_| self.resource.query_args().author(None).into_link()) .into_link()
})
} }
} }
let (before, article_id, author, limit) = ( let (before, article_id, author, limit) =
self.before, (self.before.clone(), self.article_id.clone(), self.author.clone(), self.limit);
self.article_id,
self.author.clone(),
self.limit,
);
let data = self.state.query_article_revision_stubs(move |query| { let data = self.state.query_article_revision_stubs(move |query| {
use diesel::prelude::*; use diesel::prelude::*;
@ -349,7 +285,10 @@ impl Resource for ChangesResource {
let head = self.head(); let head = self.head();
Box::new(data.join(head).and_then(move |(mut data, head)| { Box::new(data.join(head)
.and_then(move |(mut data, head)| {
use std::iter::Iterator;
let extra_element = if data.len() > self.limit as usize { let extra_element = if data.len() > self.limit as usize {
data.pop() data.pop()
} else { } else {
@ -359,41 +298,29 @@ impl Resource for ChangesResource {
let (newer, older) = match self.before { let (newer, older) = match self.before {
Some(x) => ( Some(x) => (
Some(NavLinks { Some(NavLinks {
more: self more: self.query_args().pagination(Pagination::After(x-1)).into_link(),
.query_args()
.pagination(Pagination::After(x - 1))
.into_link(),
end: self.query_args().pagination(Pagination::None).into_link(), end: self.query_args().pagination(Pagination::None).into_link(),
}), }),
extra_element.map(|_| NavLinks { extra_element.map(|_| NavLinks {
more: self more: self.query_args()
.query_args()
.pagination(Pagination::Before(data.last().unwrap().sequence_number)) .pagination(Pagination::Before(data.last().unwrap().sequence_number))
.into_link(), .into_link(),
end: self end: self.query_args().pagination(Pagination::After(0)).into_link(),
.query_args() })
.pagination(Pagination::After(0))
.into_link(),
}),
), ),
None => ( None => (
None, None,
extra_element.map(|_| NavLinks { extra_element.map(|_| NavLinks {
more: self more: self.query_args()
.query_args()
.pagination(Pagination::Before(data.last().unwrap().sequence_number)) .pagination(Pagination::Before(data.last().unwrap().sequence_number))
.into_link(), .into_link(),
end: self end: self.query_args().pagination(Pagination::After(0)).into_link(),
.query_args()
.pagination(Pagination::After(0))
.into_link(),
}), }),
), ),
}; };
let changes = &data let changes = &data.into_iter().map(|x| {
.into_iter() Row {
.map(|x| Row {
resource: &self, resource: &self,
sequence_number: x.sequence_number, sequence_number: x.sequence_number,
article_id: x.article_id, article_id: x.article_id,
@ -403,35 +330,20 @@ impl Resource for ChangesResource {
_slug: x.slug, _slug: x.slug,
title: x.title, title: x.title,
_latest: x.latest, _latest: x.latest,
diff_link: if x.revision > 1 { }
Some(format!( }).collect::<Vec<_>>();
"_diff/{}?{}",
x.article_id,
diff_resource::QueryParameters::new(
x.revision as u32 - 1,
x.revision as u32,
)
))
} else {
None
},
})
.collect::<Vec<_>>();
Ok(head.with_body( Ok(head
system_page( .with_body(Layout {
None, // Hmm, should perhaps accept `base` as argument base: None, // Hmm, should perhaps accept `base` as argument
"Changes", title: "Changes",
Template { body: &Template {
resource: &self, resource: &self,
show_authors: self.show_authors,
newer, newer,
older, older,
changes, changes
}, },
) }.to_string()))
.to_string(),
))
})) }))
} }
} }

View file

@ -1,208 +0,0 @@
use std::fmt;
use futures::future::done;
use futures::{self, Future};
use hyper::header::ContentType;
use hyper::server::*;
use crate::mimes::*;
use crate::models::ArticleRevision;
use crate::site::Layout;
use crate::state::State;
use crate::theme;
use crate::web::{Resource, ResponseFuture};
use super::changes_resource;
use super::pagination::Pagination;
type BoxResource = Box<dyn Resource + Sync + Send>;
#[derive(Clone)]
pub struct DiffLookup {
state: State,
}
#[derive(Serialize, Deserialize)]
pub struct QueryParameters {
from: u32,
to: u32,
}
impl QueryParameters {
pub fn new(from: u32, to: u32) -> QueryParameters {
QueryParameters { from, to }
}
}
impl fmt::Display for QueryParameters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&serde_urlencoded::to_string(self).expect("Serializing to String cannot fail"))
}
}
impl DiffLookup {
pub fn new(state: State) -> DiffLookup {
Self { state }
}
pub fn lookup(
&self,
article_id: u32,
query: Option<&str>,
) -> Box<dyn Future<Item = Option<BoxResource>, Error = crate::web::Error>> {
let state = self.state.clone();
Box::new(
done(serde_urlencoded::from_str(query.unwrap_or("")).map_err(Into::into))
.and_then(move |params: QueryParameters| {
let from = state.get_article_revision(article_id as i32, params.from as i32);
let to = state.get_article_revision(article_id as i32, params.to as i32);
from.join(to)
})
.and_then(move |(from, to)| match (from, to) {
(Some(from), Some(to)) => {
Ok(Some(Box::new(DiffResource::new(from, to)) as BoxResource))
}
_ => Ok(None),
}),
)
}
}
pub struct DiffResource {
from: ArticleRevision,
to: ArticleRevision,
}
impl DiffResource {
pub fn new(from: ArticleRevision, to: ArticleRevision) -> Self {
assert_eq!(from.article_id, to.article_id);
Self { from, to }
}
}
impl Resource for DiffResource {
fn allow(&self) -> Vec<hyper::Method> {
use hyper::Method::*;
vec![Options, Head, Get]
}
fn head(&self) -> ResponseFuture {
Box::new(futures::finished(
Response::new()
.with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone())),
))
}
fn get(self: Box<Self>) -> ResponseFuture {
#[derive(BartDisplay)]
#[template = "templates/diff.html"]
struct Template<'a> {
consecutive: bool,
article_id: u32,
author: Option<&'a str>,
author_link: &'a str,
article_history_link: &'a str,
from_link: &'a str,
to_link: &'a str,
title: &'a [Diff<char>],
lines: &'a [Diff<&'a str>],
}
#[derive(Default)]
struct Diff<T: fmt::Display> {
removed: Option<T>,
same: Option<T>,
added: Option<T>,
}
let head = self.head();
Box::new(head.and_then(move |head| {
let consecutive = self.to.revision - self.from.revision == 1;
let author = match consecutive {
true => self.to.author.as_deref(),
false => None,
};
let author_link = &format!(
"_changes{}",
changes_resource::QueryParameters::default()
.author(author.map(|x| x.to_owned()))
.pagination(Pagination::After(self.from.sequence_number))
.into_link()
);
let article_history_link = &format!(
"_changes{}",
changes_resource::QueryParameters::default()
.article_id(Some(self.from.article_id))
.pagination(Pagination::After(self.from.sequence_number))
.into_link()
);
let title = &diff::chars(&self.from.title, &self.to.title)
.into_iter()
.map(|x| match x {
diff::Result::Left(x) => Diff {
removed: Some(x),
..Default::default()
},
diff::Result::Both(x, _) => Diff {
same: Some(x),
..Default::default()
},
diff::Result::Right(x) => Diff {
added: Some(x),
..Default::default()
},
})
.collect::<Vec<_>>();
let lines = &diff::lines(&self.from.body, &self.to.body)
.into_iter()
.map(|x| match x {
diff::Result::Left(x) => Diff {
removed: Some(x),
..Default::default()
},
diff::Result::Both(x, _) => Diff {
same: Some(x),
..Default::default()
},
diff::Result::Right(x) => Diff {
added: Some(x),
..Default::default()
},
})
.collect::<Vec<_>>();
Ok(head.with_body(
Layout {
base: Some("../"), // Hmm, should perhaps accept `base` as argument
title: "Difference",
theme: theme::theme_from_str_hash("Difference"),
body: &Template {
consecutive,
article_id: self.from.article_id as u32,
author,
author_link,
article_history_link,
from_link: &format!(
"_revisions/{}/{}",
self.from.article_id, self.from.revision
),
to_link: &format!("_revisions/{}/{}", self.to.article_id, self.to.revision),
title,
lines,
},
}
.to_string(),
))
}))
}
}

View file

@ -1,47 +0,0 @@
use futures::{self, Future};
use hyper::header::ContentType;
use hyper::server::*;
use crate::mimes::*;
use crate::site::system_page;
use crate::web::{Resource, ResponseFuture};
pub struct HtmlResource {
base: Option<&'static str>,
title: &'static str,
html_body: &'static str,
}
impl HtmlResource {
pub fn new(base: Option<&'static str>, title: &'static str, html_body: &'static str) -> Self {
HtmlResource {
base,
title,
html_body,
}
}
}
impl Resource for HtmlResource {
fn allow(&self) -> Vec<hyper::Method> {
use hyper::Method::*;
vec![Options, Head, Get]
}
fn head(&self) -> ResponseFuture {
Box::new(futures::finished(
Response::new()
.with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone())),
))
}
fn get(self: Box<Self>) -> ResponseFuture {
let head = self.head();
Box::new(head.and_then(move |head| {
Ok(head.with_body(system_page(self.base, self.title, self.html_body).to_string()))
}))
}
}

View file

@ -1,25 +1,19 @@
pub mod pagination; pub mod pagination;
mod about_resource; mod article_redirect_resource;
mod article_resource;
mod article_revision_resource; mod article_revision_resource;
mod article_resource;
mod changes_resource; mod changes_resource;
mod diff_resource;
mod html_resource;
mod new_article_resource; mod new_article_resource;
mod read_only_resource;
mod search_resource; mod search_resource;
mod sitemap_resource; mod sitemap_resource;
mod temporary_redirect_resource; mod temporary_redirect_resource;
pub use self::about_resource::AboutResource; pub use self::article_redirect_resource::ArticleRedirectResource;
pub use self::article_resource::ArticleResource;
pub use self::article_revision_resource::ArticleRevisionResource; pub use self::article_revision_resource::ArticleRevisionResource;
pub use self::article_resource::ArticleResource;
pub use self::changes_resource::{ChangesLookup, ChangesResource}; pub use self::changes_resource::{ChangesLookup, ChangesResource};
pub use self::diff_resource::{DiffLookup, DiffResource};
pub use self::html_resource::HtmlResource;
pub use self::new_article_resource::NewArticleResource; pub use self::new_article_resource::NewArticleResource;
pub use self::read_only_resource::ReadOnlyResource;
pub use self::search_resource::SearchLookup; pub use self::search_resource::SearchLookup;
pub use self::sitemap_resource::SitemapResource; pub use self::sitemap_resource::SitemapResource;
pub use self::temporary_redirect_resource::TemporaryRedirectResource; pub use self::temporary_redirect_resource::TemporaryRedirectResource;

View file

@ -1,15 +1,16 @@
use futures::{self, Future}; use futures::{self, Future};
use hyper;
use hyper::header::{ContentType, Location}; use hyper::header::ContentType;
use hyper::server::*; use hyper::server::*;
use serde_json;
use serde_urlencoded;
use crate::assets::ScriptJs; use assets::ScriptJs;
use crate::mimes::*; use mimes::*;
use crate::rendering::render_markdown; use rendering::render_markdown;
use crate::site::Layout; use site::Layout;
use crate::state::State; use state::State;
use crate::theme::{self, Theme}; use web::{Resource, ResponseFuture};
use crate::web::{Resource, ResponseFuture};
const NEW: &str = "NEW"; const NEW: &str = "NEW";
@ -26,20 +27,11 @@ fn title_from_slug(slug: &str) -> String {
pub struct NewArticleResource { pub struct NewArticleResource {
state: State, state: State,
slug: Option<String>, slug: Option<String>,
edit: bool,
}
#[derive(Deserialize)]
struct CreateArticle {
base_revision: String,
title: String,
body: String,
theme: Option<Theme>,
} }
impl NewArticleResource { impl NewArticleResource {
pub fn new(state: State, slug: Option<String>, edit: bool) -> Self { pub fn new(state: State, slug: Option<String>) -> Self {
Self { state, slug, edit } Self { state, slug }
} }
} }
@ -50,22 +42,15 @@ impl Resource for NewArticleResource {
} }
fn head(&self) -> ResponseFuture { fn head(&self) -> ResponseFuture {
Box::new(futures::finished( Box::new(futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::NotFound) .with_status(hyper::StatusCode::NotFound)
.with_header(ContentType(TEXT_HTML.clone())), .with_header(ContentType(TEXT_HTML.clone()))
)) ))
} }
fn get(self: Box<Self>) -> ResponseFuture { fn get(self: Box<Self>) -> ResponseFuture {
// TODO Remove duplication with article_resource.rs:
struct SelectableTheme {
theme: Theme,
selected: bool,
}
#[derive(BartDisplay)] #[derive(BartDisplay)]
#[template = "templates/article.html"] #[template="templates/article.html"]
struct Template<'a> { struct Template<'a> {
revision: &'a str, revision: &'a str,
last_updated: Option<&'a str>, last_updated: Option<&'a str>,
@ -75,44 +60,34 @@ impl Resource for NewArticleResource {
title: &'a str, title: &'a str,
raw: &'a str, raw: &'a str,
rendered: &'a str, rendered: &'a str,
themes: &'a [SelectableTheme],
} script_js_checksum: &'a str,
impl<'a> Template<'a> {
fn script_js(&self) -> &'static str {
ScriptJs::resource_name()
}
} }
let title = self let title = self.slug.as_ref()
.slug
.as_ref()
.map_or("".to_owned(), |x| title_from_slug(x)); .map_or("".to_owned(), |x| title_from_slug(x));
Box::new(self.head().and_then(move |head| { Box::new(self.head()
Ok(head.with_body( .and_then(move |head| {
Layout { Ok(head
.with_body(Layout {
base: None, // Hmm, should perhaps accept `base` as argument base: None, // Hmm, should perhaps accept `base` as argument
title: &title, title: &title,
theme: theme::Theme::Gray,
body: &Template { body: &Template {
revision: NEW, revision: NEW,
last_updated: None, last_updated: None,
edit: self.edit,
cancel_url: self.slug.as_deref(), // Implicitly start in edit-mode when no slug is given. This
// currently directly corresponds to the /_new endpoint
edit: self.slug.is_none(),
cancel_url: self.slug.as_ref().map(|x| &**x),
title: &title, title: &title,
raw: "", raw: "",
rendered: EMPTY_ARTICLE_MESSAGE, rendered: EMPTY_ARTICLE_MESSAGE,
themes: &theme::THEMES script_js_checksum: ScriptJs::checksum(),
.iter()
.map(|&x| SelectableTheme {
theme: x,
selected: false,
})
.collect::<Vec<_>>(),
}, },
} }.to_string()))
.to_string(),
))
})) }))
} }
@ -120,11 +95,18 @@ impl Resource for NewArticleResource {
// TODO Check incoming Content-Type // TODO Check incoming Content-Type
// TODO Refactor? Reduce duplication with ArticleResource::put? // TODO Refactor? Reduce duplication with ArticleResource::put?
use chrono::{Local, TimeZone}; use chrono::{TimeZone, Local};
use futures::Stream; use futures::Stream;
#[derive(Deserialize)]
struct CreateArticle {
base_revision: String,
title: String,
body: String,
}
#[derive(BartDisplay)] #[derive(BartDisplay)]
#[template = "templates/article_contents.html"] #[template="templates/article_contents.html"]
struct Template<'a> { struct Template<'a> {
title: &'a str, title: &'a str,
rendered: String, rendered: String,
@ -136,92 +118,44 @@ impl Resource for NewArticleResource {
article_id: i32, article_id: i32,
revision: i32, revision: i32,
title: &'a str, title: &'a str,
body: &'a str,
theme: Theme,
rendered: &'a str, rendered: &'a str,
last_updated: &'a str, last_updated: &'a str,
} }
Box::new( Box::new(body
body.concat2() .concat2()
.map_err(Into::into) .map_err(Into::into)
.and_then(|body| serde_urlencoded::from_bytes(&body).map_err(Into::into)) .and_then(|body| {
serde_urlencoded::from_bytes(&body)
.map_err(Into::into)
})
.and_then(move |arg: CreateArticle| { .and_then(move |arg: CreateArticle| {
if arg.base_revision != NEW { if arg.base_revision != NEW {
unimplemented!("Version update conflict"); unimplemented!("Version update conflict");
} }
let theme = arg.theme.unwrap_or_else(theme::random); self.state.create_article(self.slug.clone(), arg.title, arg.body, identity)
self.state.create_article(
self.slug.clone(),
arg.title,
arg.body,
identity,
theme,
)
}) })
.and_then(|updated| { .and_then(|updated| {
futures::finished( futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::Ok) .with_status(hyper::StatusCode::Ok)
.with_header(ContentType(APPLICATION_JSON.clone())) .with_header(ContentType(APPLICATION_JSON.clone()))
.with_body( .with_body(serde_json::to_string(&PutResponse {
serde_json::to_string(&PutResponse {
slug: &updated.slug, slug: &updated.slug,
article_id: updated.article_id, article_id: updated.article_id,
revision: updated.revision, revision: updated.revision,
title: &updated.title, title: &updated.title,
body: &updated.body,
theme: updated.theme,
rendered: &Template { rendered: &Template {
title: &updated.title, title: &updated.title,
rendered: render_markdown(&updated.body), rendered: render_markdown(&updated.body),
} }.to_string(),
.to_string(),
last_updated: &super::article_resource::last_updated( last_updated: &super::article_resource::last_updated(
updated.article_id, updated.article_id,
&Local.from_utc_datetime(&updated.created), &Local.from_utc_datetime(&updated.created),
updated.author.as_deref(), updated.author.as_ref().map(|x| &**x)
), ),
}) }).expect("Should never fail"))
.expect("Should never fail"),
),
)
}),
)
}
fn post(self: Box<Self>, body: hyper::Body, identity: Option<String>) -> ResponseFuture {
// TODO Check incoming Content-Type
// TODO Refactor? Reduce duplication with ArticleResource::put?
use futures::Stream;
Box::new(
body.concat2()
.map_err(Into::into)
.and_then(|body| serde_urlencoded::from_bytes(&body).map_err(Into::into))
.and_then(move |arg: CreateArticle| {
if arg.base_revision != NEW {
unimplemented!("Version update conflict");
}
let theme = arg.theme.unwrap_or_else(theme::random);
self.state.create_article(
self.slug.clone(),
arg.title,
arg.body,
identity,
theme,
) )
}) })
.and_then(|updated| {
futures::finished(
Response::new()
.with_status(hyper::StatusCode::SeeOther)
.with_header(ContentType(TEXT_PLAIN.clone()))
.with_header(Location::new(updated.link().to_owned()))
.with_body("See other"),
)
}),
) )
} }
} }

View file

@ -8,11 +8,15 @@ pub struct Error;
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "`after` and `before` are mutually exclusive") write!(f, "{}", (self as &error::Error).description())
} }
} }
impl error::Error for Error {} impl error::Error for Error {
fn description(&self) -> &str {
"`after` and `before` are mutually exclusive"
}
}
#[derive(Deserialize)] #[derive(Deserialize)]
struct PaginationStruct<T> { struct PaginationStruct<T> {
@ -33,16 +37,16 @@ impl<T> PaginationStruct<T> {
(Some(x), None) => Ok(Pagination::After(x)), (Some(x), None) => Ok(Pagination::After(x)),
(None, Some(x)) => Ok(Pagination::Before(x)), (None, Some(x)) => Ok(Pagination::Before(x)),
(None, None) => Ok(Pagination::None), (None, None) => Ok(Pagination::None),
_ => Err(Error), _ => Err(Error)
} }
} }
} }
pub fn _from_str<'a, T: serde::Deserialize<'a>>(s: &'a str) -> Result<Pagination<T>, Error> { pub fn _from_str<'a, T: serde::Deserialize<'a>>(s: &'a str) -> Result<Pagination<T>, Error> {
let pagination: PaginationStruct<T> = serde_urlencoded::from_str(s).map_err(|_| Error)?; // TODO Proper error reporting let pagination: PaginationStruct<T> = serde_urlencoded::from_str(s).map_err(|_| Error)?; // TODO Proper error reporting
pagination.into_enum() Ok(pagination.into_enum()?)
} }
pub fn from_fields<T>(after: Option<T>, before: Option<T>) -> Result<Pagination<T>, Error> { pub fn from_fields<T>(after: Option<T>, before: Option<T>) -> Result<Pagination<T>, Error> {
PaginationStruct { after, before }.into_enum() Ok(PaginationStruct { after, before }.into_enum()?)
} }

View file

@ -1,38 +0,0 @@
use futures::Future;
use hyper::header::{CacheControl, CacheDirective, ContentLength, ContentType};
use hyper::server::*;
use hyper::StatusCode;
use crate::web::{Resource, ResponseFuture};
#[allow(unused)]
pub struct ReadOnlyResource {
pub content_type: ::hyper::mime::Mime,
pub body: Vec<u8>,
}
impl Resource for ReadOnlyResource {
fn allow(&self) -> Vec<::hyper::Method> {
use ::hyper::Method::*;
vec![Options, Head, Get]
}
fn head(&self) -> ResponseFuture {
Box::new(::futures::finished(
Response::new()
.with_status(StatusCode::Ok)
.with_header(ContentType(self.content_type.clone()))
.with_header(CacheControl(vec![
CacheDirective::MustRevalidate,
CacheDirective::NoStore,
])),
))
}
fn get(self: Box<Self>) -> ResponseFuture {
Box::new(self.head().map(move |head| {
head.with_header(ContentLength(self.body.len() as u64))
.with_body(self.body.clone())
}))
}
}

View file

@ -1,18 +1,20 @@
use futures::{self, Future}; use futures::{self, Future};
use hyper;
use hyper::header::{Accept, ContentType}; use hyper::header::{Accept, ContentType};
use hyper::server::*; use hyper::server::*;
use serde_json;
use serde_urlencoded;
use crate::mimes::*; use mimes::*;
use crate::models::SearchResult; use models;
use crate::site::system_page; use site::Layout;
use crate::state::State; use state::State;
use crate::web::{Resource, ResponseFuture}; use web::{Resource, ResponseFuture};
const DEFAULT_LIMIT: u32 = 10; const DEFAULT_LIMIT: u32 = 10;
const DEFAULT_SNIPPET_SIZE: u32 = 30; const DEFAULT_SNIPPET_SIZE: u32 = 8;
type BoxResource = Box<dyn Resource + Sync + Send>; type BoxResource = Box<Resource + Sync + Send>;
#[derive(Serialize, Deserialize, Default)] #[derive(Serialize, Deserialize, Default)]
pub struct QueryParameters { pub struct QueryParameters {
@ -32,29 +34,21 @@ impl QueryParameters {
pub fn limit(self, limit: u32) -> Self { pub fn limit(self, limit: u32) -> Self {
Self { Self {
limit: if limit != DEFAULT_LIMIT { limit: if limit != DEFAULT_LIMIT { Some(limit) } else { None },
Some(limit)
} else {
None
},
..self ..self
} }
} }
pub fn snippet_size(self, snippet_size: u32) -> Self { pub fn snippet_size(self, snippet_size: u32) -> Self {
Self { Self {
snippet_size: if snippet_size != DEFAULT_SNIPPET_SIZE { snippet_size: if snippet_size != DEFAULT_SNIPPET_SIZE { Some(snippet_size) } else { None },
Some(snippet_size)
} else {
None
},
..self ..self
} }
} }
pub fn into_link(self) -> String { pub fn into_link(self) -> String {
let args = serde_urlencoded::to_string(self).expect("Serializing to String cannot fail"); let args = serde_urlencoded::to_string(self).expect("Serializing to String cannot fail");
if !args.is_empty() { if args.len() > 0 {
format!("_search?{}", args) format!("_search?{}", args)
} else { } else {
"_search".to_owned() "_search".to_owned()
@ -72,16 +66,18 @@ impl SearchLookup {
Self { state } Self { state }
} }
pub fn lookup(&self, query: Option<&str>) -> Result<Option<BoxResource>, crate::web::Error> { pub fn lookup(&self, query: Option<&str>) -> Result<Option<BoxResource>, ::web::Error> {
let args: QueryParameters = serde_urlencoded::from_str(query.unwrap_or(""))?; let args: QueryParameters = serde_urlencoded::from_str(query.unwrap_or(""))?;
Ok(Some(Box::new(SearchResource::new( Ok(Some(Box::new(
SearchResource::new(
self.state.clone(), self.state.clone(),
args.q, args.q,
args.limit.unwrap_or(DEFAULT_LIMIT), args.limit.unwrap_or(DEFAULT_LIMIT),
args.offset.unwrap_or(0), args.offset.unwrap_or(0),
args.snippet_size.unwrap_or(DEFAULT_SNIPPET_SIZE), args.snippet_size.unwrap_or(DEFAULT_SNIPPET_SIZE),
)))) )
)))
} }
} }
@ -102,21 +98,8 @@ pub enum ResponseType {
} }
impl SearchResource { impl SearchResource {
pub fn new( pub fn new(state: State, query: Option<String>, limit: u32, offset: u32, snippet_size: u32) -> Self {
state: State, Self { state, response_type: ResponseType::Html, query, limit, offset, snippet_size }
query: Option<String>,
limit: u32,
offset: u32,
snippet_size: u32,
) -> Self {
Self {
state,
response_type: ResponseType::Html,
query,
limit,
offset,
snippet_size,
}
} }
fn query_args(&self) -> QueryParameters { fn query_args(&self) -> QueryParameters {
@ -143,24 +126,21 @@ impl Resource for SearchResource {
self.response_type = match accept.first() { self.response_type = match accept.first() {
Some(&QualityItem { item: ref mime, .. }) Some(&QualityItem { item: ref mime, .. })
if mime.type_() == mime::APPLICATION && mime.subtype() == mime::JSON => if mime.type_() == mime::APPLICATION && mime.subtype() == mime::JSON
{ => ResponseType::Json,
ResponseType::Json
}
_ => ResponseType::Html, _ => ResponseType::Html,
}; };
} }
fn head(&self) -> ResponseFuture { fn head(&self) -> ResponseFuture {
let content_type = match self.response_type { let content_type = match &self.response_type {
ResponseType::Json => ContentType(APPLICATION_JSON.clone()), &ResponseType::Json => ContentType(APPLICATION_JSON.clone()),
ResponseType::Html => ContentType(TEXT_HTML.clone()), &ResponseType::Html => ContentType(TEXT_HTML.clone()),
}; };
Box::new(futures::finished( Box::new(futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::Ok) .with_status(hyper::StatusCode::Ok)
.with_header(content_type), .with_header(content_type)
)) ))
} }
@ -168,41 +148,49 @@ impl Resource for SearchResource {
#[derive(Serialize)] #[derive(Serialize)]
struct JsonResponse<'a> { struct JsonResponse<'a> {
query: &'a str, query: &'a str,
hits: &'a [SearchResult], hits: &'a [models::SearchResult],
prev: Option<String>, prev: Option<String>,
next: Option<String>, next: Option<String>,
} }
struct Hit<'a> {
index: usize,
slug: &'a str,
title: &'a str,
snippet: &'a str,
}
impl<'a> Hit<'a> {
fn link(&self) -> &'a str {
if self.slug == "" {
"."
} else {
self.slug
}
}
}
#[derive(BartDisplay)] #[derive(BartDisplay)]
#[template = "templates/search.html"] #[template="templates/search.html"]
struct Template<'a> { struct Template<'a> {
query: &'a str, query: &'a str,
hits: &'a [(usize, &'a SearchResult)], hits: &'a [Hit<'a>],
prev: Option<String>, prev: Option<String>,
next: Option<String>, next: Option<String>,
} }
// TODO: Show a search "front page" when no query is given: // TODO: Show a search "front page" when no query is given:
let query = self let query = self.query.as_ref().map(|x| x.clone()).unwrap_or("".to_owned());
.query
.as_ref()
.cloned()
.unwrap_or_else(|| "".to_owned());
let data = self.state.search_query( let data = self.state.search_query(query, (self.limit + 1) as i32, self.offset as i32, self.snippet_size as i32);
query,
(self.limit + 1) as i32,
self.offset as i32,
self.snippet_size as i32,
);
let head = self.head(); let head = self.head();
Box::new(data.join(head).and_then(move |(mut data, head)| { Box::new(data.join(head)
.and_then(move |(mut data, head)| {
let prev = if self.offset > 0 { let prev = if self.offset > 0 {
Some( Some(self.query_args()
self.query_args()
.offset(self.offset.saturating_sub(self.limit)) .offset(self.offset.saturating_sub(self.limit))
.into_link(), .into_link()
) )
} else { } else {
None None
@ -210,38 +198,42 @@ impl Resource for SearchResource {
let next = if data.len() > self.limit as usize { let next = if data.len() > self.limit as usize {
data.pop(); data.pop();
Some( Some(self.query_args()
self.query_args()
.offset(self.offset + self.limit) .offset(self.offset + self.limit)
.into_link(), .into_link()
) )
} else { } else {
None None
}; };
match self.response_type { match &self.response_type {
ResponseType::Json => Ok(head.with_body( &ResponseType::Json => Ok(head
serde_json::to_string(&JsonResponse { .with_body(serde_json::to_string(&JsonResponse {
query: self.query.as_deref().unwrap_or(""), query: self.query.as_ref().map(|x| &**x).unwrap_or(""),
hits: &data, hits: &data,
prev, prev,
next, next,
}).expect("Should never fail"))
),
&ResponseType::Html => Ok(head
.with_body(Layout {
base: None, // Hmm, should perhaps accept `base` as argument
title: "Search",
body: &Template {
query: self.query.as_ref().map(|x| &**x).unwrap_or(""),
hits: &data.iter()
.enumerate()
.map(|(i, result)| Hit {
index: i,
slug: &result.slug,
title: &result.title,
snippet: &result.snippet,
}) })
.expect("Should never fail"), .collect::<Vec<_>>(),
)),
ResponseType::Html => Ok(head.with_body(
system_page(
None, // Hmm, should perhaps accept `base` as argument
"Search",
&Template {
query: self.query.as_deref().unwrap_or(""),
hits: &data.iter().enumerate().collect::<Vec<_>>(),
prev, prev,
next, next,
}, },
) }.to_string())),
.to_string(),
)),
} }
})) }))
} }

View file

@ -1,13 +1,12 @@
use futures::{self, Future}; use futures::{self, Future};
use hyper;
use hyper::header::ContentType; use hyper::header::ContentType;
use hyper::server::*; use hyper::server::*;
use crate::mimes::*; use mimes::*;
use crate::models::ArticleRevisionStub; use site::Layout;
use crate::site::system_page; use state::State;
use crate::state::State; use web::{Resource, ResponseFuture};
use crate::web::{Resource, ResponseFuture};
pub struct SitemapResource { pub struct SitemapResource {
state: State, state: State,
@ -26,34 +25,44 @@ impl Resource for SitemapResource {
} }
fn head(&self) -> ResponseFuture { fn head(&self) -> ResponseFuture {
Box::new(futures::finished( Box::new(futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::Ok) .with_status(hyper::StatusCode::Ok)
.with_header(ContentType(TEXT_HTML.clone())), .with_header(ContentType(TEXT_HTML.clone()))
)) ))
} }
fn get(self: Box<Self>) -> ResponseFuture { fn get(self: Box<Self>) -> ResponseFuture {
#[derive(BartDisplay)] #[derive(BartDisplay)]
#[template = "templates/sitemap.html"] #[template="templates/sitemap.html"]
struct Template<'a> { struct Template<'a> {
articles: &'a [ArticleRevisionStub], articles: &'a [ArticleReference],
}
struct ArticleReference {
link: String,
title: String,
} }
let data = self.state.get_latest_article_revision_stubs(); let data = self.state.get_latest_article_revision_stubs();
let head = self.head(); let head = self.head();
Box::new(data.join(head).and_then(move |(articles, head)| { Box::new(data.join(head)
Ok(head.with_body( .and_then(move |(articles, head)| {
system_page( use std::iter::Iterator;
None, // Hmm, should perhaps accept `base` as argument
"Sitemap", let articles = &articles.into_iter().map(|x| {
Template { ArticleReference {
articles: &articles, link: if x.slug.is_empty() { ".".to_owned() } else { x.slug },
}, title: x.title,
) }
.to_string(), }).collect::<Vec<_>>();
))
Ok(head
.with_body(Layout {
base: None, // Hmm, should perhaps accept `base` as argument
title: "Sitemap",
body: &Template { articles },
}.to_string()))
})) }))
} }
} }

View file

@ -1,9 +1,9 @@
use futures::{self, Future}; use futures::{self, Future};
use hyper;
use hyper::header::Location; use hyper::header::Location;
use hyper::server::*; use hyper::server::*;
use crate::web::{Resource, ResponseFuture}; use web::{Resource, ResponseFuture};
pub struct TemporaryRedirectResource { pub struct TemporaryRedirectResource {
location: String, location: String,
@ -13,20 +13,6 @@ impl TemporaryRedirectResource {
pub fn new(location: String) -> Self { pub fn new(location: String) -> Self {
Self { location } Self { location }
} }
pub fn from_slug<S: AsRef<str>>(slug: S, edit: bool) -> Self {
let base = if slug.as_ref().is_empty() {
"."
} else {
slug.as_ref()
};
let tail = if edit { "?edit" } else { "" };
Self {
location: format!("{}{}", base, tail),
}
}
} }
impl Resource for TemporaryRedirectResource { impl Resource for TemporaryRedirectResource {
@ -36,25 +22,25 @@ impl Resource for TemporaryRedirectResource {
} }
fn head(&self) -> ResponseFuture { fn head(&self) -> ResponseFuture {
Box::new(futures::finished( Box::new(futures::finished(Response::new()
Response::new()
.with_status(hyper::StatusCode::TemporaryRedirect) .with_status(hyper::StatusCode::TemporaryRedirect)
.with_header(Location::new(self.location.clone())), .with_header(Location::new(self.location.clone()))
)) ))
} }
fn get(self: Box<Self>) -> ResponseFuture { fn get(self: Box<Self>) -> ResponseFuture {
Box::new( Box::new(self.head()
self.head() .and_then(move |head| {
.and_then(move |head| Ok(head.with_body(format!("Moved to {}", self.location)))), Ok(head
) .with_body(format!("Moved to {}", self.location)))
}))
} }
fn put(self: Box<Self>, _body: hyper::Body, _identity: Option<String>) -> ResponseFuture { fn put(self: Box<Self>, _body: hyper::Body, _identity: Option<String>) -> ResponseFuture {
self.get() Box::new(self.head()
} .and_then(move |head| {
Ok(head
fn post(self: Box<Self>, _body: hyper::Body, _identity: Option<String>) -> ResponseFuture { .with_body(format!("Moved to {}", self.location)))
self.get() }))
} }
} }

View file

@ -4,20 +4,17 @@
use std::fmt; use std::fmt;
use futures::{self, Future}; use futures::{self, Future};
use hyper::header::{Accept, ContentType};
use hyper::header::{Accept, ContentType, Server};
use hyper::mime; use hyper::mime;
use hyper::server::*; use hyper::server::*;
use hyper;
use crate::assets::{SearchJs, StyleCss, ThemesCss}; use assets::{StyleCss, SearchJs};
use crate::build_config; use web::Lookup;
use crate::theme; use wiki_lookup::WikiLookup;
use crate::web::Lookup;
use crate::wiki_lookup::WikiLookup;
lazy_static! { lazy_static! {
static ref TEXT_HTML: mime::Mime = "text/html;charset=utf-8".parse().unwrap(); static ref TEXT_HTML: mime::Mime = "text/html;charset=utf-8".parse().unwrap();
static ref SERVER: Server = Server::new(build_config::HTTP_SERVER.as_str());
} }
header! { (XIdentity, "X-Identity") => [String] } header! { (XIdentity, "X-Identity") => [String] }
@ -27,52 +24,16 @@ header! { (XIdentity, "X-Identity") => [String] }
pub struct Layout<'a, T: 'a + fmt::Display> { pub struct Layout<'a, T: 'a + fmt::Display> {
pub base: Option<&'a str>, pub base: Option<&'a str>,
pub title: &'a str, pub title: &'a str,
pub theme: theme::Theme, pub body: &'a T,
pub body: T,
} }
impl<'a, T: 'a + fmt::Display> Layout<'a, T> { impl<'a, T: 'a + fmt::Display> Layout<'a, T> {
pub fn themes_css(&self) -> &str { pub fn style_css_checksum(&self) -> &str {
ThemesCss::resource_name() StyleCss::checksum()
}
pub fn style_css(&self) -> &str {
StyleCss::resource_name()
}
pub fn search_js(&self) -> &str {
SearchJs::resource_name()
} }
pub fn project_name(&self) -> &str { pub fn search_js_checksum(&self) -> &str {
build_config::PROJECT_NAME SearchJs::checksum()
}
pub fn version(&self) -> &str {
build_config::VERSION.as_str()
}
}
#[derive(BartDisplay)]
#[template = "templates/system_page_layout.html"]
pub struct SystemPageLayout<'a, T: 'a + fmt::Display> {
title: &'a str,
html_body: T,
}
pub fn system_page<'a, T>(
base: Option<&'a str>,
title: &'a str,
body: T,
) -> Layout<'a, SystemPageLayout<'a, T>>
where
T: 'a + fmt::Display,
{
Layout {
base,
title,
theme: theme::theme_from_str_hash(title),
body: SystemPageLayout {
title,
html_body: body,
},
} }
} }
@ -91,39 +52,41 @@ pub struct Site {
impl Site { impl Site {
pub fn new(root: WikiLookup, trust_identity: bool) -> Site { pub fn new(root: WikiLookup, trust_identity: bool) -> Site {
Site { Site { root, trust_identity }
root,
trust_identity,
}
} }
fn not_found(base: Option<&str>) -> Response { fn not_found(base: Option<&str>) -> Response {
Response::new() Response::new()
.with_header(ContentType(TEXT_HTML.clone())) .with_header(ContentType(TEXT_HTML.clone()))
.with_body(system_page(base, "Not found", NotFound).to_string()) .with_body(Layout {
base: base,
title: "Not found",
body: &NotFound,
}.to_string())
.with_status(hyper::StatusCode::NotFound) .with_status(hyper::StatusCode::NotFound)
} }
fn internal_server_error( fn internal_server_error(base: Option<&str>, err: Box<::std::error::Error + Send + Sync>) -> Response {
base: Option<&str>,
err: Box<dyn ::std::error::Error + Send + Sync>,
) -> Response {
eprintln!("Internal Server Error:\n{:#?}", err); eprintln!("Internal Server Error:\n{:#?}", err);
Response::new() Response::new()
.with_header(ContentType(TEXT_HTML.clone())) .with_header(ContentType(TEXT_HTML.clone()))
.with_body(system_page(base, "Internal server error", InternalServerError).to_string()) .with_body(Layout {
base,
title: "Internal server error",
body: &InternalServerError,
}.to_string())
.with_status(hyper::StatusCode::InternalServerError) .with_status(hyper::StatusCode::InternalServerError)
} }
} }
fn root_base_from_request_uri(path: &str) -> Option<String> { fn root_base_from_request_uri(path: &str) -> Option<String> {
assert!(path.starts_with('/')); assert!(path.starts_with("/"));
let slashes = path[1..].matches('/').count(); let slashes = path[1..].matches('/').count();
match slashes { match slashes {
0 => None, 0 => None,
n => Some("../".repeat(n)), n => Some(::std::iter::repeat("../").take(n).collect())
} }
} }
@ -131,7 +94,7 @@ impl Service for Site {
type Request = Request; type Request = Request;
type Response = Response; type Response = Response;
type Error = hyper::Error; type Error = hyper::Error;
type Future = Box<dyn futures::Future<Item = Response, Error = Self::Error>>; type Future = Box<futures::Future<Item = Response, Error = Self::Error>>;
fn call(&self, req: Request) -> Self::Future { fn call(&self, req: Request) -> Self::Future {
let (method, uri, _http_version, headers, body) = req.deconstruct(); let (method, uri, _http_version, headers, body) = req.deconstruct();
@ -143,14 +106,12 @@ impl Service for Site {
false => None, false => None,
}; };
let accept_header = headers.get().cloned().unwrap_or_else(|| Accept(vec![])); let accept_header = headers.get().map(|x: &Accept| x.clone()).unwrap_or(Accept(vec![]));
let base = root_base_from_request_uri(uri.path()); let base = root_base_from_request_uri(uri.path());
let base2 = base.clone(); // Bah, stupid clone let base2 = base.clone(); // Bah, stupid clone
Box::new( Box::new(self.root.lookup(uri.path(), uri.query())
self.root
.lookup(uri.path(), uri.query())
.and_then(move |resource| match resource { .and_then(move |resource| match resource {
Some(mut resource) => { Some(mut resource) => {
use hyper::Method::*; use hyper::Method::*;
@ -160,14 +121,12 @@ impl Service for Site {
Head => resource.head(), Head => resource.head(),
Get => resource.get(), Get => resource.get(),
Put => resource.put(body, identity), Put => resource.put(body, identity),
Post => resource.post(body, identity), _ => Box::new(futures::finished(resource.method_not_allowed()))
_ => Box::new(futures::finished(resource.method_not_allowed())),
} }
} },
None => Box::new(futures::finished(Self::not_found(base.as_deref()))), None => Box::new(futures::finished(Self::not_found(base.as_ref().map(|x| &**x))))
}) })
.or_else(move |err| Ok(Self::internal_server_error(base2.as_deref(), err))) .or_else(move |err| Ok(Self::internal_server_error(base2.as_ref().map(|x| &**x), err)))
.map(|response| response.with_header(SERVER.clone())),
) )
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,232 +0,0 @@
use std::io::Write;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, Output, ToSql};
use diesel::sql_types::Text;
use diesel::sqlite::Sqlite;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)] // Serde
#[serde(rename_all = "kebab-case")]
#[derive(AsExpression, FromSqlRow)] // Diesel
#[sql_type = "Text"]
pub enum Theme {
Red,
Pink,
Purple,
DeepPurple,
Indigo,
Blue,
LightBlue,
Cyan,
Teal,
Green,
LightGreen,
Lime,
Yellow,
Amber,
Orange,
DeepOrange,
Brown,
Gray,
BlueGray,
}
use self::Theme::*;
forward_display_to_serde!(Theme);
forward_from_str_to_serde!(Theme);
pub const THEMES: [Theme; 19] = [
Red, Pink, Purple, DeepPurple, Indigo, Blue, LightBlue, Cyan, Teal, Green, LightGreen, Lime,
Yellow, Amber, Orange, DeepOrange, Brown, Gray, BlueGray,
];
pub fn theme_from_str_hash(x: &str) -> Theme {
let hash = seahash::hash(x.as_bytes()) as usize;
let choice = hash % THEMES.len();
THEMES[choice]
}
pub fn random() -> Theme {
use rand::Rng;
*rand::thread_rng()
.choose(&THEMES)
.expect("Could only fail for an empty slice")
}
impl ToSql<Text, Sqlite> for Theme {
fn to_sql<W: Write>(&self, out: &mut Output<W, Sqlite>) -> serialize::Result {
ToSql::<Text, Sqlite>::to_sql(&self.to_string(), out)
}
}
impl FromSql<Text, Sqlite> for Theme {
fn from_sql(value: Option<&<Sqlite as Backend>::RawValue>) -> deserialize::Result<Self> {
// See Diesel's documentation on how to implement FromSql for Sqlite,
// especially with regards to the unsafe conversion below.
// http://docs.diesel.rs/diesel/deserialize/trait.FromSql.html
let text_ptr = <*const str as FromSql<Text, Sqlite>>::from_sql(value)?;
let text = unsafe { &*text_ptr };
text.parse().map_err(Into::into)
}
}
pub struct CssClass(Theme);
impl Theme {
pub fn css_class(self) -> CssClass {
CssClass(self)
}
}
use std::fmt::{self, Display, Formatter};
impl Display for CssClass {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
write!(fmt, "theme-{}", self.0)
}
}
#[cfg(test)]
mod test {
use std::error::Error;
use diesel::prelude::*;
use diesel::sql_query;
use diesel::sql_types::Text;
use super::*;
#[test]
fn basic_serialize() {
assert_eq!(serde_plain::to_string(&Theme::Red).unwrap(), "red");
}
#[test]
fn serialize_kebab_case() {
assert_eq!(
serde_plain::to_string(&Theme::LightGreen).unwrap(),
"light-green"
);
}
#[test]
fn serialize_json() {
#[derive(Serialize)]
struct Test {
x: Theme,
}
assert_eq!(
serde_json::to_string(&Test { x: Theme::Red }).unwrap(),
"{\"x\":\"red\"}"
);
}
#[test]
fn deserialize_json() {
#[derive(Deserialize, Debug, PartialEq, Eq)]
struct Test {
x: Theme,
}
assert_eq!(
serde_json::from_str::<Test>("{\"x\":\"red\"}").unwrap(),
Test { x: Theme::Red }
);
}
#[test]
fn serialize_urlencoded() {
#[derive(Serialize)]
struct Test {
x: Theme,
}
assert_eq!(
serde_urlencoded::to_string(&Test { x: Theme::Red }).unwrap(),
"x=red"
);
}
#[test]
fn deserialize_urlencoded() {
#[derive(Deserialize, Debug, PartialEq, Eq)]
struct Test {
x: Theme,
}
assert_eq!(
serde_urlencoded::from_str::<Test>("x=red").unwrap(),
Test { x: Theme::Red }
);
}
#[test]
fn basic_display() {
assert_eq!(&Theme::Red.to_string(), "red");
}
#[test]
fn display_kebab_case() {
assert_eq!(&Theme::LightGreen.to_string(), "light-green");
}
#[test]
fn basic_from_str() {
let indigo: Theme = "indigo".parse().unwrap();
assert_eq!(indigo, Theme::Indigo);
}
#[test]
fn to_number() {
assert_eq!(Theme::Red as i32, 0);
assert_eq!(Theme::LightGreen as i32, 10);
assert_eq!(Theme::BlueGray as i32, 18);
}
#[test]
fn from_str_hash() {
assert_eq!(theme_from_str_hash("Bartefjes"), Theme::Orange);
}
#[test]
fn css_class_display() {
assert_eq!(&Theme::Red.css_class().to_string(), "theme-red");
}
#[test]
fn basic_db_roundtrip() -> Result<(), Box<dyn Error>> {
let conn = SqliteConnection::establish(":memory:")?;
#[derive(QueryableByName, PartialEq, Eq, Debug)]
struct Row {
#[sql_type = "Text"]
theme: Theme,
}
let res = sql_query("SELECT ? as theme")
.bind::<Text, _>(DeepPurple)
.load::<Row>(&conn)?;
assert_eq!(&[Row { theme: DeepPurple }], res.as_slice());
Ok(())
}
#[test]
fn db_invalid_value_gives_error() -> Result<(), Box<dyn Error>> {
let conn = SqliteConnection::establish(":memory:")?;
#[derive(QueryableByName, PartialEq, Eq, Debug)]
struct Row {
#[sql_type = "Text"]
theme: Theme,
}
let res = sql_query("SELECT 'green' as theme").load::<Row>(&conn);
assert!(res.is_ok());
let res = sql_query("SELECT 'blueish-yellow' as theme").load::<Row>(&conn);
assert!(res.is_err());
Ok(())
}
}

View file

@ -1,7 +1,9 @@
use futures;
pub trait Lookup { pub trait Lookup {
type Resource; type Resource;
type Error; type Error;
type Future: futures::Future<Item = Option<Self::Resource>, Error = Self::Error>; type Future: futures::Future<Item=Option<Self::Resource>, Error=Self::Error>;
fn lookup(&self, path: &str, query: Option<&str>) -> Self::Future; fn lookup(&self, path: &str, query: Option<&str>) -> Self::Future;
} }

View file

@ -1,5 +1,5 @@
mod lookup;
mod resource; mod resource;
mod lookup;
pub use self::lookup::*;
pub use self::resource::*; pub use self::resource::*;
pub use self::lookup::*;

View file

@ -1,13 +1,14 @@
use futures::{Future, Stream}; use futures;
use hyper::server::Response;
use hyper::{self, header, mime, server}; use hyper::{self, header, mime, server};
use hyper::server::Response;
use std;
lazy_static! { lazy_static! {
static ref TEXT_PLAIN: mime::Mime = "text/plain;charset=utf-8".parse().unwrap(); static ref TEXT_PLAIN: mime::Mime = "text/plain;charset=utf-8".parse().unwrap();
} }
pub type Error = Box<dyn std::error::Error + Send + Sync>; pub type Error = Box<std::error::Error + Send + Sync>;
pub type ResponseFuture = Box<dyn futures::Future<Item = server::Response, Error = Error>>; pub type ResponseFuture = Box<futures::Future<Item = server::Response, Error = Error>>;
pub trait Resource { pub trait Resource {
fn allow(&self) -> Vec<hyper::Method>; fn allow(&self) -> Vec<hyper::Method>;
@ -21,24 +22,22 @@ pub trait Resource {
} }
fn put(self: Box<Self>, body: hyper::Body, _identity: Option<String>) -> ResponseFuture fn put(self: Box<Self>, body: hyper::Body, _identity: Option<String>) -> ResponseFuture
where where Self: 'static
Self: 'static,
{ {
Box::new( use futures::{Future, Stream};
body.fold((), |_, _| -> Result<(), hyper::Error> { Ok(()) })
.map_err(Into::into) // TODO Cleanup by moving to the built in never type, !, when it stabilizes
.and_then(move |_| futures::finished(self.method_not_allowed())), enum Never {};
) impl std::convert::From<Never> for hyper::Error {
fn from(_: Never) -> hyper::Error {
panic!()
}
} }
fn post(self: Box<Self>, body: hyper::Body, _identity: Option<String>) -> ResponseFuture Box::new(body
where .fold((), |_, _| -> Result<(), Never> { Ok(()) })
Self: 'static,
{
Box::new(
body.fold((), |_, _| -> Result<(), hyper::Error> { Ok(()) })
.map_err(Into::into) .map_err(Into::into)
.and_then(move |_| futures::finished(self.method_not_allowed())), .and_then(move |_| futures::finished(self.method_not_allowed()))
) )
} }

View file

@ -2,38 +2,44 @@ use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::str::Utf8Error; use std::str::Utf8Error;
use futures::{Future, finished, failed, done};
use futures::future::FutureResult; use futures::future::FutureResult;
use futures::{done, failed, finished, Future};
use percent_encoding::percent_decode; use percent_encoding::percent_decode;
use slug::slugify; use slug::slugify;
use crate::resources::*; use resources::*;
use crate::state::State; use assets::*;
use crate::web::{Lookup, Resource}; use state::State;
use web::{Lookup, Resource};
#[allow(unused)] type BoxResource = Box<Resource + Sync + Send>;
use crate::assets::*; type ResourceFn = Box<Fn() -> BoxResource + Sync + Send>;
type BoxResource = Box<dyn Resource + Sync + Send>;
type ResourceFn = Box<dyn Fn() -> BoxResource + Sync + Send>;
lazy_static! { lazy_static! {
static ref LICENSES_MAP: HashMap<&'static str, ResourceFn> = hashmap! { static ref ASSETS_MAP: HashMap<String, ResourceFn> = {
"bsd-3-clause" => Box::new(|| Box::new( let mut map = HashMap::new();
HtmlResource::new(Some("../"), "The 3-Clause BSD License", include_str!("licenses/bsd-3-clause.html"))
) as BoxResource) as ResourceFn, map.insert(
"gpl3" => Box::new(|| Box::new( format!("style-{}.css", StyleCss::checksum()),
HtmlResource::new(Some("../"), "GNU General Public License", include_str!("licenses/gpl3.html")) Box::new(|| Box::new(StyleCss) as BoxResource) as ResourceFn
) as BoxResource) as ResourceFn, );
"mit" => Box::new(|| Box::new(
HtmlResource::new(Some("../"), "The MIT License", include_str!("licenses/mit.html")) map.insert(
) as BoxResource) as ResourceFn, format!("script-{}.js", ScriptJs::checksum()),
"mpl2" => Box::new(|| Box::new( Box::new(|| Box::new(ScriptJs) as BoxResource) as ResourceFn
HtmlResource::new(Some("../"), "Mozilla Public License Version 2.0", include_str!("licenses/mpl2.html")) );
) as BoxResource) as ResourceFn,
"sil-ofl-1.1" => Box::new(|| Box::new( map.insert(
HtmlResource::new(Some("../"), "SIL Open Font License", include_str!("licenses/sil-ofl-1.1.html")) format!("search-{}.js", SearchJs::checksum()),
) as BoxResource) as ResourceFn, Box::new(|| Box::new(SearchJs) as BoxResource) as ResourceFn
);
map.insert(
format!("amatic-sc-v9-latin-regular.woff"),
Box::new(|| Box::new(AmaticFont) as BoxResource) as ResourceFn
);
map
}; };
} }
@ -41,7 +47,6 @@ lazy_static! {
pub struct WikiLookup { pub struct WikiLookup {
state: State, state: State,
changes_lookup: ChangesLookup, changes_lookup: ChangesLookup,
diff_lookup: DiffLookup,
search_lookup: SearchLookup, search_lookup: SearchLookup,
} }
@ -54,10 +59,7 @@ fn split_one(path: &str) -> Result<(Cow<str>, Option<&str>), Utf8Error> {
Ok((head, tail)) Ok((head, tail))
} }
fn map_lookup( fn asset_lookup(path: &str) -> FutureResult<Option<BoxResource>, Box<::std::error::Error + Send + Sync>> {
map: &HashMap<&str, ResourceFn>,
path: &str,
) -> FutureResult<Option<BoxResource>, Box<dyn ::std::error::Error + Send + Sync>> {
let (head, tail) = match split_one(path) { let (head, tail) = match split_one(path) {
Ok(x) => x, Ok(x) => x,
Err(x) => return failed(x.into()), Err(x) => return failed(x.into()),
@ -67,55 +69,18 @@ fn map_lookup(
return finished(None); return finished(None);
} }
match map.get(head.as_ref()) { match ASSETS_MAP.get(head.as_ref()) {
Some(resource_fn) => finished(Some(resource_fn())), Some(resource_fn) => finished(Some(resource_fn())),
None => finished(None), None => finished(None),
} }
} }
#[allow(unused)]
fn fs_lookup(
root: &str,
path: &str,
) -> FutureResult<Option<BoxResource>, Box<dyn ::std::error::Error + Send + Sync>> {
use std::fs::File;
use std::io::prelude::*;
let extension = path.rsplit_once('.').map(|x| x.1);
let content_type = match extension {
Some("html") => "text/html",
Some("css") => "text/css",
Some("js") => "application/javascript",
Some("woff") => "application/font-woff",
_ => "application/binary",
}
.parse()
.unwrap();
let mut filename = root.to_string();
filename.push_str(path);
let mut f = File::open(&filename).unwrap_or_else(|_| panic!("Not found: {}", filename));
let mut body = Vec::new();
f.read_to_end(&mut body).expect("Unable to read file");
finished(Some(Box::new(ReadOnlyResource { content_type, body })))
}
impl WikiLookup { impl WikiLookup {
pub fn new(state: State, show_authors: bool) -> WikiLookup { pub fn new(state: State) -> WikiLookup {
let changes_lookup = ChangesLookup::new(state.clone(), show_authors); let changes_lookup = ChangesLookup::new(state.clone());
let diff_lookup = DiffLookup::new(state.clone());
let search_lookup = SearchLookup::new(state.clone()); let search_lookup = SearchLookup::new(state.clone());
WikiLookup { WikiLookup { state, changes_lookup, search_lookup }
state,
changes_lookup,
diff_lookup,
search_lookup,
}
} }
fn revisions_lookup(&self, path: &str, _query: Option<&str>) -> <Self as Lookup>::Future { fn revisions_lookup(&self, path: &str, _query: Option<&str>) -> <Self as Lookup>::Future {
@ -133,12 +98,12 @@ impl WikiLookup {
}; };
Box::new( Box::new(
self.state self.state.get_article_revision(article_id, revision)
.get_article_revision(article_id, revision) .and_then(|article_revision|
.and_then(|article_revision| { Ok(article_revision.map(move |x| Box::new(
Ok(article_revision ArticleRevisionResource::new(x)
.map(move |x| Box::new(ArticleRevisionResource::new(x)) as BoxResource)) ) as BoxResource))
}), )
) )
} }
@ -155,27 +120,14 @@ impl WikiLookup {
Err(_) => return Box::new(finished(None)), Err(_) => return Box::new(finished(None)),
}; };
Box::new(self.state.get_article_slug(article_id).and_then(|slug| { Box::new(
Ok(slug.map(|slug| { self.state.get_article_slug(article_id)
Box::new(TemporaryRedirectResource::new(format!("../{}", slug))) as BoxResource .and_then(|slug|
})) Ok(slug.map(|slug| Box::new(
})) TemporaryRedirectResource::new(format!("../{}", slug))
} ) as BoxResource))
)
fn diff_lookup_f(&self, path: &str, query: Option<&str>) -> <Self as Lookup>::Future { )
let article_id: u32 = match (|| -> Result<_, <Self as Lookup>::Error> {
let (article_id, tail) = split_one(path)?;
if tail.is_some() {
return Err("Not found".into());
}
Ok(article_id.parse()?)
})() {
Ok(x) => x,
Err(_) => return Box::new(finished(None)),
};
Box::new(self.diff_lookup.lookup(article_id, query))
} }
fn reserved_lookup(&self, path: &str, query: Option<&str>) -> <Self as Lookup>::Future { fn reserved_lookup(&self, path: &str, query: Option<&str>) -> <Self as Lookup>::Future {
@ -185,30 +137,20 @@ impl WikiLookup {
}; };
match (head.as_ref(), tail) { match (head.as_ref(), tail) {
("_about", None) => Box::new(finished(Some( ("_assets", Some(asset)) =>
Box::new(AboutResource::new()) as BoxResource Box::new(asset_lookup(asset)),
))), ("_by_id", Some(tail)) =>
("_about", Some(license)) => Box::new(map_lookup(&LICENSES_MAP, license)), self.by_id_lookup(tail, query),
#[cfg(feature = "dynamic-assets")] ("_changes", None) =>
("_assets", Some(asset)) => Box::new(fs_lookup( Box::new(self.changes_lookup.lookup(query)),
concat!(env!("CARGO_MANIFEST_DIR"), "/assets/"), ("_new", None) =>
asset, Box::new(finished(Some(Box::new(NewArticleResource::new(self.state.clone(), None)) as BoxResource))),
)), ("_revisions", Some(tail)) =>
#[cfg(not(feature = "dynamic-assets"))] self.revisions_lookup(tail, query),
("_assets", Some(asset)) => Box::new(map_lookup(&ASSETS_MAP, asset)), ("_search", None) =>
("_by_id", Some(tail)) => self.by_id_lookup(tail, query), Box::new(done(self.search_lookup.lookup(query))),
("_changes", None) => Box::new(self.changes_lookup.lookup(query)), ("_sitemap", None) =>
("_diff", Some(tail)) => self.diff_lookup_f(tail, query), Box::new(finished(Some(Box::new(SitemapResource::new(self.state.clone())) as BoxResource))),
("_new", None) => Box::new(finished(Some(Box::new(NewArticleResource::new(
self.state.clone(),
None,
true,
)) as BoxResource))),
("_revisions", Some(tail)) => self.revisions_lookup(tail, query),
("_search", None) => Box::new(done(self.search_lookup.lookup(query))),
("_sitemap", None) => Box::new(finished(Some(Box::new(SitemapResource::new(
self.state.clone(),
)) as BoxResource))),
_ => Box::new(finished(None)), _ => Box::new(finished(None)),
} }
} }
@ -224,49 +166,42 @@ impl WikiLookup {
return Box::new(finished(None)); return Box::new(finished(None));
} }
let edit = query == Some("edit");
// Normalize all user-generated slugs: // Normalize all user-generated slugs:
let slugified_slug = slugify(&slug); let slugified_slug = slugify(&slug);
if slugified_slug != slug { if slugified_slug != slug {
return Box::new(finished(Some( return Box::new(finished(Some(
Box::new(TemporaryRedirectResource::from_slug(slugified_slug, edit)) as BoxResource, Box::new(ArticleRedirectResource::new(slugified_slug)) as BoxResource
))); )));
} }
let state = self.state.clone(); let state = self.state.clone();
let edit = query == Some("edit");
let slug = slug.into_owned(); let slug = slug.into_owned();
use crate::state::SlugLookup; use state::SlugLookup;
Box::new(self.state.lookup_slug(slug.clone()).and_then(move |x| { Box::new(self.state.lookup_slug(slug.clone())
Ok(Some(match x { .and_then(move |x| Ok(Some(match x {
SlugLookup::Miss => { SlugLookup::Miss =>
Box::new(NewArticleResource::new(state, Some(slug), edit)) as BoxResource Box::new(NewArticleResource::new(state, Some(slug))) as BoxResource,
} SlugLookup::Hit { article_id, revision } =>
SlugLookup::Hit { Box::new(ArticleResource::new(state, article_id, revision, edit)) as BoxResource,
article_id, SlugLookup::Redirect(slug) =>
revision, Box::new(ArticleRedirectResource::new(slug)) as BoxResource,
} => { })))
Box::new(ArticleResource::new(state, article_id, revision, edit)) as BoxResource )
}
SlugLookup::Redirect(slug) => {
Box::new(TemporaryRedirectResource::from_slug(slug, edit)) as BoxResource
}
}))
}))
} }
} }
impl Lookup for WikiLookup { impl Lookup for WikiLookup {
type Resource = BoxResource; type Resource = BoxResource;
type Error = Box<dyn ::std::error::Error + Send + Sync>; type Error = Box<::std::error::Error + Send + Sync>;
type Future = Box<dyn Future<Item = Option<Self::Resource>, Error = Self::Error>>; type Future = Box<Future<Item = Option<Self::Resource>, Error = Self::Error>>;
fn lookup(&self, path: &str, query: Option<&str>) -> Self::Future { fn lookup(&self, path: &str, query: Option<&str>) -> Self::Future {
assert!(path.starts_with('/')); assert!(path.starts_with("/"));
let path = &path[1..]; let path = &path[1..];
if path.starts_with('_') { if path.starts_with("_") {
self.reserved_lookup(path, query) self.reserved_lookup(path, query)
} else { } else {
self.article_lookup(path, query) self.article_lookup(path, query)

View file

@ -1,35 +0,0 @@
<p>This site is running Sausagewiki, a simple, self-contained wiki engine,
version {{version()}}.</p>
<p>Copyright &copy; 2017 Magnus Hovland Hoff.</p>
<p>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
</p>
<p>
See also <a href="_about/gpl3">the full license text</a> and the
<a href="https://github.com/maghoff/sausagewiki">project home page</a>.
</p>
<p>
Without <a href="https://www.rust-lang.org/en-US/">Rust</a> and
<a href="https://www.sqlite.org/">SQLite</a>, Sausagewiki would never have
materialized. Huge thanks to the creators. Another big thanks for the support,
discussions and testing by the amazing developers at Revolverhuset.
</p>
<p>
Sausagewiki builds on a number of projects, copyright by their respective
copyright holders and distributed under various licenses:
</p>
<table>
<thead><tr><th>Project</th><th>Copyright notice</th><th>License</th></tr></thead>
<tbody>
{{#deps}}
<tr><td>{{#.link}}<a href="{{.}}">{{..name}}</a>{{/.link}}{{^.link}}{{..name}}{{/.link}}</td><td>{{.copyright}}</td><td><a href="_about/{{.license.link()}}">{{.license.name()}}</a></td></tr>
{{/deps}}
</tbody>
</table>

View file

@ -1,24 +1,16 @@
<script src="_assets/{{script_js()}}" defer></script> <script src="_assets/script-{{script_js_checksum}}.js" defer></script>
<div class="container {{#edit?}}edit{{/edit}}"> <div class="container {{#edit?}}edit{{/edit}}">
<div class="rendered"> <div class="rendered">
{{>article_contents.html}} {{>article_contents.html}}
</div> </div>
<form autocomplete="off" id="article-editor" action="" method="POST">
<div class="editor"> <div class="editor">
<div class="hero"> <form action="" method="POST">
<header>
<h1><input autocomplete=off type=text name=title value="{{title}}" placeholder="Title" required></h1>
</header>
</div>
<div class="theme-picker"> <header>
{{#themes}} <h1><input autocomplete=off type=text name=title value="{{title}}" placeholder="Title"></h1>
<input autocomplete="off" type="radio" name="theme" value="{{.theme}}"{{#.selected?}} checked{{/.selected}} class="theme-picker--option {{.theme.css_class()}} themed"> </header>
{{/themes}}
</div>
<article> <article>
<p> <p>
@ -28,34 +20,21 @@
</p> </p>
</article> </article>
</div>
<div class="editor-controls"> <div class="editor-controls">
{{#edit?}} {{#cancel_url}}
<div class="cancel-interaction-group {{#cancel_url}}interaction-group--root--enabled{{/cancel_url}}{{^cancel_url}}interaction-group--root--disabled{{/cancel_url}}"> <a class="cancel" href="{{.}}">Cancel</a>
<a class="interaction-group--enabled button button-cancel cancel" href="{{#cancel_url}}{{.}}{{/cancel_url}}">Cancel</a> {{/cancel_url}}
<button class="interaction-group--disabled button button-cancel" disabled>Cancel</a> <button type=submit>Save</button>
</div>
<button class="button button-default" type=submit {{^edit?}}disabled{{/edit}}>Save</button>
{{/edit}}
{{^edit?}}
<div class="cancel-interaction-group interaction-group--root--disabled">
<a class="interaction-group--enabled button button-cancel cancel" href="{{#cancel_url}}{{.}}{{/cancel_url}}">Cancel</a>
<button class="interaction-group--disabled button button-cancel" disabled>Cancel</a>
</div>
<button class="button button-default" type=submit disabled>Save</button>
{{/edit}}
</div> </div>
</form>
</form>
</div>
</div> </div>
<footer> <footer>
<ul class="dense" <ul class="dense"
><li class="last-updated {{^last_updated}}missing{{/last_updated}}">{{#last_updated}}{{{.}}}{{/last_updated}}</li ><li class="last-updated {{^last_updated}}missing{{/last_updated}}">{{#last_updated}}{{{.}}}{{/last_updated}}</li
><li><a id="openEditor" href="?edit" rel="nofollow">Edit</a></li ><li><a id="openEditor" href="?edit">Edit</a></li
></ul> ></ul>
{{>footer/items.html}} {{>footer/items.html}}
</footer> </footer>
{{>dialog_prototypes.html}}

View file

@ -1,8 +1,6 @@
<div class="hero">
<header> <header>
<h1>{{title}}</h1> <h1>{{title}}</h1>
</header> </header>
</div>
<article> <article>
{{{rendered}}} {{{rendered}}}

View file

@ -1,12 +1,17 @@
<div class="container">
<div class="notice"> <div class="notice">
<p> <p>
You are viewing an historical version of <a href="{{link_current}}">this article</a>, You are viewing an historical version of <a href="{{link_current}}">this article</a>,
authored at {{{timestamp_and_author}}}. authored at {{{timestamp_and_author}}}.
</p> </p>
<p>
{{#diff_link}}See <a href="{{.}}">the changes</a> made for this revision.{{/diff_link}}
{{^diff_link}}This is the first revision of the article.{{/diff_link}}
</p>
</div> </div>
{{{rendered}}} <div class="rendered">
{{>article_contents.html}}
</div>
</div>
<footer>
{{>footer/items.html}}
</footer>

View file

@ -1,5 +1,11 @@
<div class="container">
<header>
<h1>Changes</h1>
</header>
<article>
<p> <p>
These are the {{^newer}}most recent{{/newer}} changes These are the {{^newer}}most recent{{/newer}} changes that have been
made to{{{subject_clause()}}}{{#author()}} by {{.}}{{/author()}}. made to{{{subject_clause()}}}{{#author()}} by {{.}}{{/author()}}.
</p> </p>
@ -17,16 +23,14 @@
<tr> <tr>
<th>Article</th> <th>Article</th>
<th>Updated</th> <th>Updated</th>
{{#show_authors?}}<th>Author</th>{{/show_authors}} <th>Author</th>
<th></th>
</tr> </tr>
{{/changes}} {{/changes}}
{{#changes}} {{#changes}}
<tr> <tr>
<td><a href="_revisions/{{.article_id}}/{{.revision}}">{{.title}}</a></td> <td><a href="_revisions/{{.article_id}}/{{.revision}}">{{.title}}</a></td>
<td>{{.created}}</td> <td>{{.created}}</td>
{{#show_authors?}}<td>{{#..author}}<a href="{{...author_link()}}">{{.}}</a>{{/..author}}{{^..author}}<i>Anonymous</i>{{/..author}}</td>{{/show_authors}} <td>{{#.author}}<a href="{{..author_link()}}">{{.}}</a>{{/.author}}{{^.author}}<i>Anonymous</i>{{/.author}}</td>
<td>{{#.diff_link}}<a href="{{.}}">change</a>{{/.diff_link}}{{^.diff_link}}new{{/.diff_link}}</td>
</tr> </tr>
{{/changes}} {{/changes}}
</table> </table>
@ -38,3 +42,7 @@
><li><a rel="last" href="{{.end}}">First changes</a></li ><li><a rel="last" href="{{.end}}">First changes</a></li
></ul></nav>{{/older}} ></ul></nav>{{/older}}
{{#changes?}}{{^older}}<p>There are no older changes.</p>{{/older}}{{/changes}} {{#changes?}}{{^older}}<p>There are no older changes.</p>{{/older}}{{/changes}}
</article>
</div>
{{>footer/default.html}}

View file

@ -1,35 +0,0 @@
<div class=prototype id=login>
<div class=modal-block>
<div class=popup>
<div class=message>
<p>Your changes could not be saved</p>
<p>Log in and try again</p>
</div>
<div class=btn-row>
<button>Never mind</button>
<a class=primary href='' target=login>Open login page</a>
</div>
</div>
</div>
</div>
<div class=prototype id=alert>
<div class=modal-block>
<div class=popup>
<div class=message></div>
<div class=btn-row><button class=primary>OK</button></div>
</div>
</div>
</div>
<div class=prototype id=confirm-discard>
<div class=modal-block>
<div class=popup>
<div class=message>Discard changes?</div>
<div class=btn-row>
<button class=primary>No</button>
<button data-value=true>Yes</button>
</div>
</div>
</div>
</div>

View file

@ -1,30 +0,0 @@
<div class="container">
<div class="hero">
<header>
<h1>{{#title}}{{#.removed}}<span class="removed">{{.}}</span>{{/.removed}}{{#.same}}{{.}}{{/.same}}{{#.added}}<span class="added">{{.}}</span>{{/.added}}{{/title}}</h1>
</header>
</div>
<div class="notice">
<p>
You are viewing the difference between two {{#consecutive?}}consecutive{{/consecutive}}
revisions of <a href="_by_id/{{article_id}}">this article</a>.
{{#author}}This changeset was authored by <a href="{{..author_link}}">{{.}}</a>.{{/author}}
</p>
<p>
See also the <a href="{{article_history_link}}">list of all changes</a> to this article
or the article as it was <a href="{{from_link}}">before</a> and <a href="{{to_link}}">after</a> this change.
</p>
</div>
<article>
<pre class="diff">{{#lines}}{{#.removed}}<span class="removed">{{.}}
</span>{{/.removed}}{{#.same}}<span class="same">{{.}}
</span>{{/.same}}{{#.added}}<span class="added">{{.}}
</span>{{/.added}}{{/lines}}</pre>
</article>
</div>
{{>footer/default.html}}

View file

@ -1 +1,11 @@
<p>This page was not found.</p> <div class="container">
<header>
<h1>Not found</h1>
</header>
<article>
<p>This page was not found.</p>
</article>
</div>
{{>../footer/default.html}}

View file

@ -1 +1,11 @@
<p>An error has occurred.</p> <div class="container">
<header>
<h1>Internal server error</h1>
</header>
<article>
<p>An error has occurred.</p>
</article>
</div>
{{>../footer/default.html}}

View file

@ -4,4 +4,4 @@
><li><a href="_sitemap">Sitemap</a></li ><li><a href="_sitemap">Sitemap</a></li
><li><a href="_changes">Recent changes</a></li ><li><a href="_changes">Recent changes</a></li
></ul> ></ul>
<p>Powered by <a href="_about">Sausagewiki</a></p> <p>Powered by <a href="https://github.com/maghoff/sausagewiki">Sausagewiki</a></p>

View file

@ -3,13 +3,11 @@
<head> <head>
<title>{{title}}</title> <title>{{title}}</title>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
{{#base}}<base href="{{.}}">{{/base}} {{#base}}<base href="{{.}}">{{/base}}
<link href="_assets/{{themes_css()}}" rel="stylesheet"> <link rel=preload href="_assets/amatic-sc-v9-latin-regular.woff" as=font crossorigin>
<link href="_assets/{{style_css()}}" rel="stylesheet"> <link href="_assets/style-{{style_css_checksum()}}.css" rel="stylesheet">
<meta name="generator" content="{{project_name()}} {{version()}}" />
</head> </head>
<body class="{{theme.css_class()}}"> <body>
{{>search_input.html}} {{>search_input.html}}
{{{body}}} {{{body}}}
</body> </body>

View file

@ -1,3 +1,9 @@
<div class="container">
<header>
<h1>Search</h1>
</header>
<article>
{{#hits?}} {{#hits?}}
<p>Search results for the query <b>{{query}}</b>:</p> <p>Search results for the query <b>{{query}}</b>:</p>
@ -7,7 +13,7 @@
<ul class="search-results default-keyboard-focus-control"> <ul class="search-results default-keyboard-focus-control">
{{#hits}} {{#hits}}
<li class="search-result"><a data-focusindex="{{.0}}" class="link" href="{{.1.link()}}"><p class="title">{{.1.title}}</p><p class="snippet">{{{.1.snippet}}}</p></a></li> <li class="search-result"><a data-focusindex="{{.index}}" class="link" href="{{.link()}}"><p class="title">{{.title}}</p><p class="snippet">{{.snippet}}</p></a></li>
{{/hits}} {{/hits}}
</ul> </ul>
{{/hits}} {{/hits}}
@ -19,3 +25,8 @@
{{^hits?}} {{^hits?}}
<p>Your search for <b>{{query}}</b> gave no results.</p> <p>Your search for <b>{{query}}</b> gave no results.</p>
{{/hits}} {{/hits}}
</article>
</div>
{{>footer/default.html}}

View file

@ -1,11 +1,7 @@
<div class="search-container">
<form class="search keyboard-focus-control" action=_search method=GET> <form class="search keyboard-focus-control" action=_search method=GET>
<div class="search-widget-container"> <input data-focusindex="0" type=search name=q placeholder=search autocomplete=off>
<input data-focusindex="0" type=search name=q placeholder=Search autocomplete=off>
<ul class="live-results search-results"> <ul class="live-results search-results">
</ul> </ul>
</div>
</form> </form>
<ul id="search-result-prototype" class="prototype"><li class="search-result"><a tabindex="0" class="link" href=""><span class="title"></span> &ndash; <span class="snippet"></span></a></li></ul> <ul id="search-result-prototype" class="prototype"><li class="search-result"><a tabindex="0" class="link" href=""><span class="title"></span> &ndash; <span class="snippet"></span></a></li></ul>
<script src="_assets/{{search_js()}}" defer></script> <script src="_assets/search-{{search_js_checksum()}}.js" defer></script>
</div>

View file

@ -1,5 +1,15 @@
<div class="container">
<header>
<h1>Sitemap</h1>
</header>
<article>
<ul class="dense" <ul class="dense"
{{#articles}} {{#articles}}
><li><a href="{{.link()}}">{{.title}}</a></li ><li><a href="{{.link}}">{{.title}}</a></li
{{/articles}} {{/articles}}
></ul> ></ul>
</article>
</div>
{{>footer/default.html}}

View file

@ -1,13 +0,0 @@
<div class="container">
<div class="hero">
<header>
<h1>{{title}}</h1>
</header>
</div>
<article>
{{{html_body}}}
</article>
</div>
{{>footer/default.html}}

View file

@ -1,74 +0,0 @@
#!/usr/bin/env python3
import json, colorsys
colors = json.load(open("material-colors.json", "r"))
palettes = colors['palettes']
def hex_to_rgb(h):
return tuple(int(h[i:i+2], 16) / 255 for i in (0, 2 ,4))
def to_linear(x):
if x < 0.04045:
return x / 12.92
else:
return pow((x + 0.055) / 1.055, 2.4)
def rgb_to_linear(rgb):
return [to_linear(x) for x in rgb]
def luma(rgb):
r, g, b = rgb_to_linear(rgb)
return (0.2126*r + 0.7152*g + 0.0722*b)
def prep(x):
cols = x['colors']
rgb = [hex_to_rgb(c[1:]) for c in cols]
brightness = [luma(c) for c in rgb]
hue = [colorsys.rgb_to_hsv(*c)[0] * 360 for c in rgb]
sat = [colorsys.rgb_to_hsv(*c)[1] for c in rgb]
main_index = 5
if brightness[main_index] >= 0.4:
main_index = 6
dark_main = brightness[main_index] < 0.5
input_index = main_index + (-2 if dark_main else 1)
h = hue[main_index]
s = sat[main_index]
alt = blues
if s > 0.3 and (h < 40 or h >= 300):
alt = yellows
return {
"name": x['shade'].lower().replace(' ', '-'),
"main": cols[main_index],
"input": cols[input_index],
"text": "white",
"link": alt[2 if dark_main else 7],
}
blues = [x for x in palettes if x['shade'] == "Blue"][0]["colors"]
yellows = [x for x in palettes if x['shade'] == "Yellow"][0]["colors"]
themes = [prep(palette) for palette in palettes]
print(
"\n".join(
"\
.theme-{name} {{\n\
--theme-main: {main};\n\
--theme-text: {text};\n\
--theme-input: {input};\n\
--theme-link: {link};\n\
}}\n".format(**x)
for x in themes
)
)
print()
# print("[" + ', '.join('"'+x['name']+'"' for x in themes) + "]")

View file

@ -1,369 +0,0 @@
{
"names": [
"50",
"100",
"200",
"300",
"400",
"500",
"600",
"700",
"800",
"900",
"A100",
"A200",
"A400",
"A700"
],
"palettes": [
{
"shade": "Red",
"colors": [
"#FFEBEE",
"#FFCDD2",
"#EF9A9A",
"#E57373",
"#EF5350",
"#F44336",
"#E53935",
"#D32F2F",
"#C62828",
"#B71C1C",
"#FF8A80",
"#FF5252",
"#FF1744",
"#D50000"
]
},
{
"shade": "Pink",
"colors": [
"#FCE4EC",
"#F8BBD0",
"#F48FB1",
"#F06292",
"#EC407A",
"#E91E63",
"#D81B60",
"#C2185B",
"#AD1457",
"#880E4F",
"#FF80AB",
"#FF4081",
"#F50057",
"#C51162"
]
},
{
"shade": "Purple",
"colors": [
"#F3E5F5",
"#E1BEE7",
"#CE93D8",
"#BA68C8",
"#AB47BC",
"#9C27B0",
"#8E24AA",
"#7B1FA2",
"#6A1B9A",
"#4A148C",
"#EA80FC",
"#E040FB",
"#D500F9",
"#AA00FF"
]
},
{
"shade": "Deep purple",
"colors": [
"#EDE7F6",
"#D1C4E9",
"#B39DDB",
"#9575CD",
"#7E57C2",
"#673AB7",
"#5E35B1",
"#512DA8",
"#4527A0",
"#311B92",
"#B388FF",
"#7C4DFF",
"#651FFF",
"#6200EA"
]
},
{
"shade": "Indigo",
"colors": [
"#E8EAF6",
"#C5CAE9",
"#9FA8DA",
"#7986CB",
"#5C6BC0",
"#3F51B5",
"#3949AB",
"#303F9F",
"#283593",
"#1A237E",
"#8C9EFF",
"#536DFE",
"#3D5AFE",
"#304FFE"
]
},
{
"shade": "Blue",
"colors": [
"#E3F2FD",
"#BBDEFB",
"#90CAF9",
"#64B5F6",
"#42A5F5",
"#2196F3",
"#1E88E5",
"#1976D2",
"#1565C0",
"#0D47A1",
"#82B1FF",
"#448AFF",
"#2979FF",
"#2962FF"
]
},
{
"shade": "Light Blue",
"colors": [
"#E1F5FE",
"#B3E5FC",
"#81D4FA",
"#4FC3F7",
"#29B6F6",
"#03A9F4",
"#039BE5",
"#0288D1",
"#0277BD",
"#01579B",
"#80D8FF",
"#40C4FF",
"#00B0FF",
"#0091EA"
]
},
{
"shade": "Cyan",
"colors": [
"#E0F7FA",
"#B2EBF2",
"#80DEEA",
"#4DD0E1",
"#26C6DA",
"#00BCD4",
"#00ACC1",
"#0097A7",
"#00838F",
"#006064",
"#84FFFF",
"#18FFFF",
"#00E5FF",
"#00B8D4"
]
},
{
"shade": "Teal",
"colors": [
"#E0F2F1",
"#B2DFDB",
"#80CBC4",
"#4DB6AC",
"#26A69A",
"#009688",
"#00897B",
"#00796B",
"#00695C",
"#004D40",
"#A7FFEB",
"#64FFDA",
"#1DE9B6",
"#00BFA5"
]
},
{
"shade": "Green",
"colors": [
"#E8F5E9",
"#C8E6C9",
"#A5D6A7",
"#81C784",
"#66BB6A",
"#4CAF50",
"#43A047",
"#388E3C",
"#2E7D32",
"#1B5E20",
"#B9F6CA",
"#69F0AE",
"#00E676",
"#00C853"
]
},
{
"shade": "Light Green",
"colors": [
"#F1F8E9",
"#DCEDC8",
"#C5E1A5",
"#AED581",
"#9CCC65",
"#8BC34A",
"#7CB342",
"#689F38",
"#558B2F",
"#33691E",
"#CCFF90",
"#B2FF59",
"#76FF03",
"#64DD17"
]
},
{
"shade": "Lime",
"colors": [
"#F9FBE7",
"#F0F4C3",
"#E6EE9C",
"#DCE775",
"#D4E157",
"#CDDC39",
"#C0CA33",
"#AFB42B",
"#9E9D24",
"#827717",
"#F4FF81",
"#EEFF41",
"#C6FF00",
"#AEEA00"
]
},
{
"shade": "Yellow",
"colors": [
"#FFFDE7",
"#FFF9C4",
"#FFF59D",
"#FFF176",
"#FFEE58",
"#FFEB3B",
"#FDD835",
"#FBC02D",
"#F9A825",
"#F57F17",
"#FFFF8D",
"#FFFF00",
"#FFEA00",
"#FFD600"
]
},
{
"shade": "Amber",
"colors": [
"#FFF8E1",
"#FFECB3",
"#FFE082",
"#FFD54F",
"#FFCA28",
"#FFC107",
"#FFB300",
"#FFA000",
"#FF8F00",
"#FF6F00",
"#FFE57F",
"#FFD740",
"#FFC400",
"#FFAB00"
]
},
{
"shade": "Orange",
"colors": [
"#FFF3E0",
"#FFE0B2",
"#FFCC80",
"#FFB74D",
"#FFA726",
"#FF9800",
"#FB8C00",
"#F57C00",
"#EF6C00",
"#E65100",
"#FFD180",
"#FFAB40",
"#FF9100",
"#FF6D00"
]
},
{
"shade": "Deep Orange",
"colors": [
"#FBE9E7",
"#FFCCBC",
"#FFAB91",
"#FF8A65",
"#FF7043",
"#FF5722",
"#F4511E",
"#E64A19",
"#D84315",
"#BF360C",
"#FF9E80",
"#FF6E40",
"#FF3D00",
"#DD2C00"
]
},
{
"shade": "Brown",
"colors": [
"#EFEBE9",
"#D7CCC8",
"#BCAAA4",
"#A1887F",
"#8D6E63",
"#795548",
"#6D4C41",
"#5D4037",
"#4E342E",
"#3E2723"
]
},
{
"shade": "Gray",
"colors": [
"#FAFAFA",
"#F5F5F5",
"#EEEEEE",
"#E0E0E0",
"#BDBDBD",
"#9E9E9E",
"#757575",
"#616161",
"#424242",
"#212121"
]
},
{
"shade": "Blue Gray",
"colors": [
"#ECEFF1",
"#CFD8DC",
"#B0BEC5",
"#90A4AE",
"#78909C",
"#607D8B",
"#546E7A",
"#455A64",
"#37474F",
"#263238"
]
}
]
}