use std::path::Path;
use lean_ctx_doc::local::{self, Author, Entry, LocalDocs, Revision};
use lean_ctx_doc::replica::DocSpace;
use lean_ctx_doc::write::{EventSpec, field_set as doc_field_set};
use serde::Serialize;
use serde_json::{Value, json};
use crate::CloudError;
fn local_err(e: impl std::fmt::Display) -> CloudError {
CloudError::Local(e.to_string())
}
impl From<local::LocalError> for CloudError {
fn from(e: local::LocalError) -> Self {
local_err(e)
}
}
pub fn store(root: &str) -> Result<LocalDocs, CloudError> {
if lean_ctx::core::pathutil::is_broad_or_unsafe_root(Path::new(root)) {
return Err(CloudError::Config(format!("{root} is not a project")));
}
let data = lean_ctx::core::data_dir::lean_ctx_data_dir().map_err(CloudError::Local)?;
Ok(LocalDocs::at(data.join("docs").join(
lean_ctx::core::project_hash::hash_project_root(root),
)))
}
pub fn is_linked(root: &str) -> Result<bool, String> {
let unavailable = |e: &dyn std::fmt::Display| {
format!("the LeanCTX Cloud link of this project cannot be read: {e}")
};
let store = crate::CloudStore::open().map_err(|e| unavailable(&e))?;
let path = store
.data_dir()
.join(lean_ctx::core::vault_map::VAULTS_FILE);
let map: crate::vault::VaultMap = match std::fs::read(&path) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(unavailable(&e)),
};
Ok(map.for_root(root).is_some())
}
pub fn now() -> String {
lean_ctx_time::UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
}
pub fn read(
root: &str,
store: &LocalDocs,
upto: Option<u64>,
) -> Result<(Vec<Entry>, DocSpace), CloudError> {
let entries = store.entries()?;
let space = local::space_of(&entries, upto, &[]);
let anchored = space.pages.values().any(|p| {
p.page
.fields
.get("anchors")
.and_then(Value::as_array)
.is_some_and(|a| !a.is_empty())
});
if !anchored || upto.is_some() {
return Ok((entries, space));
}
let extra: Vec<EventSpec> = crate::docs::recheck(root, &space);
if extra.is_empty() {
return Ok((entries, space));
}
let checked = local::space_of(&entries, None, &extra);
Ok((entries, checked))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SharedTo {
pub vault: String,
pub page_id: String,
pub at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LocalPage {
pub id: String,
pub slug: String,
pub title: String,
pub body: String,
pub kind: String,
pub status: String,
pub updated: Option<String>,
pub updated_by: Option<Author>,
pub shared: Option<SharedTo>,
}
pub fn shared_of(p: &lean_ctx_doc::replica::PageView) -> Option<SharedTo> {
let s = p.page.fields.get("shared")?;
Some(SharedTo {
vault: s.get("vault")?.as_str()?.to_owned(),
page_id: s.get("page_id")?.as_str()?.to_owned(),
at: s.get("at")?.as_str()?.to_owned(),
})
}
pub fn pages(root: &str) -> Result<Vec<LocalPage>, CloudError> {
let store = store(root)?;
let (entries, space) = read(root, &store, None)?;
let last = local::last_revisions(&entries);
let slug_of = |id: &str| space.pages.get(id).map(|p| p.slug().to_owned());
let mut out: Vec<LocalPage> = space
.pages
.values()
.map(|p| {
let rev: Option<&Revision> = last.get(&p.page.id);
LocalPage {
id: p.page.id.clone(),
slug: p.slug().to_owned(),
title: p.title().to_owned(),
body: lean_ctx_doc::links::to_slugs(&p.markdown(), slug_of),
kind: p.page.str("type").unwrap_or("reference").to_owned(),
status: p.page.str("status").unwrap_or("draft").to_owned(),
updated: rev.map(|r| r.at.clone()),
updated_by: rev.map(|r| r.author.clone()),
shared: shared_of(p),
}
})
.collect();
out.sort_by(|a, b| a.slug.cmp(&b.slug));
Ok(out)
}
pub fn mark_shared(
root: &str,
local_id: &str,
vault: &str,
vault_page_id: &str,
author: &Author,
) -> Result<(), CloudError> {
let store = store(root)?;
let at = now();
store.commit::<CloudError>(author, &at, "share", |space| {
let page = space
.pages
.get(local_id)
.ok_or_else(|| CloudError::Config(format!("no local page {local_id}")))?;
Ok(vec![doc_field_set(
local_id,
"shared",
json!({ "vault": vault, "page_id": vault_page_id, "at": at }),
&page.page.head,
)])
})?;
Ok(())
}