lean_ctx_cloud/
local_docs.rs1use std::path::Path;
11
12use lean_ctx_doc::local::{self, Author, Entry, LocalDocs, Revision};
13use lean_ctx_doc::replica::DocSpace;
14use lean_ctx_doc::write::{EventSpec, field_set as doc_field_set};
17use serde::Serialize;
18use serde_json::{Value, json};
19
20use crate::CloudError;
21
22fn local_err(e: impl std::fmt::Display) -> CloudError {
23 CloudError::Local(e.to_string())
24}
25
26impl From<local::LocalError> for CloudError {
27 fn from(e: local::LocalError) -> Self {
28 local_err(e)
29 }
30}
31
32pub fn store(root: &str) -> Result<LocalDocs, CloudError> {
34 if lean_ctx::core::pathutil::is_broad_or_unsafe_root(Path::new(root)) {
35 return Err(CloudError::Config(format!("{root} is not a project")));
36 }
37 let data = lean_ctx::core::data_dir::lean_ctx_data_dir().map_err(CloudError::Local)?;
38 Ok(LocalDocs::at(data.join("docs").join(
39 lean_ctx::core::project_hash::hash_project_root(root),
40 )))
41}
42
43pub fn is_linked(root: &str) -> Result<bool, String> {
55 let unavailable = |e: &dyn std::fmt::Display| {
56 format!("the LeanCTX Cloud link of this project cannot be read: {e}")
57 };
58 let store = crate::CloudStore::open().map_err(|e| unavailable(&e))?;
59 let path = store
60 .data_dir()
61 .join(lean_ctx::core::vault_map::VAULTS_FILE);
62 let map: crate::vault::VaultMap = match std::fs::read(&path) {
63 Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
64 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
65 Err(e) => return Err(unavailable(&e)),
66 };
67 Ok(map.for_root(root).is_some())
68}
69
70pub fn now() -> String {
72 lean_ctx_time::UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
73}
74
75pub fn read(
79 root: &str,
80 store: &LocalDocs,
81 upto: Option<u64>,
82) -> Result<(Vec<Entry>, DocSpace), CloudError> {
83 let entries = store.entries()?;
84 let space = local::space_of(&entries, upto, &[]);
85 let anchored = space.pages.values().any(|p| {
86 p.page
87 .fields
88 .get("anchors")
89 .and_then(Value::as_array)
90 .is_some_and(|a| !a.is_empty())
91 });
92 if !anchored || upto.is_some() {
93 return Ok((entries, space));
94 }
95 let extra: Vec<EventSpec> = crate::docs::recheck(root, &space);
96 if extra.is_empty() {
97 return Ok((entries, space));
98 }
99 let checked = local::space_of(&entries, None, &extra);
100 Ok((entries, checked))
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
105pub struct SharedTo {
106 pub vault: String,
108 pub page_id: String,
109 pub at: String,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
114pub struct LocalPage {
115 pub id: String,
117 pub slug: String,
118 pub title: String,
119 pub body: String,
121 pub kind: String,
122 pub status: String,
123 pub updated: Option<String>,
124 pub updated_by: Option<Author>,
125 pub shared: Option<SharedTo>,
126}
127
128pub fn shared_of(p: &lean_ctx_doc::replica::PageView) -> Option<SharedTo> {
130 let s = p.page.fields.get("shared")?;
131 Some(SharedTo {
132 vault: s.get("vault")?.as_str()?.to_owned(),
133 page_id: s.get("page_id")?.as_str()?.to_owned(),
134 at: s.get("at")?.as_str()?.to_owned(),
135 })
136}
137
138pub fn pages(root: &str) -> Result<Vec<LocalPage>, CloudError> {
140 let store = store(root)?;
141 let (entries, space) = read(root, &store, None)?;
142 let last = local::last_revisions(&entries);
143 let slug_of = |id: &str| space.pages.get(id).map(|p| p.slug().to_owned());
144 let mut out: Vec<LocalPage> = space
145 .pages
146 .values()
147 .map(|p| {
148 let rev: Option<&Revision> = last.get(&p.page.id);
149 LocalPage {
150 id: p.page.id.clone(),
151 slug: p.slug().to_owned(),
152 title: p.title().to_owned(),
153 body: lean_ctx_doc::links::to_slugs(&p.markdown(), slug_of),
154 kind: p.page.str("type").unwrap_or("reference").to_owned(),
155 status: p.page.str("status").unwrap_or("draft").to_owned(),
156 updated: rev.map(|r| r.at.clone()),
157 updated_by: rev.map(|r| r.author.clone()),
158 shared: shared_of(p),
159 }
160 })
161 .collect();
162 out.sort_by(|a, b| a.slug.cmp(&b.slug));
163 Ok(out)
164}
165
166pub fn mark_shared(
170 root: &str,
171 local_id: &str,
172 vault: &str,
173 vault_page_id: &str,
174 author: &Author,
175) -> Result<(), CloudError> {
176 let store = store(root)?;
177 let at = now();
178 store.commit::<CloudError>(author, &at, "share", |space| {
179 let page = space
180 .pages
181 .get(local_id)
182 .ok_or_else(|| CloudError::Config(format!("no local page {local_id}")))?;
183 Ok(vec![doc_field_set(
184 local_id,
185 "shared",
186 json!({ "vault": vault, "page_id": vault_page_id, "at": at }),
187 &page.page.head,
188 )])
189 })?;
190 Ok(())
191}