From 1a02a4eb5b333bb99a7a65a7b9b35183dabd5322 Mon Sep 17 00:00:00 2001 From: Roland Date: Mon, 15 Dec 2025 16:53:24 -0700 Subject: [PATCH] Adding Download and Refresh buttons to the Controller log modals. --- app/src/components/admin/AdminRoute.js | 2 +- app/src/components/admin/ControllerPage.js | 87 ++++++++++++++-- controller/lib/fstab.py | 45 ++++++-- controller/templates/index.html | 103 +++++++++++++++++- controller/test/test_fstab.py | 116 +++++++++++++++++++-- 5 files changed, 327 insertions(+), 26 deletions(-) diff --git a/app/src/components/admin/AdminRoute.js b/app/src/components/admin/AdminRoute.js index 4031d4d9..7996cfc9 100644 --- a/app/src/components/admin/AdminRoute.js +++ b/app/src/components/admin/AdminRoute.js @@ -12,7 +12,7 @@ export default function AdminRoute() { {text: 'Downloads', to: '/admin', key: 'admin', end: true}, {text: 'Settings', to: '/admin/settings', key: 'settings'}, {text: 'Status', to: '/admin/status', key: 'status'}, - {text: 'Controller', to: '/admin/controller', key: 'controller'}, + {text: 'Control', to: '/admin/controller', key: 'controller'}, ]; return diff --git a/app/src/components/admin/ControllerPage.js b/app/src/components/admin/ControllerPage.js index 5292f82d..e2dda050 100644 --- a/app/src/components/admin/ControllerPage.js +++ b/app/src/components/admin/ControllerPage.js @@ -1,5 +1,5 @@ import React from 'react'; -import {Container, Icon} from "semantic-ui-react"; +import {Container, Dropdown, Icon} from "semantic-ui-react"; import {Button, Header, Loader, Modal, Segment, Table} from "../Theme"; import { APIButton, @@ -34,11 +34,22 @@ const statusColors = { }; +const linesOptions = [ + {key: 100, text: '100 lines', value: 100}, + {key: 250, text: '250 lines', value: 250}, + {key: 500, text: '500 lines', value: 500}, + {key: 1000, text: '1000 lines', value: 1000}, + {key: 5000, text: '5000 lines', value: 5000}, +]; + function ServiceRow({service, onAction, dockerized}) { const [loading, setLoading] = React.useState(false); const [logsOpen, setLogsOpen] = React.useState(false); const [logs, setLogs] = React.useState(''); const [logsLoading, setLogsLoading] = React.useState(false); + const [linesCount, setLinesCount] = React.useState(250); + const [countdown, setCountdown] = React.useState(10); + const logsRef = React.useRef(null); const handleAction = async (action, actionFn) => { setLoading(true); @@ -63,19 +74,71 @@ function ServiceRow({service, onAction, dockerized}) { } }; - const handleViewLogs = async () => { - setLogsOpen(true); - setLogsLoading(true); + const fetchLogs = async (lines, showLoading = false) => { + if (showLoading) setLogsLoading(true); try { - const result = await getServiceLogs(service.name, 100); + const result = await getServiceLogs(service.name, lines); setLogs(result.logs || 'No logs available'); } catch (e) { setLogs(`Error fetching logs: ${e.message}`); } finally { - setLogsLoading(false); + if (showLoading) setLogsLoading(false); } }; + // Scroll to bottom when logs finish loading + React.useEffect(() => { + if (!logsLoading && logsRef.current) { + logsRef.current.scrollTop = logsRef.current.scrollHeight; + } + }, [logsLoading]); + + // Auto-refresh countdown timer (only when scrolled to bottom) + React.useEffect(() => { + if (!logsOpen) return; + + const interval = setInterval(() => { + setCountdown(prev => { + if (prev <= 1) { + // Check if scrolled to bottom (within 50px threshold) + if (logsRef.current) { + const {scrollTop, scrollHeight, clientHeight} = logsRef.current; + const isAtBottom = scrollHeight - scrollTop - clientHeight < 50; + if (isAtBottom) { + fetchLogs(linesCount); + } + } + return 10; // Reset countdown + } + return prev - 1; + }); + }, 1000); + + return () => clearInterval(interval); + }, [logsOpen, linesCount]); + + const handleViewLogs = async () => { + setLogsOpen(true); + fetchLogs(linesCount, true); // Show loading on initial open + }; + + const handleLinesChange = (e, {value}) => { + setLinesCount(value); + fetchLogs(value); + }; + + const handleDownloadLogs = () => { + const datetime = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const filename = `${service.name}_${datetime}.txt`; + const blob = new Blob([logs], {type: 'text/plain'}); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + a.click(); + URL.revokeObjectURL(url); + }; + const isRunning = service.status === 'running'; const isStopped = service.status === 'stopped'; const statusColor = statusColors[service.status] || 'grey'; @@ -140,7 +203,7 @@ function ServiceRow({service, onAction, dockerized}) { {logsLoading ? ( ) : ( -
                     
+                        {countdown}s
+                        
+                        
                     
                 
diff --git a/controller/lib/fstab.py b/controller/lib/fstab.py
index e97e3255..09bf9a6e 100644
--- a/controller/lib/fstab.py
+++ b/controller/lib/fstab.py
@@ -60,6 +60,39 @@ def parse_fstab() -> list[dict]:
     return entries
 
 
+def _filter_entry_with_comment(entries: list[dict], mount_point: str) -> list[dict]:
+    """
+    Remove a mount entry and its preceding WROLPi comment if present.
+
+    Args:
+        entries: List of parsed fstab entries
+        mount_point: Mount point to remove
+
+    Returns:
+        Filtered list without the mount entry and its associated WROLPi comment
+    """
+    result = []
+    skip_indices = set()
+
+    # First pass: identify which entries to skip
+    for i, entry in enumerate(entries):
+        if entry.get("mount_point") == mount_point:
+            skip_indices.add(i)
+            # Check if previous entry is a WROLPi comment
+            if i > 0:
+                prev_entry = entries[i - 1]
+                if (prev_entry["type"] == "comment" and
+                        "WROLPi managed mount" in prev_entry.get("line", "")):
+                    skip_indices.add(i - 1)
+
+    # Second pass: build result without skipped entries
+    for i, entry in enumerate(entries):
+        if i not in skip_indices:
+            result.append(entry)
+
+    return result
+
+
 def add_fstab_entry(
         device: str,
         mount_point: str,
@@ -108,8 +141,8 @@ def add_fstab_entry(
     # Read current fstab
     entries = parse_fstab()
 
-    # Remove any existing entry for this mount point
-    entries = [e for e in entries if e.get("mount_point") != mount_point]
+    # Remove any existing entry for this mount point (and its WROLPi comment)
+    entries = _filter_entry_with_comment(entries, mount_point)
 
     # Build new entry line
     new_entry = f"{device_spec} {mount_point} {fstype} {options} 0 2\n"
@@ -166,8 +199,8 @@ def remove_fstab_entry(mount_point: str) -> dict:
     entries = parse_fstab()
     original_count = len([e for e in entries if e["type"] == "mount"])
 
-    # Remove entry
-    entries = [e for e in entries if e.get("mount_point") != mount_point]
+    # Remove entry (and its WROLPi comment)
+    entries = _filter_entry_with_comment(entries, mount_point)
     new_count = len([e for e in entries if e["type"] == "mount"])
 
     if original_count == new_count:
@@ -190,9 +223,9 @@ def remove_fstab_entry(mount_point: str) -> dict:
 
 
 def get_wrolpi_fstab_entries() -> list[dict]:
-    """Get all fstab entries for mounts under /media/wrolpi."""
+    """Get all fstab entries for mounts under /media (WROLPi-managed mounts)."""
     entries = parse_fstab()
     return [
         e for e in entries
-        if e["type"] == "mount" and e["mount_point"].startswith("/media/wrolpi")
+        if e["type"] == "mount" and e["mount_point"].startswith("/media")
     ]
diff --git a/controller/templates/index.html b/controller/templates/index.html
index 507d6c2e..078cbd3c 100644
--- a/controller/templates/index.html
+++ b/controller/templates/index.html
@@ -444,6 +444,15 @@
             margin-top: 0.5rem;
         }
 
+        .logs-select {
+            background: #1a1a2e;
+            border: 1px solid #333;
+            border-radius: 4px;
+            color: #fff;
+            padding: 0.4rem 0.8rem;
+            font-size: 0.85rem;
+        }
+
         /* Sections */
         section {
             margin-bottom: 2rem;
@@ -663,7 +672,7 @@
                     {% endif %}
                     
-                    
+                    
                     {% if service.viewable and service.status == 'running' and service.port %}
                     View
@@ -724,6 +733,19 @@
         
+        
     
 
 
@@ -901,24 +923,95 @@
 
     // ===== LOGS MODAL =====
 
-    async function showLogs(serviceName) {
+    let currentLogsService = null;
+    let logsCountdown = 10;
+    let logsCountdownInterval = null;
+
+    function startLogsCountdown() {
+        if (logsCountdownInterval) clearInterval(logsCountdownInterval);
+        logsCountdown = 10;
+        document.getElementById('logs-countdown').textContent = '10s';
+
+        logsCountdownInterval = setInterval(() => {
+            logsCountdown--;
+            document.getElementById('logs-countdown').textContent = logsCountdown + 's';
+
+            if (logsCountdown <= 0) {
+                // Check if scrolled to bottom (within 50px threshold)
+                const modalBody = document.getElementById('logs-content').closest('.modal-body');
+                const isAtBottom = modalBody.scrollHeight - modalBody.scrollTop - modalBody.clientHeight < 50;
+
+                if (isAtBottom && currentLogsService) {
+                    showLogs(currentLogsService);
+                }
+                logsCountdown = 10;
+                document.getElementById('logs-countdown').textContent = '10s';
+            }
+        }, 1000);
+    }
+
+    function stopLogsCountdown() {
+        if (logsCountdownInterval) {
+            clearInterval(logsCountdownInterval);
+            logsCountdownInterval = null;
+        }
+    }
+
+    async function showLogs(serviceName, showLoading = false) {
         const modal = document.getElementById('logs-modal');
         const title = document.getElementById('logs-title');
         const content = document.getElementById('logs-content');
+        const modalBody = content.closest('.modal-body');
+        const linesSelect = document.getElementById('logs-lines-select');
+
+        currentLogsService = serviceName;
+        const lines = linesSelect.value;
 
         title.textContent = `${serviceName} Logs`;
-        content.innerHTML = ' Loading logs...';
+        if (showLoading) {
+            content.innerHTML = ' Loading logs...';
+        }
         modal.classList.add('show');
 
         try {
-            const data = await apiCall(`api/services/${serviceName}/logs?lines=200`);
+            const data = await apiCall(`api/services/${serviceName}/logs?lines=${lines}`);
             content.textContent = data.logs || 'No logs available';
+            // Scroll modal-body to bottom of logs
+            modalBody.scrollTop = modalBody.scrollHeight;
+            // Start countdown after logs loaded
+            startLogsCountdown();
         } catch (e) {
             content.textContent = `Error loading logs: ${e.message}`;
         }
     }
 
+    function changeLogLines() {
+        if (currentLogsService) {
+            showLogs(currentLogsService);
+        }
+    }
+
+    function refreshLogs() {
+        if (currentLogsService) {
+            showLogs(currentLogsService);
+        }
+    }
+
+    function downloadLogs() {
+        const content = document.getElementById('logs-content').textContent;
+        const datetime = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
+        const filename = `${currentLogsService}_${datetime}.txt`;
+        const blob = new Blob([content], {type: 'text/plain'});
+        const url = URL.createObjectURL(blob);
+        const a = document.createElement('a');
+        a.href = url;
+        a.download = filename;
+        a.click();
+        URL.revokeObjectURL(url);
+    }
+
     function closeLogsModal() {
+        stopLogsCountdown();
         document.getElementById('logs-modal').classList.remove('show');
     }
 
@@ -1432,7 +1525,7 @@
                 }
 
                 html += `
-                    `;
+                    `;
 
                 if (service.viewable && service.status === 'running' && service.port) {
                     const protocol = service.use_https ? 'https' : 'http';
diff --git a/controller/test/test_fstab.py b/controller/test/test_fstab.py
index 0754f231..c3aedaea 100644
--- a/controller/test/test_fstab.py
+++ b/controller/test/test_fstab.py
@@ -102,6 +102,35 @@ class TestAddFstabEntry:
                             # Check that something was written
                             assert len(written_content) > 0
 
+    def test_replaces_entry_without_duplicating_comments(self):
+        """Should remove old WROLPi comment when replacing an entry."""
+        fstab_content = """\
+# /etc/fstab
+UUID=1234 / ext4 defaults 0 1
+# WROLPi managed mount - added 2025-12-15T15:57:37.675757
+UUID=5678 /media/test ext4 defaults,nofail 0 2
+"""
+        written_content = []
+
+        def mock_write(content):
+            written_content.append(content)
+
+        mock_file = mock.mock_open(read_data=fstab_content)
+        mock_file().write = mock_write
+
+        with mock.patch("controller.lib.fstab.require_normal_mode"):
+            with mock.patch("controller.lib.fstab.get_uuid", return_value="5678"):
+                with mock.patch("controller.lib.fstab.backup_fstab"):
+                    with mock.patch("builtins.open", mock_file):
+                        with mock.patch("subprocess.run"):
+                            result = add_fstab_entry("/dev/sda1", "/media/test", "ext4")
+                            assert result["success"] is True
+                            written_str = "".join(written_content)
+                            # Should have exactly ONE WROLPi comment (the new one)
+                            assert written_str.count("WROLPi managed mount") == 1
+                            # The old timestamp should NOT be there
+                            assert "2025-12-15T15:57:37.675757" not in written_str
+
 
 class TestRemoveFstabEntry:
     """Tests for remove_fstab_entry function."""
@@ -128,26 +157,99 @@ class TestRemoveFstabEntry:
                     assert result["success"] is False
                     assert "No entry found" in result["error"]
 
+    def test_removes_wrolpi_comment_with_entry(self):
+        """Should remove WROLPi comment when removing its associated entry."""
+        fstab_content = """\
+# /etc/fstab
+UUID=1234 / ext4 defaults 0 1
+# WROLPi managed mount - added 2025-12-15T15:57:37.675757
+UUID=5678 /media/test ext4 defaults,nofail 0 2
+"""
+        written_content = []
+
+        def mock_write(content):
+            written_content.append(content)
+
+        mock_file = mock.mock_open(read_data=fstab_content)
+        mock_file().write = mock_write
+
+        with mock.patch("controller.lib.fstab.require_normal_mode"):
+            with mock.patch("controller.lib.fstab.backup_fstab"):
+                with mock.patch("builtins.open", mock_file):
+                    with mock.patch("subprocess.run"):
+                        result = remove_fstab_entry("/media/test")
+                        assert result["success"] is True
+                        # WROLPi comment should NOT be in written content
+                        written_str = "".join(written_content)
+                        assert "WROLPi managed mount" not in written_str
+                        # Regular comment should still be there
+                        assert "# /etc/fstab" in written_str
+
+    def test_preserves_non_wrolpi_comments(self):
+        """Should preserve comments that are not WROLPi managed mount comments."""
+        fstab_content = """\
+# /etc/fstab
+UUID=1234 / ext4 defaults 0 1
+# User added this mount manually
+UUID=5678 /media/test ext4 defaults,nofail 0 2
+"""
+        written_content = []
+
+        def mock_write(content):
+            written_content.append(content)
+
+        mock_file = mock.mock_open(read_data=fstab_content)
+        mock_file().write = mock_write
+
+        with mock.patch("controller.lib.fstab.require_normal_mode"):
+            with mock.patch("controller.lib.fstab.backup_fstab"):
+                with mock.patch("builtins.open", mock_file):
+                    with mock.patch("subprocess.run"):
+                        result = remove_fstab_entry("/media/test")
+                        assert result["success"] is True
+                        # User's manual comment should still be there
+                        written_str = "".join(written_content)
+                        assert "# User added this mount manually" in written_str
+
 
 class TestGetWrolpiFstabEntries:
     """Tests for get_wrolpi_fstab_entries function."""
 
-    def test_returns_wrolpi_entries(self):
-        """Should return entries for /media/wrolpi."""
+    def test_returns_all_media_entries(self):
+        """Should return all entries under /media, not just /media/wrolpi."""
         fstab_content = """\
 UUID=1234 / ext4 defaults 0 1
 UUID=5678 /media/wrolpi ext4 defaults 0 2
 UUID=9abc /media/wrolpi/data ext4 defaults 0 2
 UUID=defg /media/usb vfat defaults 0 0
+UUID=hijk /media/roland/64GB exfat defaults 0 0
 """
         with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
             result = get_wrolpi_fstab_entries()
-            assert len(result) == 2
-            assert result[0]["mount_point"] == "/media/wrolpi"
-            assert result[1]["mount_point"] == "/media/wrolpi/data"
+            # Should include all /media/* entries
+            assert len(result) == 4
+            mount_points = [e["mount_point"] for e in result]
+            assert "/media/wrolpi" in mount_points
+            assert "/media/wrolpi/data" in mount_points
+            assert "/media/usb" in mount_points
+            assert "/media/roland/64GB" in mount_points
+            # Root should NOT be included
+            assert "/" not in mount_points
 
-    def test_returns_empty_if_no_wrolpi_entries(self):
-        """Should return empty list if no WROLPi entries."""
+    def test_excludes_non_media_mounts(self):
+        """Should exclude mounts outside /media."""
+        fstab_content = """\
+UUID=1234 / ext4 defaults 0 1
+UUID=5678 /home ext4 defaults 0 2
+UUID=9abc /media/wrolpi ext4 defaults 0 2
+"""
+        with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
+            result = get_wrolpi_fstab_entries()
+            assert len(result) == 1
+            assert result[0]["mount_point"] == "/media/wrolpi"
+
+    def test_returns_empty_if_no_media_entries(self):
+        """Should return empty list if no entries under /media."""
         fstab_content = "UUID=1234 / ext4 defaults 0 1\n"
         with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
             result = get_wrolpi_fstab_entries()