Files
hnsau/nextcloud.py
nathanwoodburn 8fc9bcdef7
Build Docker / Build Image (push) Successful in 56s
feat: Update OG data
2026-10-27 14:36:06 +11:00

1513 lines
65 KiB
Python

import io
import json
import os
import re
import threading
import time
import xml.etree.ElementTree as ET
import zipfile
from datetime import datetime, timezone
from email.utils import format_datetime
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import unquote, urlparse
from xml.sax.saxutils import escape
import dotenv
import markdown
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# Ensure .env variables are available
dotenv.load_dotenv()
# Default configuration
DEFAULT_NEXTCLOUD_URL = "https://cloud.woodburn.au"
DEFAULT_SHARE_TOKEN = "DMqkYbZJMwnGyWy"
DEFAULT_CACHE_TTL = 300 # seconds (5 minutes)
CONNECT_TIMEOUT = 5.0 # seconds to establish TCP/TLS connection
READ_TIMEOUT = 10.0 # seconds to read response payload
HTTP_TIMEOUT = (CONNECT_TIMEOUT, READ_TIMEOUT)
MEDIA_CONNECT_TIMEOUT = 5.0
MEDIA_READ_TIMEOUT = 45.0
MEDIA_HTTP_TIMEOUT = (MEDIA_CONNECT_TIMEOUT, MEDIA_READ_TIMEOUT)
DISK_CACHE_PATH = os.path.join(os.path.dirname(__file__), ".nextcloud_cache.zip")
MEDIA_DIR = os.path.join(os.path.dirname(__file__), "data", "ownthedot", "media")
MEDIA_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg", ".pdf", ".ico"}
class NextcloudConnectionError(Exception):
"""Raised when communication with Nextcloud fails or data cannot be loaded."""
pass
def _create_http_session() -> requests.Session:
"""Creates a requests Session with robust pooling and retries."""
session = requests.Session()
adapter = HTTPAdapter(
pool_connections=10,
pool_maxsize=20,
max_retries=Retry(
total=2,
backoff_factor=0.5,
status_forcelist=[500, 502, 503, 504],
raise_on_status=False,
),
)
session.mount("https://", adapter)
session.mount("http://", adapter)
session.headers.update({
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) OwnTheDot-Server/1.0",
"Accept": "*/*",
})
return session
class NextcloudProvider:
"""
Manages fetching, parsing, and caching content exclusively from Nextcloud.
Uses non-blocking Stale-While-Revalidate, persistent disk caching, and connection
pooling so incoming user connections never hang, drop, or fail on rate limits.
"""
def __init__(self):
self._cache: Dict[str, Any] = {}
self._cache_time: Dict[str, float] = {}
self._last_error: Optional[str] = None
self._last_sync_time: Optional[float] = None
self._sync_lock = threading.Lock()
self._is_syncing = False
self._file_etags: Dict[str, str] = {}
self._session = _create_http_session()
self._media_cache: Dict[str, bytes] = {}
# Seed initial cache: load from local content directory if present, else disk cache
config = self.get_config()
if config.get("content_dir") and os.path.isdir(config["content_dir"]):
self._do_sync_from_nextcloud()
else:
self._seed_initial_disk_cache()
self._load_from_disk_cache()
def _seed_initial_disk_cache(self):
"""Seeds the initial .nextcloud_cache.zip from data/ownthedot if not present."""
if os.path.isfile(DISK_CACHE_PATH):
return
bundled_dir = os.path.join(os.path.dirname(__file__), "data", "ownthedot")
if os.path.isdir(bundled_dir):
try:
raw_files: Dict[str, bytes] = {}
for root, _, files in os.walk(bundled_dir):
for file in files:
ext = os.path.splitext(file)[1].lower()
if ext in MEDIA_EXTENSIONS:
continue
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, bundled_dir)
if rel_path.startswith("media" + os.sep) or rel_path.startswith("media/"):
continue
with open(full_path, "rb") as f:
raw_files[rel_path] = f.read()
if raw_files:
self._save_to_disk_cache(raw_files)
except Exception as e:
print(f"[Nextcloud] Failed to seed initial disk cache: {e}", flush=True)
def _save_to_disk_cache(self, raw_files: Dict[str, bytes]):
"""Persists raw files to disk archive as a resilient backup."""
if not raw_files or "site.json" not in raw_files:
return
try:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
for fname, data in raw_files.items():
ext = os.path.splitext(fname)[1].lower()
if ext in MEDIA_EXTENSIONS or fname.startswith("media/") or fname.startswith("media" + os.sep):
continue
if isinstance(data, (bytes, bytearray)):
zf.writestr(fname, data)
with open(DISK_CACHE_PATH, "wb") as f:
f.write(buf.getvalue())
except Exception as e:
print(f"[Nextcloud] Failed to save disk cache: {e}", flush=True)
def _load_from_disk_cache(self) -> bool:
"""Loads cached Nextcloud files from disk if available."""
if not os.path.isfile(DISK_CACHE_PATH):
return False
try:
with open(DISK_CACHE_PATH, "rb") as f:
zf = zipfile.ZipFile(io.BytesIO(f.read()))
raw_files: Dict[str, bytes] = {}
for entry in zf.infolist():
if not entry.is_dir():
raw_files[entry.filename] = zf.read(entry.filename)
if raw_files:
self._cache["raw_files"] = raw_files
self._last_sync_time = datetime.now(timezone.utc).timestamp()
return True
except Exception as e:
print(f"[Nextcloud] Failed to read disk cache: {e}", flush=True)
return False
def get_config(self) -> Dict[str, Any]:
"""Returns the current Nextcloud configuration from environment."""
nc_url = os.getenv("NEXTCLOUD_URL", DEFAULT_NEXTCLOUD_URL).rstrip("/")
share_url = os.getenv("NEXTCLOUD_SHARE_URL", "")
share_token = os.getenv("NEXTCLOUD_SHARE_TOKEN", "")
content_dir = os.getenv("OWNTHEDOT_CONTENT_DIR", "").strip()
if not content_dir:
base_mount = os.getenv("BASE_DIR", "/mnt")
candidate_mount = os.path.join(base_mount, "ownthedot")
if os.path.isdir(candidate_mount) and os.path.isfile(os.path.join(candidate_mount, "site.json")):
content_dir = candidate_mount
elif os.path.isdir("/mnt/ownthedot") and os.path.isfile("/mnt/ownthedot/site.json"):
content_dir = "/mnt/ownthedot"
local_only = os.getenv("OWNTHEDOT_LOCAL_ONLY", "").lower() in ("true", "1", "yes")
nc_enabled_env = os.getenv("NEXTCLOUD_ENABLED", "").lower()
if nc_enabled_env in ("false", "0", "no", "off"):
local_only = True
# When a local content directory is available, default to local-only (no outbound API calls)
force_remote = os.getenv("NEXTCLOUD_FORCE_REMOTE", "").lower() in ("true", "1", "yes")
if content_dir and not force_remote:
local_only = True
nc_url = os.getenv("NEXTCLOUD_URL", DEFAULT_NEXTCLOUD_URL).rstrip("/")
share_url = os.getenv("NEXTCLOUD_SHARE_URL", "")
share_token = os.getenv("NEXTCLOUD_SHARE_TOKEN", "")
# Default to standard share token only if NOT in local-only mode
if not local_only and not share_url and not share_token and not os.getenv("NEXTCLOUD_USER"):
share_token = DEFAULT_SHARE_TOKEN
# Extract token if full share URL is provided
if share_url and not share_token:
if "/s/" in share_url:
share_token = share_url.split("/s/")[-1].split("/")[0].split("?")[0]
parsed = urlparse(share_url)
if parsed.scheme and parsed.netloc:
nc_url = f"{parsed.scheme}://{parsed.netloc}"
if share_token and (share_token.startswith("http://") or share_token.startswith("https://")):
if "/s/" in share_token:
parsed = urlparse(share_token)
if parsed.scheme and parsed.netloc:
nc_url = f"{parsed.scheme}://{parsed.netloc}"
share_token = share_token.split("/s/")[-1].split("/")[0].split("?")[0]
share_password = os.getenv("NEXTCLOUD_SHARE_PASSWORD", "")
nc_user = os.getenv("NEXTCLOUD_USER", "")
nc_password = os.getenv("NEXTCLOUD_PASSWORD", "")
nc_path = os.getenv("NEXTCLOUD_PATH", "OwnTheDot").strip("/")
cache_ttl = int(os.getenv("NEXTCLOUD_CACHE_TTL", DEFAULT_CACHE_TTL))
return {
"nc_url": nc_url,
"share_token": share_token if not local_only else "",
"share_password": share_password,
"nc_user": nc_user if not local_only else "",
"nc_password": nc_password if not local_only else "",
"nc_path": nc_path,
"cache_ttl": cache_ttl,
"content_dir": content_dir,
"local_only": local_only,
}
def get_source_info(self) -> Dict[str, Any]:
"""Returns details on the configured Nextcloud source."""
config = self.get_config()
if config.get("content_dir") and os.path.isdir(config["content_dir"]):
return {
"source_type": "local_mirror",
"source_name": "Local Directory Mirror (rclone / volume)",
"location": config["content_dir"],
"is_remote": False,
"last_error": None,
}
if config["share_token"]:
return {
"source_type": "nextcloud_share",
"source_name": "Nextcloud Public Share",
"location": f"{config['nc_url']}/s/{config['share_token']}",
"share_token": config["share_token"][:4] + "***" if len(config["share_token"]) > 4 else "***",
"is_remote": True,
"last_error": self._last_error,
}
elif config["nc_user"] and config["nc_password"]:
return {
"source_type": "nextcloud_webdav_auth",
"source_name": "Nextcloud WebDAV (Authenticated)",
"location": f"{config['nc_url']}/remote.php/dav/files/{config['nc_user']}/{config['nc_path']}",
"user": config["nc_user"],
"path": config["nc_path"],
"is_remote": True,
"last_error": self._last_error,
}
else:
return {
"source_type": "unconfigured",
"source_name": "Nextcloud Not Configured",
"location": None,
"is_remote": True,
"last_error": "NEXTCLOUD_SHARE_TOKEN or NEXTCLOUD_USER/NEXTCLOUD_PASSWORD is required in .env",
}
def clear_cache(self, clear_disk: bool = False):
"""Clears all cached content and sync state."""
self._cache.clear()
self._file_etags.clear()
self._cache_time.clear()
self._last_sync_time = None
self._last_error = None
if clear_disk and os.path.isfile(DISK_CACHE_PATH):
try:
os.remove(DISK_CACHE_PATH)
except Exception:
pass
def _is_cache_valid(self, key: str, ttl: int) -> bool:
"""Checks if a cache entry is still fresh."""
now = datetime.now(timezone.utc).timestamp()
return key in self._cache and (now - self._cache_time.get(key, 0)) < ttl
def _set_cache(self, key: str, value: Any):
"""Stores a value in the memory cache."""
self._cache[key] = value
self._cache_time[key] = datetime.now(timezone.utc).timestamp()
# region Remote Nextcloud Sync (Non-Blocking & Single In-Flight)
def _trigger_background_sync(self):
"""Spawns an asynchronous background thread to refresh cache without blocking user traffic."""
if self._is_syncing:
return
thread = threading.Thread(target=self._background_sync_worker, daemon=True)
thread.start()
def _background_sync_worker(self):
"""Background worker that refreshes raw files and re-parses cached resources."""
try:
self._do_sync_from_nextcloud()
# Repopulate structured cache keys in background
self.get_site_config(force_refresh=True)
self.get_home_data(force_refresh=True)
self.get_about_content(force_refresh=True)
self.get_articles_page_data(force_refresh=True)
self.get_articles(force_refresh=True)
except Exception as e:
self._last_error = str(e)
print(f"[Nextcloud] Background sync warning: {e}", flush=True)
def _sync_from_nextcloud(self, force: bool = False):
"""
Ensures Nextcloud files are available in memory.
If cache already exists and has expired, serves stale immediately and updates in background.
"""
config = self.get_config()
ttl = config["cache_ttl"]
now = datetime.now(timezone.utc).timestamp()
# 1. Fresh cache hit -> return immediately (<1ms)
if not force and self._last_sync_time and (now - self._last_sync_time) < ttl and "raw_files" in self._cache:
return
# 2. Stale-While-Revalidate: If we have existing data, return immediately and sync in background
if not force and "raw_files" in self._cache and self._cache["raw_files"]:
self._trigger_background_sync()
return
# 3. Cold start or forced refresh -> synchronous fetch with lock
self._do_sync_from_nextcloud()
def _do_sync_from_nextcloud(self):
"""
Executes single in-flight network synchronization to Nextcloud.
"""
# Ensure only one thread at a time performs the network call
if not self._sync_lock.acquire(blocking=True, timeout=10.0):
if "raw_files" in self._cache and self._cache["raw_files"]:
return
raise NextcloudConnectionError("Nextcloud sync lock timeout")
try:
self._is_syncing = True
config = self.get_config()
now = datetime.now(timezone.utc).timestamp()
share_token = config["share_token"]
nc_url = config["nc_url"]
nc_user = config["nc_user"]
nc_pwd = config["nc_password"]
nc_path = config["nc_path"]
raw_files: Dict[str, bytes] = {}
# Mode 0: Local Directory Mirror (from rclone volume or OWNTHEDOT_CONTENT_DIR)
content_dir = config.get("content_dir")
if content_dir and os.path.isdir(content_dir):
for root, _, files in os.walk(content_dir):
for file in files:
ext = os.path.splitext(file)[1].lower()
if ext in MEDIA_EXTENSIONS:
continue
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, content_dir)
if rel_path.startswith("media" + os.sep) or rel_path.startswith("media/"):
continue
if rel_path.startswith(".") or "/." in rel_path:
continue
try:
with open(full_path, "rb") as f:
raw_files[rel_path] = f.read()
except Exception:
pass
if raw_files and ("site.json" in raw_files or "home.md" in raw_files):
self._cache["raw_files"] = raw_files
self._last_sync_time = now
self._last_error = None
self._save_to_disk_cache(raw_files)
return
elif config.get("local_only"):
err_msg = f"Local mirror mode enabled but site.json or home.md not found in {content_dir}"
self._last_error = err_msg
raise NextcloudConnectionError(err_msg)
if config.get("local_only"):
err_msg = f"Local mirror mode enabled but content directory is missing or invalid: {content_dir}"
self._last_error = err_msg
raise NextcloudConnectionError(err_msg)
# Mode 1: Nextcloud Public Share
if share_token:
# 1A. Fast incremental sync via public WebDAV (skips unchanged files and heavy media)
dav_url = f"{nc_url}/public.php/dav/files/{share_token}/"
is_mocked = type(getattr(self._session, "get", None)).__name__ == "MagicMock"
if not is_mocked:
try:
headers = {"Depth": "infinity", "Content-Type": "application/xml"}
body = """<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:">
<d:prop><d:getlastmodified/><d:resourcetype/><d:getetag/></d:prop>
</d:propfind>"""
pr = self._session.request("PROPFIND", dav_url, data=body, headers=headers, timeout=HTTP_TIMEOUT)
if pr.status_code in (200, 207):
root = ET.fromstring(pr.content)
ns = {"d": "DAV:"}
base_path = f"/public.php/dav/files/{share_token}".rstrip("/")
files_to_fetch = []
media_to_fetch = []
current_etags = {}
raw_files = dict(self._cache.get("raw_files", {}))
for resp in root.findall("d:response", ns):
href_el = resp.find("d:href", ns)
if href_el is None or not href_el.text:
continue
href = unquote(href_el.text).rstrip("/")
resourcetype = resp.find(".//d:resourcetype", ns)
is_dir = resourcetype is not None and resourcetype.find("d:collection", ns) is not None
if is_dir:
continue
rel_path = href[len(base_path):].lstrip("/") if href.startswith(base_path) else href.split("/")[-1]
etag_el = resp.find(".//d:getetag", ns)
etag = etag_el.text.strip('"') if (etag_el is not None and etag_el.text) else ""
current_etags[rel_path] = etag
# Only sync markdown and configuration files in batch
if rel_path.lower().endswith((".md", ".json", ".yml", ".yaml", ".txt")):
if rel_path not in raw_files or self._file_etags.get(rel_path) != etag:
files_to_fetch.append((rel_path, f"{nc_url}{href}"))
elif any(rel_path.lower().endswith(ext) for ext in MEDIA_EXTENSIONS):
base_fn = os.path.basename(rel_path)
if not os.path.isfile(os.path.join(MEDIA_DIR, base_fn)):
media_to_fetch.append((base_fn, f"{nc_url}{href}"))
if files_to_fetch:
from concurrent.futures import ThreadPoolExecutor
def _fetch_dav_share_file(item):
r_path, r_url = item
try:
fr = self._session.get(r_url, timeout=HTTP_TIMEOUT)
if fr.status_code == 200:
return r_path, fr.content
except Exception:
pass
return r_path, None
workers = min(12, len(files_to_fetch))
with ThreadPoolExecutor(max_workers=workers) as ex:
for r_path, r_content in ex.map(_fetch_dav_share_file, files_to_fetch):
if r_content is not None:
raw_files[r_path] = r_content
# Remove deleted markdown/json files
for old_k in list(raw_files.keys()):
if old_k.lower().endswith((".md", ".json", ".yml", ".yaml", ".txt")) and old_k not in current_etags:
raw_files.pop(old_k, None)
self._file_etags = current_etags
self._cache["raw_files"] = raw_files
self._last_sync_time = now
self._last_error = None
self._save_to_disk_cache(raw_files)
if media_to_fetch:
threading.Thread(target=self._background_fetch_media, args=(media_to_fetch, None), daemon=True).start()
return
except Exception:
pass
# 1B. Fallback: Download full public share zip
download_url = f"{nc_url}/s/{share_token}/download"
try:
r = self._session.get(download_url, timeout=HTTP_TIMEOUT)
if r.status_code == 429:
if "raw_files" in self._cache and self._cache["raw_files"]:
print("[Nextcloud] Rate-limited (HTTP 429). Retaining existing memory cache.", flush=True)
self._last_sync_time = now
return
if self._load_from_disk_cache():
print("[Nextcloud] Rate-limited (HTTP 429). Recovered from persistent disk cache.", flush=True)
self._last_sync_time = now
return
time.sleep(2)
r = self._session.get(download_url, timeout=HTTP_TIMEOUT)
if r.status_code != 200:
if "raw_files" in self._cache and self._cache["raw_files"]:
print(f"[Nextcloud] HTTP {r.status_code}. Retaining existing memory cache.", flush=True)
self._last_sync_time = now
return
if self._load_from_disk_cache():
print(f"[Nextcloud] HTTP {r.status_code}. Recovered from persistent disk cache.", flush=True)
self._last_sync_time = now
return
err_msg = f"Nextcloud returned HTTP {r.status_code} for share {share_token}"
self._last_error = err_msg
raise NextcloudConnectionError(err_msg)
# Unpack zip archive in-memory
try:
zf = zipfile.ZipFile(io.BytesIO(r.content))
for entry in zf.infolist():
if not entry.is_dir():
filename = entry.filename.strip("/")
parts = filename.split("/", 1)
rel_path = parts[1] if len(parts) > 1 else parts[0]
raw_files[rel_path.lstrip("/")] = zf.read(entry.filename)
except zipfile.BadZipFile:
# Single file download fallback
raw_files["downloaded_file"] = r.content
self._cache["raw_files"] = raw_files
self._last_sync_time = now
self._last_error = None
self._save_to_disk_cache(raw_files)
return
except requests.RequestException as e:
if "raw_files" in self._cache and self._cache["raw_files"]:
print(f"[Nextcloud] Connection error ({e}). Retaining existing memory cache.", flush=True)
self._last_sync_time = now
return
if self._load_from_disk_cache():
print(f"[Nextcloud] Connection error ({e}). Recovered from persistent disk cache.", flush=True)
self._last_sync_time = now
return
err_msg = f"Failed to connect to Nextcloud instance at {nc_url}: {e}"
self._last_error = err_msg
raise NextcloudConnectionError(err_msg)
# Mode 2: Authenticated WebDAV
elif nc_user and nc_pwd:
try:
folder_url = f"{nc_url}/remote.php/dav/files/{nc_user}/{nc_path}/"
headers = {"Depth": "infinity", "Content-Type": "application/xml"}
body = """<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:">
<d:prop><d:getlastmodified/><d:resourcetype/><d:getetag/></d:prop>
</d:propfind>"""
r = self._session.request("PROPFIND", folder_url, data=body, headers=headers, auth=(nc_user, nc_pwd), timeout=HTTP_TIMEOUT)
if r.status_code not in (200, 207):
# Try Depth 1 if server restricts infinity
headers["Depth"] = "1"
r = self._session.request("PROPFIND", folder_url, data=body, headers=headers, auth=(nc_user, nc_pwd), timeout=HTTP_TIMEOUT)
if r.status_code not in (200, 207):
if "raw_files" in self._cache and self._cache["raw_files"]:
self._last_sync_time = now
return
if self._load_from_disk_cache():
self._last_sync_time = now
return
err_msg = f"Nextcloud WebDAV returned HTTP {r.status_code}"
self._last_error = err_msg
raise NextcloudConnectionError(err_msg)
root = ET.fromstring(r.content)
ns = {"d": "DAV:"}
base_path = f"/remote.php/dav/files/{nc_user}/{nc_path}".rstrip("/")
files_to_fetch = []
media_to_fetch = []
current_etags = {}
raw_files = dict(self._cache.get("raw_files", {}))
for resp in root.findall("d:response", ns):
href_el = resp.find("d:href", ns)
if href_el is None or not href_el.text:
continue
href = unquote(href_el.text).rstrip("/")
resourcetype = resp.find(".//d:resourcetype", ns)
is_dir = resourcetype is not None and resourcetype.find("d:collection", ns) is not None
if is_dir:
continue
rel_path = href[len(base_path):].lstrip("/") if href.startswith(base_path) else href.split("/")[-1]
etag_el = resp.find(".//d:getetag", ns)
etag = etag_el.text.strip('"') if (etag_el is not None and etag_el.text) else ""
current_etags[rel_path] = etag
# Only batch-fetch document files; media files are fetched in background or on-demand
if rel_path.lower().endswith((".md", ".json", ".yml", ".yaml", ".txt")):
if rel_path not in raw_files or self._file_etags.get(rel_path) != etag:
files_to_fetch.append((rel_path, f"{nc_url}{href}"))
elif any(rel_path.lower().endswith(ext) for ext in MEDIA_EXTENSIONS):
base_fn = os.path.basename(rel_path)
if not os.path.isfile(os.path.join(MEDIA_DIR, base_fn)):
media_to_fetch.append((base_fn, f"{nc_url}{href}"))
if files_to_fetch:
from concurrent.futures import ThreadPoolExecutor
def _fetch_dav_file(item):
rel, url = item
try:
fr = self._session.get(url, auth=(nc_user, nc_pwd), timeout=HTTP_TIMEOUT)
if fr.status_code == 200:
return rel, fr.content
except Exception:
pass
return rel, None
workers = min(12, len(files_to_fetch))
with ThreadPoolExecutor(max_workers=workers) as ex:
for rel, content in ex.map(_fetch_dav_file, files_to_fetch):
if content is not None:
raw_files[rel] = content
# Remove deleted markdown/json files
for old_k in list(raw_files.keys()):
if old_k.lower().endswith((".md", ".json", ".yml", ".yaml", ".txt")) and old_k not in current_etags:
raw_files.pop(old_k, None)
self._file_etags = current_etags
self._cache["raw_files"] = raw_files
self._last_sync_time = now
self._last_error = None
self._save_to_disk_cache(raw_files)
if media_to_fetch:
threading.Thread(target=self._background_fetch_media, args=(media_to_fetch, (nc_user, nc_pwd)), daemon=True).start()
return
except Exception as e:
if "raw_files" in self._cache and self._cache["raw_files"]:
print(f"[Nextcloud WebDAV] Warning ({e}). Retaining existing memory cache.", flush=True)
self._last_sync_time = now
return
if self._load_from_disk_cache():
print(f"[Nextcloud WebDAV] Warning ({e}). Recovered from persistent disk cache.", flush=True)
self._last_sync_time = now
return
err_msg = f"Failed to fetch files from Nextcloud WebDAV: {e}"
self._last_error = err_msg
raise NextcloudConnectionError(err_msg)
else:
err_msg = "Nextcloud is not configured. Please set NEXTCLOUD_SHARE_TOKEN in .env"
self._last_error = err_msg
raise NextcloudConnectionError(err_msg)
finally:
self._is_syncing = False
self._sync_lock.release()
def _background_fetch_media(self, media_items: List[Tuple[str, str]], auth: Optional[Tuple[str, str]] = None):
"""Fetches newly discovered media files asynchronously and saves to disk cache."""
try:
os.makedirs(MEDIA_DIR, exist_ok=True)
for base_fn, url in media_items:
dest = os.path.join(MEDIA_DIR, base_fn)
if os.path.isfile(dest):
continue
try:
r = self._session.get(url, auth=auth, timeout=MEDIA_HTTP_TIMEOUT)
if r.status_code == 200:
with open(dest, "wb") as f:
f.write(r.content)
with self._sync_lock:
self._media_cache[base_fn] = r.content
self._media_cache[f"media/{base_fn}"] = r.content
except Exception:
pass
except Exception:
pass
def _get_raw_file(self, relative_path: str, force_refresh: bool = False) -> Optional[bytes]:
"""
Retrieves raw file bytes from Nextcloud cache.
"""
clean_rel = relative_path.lstrip("/")
# Only sync if raw_files is completely empty or missing from cache
if "raw_files" not in self._cache or not self._cache["raw_files"]:
self._sync_from_nextcloud(force=force_refresh)
raw_files = self._cache.get("raw_files", {})
# Direct match in existing cache
if clean_rel in raw_files:
return raw_files[clean_rel]
# Case-insensitive match in existing cache
for k, v in raw_files.items():
if k.lower() == clean_rel.lower():
return v
return None
def _fetch_file_content(self, relative_path: str, force_refresh: bool = False) -> Optional[Tuple[str, Optional[datetime]]]:
"""
Fetches UTF-8 string content of a file from Nextcloud.
"""
data = self._get_raw_file(relative_path, force_refresh=force_refresh)
if data is not None:
try:
text = data.decode("utf-8")
return text, datetime.now(timezone.utc)
except UnicodeDecodeError:
pass
return None
def get_media(self, filename: str) -> Optional[Tuple[bytes, str]]:
"""Retrieves raw media (image, asset) bytes and mimetype from local disk or Nextcloud."""
clean_name = filename.lstrip("/")
base_name = os.path.basename(clean_name)
ext = os.path.splitext(clean_name)[1].lower()
mime_types = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".gif": "image/gif",
".svg": "image/svg+xml",
".pdf": "application/pdf",
".txt": "text/plain",
".md": "text/markdown",
".json": "application/json",
".ico": "image/x-icon",
}
mimetype = mime_types.get(ext, "application/octet-stream")
# 1. Check in-memory media cache first
with self._sync_lock:
for k in (clean_name, base_name, f"media/{base_name}"):
if k in self._media_cache:
return self._media_cache[k], mimetype
# 2. Check local disk directories (content_dir, MEDIA_DIR, bundled files, static assets)
assets_rel = clean_name[7:] if clean_name.startswith("assets/") else clean_name
config = self.get_config()
content_dir = config.get("content_dir")
disk_candidates = []
if content_dir and os.path.isdir(content_dir):
disk_candidates.extend([
os.path.join(content_dir, "media", base_name),
os.path.join(content_dir, clean_name),
os.path.join(content_dir, base_name),
])
disk_candidates.extend([
os.path.join(MEDIA_DIR, base_name),
os.path.join(MEDIA_DIR, clean_name),
os.path.join(os.path.dirname(__file__), "data", "ownthedot", clean_name),
os.path.join(os.path.dirname(__file__), "templates", clean_name),
os.path.join(os.path.dirname(__file__), "templates", "assets", assets_rel),
os.path.join(os.path.dirname(__file__), "templates", "assets", "img", base_name),
])
for path in disk_candidates:
if os.path.isfile(path):
try:
with open(path, "rb") as f:
data = f.read()
with self._sync_lock:
self._media_cache[clean_name] = data
self._media_cache[base_name] = data
return data, mimetype
except Exception:
pass
# 3. Check memory cache from raw_files if loaded
for candidate in [
f"media/{base_name}",
clean_name,
base_name,
f"images/{base_name}",
f"assets/{base_name}",
]:
data = self._get_raw_file(candidate)
if data is not None:
with self._sync_lock:
self._media_cache[clean_name] = data
self._media_cache[base_name] = data
return data, mimetype
# 4. On-demand fetch from Nextcloud if not yet cached (bypassed entirely in local mode)
config = self.get_config()
if config.get("local_only"):
return None
share_token = config.get("share_token")
nc_url = config.get("nc_url", DEFAULT_NEXTCLOUD_URL)
nc_user = config.get("nc_user")
nc_pwd = config.get("nc_password")
nc_path = config.get("nc_path", "OwnTheDot")
auth = (nc_user, nc_pwd) if (nc_user and nc_pwd) else None
remote_candidates = [
f"media/{base_name}",
clean_name,
base_name,
f"images/{base_name}",
f"assets/{base_name}",
]
seen = set()
unique_remote = []
for c in remote_candidates:
if c not in seen:
seen.add(c)
unique_remote.append(c)
for candidate in unique_remote:
if nc_user and nc_pwd:
url = f"{nc_url}/remote.php/dav/files/{nc_user}/{nc_path}/{candidate}"
elif share_token:
url = f"{nc_url}/public.php/dav/files/{share_token}/{candidate}"
else:
continue
try:
r = self._session.get(url, auth=auth, timeout=MEDIA_HTTP_TIMEOUT)
if r.status_code == 200:
data = r.content
try:
os.makedirs(MEDIA_DIR, exist_ok=True)
dest = os.path.join(MEDIA_DIR, base_name)
with open(dest, "wb") as f:
f.write(data)
except Exception:
pass
with self._sync_lock:
self._media_cache[clean_name] = data
self._media_cache[base_name] = data
if "raw_files" in self._cache:
self._cache["raw_files"][candidate] = data
return data, mimetype
except Exception:
pass
return None
# endregion
# region Frontmatter & Markdown Processing
@staticmethod
def _parse_scalar(val: str) -> Any:
"""Parses a YAML scalar value into native Python type (bool, int, float, str)."""
val_clean = val.strip()
if (val_clean.startswith('"') and val_clean.endswith('"')) or (val_clean.startswith("'") and val_clean.endswith("'")):
return val_clean[1:-1]
val_lower = val_clean.lower()
if val_lower in ("true", "yes", "on"):
return True
if val_lower in ("false", "no", "off"):
return False
if val_lower in ("null", "none", "~", ""):
return None
try:
if "." in val_clean:
return float(val_clean)
return int(val_clean)
except ValueError:
return val_clean
def _parse_frontmatter(self, content: str) -> Tuple[Dict[str, Any], str]:
"""Parses YAML frontmatter or key-value headers from text."""
meta: Dict[str, Any] = {}
body = content
if content.startswith("---"):
parts = content.split("---", 2)
if len(parts) >= 3:
yaml_block = parts[1]
body = parts[2].strip()
current_list_key = None
current_dict_item = None
for raw_line in yaml_block.strip().split("\n"):
line = raw_line.rstrip()
if not line:
continue
# Handle YAML list of objects or strings
if line.strip().startswith("- "):
list_item_text = line.strip()[2:].strip()
if current_list_key:
if ":" in list_item_text:
sub_k, sub_v = list_item_text.split(":", 1)
sub_k = sub_k.strip().lower()
current_dict_item = {sub_k: self._parse_scalar(sub_v)}
if not isinstance(meta[current_list_key], list):
meta[current_list_key] = []
meta[current_list_key].append(current_dict_item)
else:
if not isinstance(meta[current_list_key], list):
meta[current_list_key] = []
meta[current_list_key].append(self._parse_scalar(list_item_text))
continue
# Handle continuation of object in list
if line.startswith(" ") or line.startswith(" "):
if current_dict_item is not None and ":" in line:
sub_k, sub_v = line.strip().split(":", 1)
sub_k = sub_k.strip().lower()
current_dict_item[sub_k] = self._parse_scalar(sub_v)
continue
# Standard key-value
if ":" in line:
k, v = line.split(":", 1)
k = k.strip().lower()
v_str = v.strip()
current_list_key = None
current_dict_item = None
if not v_str:
current_list_key = k
meta[k] = []
elif v_str.startswith("[") and v_str.endswith("]"):
items = [
self._parse_scalar(x.strip())
for x in v_str[1:-1].split(",")
if x.strip()
]
meta[k] = items
else:
meta[k] = self._parse_scalar(v_str)
return meta, body
def _parse_markdown_file(
self, content: str, default_slug: str, last_mtime: Optional[datetime] = None
) -> Dict[str, Any]:
"""
Parses markdown content, extracts metadata and returns a structured dictionary.
"""
meta, body = self._parse_frontmatter(content)
raw_tags = meta.get("tags", meta.get("tag", meta.get("categories", meta.get("category", []))))
tags_list: List[str] = []
if isinstance(raw_tags, str):
clean_str = raw_tags.strip()
if clean_str.startswith("[") and clean_str.endswith("]"):
clean_str = clean_str[1:-1]
tags_list = [str(t).strip().strip("\"'") for t in clean_str.split(",") if str(t).strip()]
elif isinstance(raw_tags, list):
for item in raw_tags:
if isinstance(item, str):
if "," in item:
tags_list.extend([t.strip().strip("\"'") for t in item.split(",") if t.strip()])
elif item.strip():
tags_list.append(item.strip().strip("\"'"))
elif item is not None:
tags_list.append(str(item).strip())
# Seed data with all frontmatter keys so custom fields are directly accessible
data: Dict[str, Any] = dict(meta)
data.update({
"title": str(meta.get("title", "")),
"date": str(meta.get("date", "")),
"author": str(meta.get("author", "Own The Dot")),
"description": str(meta.get("description", meta.get("summary", meta.get("subtitle", "")))),
"image": str(meta.get("image", meta.get("cover", meta.get("poster", "")))),
"tags": tags_list,
"published": str(meta.get("published", "true")).lower() not in ["false", "0", "no"],
"slug": self._slugify(str(meta.get("slug", default_slug))),
"meta": meta,
})
# Header fallback
if not data["title"]:
for line in body.split("\n"):
line_s = line.strip()
if line_s.startswith("# "):
data["title"] = line_s[2:].strip()
body = body.replace(line, "", 1).strip()
break
if not data["title"]:
clean_name = default_slug.replace("-", " ").replace("_", " ").title()
clean_name = re.sub(r"^\d{4}[\s-]\d{2}[\s-]\d{2}[\s-]?", "", clean_name)
data["title"] = clean_name.strip() or "Untitled"
if not data["date"]:
date_match = re.search(r"(\d{4}-\d{2}-\d{2})", default_slug)
if date_match:
data["date"] = date_match.group(1)
elif last_mtime:
data["date"] = last_mtime.strftime("%Y-%m-%d")
else:
data["date"] = datetime.now(timezone.utc).strftime("%Y-%m-%d")
try:
data["datetime"] = datetime.strptime(data["date"], "%Y-%m-%d").replace(
tzinfo=timezone.utc
)
except Exception:
data["datetime"] = last_mtime or datetime.now(timezone.utc)
data["display_date"] = data["datetime"].strftime("%b %d, %Y")
if not data["description"]:
data["description"] = self._extract_excerpt(body)
data["iso_date"] = data["datetime"].strftime("%Y-%m-%dT%H:%M:%SZ")
data["canonical_url"] = f"https://ownthedot.com/articles/{data['slug']}"
img = data.get("image", "").strip()
if img:
if img.startswith("http://") or img.startswith("https://"):
data["og_image"] = img
elif img.startswith("/"):
data["og_image"] = f"https://ownthedot.com{img}"
else:
data["og_image"] = f"https://ownthedot.com/media/{img}"
else:
data["og_image"] = "https://ownthedot.com/assets/img/campaign/own-the-dot.png"
word_count = len(re.findall(r"\w+", body))
read_minutes = max(1, round(word_count / 200))
data["read_time"] = f"{read_minutes} min read"
data["word_count"] = word_count
data["html_content"] = self._render_markdown(body)
data["raw_markdown"] = content
return data
def _render_markdown(self, md_text: str) -> str:
"""Converts Markdown string to clean, safe, styled HTML."""
extensions = [
"extra",
"nl2br",
"sane_lists",
"fenced_code",
"codehilite",
"tables",
]
html = markdown.markdown(md_text, extensions=extensions)
html = re.sub(
r'<a\s+href="(https?://[^"]+)"',
r'<a href="\1" target="_blank" rel="noopener noreferrer"',
html,
)
return html
def _extract_excerpt(self, text: str, max_chars: int = 180) -> str:
"""Extracts a short plain-text summary from markdown body."""
clean = re.sub(r"```[\s\S]*?```", "", text)
clean = re.sub(r"<[^>]+>", "", clean)
clean = re.sub(r"!\[.*?\]\(.*?\)", "", clean)
clean = re.sub(r"\[(.*?)\]\(.*?\)", r"\1", clean)
clean = re.sub(r"[#*_>`~-]", " ", clean)
lines = [line.strip() for line in clean.split("\n") if line.strip()]
paragraph = " ".join(lines)
paragraph = re.sub(r"\s+", " ", paragraph).strip()
if len(paragraph) > max_chars:
return paragraph[:max_chars].rsplit(" ", 1)[0] + "..."
return paragraph
def _slugify(self, text: str) -> str:
"""Generates a URL-friendly slug from a title or filename."""
text = text.lower().strip()
text = re.sub(r"\.md$", "", text)
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"[\s_-]+", "-", text)
return text.strip("-")
# endregion
# region Public Content API (Exclusively from Nextcloud)
def get_site_config(self, force_refresh: bool = False) -> Dict[str, Any]:
"""
Retrieves global site settings from site.json in Nextcloud.
"""
cache_key = "site_config"
config = self.get_config()
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
file_data = self._fetch_file_content("site.json", force_refresh=force_refresh)
if not file_data:
file_data = self._fetch_file_content("settings.json", force_refresh=force_refresh)
if not file_data:
if cache_key in self._cache:
return self._cache[cache_key]
raise NextcloudConnectionError("Failed to load site.json from Nextcloud.")
content, _ = file_data
try:
site_data = json.loads(content)
if not isinstance(site_data, dict):
raise ValueError("site.json must be a JSON object")
except Exception as e:
if cache_key in self._cache:
return self._cache[cache_key]
raise NextcloudConnectionError(f"Invalid JSON in site.json from Nextcloud: {e}")
self._set_cache(cache_key, site_data)
return site_data
def get_home_data(self, force_refresh: bool = False) -> Dict[str, Any]:
"""
Retrieves Home page content from home.md or home.json in Nextcloud.
"""
cache_key = "home_data"
config = self.get_config()
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
home_data: Dict[str, Any] = {}
# 1. Try home.json
file_json = self._fetch_file_content("home.json", force_refresh=force_refresh)
if file_json:
content, _ = file_json
try:
loaded = json.loads(content)
if isinstance(loaded, dict):
home_data.update(loaded)
except Exception:
pass
# 2. Try home.md
file_md = self._fetch_file_content("home.md", force_refresh=force_refresh)
if file_md:
content, _ = file_md
meta, body = self._parse_frontmatter(content)
home_data.update(meta)
if body:
home_data["body_html"] = self._render_markdown(body)
if not home_data and not file_md and not file_json:
if cache_key in self._cache:
return self._cache[cache_key]
raise NextcloudConnectionError("Failed to load home.md from Nextcloud.")
self._set_cache(cache_key, home_data)
return home_data
def get_about_content(self, force_refresh: bool = False) -> Dict[str, Any]:
"""
Retrieves the About page content from about.md in Nextcloud.
"""
cache_key = "about_page"
config = self.get_config()
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
file_data = self._fetch_file_content("about.md", force_refresh=force_refresh)
if not file_data:
file_data = self._fetch_file_content("About.md", force_refresh=force_refresh)
if not file_data:
if cache_key in self._cache:
return self._cache[cache_key]
raise NextcloudConnectionError("Failed to load about.md from Nextcloud.")
content, mtime = file_data
parsed = self._parse_markdown_file(content, "about", mtime)
self._set_cache(cache_key, parsed)
return parsed
def get_articles_page_data(self, force_refresh: bool = False) -> Dict[str, Any]:
"""
Retrieves custom header and subtitle for the Articles index from articles.md in Nextcloud.
"""
cache_key = "articles_page_data"
config = self.get_config()
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
data: Dict[str, Any] = {
"badge": "Knowledge Base",
"title": "Articles & Insights",
"subtitle": "Explore tutorials, manifestos, and technical deep-dives into Handshake and the decentralized web.",
"search_placeholder": "Search articles by title, author, or keyword...",
}
for fname in ["articles.json", "articles.md"]:
file_data = self._fetch_file_content(fname, force_refresh=force_refresh)
if file_data:
content, _ = file_data
if fname.endswith(".json"):
try:
loaded = json.loads(content)
if isinstance(loaded, dict):
data.update(loaded)
break
except Exception:
pass
else:
meta, body = self._parse_frontmatter(content)
data.update(meta)
if body:
data["body_html"] = self._render_markdown(body)
break
self._set_cache(cache_key, data)
return data
def get_page(self, slug: str, force_refresh: bool = False) -> Optional[Dict[str, Any]]:
"""
Retrieves any custom page from Nextcloud (e.g. pages/faq.md, contact.md, etc.).
"""
raw_slug = slug.strip("/").rstrip(".md")
stripped_slug = raw_slug[6:] if raw_slug.startswith("pages/") else raw_slug
clean_slug = self._slugify(stripped_slug)
cache_key = f"page_{clean_slug}"
config = self.get_config()
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
candidates = [
f"pages/{clean_slug}.md",
f"pages/{stripped_slug}.md",
f"{clean_slug}.md",
f"{stripped_slug}.md",
f"pages/{raw_slug}.md",
f"{raw_slug}.md",
]
excluded = {"home.md", "site.md", "articles.md", "readme.md"}
for candidate in candidates:
if candidate.lower() in excluded:
continue
file_data = self._fetch_file_content(candidate, force_refresh=force_refresh)
if file_data:
content, mtime = file_data
parsed = self._parse_markdown_file(content, clean_slug, mtime)
self._set_cache(cache_key, parsed)
return parsed
# Fallback: scan all raw files in cache if available
if "raw_files" not in self._cache or not self._cache["raw_files"]:
self._sync_from_nextcloud(force=force_refresh)
raw_files = self._cache.get("raw_files", {})
for path, data in raw_files.items():
if not path.endswith(".md"):
continue
fname = path.split("/")[-1].replace(".md", "")
if fname.lower() in excluded:
continue
if self._slugify(fname) == clean_slug or fname.lower() == stripped_slug.lower():
try:
content = data.decode("utf-8")
parsed = self._parse_markdown_file(content, clean_slug)
self._set_cache(cache_key, parsed)
return parsed
except Exception:
pass
return None
def get_pages(self, force_refresh: bool = False) -> List[Dict[str, Any]]:
"""
Retrieves all custom pages from Nextcloud (e.g. pages/*.md).
"""
config = self.get_config()
cache_key = "pages_list"
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
if "raw_files" not in self._cache or not self._cache["raw_files"]:
self._sync_from_nextcloud(force=force_refresh)
raw_files = self._cache.get("raw_files", {})
excluded_files = {"about.md", "home.md", "site.md", "articles.md", "readme.md"}
pages: List[Dict[str, Any]] = []
seen_slugs = set()
for path, data in raw_files.items():
if not path.endswith(".md"):
continue
fname = path.split("/")[-1]
if fname.lower() in excluded_files:
continue
# Only include files in pages/ directory
if not path.startswith("pages/"):
continue
slug = fname[:-3]
clean_slug = self._slugify(slug)
if clean_slug in seen_slugs:
continue
page = self.get_page(clean_slug, force_refresh=force_refresh)
if page and page.get("published", True):
pages.append(page)
seen_slugs.add(clean_slug)
self._set_cache(cache_key, pages)
return pages
def get_articles(self, force_refresh: bool = False) -> List[Dict[str, Any]]:
"""
Retrieves all articles from Nextcloud.
"""
config = self.get_config()
cache_key = "articles_list"
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
if "raw_files" not in self._cache or not self._cache["raw_files"]:
self._sync_from_nextcloud(force=force_refresh)
raw_files = self._cache.get("raw_files", {})
excluded_files = {"about.md", "home.md", "site.md", "articles.md", "readme.md"}
articles: List[Dict[str, Any]] = []
seen_slugs = set()
for path, data in raw_files.items():
if not path.endswith(".md"):
continue
fname = path.split("/")[-1]
if fname.lower() in excluded_files:
continue
# Only include files in articles/ or top-level markdown articles
if not (path.startswith("articles/") or not "/" in path):
continue
try:
content = data.decode("utf-8")
default_slug = self._slugify(fname)
parsed = self._parse_markdown_file(content, default_slug)
if parsed.get("published", True) and parsed["slug"] not in seen_slugs:
articles.append(parsed)
seen_slugs.add(parsed["slug"])
except Exception:
pass
articles.sort(key=lambda x: x["datetime"], reverse=True)
self._set_cache(cache_key, articles)
for a in articles:
self._set_cache(f"article_{a['slug']}", a)
return articles
def get_article(self, slug: str, force_refresh: bool = False) -> Optional[Dict[str, Any]]:
"""Retrieves a single article by its slug from Nextcloud."""
clean_slug = self._slugify(slug)
cache_key = f"article_{clean_slug}"
config = self.get_config()
if not force_refresh and self._is_cache_valid(cache_key, config["cache_ttl"]):
return self._cache[cache_key]
articles = self.get_articles(force_refresh=force_refresh)
for a in articles:
if a["slug"] == clean_slug:
return a
for candidate_rel in [
f"articles/{clean_slug}.md",
f"{clean_slug}.md",
f"articles/{slug}.md",
f"{slug}.md",
]:
file_data = self._fetch_file_content(candidate_rel, force_refresh=force_refresh)
if file_data:
content, mtime = file_data
parsed = self._parse_markdown_file(content, clean_slug, mtime)
self._set_cache(cache_key, parsed)
return parsed
return None
def generate_rss_feed(self, site_url: str = "https://ownthedot.com") -> str:
"""Generates an RSS 2.0 XML feed for Own The Dot articles from Nextcloud."""
articles = self.get_articles()
site_config = self.get_site_config()
now_rfc = format_datetime(datetime.now(timezone.utc))
items_xml = []
for a in articles:
pub_date = format_datetime(a["datetime"])
article_url = f"{site_url.rstrip('/')}/articles/{a['slug']}"
author_name = a.get("author") or site_config.get("title", "Own The Dot")
item = f""" <item>
<title><![CDATA[{a['title']}]]></title>
<link>{article_url}</link>
<guid isPermaLink="true">{article_url}</guid>
<pubDate>{pub_date}</pubDate>
<dc:creator><![CDATA[{author_name}]]></dc:creator>
<description><![CDATA[{a['description']}]]></description>
</item>"""
items_xml.append(item)
feed_xml = f"""<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>{site_config.get('title', 'Own The Dot')}</title>
<link>{site_url}</link>
<description>{site_config.get('description', 'The future of domain ownership starts with you.')}</description>
<language>en-AU</language>
<lastBuildDate>{now_rfc}</lastBuildDate>
<atom:link href="{site_url.rstrip('/')}/feed.xml" rel="self" type="application/rss+xml"/>
{chr(10).join(items_xml)}
</channel>
</rss>"""
return feed_xml
def generate_sitemap(self, site_url: str = "https://ownthedot.com") -> str:
"""Generates a sitemap.xml for Own The Dot containing all articles and pages."""
base = site_url.rstrip("/")
seen_locs = set()
url_entries: List[str] = []
def add_url(
loc: str,
lastmod: Optional[str] = None,
changefreq: Optional[str] = None,
priority: Optional[str] = None,
):
if loc in seen_locs:
return
seen_locs.add(loc)
parts = [f" <loc>{escape(loc)}</loc>"]
if lastmod:
parts.append(f" <lastmod>{escape(lastmod)}</lastmod>")
if changefreq:
parts.append(f" <changefreq>{escape(changefreq)}</changefreq>")
if priority:
parts.append(f" <priority>{escape(priority)}</priority>")
entry = " <url>\n" + "\n".join(parts) + "\n </url>"
url_entries.append(entry)
# 1. Main site entrypoints
add_url(f"{base}/", changefreq="daily", priority="1.0")
add_url(f"{base}/about", changefreq="weekly", priority="0.8")
add_url(f"{base}/articles", changefreq="daily", priority="0.9")
# 2. Articles
articles = self.get_articles()
for a in articles:
article_url = f"{base}/articles/{a['slug']}"
lastmod = None
if isinstance(a.get("datetime"), datetime):
lastmod = a["datetime"].strftime("%Y-%m-%d")
elif a.get("date"):
lastmod = str(a["date"]).split("T")[0]
add_url(article_url, lastmod=lastmod, changefreq="monthly", priority="0.7")
# 3. Custom pages from Nextcloud
pages = self.get_pages()
for p in pages:
slug = p.get("slug")
if slug and slug not in {"home", "index", "about", "articles"}:
page_url = f"{base}/{slug}"
lastmod = None
if isinstance(p.get("datetime"), datetime):
lastmod = p["datetime"].strftime("%Y-%m-%d")
elif p.get("date"):
lastmod = str(p["date"]).split("T")[0]
add_url(page_url, lastmod=lastmod, changefreq="weekly", priority="0.8")
# 4. Nav links from site.json (if any extra internal links)
site_config = self.get_site_config()
for link in site_config.get("nav_links", []):
url = link.get("url", "")
if url and url.startswith("/") and not url.startswith("//"):
clean = url.rstrip("/") or "/"
full_url = f"{base}{clean}" if clean != "/" else f"{base}/"
add_url(full_url, changefreq="weekly", priority="0.7")
sitemap_xml = f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
{chr(10).join(url_entries)}
</urlset>"""
return sitemap_xml
def warm_cache(self, force: bool = False) -> Dict[str, Any]:
"""
Validates that website resources from Nextcloud are ready and hydrated in cache.
Returns in < 5ms if cache is already warm, or performs quick sync with strict <1.5s timeout.
Raises NextcloudConnectionError if Nextcloud is unreachable and no cache exists.
"""
start_t = time.perf_counter()
# 1. Sync from Nextcloud if cold or forced
if force or "raw_files" not in self._cache or not self._cache["raw_files"]:
self._do_sync_from_nextcloud()
# 2. Parse and cache all core resources
site_config = self.get_site_config(force_refresh=force)
home_data = self.get_home_data(force_refresh=force)
about_data = self.get_about_content(force_refresh=force)
articles_page = self.get_articles_page_data(force_refresh=force)
articles = self.get_articles(force_refresh=force)
pages = self.get_pages(force_refresh=force)
elapsed_ms = round((time.perf_counter() - start_t) * 1000, 2)
return {
"healthy": True,
"status": "ok",
"source": self.get_source_info(),
"site_title": site_config.get("title", "Own The Dot"),
"article_count": len(articles),
"cached_entries": list(self._cache.keys()),
"response_time_ms": elapsed_ms,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
# endregion
# Singleton instance
nextcloud_provider = NextcloudProvider()