import React from 'react'; import {IconInfoCircle, IconPlayerEject} from '@tabler/icons-react'; import { Button, Checkbox, Confirm, Group, Header, Icon, IconButton, Loading, Message, Modal, Panel, Select, Status, Table, TextInput, toast, } from "../ui"; import {APIButton, BluetoothToggle, DesktopToggle, DirectorySearch, HandPointMessage, HotspotToggle, InfoMessage, ThrottleToggle, Toggle, VncToggle,} from "../Common"; import {useDockerized, useMediaDirectory} from "../../hooks/customHooks"; import {Media} from "../../contexts/contexts"; import { addFstabEntry, addSambaShare, disableService, enableService, getDisks, getFstabEntries, getHotspotDevices, getHotspotProtocols, getHotspotSettings, getSambaStatus, getServiceLogs, getServices, getSmartStatus, mountDisk, removeFstabEntry, removeSambaShare, restartService, restartServices, startService, stopService, unmountDisk, updateHotspotSettings, } from "../../api/controller"; import QRCode from "react-qr-code"; import {RestartButton, ShutdownButton} from "./Settings"; import {CONTROLLER_URI} from "../Vars"; // Service status kind mapping. Status only knows complete/active/pending/failed, // so "stopped" and "unknown" both land on pending -- the Start/Stop button and // service name still tell them apart, this dot only carries running vs. failed. const statusKinds = { running: 'complete', stopped: 'pending', failed: 'failed', unknown: 'pending', }; // Sort order within a group: problems first so they stay visible. const statusSortOrder = { failed: 0, unknown: 1, stopped: 2, running: 3, }; // Partition services into the two Controller groups. The backend computes each // service's `group` ("core" | "optional"); a missing group (e.g. Docker // containers) is treated as core so nothing is hidden. Within each group, // failed/stopped services sort first, then alphabetically. export const groupServices = (services) => { const byStatusThenName = (a, b) => { const sa = statusSortOrder[a.status] ?? 1; const sb = statusSortOrder[b.status] ?? 1; if (sa !== sb) return sa - sb; return a.name.localeCompare(b.name); }; const core = services.filter(s => s.group !== 'optional').sort(byStatusThenName); const optional = services.filter(s => s.group === 'optional').sort(byStatusThenName); return {core, optional}; }; const linesOptions = [ {value: '100', label: '100 lines'}, {value: '250', label: '250 lines'}, {value: '500', label: '500 lines'}, {value: '1000', label: '1000 lines'}, {value: '5000', label: '5000 lines'}, ]; // Custom hook for service row state and handlers function useServiceRow(service, onAction) { 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); try { await actionFn(service.name); toast({ type: 'success', title: `${action} ${service.name}`, description: `Successfully ${action.toLowerCase()}ed ${service.name}`, time: 3000, }); if (onAction) onAction(); } catch (e) { toast({ type: 'error', title: `${action} Failed`, description: e.message, time: 5000, }); } finally { setLoading(false); } }; const fetchLogs = async (lines, showLoading = false) => { if (showLoading) setLogsLoading(true); try { const result = await getServiceLogs(service.name, lines); setLogs(result.logs || 'No logs available'); } catch (e) { setLogs(`Error fetching logs: ${e.message}`); } finally { 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 = (value) => { const lines = parseInt(value, 10); setLinesCount(lines); fetchLogs(lines); }; 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 statusKind = statusKinds[service.status] || 'pending'; // Build view URL if service is viewable let viewUrl = null; if (service.viewable && service.port && isRunning) { const protocol = service.use_https ? 'https' : 'http'; const host = window.location.hostname; const path = service.view_path || ''; const isDefaultPort = (protocol === 'https' && service.port === 443) || (protocol === 'http' && service.port === 80); const portSuffix = isDefaultPort ? '' : `:${service.port}`; viewUrl = `${protocol}://${host}${portSuffix}${path}`; } return { loading, logsOpen, setLogsOpen, logs, logsLoading, linesCount, countdown, logsRef, handleAction, fetchLogs, handleViewLogs, handleLinesChange, handleDownloadLogs, isRunning, statusKind, viewUrl }; } // Logs modal component (shared between mobile and desktop) function ServiceLogsModal({ service, logsOpen, setLogsOpen, logs, logsLoading, logsRef, linesCount, countdown, handleLinesChange, handleDownloadLogs, fetchLogs }) { return ( setLogsOpen(false)} size='fullscreen' > Logs: {service.name} {logsLoading ? ( ) : (
                        {logs}
                    
)}
{countdown}s setForm({...form, device: value})} />