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 =
56 |e: &dyn std::fmt::Display| format!("the Cloud link of this project cannot be read: {e}");
57 let store = crate::CloudStore::open().map_err(|e| unavailable(&e))?;
58 let path = store
59 .data_dir()
60 .join(lean_ctx::core::vault_map::VAULTS_FILE);
61 let map: crate::vault::VaultMap = match std::fs::read(&path) {
62 Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| unavailable(&e))?,
63 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
64 Err(e) => return Err(unavailable(&e)),
65 };
66 Ok(map.for_root(root).is_some())
67}
68
69pub fn now() -> String {
71 lean_ctx_time::UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
72}
73
74pub fn read(
78 root: &str,
79 store: &LocalDocs,
80 upto: Option<u64>,
81) -> Result<(Vec<Entry>, DocSpace), CloudError> {
82 let entries = store.entries()?;
83 let space = local::space_of(&entries, upto, &[]);
84 let anchored = space.pages.values().any(|p| {
85 p.page
86 .fields
87 .get("anchors")
88 .and_then(Value::as_array)
89 .is_some_and(|a| !a.is_empty())
90 });
91 if !anchored || upto.is_some() {
92 return Ok((entries, space));
93 }
94 let extra: Vec<EventSpec> = crate::docs::recheck(root, &space);
95 if extra.is_empty() {
96 return Ok((entries, space));
97 }
98 let checked = local::space_of(&entries, None, &extra);
99 Ok((entries, checked))
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
104pub struct SharedTo {
105 pub vault: String,
107 pub page_id: String,
108 pub at: String,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
113pub struct LocalPage {
114 pub id: String,
116 pub slug: String,
117 pub title: String,
118 pub body: String,
120 pub kind: String,
121 pub status: String,
122 pub updated: Option<String>,
123 pub updated_by: Option<Author>,
124 pub shared: Option<SharedTo>,
125}
126
127pub fn shared_of(p: &lean_ctx_doc::replica::PageView) -> Option<SharedTo> {
129 let s = p.page.fields.get("shared")?;
130 Some(SharedTo {
131 vault: s.get("vault")?.as_str()?.to_owned(),
132 page_id: s.get("page_id")?.as_str()?.to_owned(),
133 at: s.get("at")?.as_str()?.to_owned(),
134 })
135}
136
137pub fn pages(root: &str) -> Result<Vec<LocalPage>, CloudError> {
139 let store = store(root)?;
140 let (entries, space) = read(root, &store, None)?;
141 let last = local::last_revisions(&entries);
142 let slug_of = |id: &str| space.pages.get(id).map(|p| p.slug().to_owned());
143 let mut out: Vec<LocalPage> = space
144 .pages
145 .values()
146 .map(|p| {
147 let rev: Option<&Revision> = last.get(&p.page.id);
148 LocalPage {
149 id: p.page.id.clone(),
150 slug: p.slug().to_owned(),
151 title: p.title().to_owned(),
152 body: lean_ctx_doc::links::to_slugs(&p.markdown(), slug_of),
153 kind: p.page.str("type").unwrap_or("reference").to_owned(),
154 status: p.page.str("status").unwrap_or("draft").to_owned(),
155 updated: rev.map(|r| r.at.clone()),
156 updated_by: rev.map(|r| r.author.clone()),
157 shared: shared_of(p),
158 }
159 })
160 .collect();
161 out.sort_by(|a, b| a.slug.cmp(&b.slug));
162 Ok(out)
163}
164
165pub fn mark_shared(
169 root: &str,
170 local_id: &str,
171 vault: &str,
172 vault_page_id: &str,
173 author: &Author,
174) -> Result<(), CloudError> {
175 let store = store(root)?;
176 let at = now();
177 store.commit::<CloudError>(author, &at, "share", |space| {
178 let page = space
179 .pages
180 .get(local_id)
181 .ok_or_else(|| CloudError::Config(format!("no local page {local_id}")))?;
182 Ok(vec![doc_field_set(
183 local_id,
184 "shared",
185 json!({ "vault": vault, "page_id": vault_page_id, "at": at }),
186 &page.page.head,
187 )])
188 })?;
189 Ok(())
190}