use super::*;
use gent_protocol::dashboard::{Action, MAX_HTML_BYTES, Widget};
const UNIT: &str = "Gent published HTML v1";
pub(super) fn schema(db: &Connection) -> Result<()> {
db.execute_batch(
"CREATE TABLE IF NOT EXISTS dashboard_publications(
agent TEXT PRIMARY KEY REFERENCES dashboards(agent) ON DELETE CASCADE,
revision INTEGER NOT NULL, sha256 TEXT NOT NULL, html TEXT NOT NULL);
CREATE TRIGGER IF NOT EXISTS dashboard_publication_clear AFTER UPDATE ON dashboards
WHEN NEW.revision != OLD.revision OR NEW.body IS NOT OLD.body BEGIN
DELETE FROM dashboard_publications WHERE agent=OLD.agent;
END;",
)?;
if !db
.prepare("SELECT 1 FROM pragma_table_info('dashboard_sent') WHERE name='publication'")?
.exists([])?
{
db.execute_batch(
"ALTER TABLE dashboard_sent ADD COLUMN publication INTEGER NOT NULL DEFAULT 0;
INSERT OR IGNORE INTO presence_requests SELECT peer FROM network_links;",
)?;
}
Ok(())
}
pub(in crate::store) fn verify<'a>(board: Option<&'a Board>, html: &str) -> Result<&'a str> {
ensure!(
(1..=MAX_HTML_BYTES).contains(&html.len()),
"invalid published HTML size"
);
let pin = board
.and_then(pin)
.context("missing published HTML digest")?;
ensure!(hash(html) == pin, "published HTML digest mismatch");
Ok(pin)
}
pub(in crate::store) fn pin(board: &Board) -> Option<&str> {
let marker = board.widgets.first()?;
(marker.kind == Kind::Text
&& marker.unit.as_deref() == Some(UNIT)
&& marker.id.len() == 64
&& marker
.id
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
.then_some(&marker.id)
}
pub(super) fn fallback(
title: String,
digest: &str,
actions: Option<Vec<Action>>,
previous: Option<&Board>,
) -> Result<Board> {
let marker = Widget {
id: digest.into(),
kind: Kind::Text,
label: "HTML dashboard".into(),
value: "Open this dashboard in an updated Gent Desktop.".into(),
unit: Some(UNIT.into()),
x_unit: None,
min: None,
max: None,
};
let mut widgets = vec![marker];
if let Some(actions) = actions {
widgets.extend(actions.into_iter().map(|a| Widget {
id: a.id,
label: a.label,
kind: Kind::Button,
value: a.message.into(),
unit: None,
x_unit: None,
min: None,
max: None,
}));
} else if let Some(previous) = previous {
widgets.extend(
previous
.widgets
.iter()
.filter(|w| w.kind == Kind::Button)
.cloned(),
);
}
let board = Board { title, widgets };
board.validate().map_err(anyhow::Error::msg)?;
Ok(board)
}
impl StoreSession<'_> {
pub(super) fn publication_input(
&self,
who: &Agent,
file: Option<uuid::Uuid>,
inline: Option<String>,
) -> Result<String> {
match (file, inline) {
(Some(file), None) => {
let file = file.to_string();
ensure!(
self.db
.prepare_cached(
"SELECT 1 FROM agent_files WHERE object_id=?1 AND agent=?2"
)?
.exists(params![file, who.id])?,
"publisher import unavailable"
);
self.board_html_file(who, &file).map(|(_, html)| html)
}
(None, Some(html)) => {
ensure!(
(1..=MAX_HTML_BYTES).contains(&html.len()),
"publish 1–65536 UTF-8 bytes"
);
Ok(html)
}
_ => anyhow::bail!("supply exactly one of file_id and html"),
}
}
pub(super) fn save_publication(
&self,
agent: &str,
revision: u64,
digest: &str,
html: &str,
) -> Result<()> {
self.db.execute("INSERT INTO dashboard_publications(agent,revision,sha256,html) VALUES(?1,?2,?3,?4)
ON CONFLICT(agent) DO UPDATE SET revision=excluded.revision,sha256=excluded.sha256,html=excluded.html",
params![agent,revision,digest,html])?;
Ok(())
}
pub(super) fn publication_exists(&self, agent: &str, revision: u64) -> Result<bool> {
Ok(self
.db
.prepare_cached("SELECT 1 FROM dashboard_publications WHERE agent=?1 AND revision=?2")?
.exists(params![agent, revision])?)
}
pub(super) fn publication_receipt(&self, agent: &str, revision: u64) -> Result<Value> {
let sha256: String = self
.db
.query_row(
"SELECT sha256 FROM dashboard_publications WHERE agent=?1 AND revision=?2",
params![agent, revision],
|r| r.get(0),
)
.context("published document unavailable")?;
Ok(json!({"agent":agent,"revision":revision,"sha256":sha256}))
}
pub(super) fn project_publication(
&self,
agent: &str,
revision: u64,
board: Board,
) -> Result<Value> {
let digest = pin(&board).map(str::to_owned);
let mut value = serde_json::to_value(display_board(board))?;
if let Some(digest) = digest {
let body: Option<String> = self.db.query_row("SELECT html FROM dashboard_publications WHERE agent=?1 AND revision=?2 AND sha256=?3",
params![agent,revision,digest], |r| r.get(0)).optional()?;
value["html_sha256"] = digest.into();
if let Some(body) = body {
value["html"] = body.into();
}
}
Ok(value)
}
}