communitas-core 0.12.1

Core business logic for Communitas - PQC collaboration with virtual disks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// SPDX-License-Identifier: MIT OR Apache-2.0

// Copyright (c) 2025 Saorsa Labs Limited
//
// Licensed under the AGPL-3.0 license

//! Website Manager - Handles website storage and operations

use super::markdown::render_and_sanitize;
use super::types::{MarkdownPage, WebsiteError, WebsiteMetadata, WebsiteResult};
use crate::crdt_manager::CrdtManager;
use std::sync::Arc;
use yrs::updates::decoder::Decode;
use yrs::{Doc, GetString, Map, ReadTxn, Text, Transact, WriteTxn};

/// Manager for website storage and operations
pub struct WebsiteManager {
    crdt_manager: Arc<CrdtManager>,
}

impl WebsiteManager {
    /// Create a new website manager
    pub fn new(crdt_manager: Arc<CrdtManager>) -> Self {
        Self { crdt_manager }
    }

    /// Validate and sanitize a page path
    fn validate_page_path(path: &str) -> WebsiteResult<String> {
        // Max length check
        if path.len() > 255 {
            return Err(WebsiteError::InvalidPath("Path too long".into()));
        }

        if path.is_empty() {
            return Err(WebsiteError::InvalidPath("Empty path".into()));
        }

        // Split into components
        let parts: Vec<&str> = path.split('/').filter(|c| !c.is_empty()).collect();

        if parts.is_empty() {
            return Err(WebsiteError::InvalidPath("No valid path components".into()));
        }

        let mut components = Vec::new();

        // Validate each component
        for comp in parts {
            // Reject dangerous components
            if comp == "." || comp == ".." {
                return Err(WebsiteError::InvalidPath("Path traversal attempt".into()));
            }

            // Only allow alphanumeric, dash, underscore, dot
            if !comp
                .chars()
                .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.')
            {
                return Err(WebsiteError::InvalidPath(format!(
                    "Invalid characters in: {}",
                    comp
                )));
            }

            // Don't allow components that are just dots (e.g., "...")
            if comp.chars().all(|c| c == '.') {
                return Err(WebsiteError::InvalidPath("Invalid component".into()));
            }

            // Don't allow consecutive dots anywhere
            if comp.contains("..") {
                return Err(WebsiteError::InvalidPath(
                    "Consecutive dots not allowed".into(),
                ));
            }

            components.push(comp);
        }

        Ok(components.join("/"))
    }

    /// Get the document ID for a website page
    fn page_doc_id(four_word_address: &str, path: &str) -> WebsiteResult<String> {
        let safe_path = Self::validate_page_path(path)?;
        Ok(format!("website:{}:page:{}", four_word_address, safe_path))
    }

    /// Get the document ID for website metadata
    fn metadata_doc_id(four_word_address: &str) -> String {
        format!("website:{}:metadata", four_word_address)
    }

    /// Save a markdown page
    pub async fn save_page(
        &self,
        four_word_address: &str,
        page: &MarkdownPage,
    ) -> WebsiteResult<()> {
        let doc_id = Self::page_doc_id(four_word_address, &page.path)?;
        let doc = Doc::new();

        {
            let mut txn = doc.transact_mut();
            let root = txn.get_or_insert_map("root");

            // Store content as Text for collaborative editing
            root.insert(&mut txn, "content", yrs::TextPrelim::new(&page.content));

            // Store metadata
            CrdtManager::set_map_string(&root, &mut txn, "path", &page.path);
            if let Some(ref title) = page.title {
                CrdtManager::set_map_string(&root, &mut txn, "title", title);
            }
            CrdtManager::set_map_i64(&root, &mut txn, "created_at", page.created_at);
            CrdtManager::set_map_i64(&root, &mut txn, "updated_at", page.updated_at);
        }

        self.crdt_manager
            .save_document(&doc_id, "website", four_word_address, &doc)
            .await?;

        Ok(())
    }

    /// Load a markdown page
    pub async fn load_page(
        &self,
        four_word_address: &str,
        path: &str,
    ) -> WebsiteResult<MarkdownPage> {
        let doc_id = Self::page_doc_id(four_word_address, path)?;
        let doc = self
            .crdt_manager
            .load_document(&doc_id)
            .await
            .map_err(|_| WebsiteError::PageNotFound(path.to_string()))?;

        let root = doc.get_or_insert_map("root");
        let txn = doc.transact();

        // Extract content from Text
        let content = if let Some(text_val) = root.get(&txn, "content") {
            if let Ok(text_ref) = yrs::TextRef::try_from(text_val) {
                text_ref.get_string(&txn)
            } else {
                String::new()
            }
        } else {
            String::new()
        };

        let path =
            CrdtManager::get_map_string(&root, &txn, "path").unwrap_or_else(|| path.to_string());
        let title = CrdtManager::get_map_string(&root, &txn, "title");
        let created_at = CrdtManager::get_map_i64(&root, &txn, "created_at").unwrap_or(0);
        let updated_at = CrdtManager::get_map_i64(&root, &txn, "updated_at").unwrap_or(0);

        Ok(MarkdownPage {
            path,
            content,
            title,
            created_at,
            updated_at,
        })
    }

    /// Load a page as a Yrs document for collaborative editing
    pub async fn load_page_doc(&self, four_word_address: &str, path: &str) -> WebsiteResult<Doc> {
        let doc_id = Self::page_doc_id(four_word_address, path)?;
        self.crdt_manager
            .load_document(&doc_id)
            .await
            .map_err(|_| WebsiteError::PageNotFound(path.to_string()))
    }

    /// Append text to a page document (collaborative editing)
    pub fn append_text(&self, doc: &Doc, text: &str) -> WebsiteResult<()> {
        let root = doc.get_or_insert_map("root");
        let mut txn = doc.transact_mut();

        if let Some(content_val) = root.get(&txn, "content")
            && let Ok(content_text) = yrs::TextRef::try_from(content_val)
        {
            let len = content_text.len(&txn);
            content_text.insert(&mut txn, len, text);
            return Ok(());
        }

        Err(WebsiteError::Rendering("No content text found".to_string()))
    }

    /// Insert text at a specific position (collaborative editing)
    pub fn insert_text_at(&self, doc: &Doc, index: u32, text: &str) -> WebsiteResult<()> {
        let root = doc.get_or_insert_map("root");
        let mut txn = doc.transact_mut();

        if let Some(content_val) = root.get(&txn, "content")
            && let Ok(content_text) = yrs::TextRef::try_from(content_val)
        {
            content_text.insert(&mut txn, index, text);
            return Ok(());
        }

        Err(WebsiteError::Rendering("No content text found".to_string()))
    }

    /// Extract content from a document
    pub fn extract_content(&self, doc: &Doc) -> WebsiteResult<String> {
        let root = doc.get_or_insert_map("root");
        let txn = doc.transact();

        if let Some(content_val) = root.get(&txn, "content")
            && let Ok(content_text) = yrs::TextRef::try_from(content_val)
        {
            return Ok(content_text.get_string(&txn));
        }

        Err(WebsiteError::Rendering("No content found".to_string()))
    }

    /// Merge multiple page documents (collaborative editing)
    pub async fn merge_page_docs(&self, mut docs: Vec<Doc>) -> WebsiteResult<Doc> {
        if docs.is_empty() {
            return Err(WebsiteError::Rendering("No documents to merge".to_string()));
        }

        // Take the first document as base
        let base = docs.remove(0);

        // Apply updates from all other documents to the base
        for doc in docs {
            let update_bytes = doc
                .transact()
                .encode_state_as_update_v1(&yrs::StateVector::default());

            let update = yrs::Update::decode_v1(&update_bytes)
                .map_err(|e| WebsiteError::Rendering(format!("Failed to decode update: {}", e)))?;

            let mut txn = base.transact_mut();
            txn.apply_update(update);
        }

        Ok(base)
    }

    /// List all pages for a website
    pub async fn list_pages(&self, four_word_address: &str) -> WebsiteResult<Vec<String>> {
        let pages = self.crdt_manager.list_documents("website").await?;

        // Filter pages that belong to this address
        let prefix = format!("website:{}:page:", four_word_address);
        let mut result = Vec::new();

        for doc_id in pages {
            if doc_id.starts_with(&prefix) {
                // Extract path from doc_id
                if let Some(path) = doc_id.strip_prefix(&prefix) {
                    result.push(path.to_string());
                }
            }
        }

        Ok(result)
    }

    /// Delete a page
    pub async fn delete_page(&self, four_word_address: &str, path: &str) -> WebsiteResult<()> {
        let doc_id = Self::page_doc_id(four_word_address, path)?;
        self.crdt_manager.delete_document(&doc_id).await?;
        Ok(())
    }

    /// Save website metadata
    pub async fn save_metadata(
        &self,
        four_word_address: &str,
        metadata: &WebsiteMetadata,
    ) -> WebsiteResult<()> {
        let doc_id = Self::metadata_doc_id(four_word_address);
        let doc = Doc::new();

        {
            let mut txn = doc.transact_mut();
            let root = txn.get_or_insert_map("root");

            CrdtManager::set_map_string(
                &root,
                &mut txn,
                "four_word_address",
                &metadata.four_word_address,
            );
            CrdtManager::set_map_string(&root, &mut txn, "title", &metadata.title);

            if let Some(ref desc) = metadata.description {
                CrdtManager::set_map_string(&root, &mut txn, "description", desc);
            }

            CrdtManager::set_map_string(&root, &mut txn, "home_page", &metadata.home_page);
            CrdtManager::set_map_bool(&root, &mut txn, "published", metadata.published);

            if let Some(published_at) = metadata.published_at {
                CrdtManager::set_map_i64(&root, &mut txn, "published_at", published_at);
            }

            CrdtManager::set_map_i64(&root, &mut txn, "created_at", metadata.created_at);
            CrdtManager::set_map_i64(&root, &mut txn, "updated_at", metadata.updated_at);
        }

        self.crdt_manager
            .save_document(&doc_id, "website", four_word_address, &doc)
            .await?;

        Ok(())
    }

    /// Get website metadata
    pub async fn get_metadata(&self, four_word_address: &str) -> WebsiteResult<WebsiteMetadata> {
        let doc_id = Self::metadata_doc_id(four_word_address);
        let doc = self
            .crdt_manager
            .load_document(&doc_id)
            .await
            .map_err(|_| WebsiteError::WebsiteNotFound(four_word_address.to_string()))?;

        let root = doc.get_or_insert_map("root");
        let txn = doc.transact();

        let four_word_address = CrdtManager::get_map_string(&root, &txn, "four_word_address")
            .unwrap_or_else(|| four_word_address.to_string());
        let title = CrdtManager::get_map_string(&root, &txn, "title").unwrap_or_default();
        let description = CrdtManager::get_map_string(&root, &txn, "description");
        let home_page = CrdtManager::get_map_string(&root, &txn, "home_page")
            .unwrap_or_else(|| "home.md".to_string());
        let published = CrdtManager::get_map_bool(&root, &txn, "published").unwrap_or(false);
        let published_at = CrdtManager::get_map_i64(&root, &txn, "published_at");
        let created_at = CrdtManager::get_map_i64(&root, &txn, "created_at").unwrap_or(0);
        let updated_at = CrdtManager::get_map_i64(&root, &txn, "updated_at").unwrap_or(0);

        Ok(WebsiteMetadata {
            four_word_address,
            title,
            description,
            home_page,
            published,
            published_at,
            created_at,
            updated_at,
        })
    }

    /// Publish a website
    pub async fn publish(&self, four_word_address: &str, _publisher_id: &str) -> WebsiteResult<()> {
        let mut metadata = self
            .get_metadata(four_word_address)
            .await
            .unwrap_or_else(|_| WebsiteMetadata {
                four_word_address: four_word_address.to_string(),
                title: four_word_address.to_string(),
                ..Default::default()
            });

        metadata.published = true;
        metadata.published_at = Some(chrono::Utc::now().timestamp());
        metadata.updated_at = chrono::Utc::now().timestamp();

        self.save_metadata(four_word_address, &metadata).await?;
        Ok(())
    }

    /// Unpublish a website
    pub async fn unpublish(&self, four_word_address: &str) -> WebsiteResult<()> {
        let mut metadata = self.get_metadata(four_word_address).await?;

        metadata.published = false;
        metadata.updated_at = chrono::Utc::now().timestamp();

        self.save_metadata(four_word_address, &metadata).await?;
        Ok(())
    }

    /// Check if a website is published
    pub async fn is_published(&self, four_word_address: &str) -> WebsiteResult<bool> {
        match self.get_metadata(four_word_address).await {
            Ok(metadata) => Ok(metadata.published),
            Err(_) => Ok(false),
        }
    }

    /// Resolve a 4-word address to a page
    pub async fn resolve_address(
        &self,
        four_word_address: &str,
        path: &str,
    ) -> WebsiteResult<MarkdownPage> {
        self.load_page(four_word_address, path).await
    }

    /// Render a page to HTML
    pub async fn render_to_html(
        &self,
        four_word_address: &str,
        path: &str,
    ) -> WebsiteResult<String> {
        let page = self.load_page(four_word_address, path).await?;
        Ok(render_and_sanitize(&page.content))
    }
}