diff --git a/appctl b/appctl index d6eb50d..3333048 100755 --- a/appctl +++ b/appctl @@ -65,7 +65,6 @@ load_app_env() { export SERVICE_DOMAIN="$LEARNING_DOMAIN" export APP_PORT="$LEARNING_APP_PORT" export PROXY_NETWORK="$PROXY_NETWORK" - export SOCKET_PROXY_NETWORK="$LEARNING_SOCKET_PROXY_NETWORK" export TURSO_DATABASE_URL="$TURSO_DATABASE_URL" export TURSO_AUTH_TOKEN="$TURSO_AUTH_TOKEN" ;; @@ -74,6 +73,12 @@ load_app_env() { export PROXY_NETWORK="$PROXY_NETWORK" export SERVICE_NAME="$MERMAID_SERVICE_NAME" ;; + docs) + export SERVICE_NAME="docs" + export SERVICE_DOMAIN="$DOCS_DOMAIN" + export PROJECT_PATH="$DOCS_PROJECT_PATH" + export PROXY_NETWORK="$PROXY_NETWORK" + ;; mongo-docker) export MONGO_ROOT_USERNAME="$MONGO_ROOT_USERNAME" export MONGO_ROOT_PASSWORD="$MONGO_ROOT_PASSWORD" @@ -144,6 +149,7 @@ cmd_list() { excalidraw) domain_info="$EXCALIDRAW_DOMAIN" ;; gitea) domain_info="$GITEA_DOMAIN" ;; jellyfin) domain_info="$JELLYFIN_DOMAIN" ;; + docs) domain_info="$DOCS_DOMAIN" ;; learning) domain_info="$LEARNING_DOMAIN" ;; mermaid) domain_info="$MERMAID_DOMAIN" ;; mongo-docker) domain_info="$MONGO_DOMAIN" ;; @@ -195,7 +201,7 @@ case "$COMMAND" in if [ -z "$APP" ]; then echo "Error: Service name required"; exit 1; fi load_app_env "$APP" echo "=== Active Environment Variables for $APP ===" - env | grep -E "^(PROXY_NETWORK|CERT_RESOLVER|DOMAIN|SERVICE_DOMAIN|SERVICE_NAME|CONTAINER_NAME|IMAGE_TAG|TZ|PUID|PGID|MEDIA_PATH|HTTP_ENTRYPOINT|HTTPS_ENTRYPOINT|RATE_LIMIT_AVG|RATE_LIMIT_BURST|APP_PORT|SOCKET_PROXY_NETWORK|TURSO_DATABASE_URL|TURSO_AUTH_TOKEN|DOCKER_HOST|MONGO_ROOT_USERNAME|MONGO_ROOT_PASSWORD|MONGO_DOMAIN|POSTGRES_USER|POSTGRES_PASSWORD|POSTGRES_DB|POSTGRES_DOMAIN|OLLAMA_API_KEY|REPLICAS|OLLAMA_DATA_VOLUME|GITEA_VERSION|GITEA_DOMAIN|GITEA_SSH_DOMAIN|GITEA_AUTH_MIDDLEWARE|SSH_DOMAIN|DATA_PATH|AUTH_MIDDLEWARE|HTTPS_REDIRECT_MIDDLEWARE)" | sort + env | grep -E "^(PROXY_NETWORK|CERT_RESOLVER|DOMAIN|SERVICE_DOMAIN|SERVICE_NAME|CONTAINER_NAME|IMAGE_TAG|TZ|PUID|PGID|MEDIA_PATH|HTTP_ENTRYPOINT|HTTPS_ENTRYPOINT|RATE_LIMIT_AVG|RATE_LIMIT_BURST|APP_PORT|SOCKET_PROXY_NETWORK|TURSO_DATABASE_URL|TURSO_AUTH_TOKEN|DOCKER_HOST|MONGO_ROOT_USERNAME|MONGO_ROOT_PASSWORD|MONGO_DOMAIN|POSTGRES_USER|POSTGRES_PASSWORD|POSTGRES_DB|POSTGRES_DOMAIN|OLLAMA_API_KEY|REPLICAS|OLLAMA_DATA_VOLUME|GITEA_VERSION|GITEA_DOMAIN|GITEA_SSH_DOMAIN|GITEA_AUTH_MIDDLEWARE|SSH_DOMAIN|DATA_PATH|AUTH_MIDDLEWARE|HTTPS_REDIRECT_MIDDLEWARE|PROJECT_PATH|DOCS_PROJECT_PATH|DOCS_DOMAIN)" | sort ;; *) show_help diff --git a/docs/Dockerfile b/docs/Dockerfile new file mode 100644 index 0000000..71f76e0 --- /dev/null +++ b/docs/Dockerfile @@ -0,0 +1,17 @@ +FROM python:3.11-alpine + +WORKDIR /app + +# Install dependencies +RUN pip install --no-cache-dir markdown + +# Copy application files +COPY app/ /app/ + +# Default Environment Variables +ENV PORT=8000 +ENV DOCS_ROOT=/docs + +EXPOSE 8000 + +CMD ["python", "main.py"] diff --git a/docs/app/layout.html b/docs/app/layout.html new file mode 100644 index 0000000..f3cf6cd --- /dev/null +++ b/docs/app/layout.html @@ -0,0 +1,943 @@ + + + + + + {{ title }} - Documentation + + + + + + + + + + + + + + +
+ +
+ + + +
+ + +
+
+ {{ content }} + + +
+ + {% if has_toc %} + + {% endif %} +
+
+ + + + + + + + + + + diff --git a/docs/app/main.py b/docs/app/main.py new file mode 100644 index 0000000..c351bf6 --- /dev/null +++ b/docs/app/main.py @@ -0,0 +1,387 @@ +import os +import sys +import re +import mimetypes +import urllib.parse +import posixpath +from http.server import HTTPServer, BaseHTTPRequestHandler +import markdown + +# Configurable paths +DOCS_ROOT = os.path.realpath(os.environ.get("DOCS_ROOT", "/docs")) +PORT = int(os.environ.get("PORT", "8000")) + +# Read layout template +TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'layout.html') +try: + with open(TEMPLATE_PATH, 'r', encoding='utf-8') as f: + TEMPLATE = f.read() +except OSError: + print(f"Error: Could not read template from {TEMPLATE_PATH}", file=sys.stderr) + TEMPLATE = "{{ content }}" + + +def is_safe_path(path): + """Ensure the path is within the DOCS_ROOT directory to prevent traversal.""" + real_path = os.path.realpath(path) + return real_path == DOCS_ROOT or real_path.startswith(DOCS_ROOT + os.sep) + + +def get_breadcrumbs(url_path): + """Generate beautiful navigation breadcrumbs.""" + parts = [p for p in url_path.split('/') if p] + breadcrumbs_html = 'Home' + + current_acc = "" + for i, part in enumerate(parts): + current_acc += f"/{part}" + breadcrumbs_html += ' / ' + if i == len(parts) - 1: + breadcrumbs_html += f'{part}' + else: + breadcrumbs_html += f'{part}' + + return breadcrumbs_html + + +def build_tree(path): + """Recursively build a tree of folders and markdown files.""" + items = [] + try: + names = os.listdir(path) + except OSError: + return [] + + for name in names: + if name.startswith('.'): + continue + if name in ('node_modules', 'venv', '.git', '__pycache__', 'data'): + continue + + full_path = os.path.join(path, name) + rel_path = os.path.relpath(full_path, DOCS_ROOT) + + if os.path.isdir(full_path): + children = build_tree(full_path) + # Only list directory if it contains markdown files or subdirs with markdown files + if children: + items.append({ + 'name': name, + 'type': 'dir', + 'rel_path': rel_path.replace(os.sep, '/'), + 'children': children + }) + elif name.endswith('.md'): + url_name = name[:-3] + # Handle root readme differently or filter it + if url_name.lower() in ('readme', 'index') and rel_path == name: + # We skip showing root readme directly in sidebar tree to prevent clutter, + # as it is already mapped to the Home button. + continue + + # Form clean url + url_path = os.path.splitext(rel_path)[0] + url = '/' + url_path.replace(os.sep, '/') + + # If it's a subdirectory README, we want to link it to the folder URL + if url_name.lower() in ('readme', 'index'): + parent_dir = os.path.dirname(rel_path) + url = '/' + parent_dir.replace(os.sep, '/') if parent_dir else '/' + display_name = os.path.basename(parent_dir) if parent_dir else 'Home' + else: + display_name = url_name + + items.append({ + 'name': display_name, + 'type': 'file', + 'url': url, + 'rel_path': rel_path.replace(os.sep, '/') + }) + + # Sort folders first, then files + items.sort(key=lambda x: (0 if x['type'] == 'dir' else 1, x['name'].lower())) + return items + + +def render_tree(tree, active_url): + """Render the built tree into HTML nested ul/details list.""" + if not tree: + return "" + + html = '' + return html + + +def process_alerts(html): + """Convert GitHub-style alerts > [!NOTE] into beautiful callouts.""" + pattern = re.compile( + r'
\s*

\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](.*?)

(.*?)
', + re.DOTALL | re.IGNORECASE + ) + + def replace_alert(match): + alert_type = match.group(1).upper() + content = match.group(2).strip() + rest = match.group(3).strip() + + # Colors, icons and styling + alerts = { + 'NOTE': ('#3b82f6', 'â„šī¸', 'Note', 'rgba(59, 130, 246, 0.08)'), + 'TIP': ('#10b981', '💡', 'Tip', 'rgba(16, 185, 129, 0.08)'), + 'IMPORTANT': ('#8b5cf6', 'đŸ“ĸ', 'Important', 'rgba(139, 92, 246, 0.08)'), + 'WARNING': ('#f59e0b', 'âš ī¸', 'Warning', 'rgba(245, 158, 11, 0.08)'), + 'CAUTION': ('#ef4444', '🚨', 'Caution', 'rgba(239, 68, 68, 0.08)') + } + + color, icon, title, bg = alerts.get(alert_type, ('#64748b', 'â„šī¸', 'Note', 'rgba(100, 116, 139, 0.08)')) + + full_content = content + if rest: + full_content += f"

{rest}

" + + return f'''
+
+ {icon} + {title} +
+
{full_content}
+
''' + + return pattern.sub(replace_alert, html) + + +def generate_folder_index(folder_path, rel_url_path): + """Renders a directory list when no index README is present.""" + try: + names = os.listdir(folder_path) + except OSError: + return "

Error loading directory

" + + names.sort() + + html = f"

Index of {rel_url_path}

" + html += "" + return html + + +class DocsHTTPHandler(BaseHTTPRequestHandler): + def log_message(self, format, *args): + # Override to log cleanly to stdout/stderr + sys.stdout.write("%s - - [%s] %s\n" % + (self.address_string(), + self.log_date_time_string(), + format%args)) + + def resolve_url_to_file(self, path_str): + """Maps HTTP path to filesystem path inside DOCS_ROOT.""" + path_str = urllib.parse.unquote(path_str) + parsed = urllib.parse.urlparse(path_str) + clean_path = posixpath.normpath(parsed.path) + + if clean_path.startswith('../') or '/../' in clean_path: + return None, None, False + + rel_path = clean_path.lstrip('/') + + # If accessing root directory + if not rel_path: + for name in ('README.md', 'index.md', 'readme.md', 'README.markdown', 'readme.markdown'): + full_p = os.path.join(DOCS_ROOT, name) + if os.path.isfile(full_p): + return full_p, '/', True + # No root readme, return DOCS_ROOT directory for auto-index + return DOCS_ROOT, '/', False + + full_p = os.path.join(DOCS_ROOT, rel_path) + + # 1. Direct file check + if os.path.isfile(full_p): + is_md = full_p.endswith('.md') or full_p.endswith('.markdown') + return full_p, '/' + rel_path, is_md + + # 2. Check path + .md + if not rel_path.endswith('.md'): + md_path = full_p + '.md' + if os.path.isfile(md_path): + return md_path, '/' + rel_path, True + + # 3. Check directory + if os.path.isdir(full_p): + for name in ('README.md', 'index.md', 'readme.md'): + sub_p = os.path.join(full_p, name) + if os.path.isfile(sub_p): + return sub_p, '/' + rel_path, True + # Folder without index README, serve directory index page + return full_p, '/' + rel_path, False + + return None, '/' + rel_path, False + + def do_GET(self): + filepath, active_url, is_md = self.resolve_url_to_file(self.path) + + if not filepath or not is_safe_path(filepath): + self.render_error(404, "Page Not Found", active_url) + return + + # Serve static asset + if not is_md and os.path.isfile(filepath): + self.serve_static_file(filepath) + return + + # Serve Markdown or Directory Index + if is_md: + try: + with open(filepath, 'r', encoding='utf-8') as f: + md_content = f.read() + except OSError: + self.render_error(500, "Internal Server Error - Could not read file", active_url) + return + + # Render Markdown + md = markdown.Markdown(extensions=['extra', 'toc', 'nl2br']) + html_content = md.convert(md_content) + html_content = process_alerts(html_content) + + toc_html = md.toc + has_toc = 'href=' in toc_html + + title = os.path.basename(filepath) + if title.endswith('.md'): + title = title[:-3] + if title.lower() in ('readme', 'index'): + parent_dir = os.path.basename(os.path.dirname(filepath)) + title = parent_dir if parent_dir else "Home" + else: + # Renders folder directory index + html_content = generate_folder_index(filepath, active_url) + toc_html = "" + has_toc = False + title = os.path.basename(filepath) or "Index" + + # Generate Sidebar tree + sidebar_tree_data = build_tree(DOCS_ROOT) + sidebar_html = render_tree(sidebar_tree_data, active_url) + + # Build breadcrumbs + breadcrumbs = get_breadcrumbs(active_url) + + # Render page using layout + page_html = TEMPLATE + page_html = page_html.replace('{{ title }}', title) + page_html = page_html.replace('{{ home_active }}', ' active' if active_url == '/' else '') + page_html = page_html.replace('{{ sidebar_tree }}', sidebar_html) + page_html = page_html.replace('{{ breadcrumbs }}', breadcrumbs) + page_html = page_html.replace('{{ content }}', html_content) + page_html = page_html.replace('{{ toc }}', toc_html) + page_html = page_html.replace('{{ grid_class }}', ' has-toc' if has_toc else '') + + # Conditional template logic for TOC + if has_toc: + page_html = page_html.replace('{% if has_toc %}', '').replace('{% endif %}', '') + else: + page_html = re.sub(r'{% if has_toc %}.*?{% endif %}', '', page_html, flags=re.DOTALL) + + self.send_response(200) + self.send_header('Content-Type', 'text/html; charset=utf-8') + self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate') + self.end_headers() + self.wfile.write(page_html.encode('utf-8')) + + def serve_static_file(self, filepath): + try: + with open(filepath, 'rb') as f: + content = f.read() + except OSError: + self.send_error(404, "File not found") + return + + self.send_response(200) + ctype, _ = mimetypes.guess_type(filepath) + if not ctype: + ctype = 'application/octet-stream' + self.send_header('Content-Type', ctype) + self.send_header('Content-Length', str(len(content))) + self.send_header('Cache-Control', 'public, max-age=600') + self.end_headers() + self.wfile.write(content) + + def render_error(self, code, message, active_url): + # Render a nice formatted error inside the layout + error_html = f''' +
+

{code}

+

{message}

+ Go Home +
+ ''' + sidebar_tree_data = build_tree(DOCS_ROOT) + sidebar_html = render_tree(sidebar_tree_data, active_url) + breadcrumbs = get_breadcrumbs(active_url) + + page_html = TEMPLATE + page_html = page_html.replace('{{ title }}', f"Error {code}") + page_html = page_html.replace('{{ home_active }}', '') + page_html = page_html.replace('{{ sidebar_tree }}', sidebar_html) + page_html = page_html.replace('{{ breadcrumbs }}', breadcrumbs) + page_html = page_html.replace('{{ content }}', error_html) + page_html = page_html.replace('{{ toc }}', '') + page_html = page_html.replace('{{ grid_class }}', '') + page_html = re.sub(r'{% if has_toc %}.*?{% endif %}', '', page_html, flags=re.DOTALL) + + self.send_response(code) + self.send_header('Content-Type', 'text/html; charset=utf-8') + self.end_headers() + self.wfile.write(page_html.encode('utf-8')) + + +def run_server(): + server_address = ('', PORT) + httpd = HTTPServer(server_address, DocsHTTPHandler) + print(f"Starting markdown docs server on port {PORT}...") + print(f"Serving files from {DOCS_ROOT}") + try: + httpd.serve_forever() + except KeyboardInterrupt: + pass + print("\nStopping server.") + +if __name__ == '__main__': + run_server() diff --git a/docs/data/README.md b/docs/data/README.md new file mode 100644 index 0000000..c77cb5e --- /dev/null +++ b/docs/data/README.md @@ -0,0 +1,71 @@ +# 📝 Documentation Viewer + +Self-hosted local documentation viewer. This service serves markdown files from a designated directory as a lightweight, reactive HTML site with instant reloads. + +> [!NOTE] +> Any changes you made to the markdown files in the documentation directory will show up here immediately upon refreshing the page. No rebuild steps, no compilation delay. + +--- + +## 🚀 Getting Started + +To mount your project documentation, configure the following environment variables in your deployment setup: + +1. **`DOCS_DOMAIN`**: The domain you want Traefik to route to this viewer (e.g. `docs.homelab.local`). +2. **`DOCS_PROJECT_PATH`**: The absolute path on your host machine pointing to your markdown files (e.g. `/home/kiskaadee/Projects/my-app/docs`). + +For example, when using the repository's `appctl` CLI wrapper: +```bash +# Sourcing environment, appctl maps: +# DOCS_PROJECT_PATH -> PROJECT_PATH +./appctl up docs +``` + +--- + +## đŸ› ī¸ Features + +Here is a breakdown of what this documentation server provides out-of-the-box: + +### 1. Dynamic Routing +- `GET /` resolves to `README.md` or `index.md` at your documentation root. +- `GET /docs/infra` matches `docs/infra.md` or `docs/infra/README.md`. +- Clicking directories with no `README.md` serves an automatic, styled list of that folder's contents. + +### 2. Search & Sidebar Navigation +- The sidebar dynamically scans the directories of your project workspace for `.md` files. +- You can filter documentation files instantly using the **Search** input at the top of the sidebar. It searches across names and URLs. + +### 3. Sleek Themes (Light & Dark) +- Persisted theme settings using `localStorage`. +- Click the toggle button in the bottom-left corner of the sidebar to switch between a gorgeous dark slate mode and a clean light mode. + +### 4. Code Highlight & Copy +- Code blocks are automatically highlighted with Prism.js. +- Hovering over a code block shows a **Copy** button to copy code instantly. + +```python +# Test Python block +def hello_world(): + print("Welcome to your local docs!") + return True +``` + +### 5. Mermaid.js Support +You can render flowcharts, sequence diagrams, and class diagrams directly inside your markdown pages using standard fenced code blocks labeled `mermaid`. + +```mermaid +graph TD + A[Browse Docs] -->|GET /path| B(Safe Path Resolver) + B -->|Found .md| C{Render Markdown} + B -->|Found Folder| D[Generate Directory Listing] + C -->|Parse HTML| E[Inject layout.html Template] + D -->|Inject list| E + E -->|Serve Browser| F((Wow User!)) +``` + +### 6. Alert Callouts +Use standard GitHub alert formatting to highlight notices: + +> [!TIP] +> Use callout boxes to highlight important tips, warnings, or caution sections. They render with custom icons and borders. diff --git a/docs/docker-compose.yml b/docs/docker-compose.yml new file mode 100644 index 0000000..55a6bba --- /dev/null +++ b/docs/docker-compose.yml @@ -0,0 +1,31 @@ +services: + docs: + build: . + container_name: ${SERVICE_NAME} + restart: unless-stopped + volumes: + - ${PROJECT_PATH:-./data}:/docs:ro + environment: + - DOCS_ROOT=/docs + - PORT=8000 + networks: + - proxy + labels: + - "traefik.enable=true" + - "traefik.http.routers.${SERVICE_NAME}.rule=Host(`${SERVICE_DOMAIN}`)" + - "traefik.http.routers.${SERVICE_NAME}.entrypoints=websecure" + - "traefik.http.routers.${SERVICE_NAME}.tls=true" + - "traefik.http.routers.${SERVICE_NAME}.service=${SERVICE_NAME}-svc" + + # HTTP to HTTPS redirect + - "traefik.http.routers.${SERVICE_NAME}-red.rule=Host(`${SERVICE_DOMAIN}`)" + - "traefik.http.routers.${SERVICE_NAME}-red.entrypoints=web" + - "traefik.http.routers.${SERVICE_NAME}-red.middlewares=https-redirect@docker" + + # Target Port + - "traefik.http.services.${SERVICE_NAME}-svc.loadbalancer.server.port=8000" + +networks: + proxy: + name: ${PROXY_NETWORK} + external: true