import React from 'react';
import {Checkbox, Container, Dropdown, Form, Icon, Input} from "semantic-ui-react";
import {Button, Confirm, Header, Loader, Modal, Segment, Table} from "../Theme";
import {APIButton, BluetoothToggle, HandPointMessage, HotspotToggle, InfoMessage, ThrottleToggle, Toggle,} from "../Common";
import {useDockerized} from "../../hooks/customHooks";
import {Media} from "../../contexts/contexts";
import {
addFstabEntry,
disableService,
enableService,
getDisks,
getFstabEntries,
getServiceLogs,
getServices,
getSmartStatus,
mountDisk,
removeFstabEntry,
restartService,
restartServices,
startService,
stopService,
unmountDisk,
} from "../../api/controller";
import {toast} from "react-semantic-toasts-2";
import {RestartButton, ShutdownButton} from "./Settings";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {CONTROLLER_URI} from "../Vars";
// Service status color mapping
const statusColors = {
running: 'green',
stopped: 'red',
failed: 'red',
unknown: 'yellow',
};
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},
];
// 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 = (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 statusColor = statusColors[service.status] || 'grey';
// 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 || '';
viewUrl = `${protocol}://${host}:${service.port}${path}`;
}
return {
loading, logsOpen, setLogsOpen, logs, logsLoading, linesCount, countdown, logsRef,
handleAction, fetchLogs, handleViewLogs, handleLinesChange, handleDownloadLogs,
isRunning, statusColor, viewUrl
};
}
// Logs modal component (shared between mobile and desktop)
function ServiceLogsModal({
service,
logsOpen,
setLogsOpen,
logs,
logsLoading,
logsRef,
linesCount,
countdown,
handleViewLogs,
handleLinesChange,
handleDownloadLogs,
fetchLogs
}) {
return (
setLogsOpen(false)}
onOpen={handleViewLogs}
trigger={ }
size='fullscreen'
>
Logs: {service.name}
{logsLoading ? (
) : (
{logs}
)}
{countdown}s
fetchLogs(linesCount)} color='blue' icon='refresh' content='Refresh'/>
setLogsOpen(false)}>Close
);
}
// Mobile service row - simplified layout
function MobileServiceRow({service, onAction}) {
const {
loading, logsOpen, setLogsOpen, logs, logsLoading, linesCount, countdown, logsRef,
handleAction, fetchLogs, handleViewLogs, handleLinesChange, handleDownloadLogs,
isRunning, statusColor, viewUrl
} = useServiceRow(service, onAction);
return (
{service.name}
{service.description && {service.description}
}
{isRunning ? (
handleAction('Stop', stopService)}
/>
) : (
handleAction('Start', startService)}
/>
)}
handleAction('Restart', restartService)}
/>
{viewUrl && (
)}
);
}
// Desktop service row - full layout with all columns
function DesktopServiceRow({service, onAction, dockerized}) {
const {
loading, logsOpen, setLogsOpen, logs, logsLoading, linesCount, countdown, logsRef,
handleAction, fetchLogs, handleViewLogs, handleLinesChange, handleDownloadLogs,
isRunning, statusColor, viewUrl
} = useServiceRow(service, onAction);
return (
{service.name}
{service.description && {service.description}
}
{service.port || '-'}
{isRunning ? (
handleAction('Stop', stopService)}
/>
) : (
handleAction('Start', startService)}
/>
)}
handleAction('Restart', restartService)}
/>
{viewUrl && (
)}
{!dockerized && (
{
if (checked) {
await handleAction('Enable', enableService);
} else {
await handleAction('Disable', disableService);
}
}}
label={service.enabled ? 'Enabled' : 'Disabled'}
/>
)}
);
}
function ServicesSection() {
const [services, setServices] = React.useState([]);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);
const [restarting, setRestarting] = React.useState(false);
const dockerized = useDockerized();
const handleRestartServices = async () => {
setRestarting(true);
try {
await restartServices();
toast({
type: 'success',
title: 'Services Restarting',
description: 'All WROLPi services are being restarted.',
time: 5000,
});
// Refresh service list after restart initiated
fetchServices();
} catch (e) {
toast({
type: 'error',
title: 'Restart Failed',
description: e.message,
time: 5000,
});
} finally {
setRestarting(false);
}
};
const fetchServices = async () => {
setLoading(true);
setError(null);
try {
const result = await getServices();
setServices(Array.isArray(result) ? result : []);
} catch (e) {
setError(e.message);
setServices([]);
} finally {
setLoading(false);
}
};
React.useEffect(() => {
fetchServices();
// Refresh every 10 seconds
const interval = setInterval(fetchServices, 10000);
return () => clearInterval(interval);
}, []);
if (loading && services.length === 0) {
return
;
}
if (error) {
return
Error loading services: {error}
Retry
;
}
const restartButton = (colSpan) => (
{restarting ? 'Restarting...' : 'Restart All Services'}
);
return (
{/* Mobile table - 2 columns */}
Service
Actions
{services.map(service => (
))}
{restartButton(2)}
{/* Desktop table - full columns */}
Service
Port
Actions
{!dockerized && Boot }
{services.map(service => (
))}
{restartButton(dockerized ? 4 : 5)}
{services.length === 0 && (
No services found. Services may not be available in this environment.
)}
);
}
// Helper to get health status color from SMART assessment
const getHealthColor = (assessment) => {
if (!assessment) return 'grey';
const upper = assessment.toUpperCase();
if (upper === 'PASS') return 'green';
if (upper === 'WARN') return 'yellow';
if (upper === 'FAIL') return 'red';
return 'grey';
};
// Helper to format power-on hours
const formatPowerOnHours = (hours) => {
if (hours === null || hours === undefined) return '-';
const days = Math.floor(hours / 24);
const years = Math.floor(days / 365);
if (years > 0) return `${hours.toLocaleString()} hrs (${years}y ${days % 365}d)`;
if (days > 0) return `${hours.toLocaleString()} hrs (${days}d)`;
return `${hours} hrs`;
};
function SmartDetailsModal({drive, open, onClose}) {
if (!drive) return null;
const healthColor = getHealthColor(drive.assessment);
return (
SMART Details: {drive.device}
Model
{drive.model || '-'}
Serial
{drive.serial || '-'}
Capacity
{drive.capacity || '-'}
Assessment
{drive.assessment || 'Unknown'}
Temperature
{drive.temperature !== null && drive.temperature !== undefined
? `${drive.temperature}°C`
: '-'}
Power-On Hours
{formatPowerOnHours(drive.power_on_hours)}
Reallocated Sectors
0 ? 'orange' : 'inherit'}}>
{drive.reallocated_sectors !== null && drive.reallocated_sectors !== undefined
? drive.reallocated_sectors
: '-'}
Pending Sectors
0 ? 'orange' : 'inherit'}}>
{drive.pending_sectors !== null && drive.pending_sectors !== undefined
? drive.pending_sectors
: '-'}
SMART Enabled
{drive.smart_enabled ? 'Yes' : 'No'}
Close
);
}
// Protected mount points that should not be unmounted
const PROTECTED_MOUNTS = ['/', '/boot', '/boot/firmware'];
// Helper to format disk size
const formatSize = (size) => {
if (!size) return '-';
// If already a string (e.g., "59.5G" from lsblk), return as-is
if (typeof size === 'string') return size;
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let bytes = size;
while (bytes >= 1024 && i < units.length - 1) {
bytes /= 1024;
i++;
}
return `${bytes.toFixed(1)} ${units[i]}`;
};
function MountModal({disk, open, onClose, onMount}) {
const [mountPoint, setMountPoint] = React.useState('');
const [persist, setPersist] = React.useState(false);
const [loading, setLoading] = React.useState(false);
// Set default mount point when disk changes
React.useEffect(() => {
if (disk) {
const defaultMount = disk.label ? `/media/${disk.label}` : `/media/${disk.name}`;
setMountPoint(defaultMount);
setPersist(false);
}
}, [disk]);
const handleMount = async () => {
if (!mountPoint.trim()) {
toast({
type: 'error',
title: 'Mount point required',
description: 'Please enter a mount point.',
time: 3000,
});
return;
}
setLoading(true);
try {
await mountDisk(disk.path, mountPoint.trim(), disk.fstype, 'defaults', persist);
toast({
type: 'success',
title: 'Disk Mounted',
description: `${disk.name} mounted at ${mountPoint}`,
time: 3000,
});
onClose();
if (onMount) onMount();
} catch (e) {
toast({
type: 'error',
title: 'Mount Failed',
description: e.message,
time: 5000,
});
} finally {
setLoading(false);
}
};
if (!disk) return null;
return (
Mount Disk: {disk.name}
Mount Point
setMountPoint(e.target.value)}
placeholder="/media/..."
fluid
/>
setPersist(checked)}
/>
{disk.fstype && (
Filesystem: {disk.fstype}
{disk.label && ` | Label: ${disk.label}`}
{disk.size && ` | Size: ${formatSize(disk.size)}`}
)}
Cancel
Mount
);
}
function DiskSection() {
const [disks, setDisks] = React.useState([]);
const [fstabEntries, setFstabEntries] = React.useState([]);
const [smartDrives, setSmartDrives] = React.useState([]);
const [smartAvailable, setSmartAvailable] = React.useState(true);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);
const [selectedDrive, setSelectedDrive] = React.useState(null);
const [detailsOpen, setDetailsOpen] = React.useState(false);
const [mountModalOpen, setMountModalOpen] = React.useState(false);
const [selectedDisk, setSelectedDisk] = React.useState(null);
const [unmountConfirmOpen, setUnmountConfirmOpen] = React.useState(false);
const [unmountTarget, setUnmountTarget] = React.useState(null);
const dockerized = useDockerized();
const fetchDiskInfo = async () => {
setLoading(true);
setError(null);
try {
const [disksResult, fstabResult, smartResult] = await Promise.allSettled([
getDisks(),
getFstabEntries(),
getSmartStatus(),
]);
if (disksResult.status === 'fulfilled') {
setDisks(Array.isArray(disksResult.value) ? disksResult.value : []);
}
if (fstabResult.status === 'fulfilled') {
setFstabEntries(Array.isArray(fstabResult.value) ? fstabResult.value : []);
}
if (smartResult.status === 'fulfilled' && smartResult.value) {
// Handle new API format: {available: bool, drives: [...]}
const smartData = smartResult.value;
setSmartAvailable(smartData.available !== false);
setSmartDrives(Array.isArray(smartData.drives) ? smartData.drives : []);
} else {
setSmartAvailable(false);
setSmartDrives([]);
}
} catch (e) {
setError(e.message);
} finally {
setLoading(false);
}
};
const handleShowDetails = (drive) => {
setSelectedDrive(drive);
setDetailsOpen(true);
};
const handleOpenMountModal = (disk) => {
setSelectedDisk(disk);
setMountModalOpen(true);
};
const handleCloseMountModal = () => {
setMountModalOpen(false);
setSelectedDisk(null);
};
const handleUnmountClick = (mountPoint) => {
setUnmountTarget(mountPoint);
setUnmountConfirmOpen(true);
};
const handleUnmountConfirm = async () => {
if (!unmountTarget) return;
try {
await unmountDisk(unmountTarget);
toast({
type: 'success',
title: 'Disk Unmounted',
description: `Unmounted ${unmountTarget}`,
time: 3000,
});
fetchDiskInfo();
} catch (e) {
toast({
type: 'error',
title: 'Unmount Failed',
description: e.message,
time: 5000,
});
} finally {
setUnmountConfirmOpen(false);
setUnmountTarget(null);
}
};
const handleTogglePersist = async (disk, enable) => {
try {
if (enable) {
await addFstabEntry(disk.path, disk.mountpoint, disk.fstype || 'auto');
toast({
type: 'success',
title: 'Persistence Enabled',
description: `${disk.mountpoint} will persist across reboots`,
time: 3000,
});
} else {
await removeFstabEntry(disk.mountpoint);
toast({
type: 'success',
title: 'Persistence Disabled',
description: `${disk.mountpoint} will not persist across reboots`,
time: 3000,
});
}
fetchDiskInfo();
} catch (e) {
toast({
type: 'error',
title: 'Failed to update persistence',
description: e.message,
time: 5000,
});
}
};
// Check if a mount point is in fstab (persistent)
const isPersistent = (mountpoint) => {
return fstabEntries.some(entry => entry.mount_point === mountpoint);
};
React.useEffect(() => {
fetchDiskInfo();
}, []);
if (dockerized) {
return (
Disk management is not available in Docker environments.
);
}
if (loading) {
return
;
}
return (
{error && Some disk information unavailable: {error}
}
{disks.length > 0 ? (
Name
Size
Type
Label
Mount Point
Persist
Actions
{disks.map((disk) => {
const isMounted = disk.mountpoint && disk.mountpoint !== '';
const isProtected = PROTECTED_MOUNTS.includes(disk.mountpoint);
const persistent = isMounted && isPersistent(disk.mountpoint);
return (
{disk.name}
{formatSize(disk.size)}
{disk.fstype || '-'}
{disk.label || '-'}
{isMounted ? (
{disk.mountpoint}
) : (
-
)}
{isMounted && !isProtected ? (
handleTogglePersist(disk, checked)}
label={persistent ? 'Enabled' : 'Disabled'}
/>
) : (
-
)}
{isMounted && isProtected ? (
System
) : isMounted ? (
handleUnmountClick(disk.mountpoint)}
/>
) : (
handleOpenMountModal(disk)}
/>
)}
);
})}
) : (
No disks detected.
)}
{!smartAvailable ? (
SMART monitoring not available (pySMART not installed or not supported)
) : smartDrives.length > 0 ? (
Device
Health
Temperature
Actions
{smartDrives.map((drive) => (
{drive.device}
{drive.assessment || 'Unknown'}
{drive.temperature !== null && drive.temperature !== undefined
? `${drive.temperature}°C`
: '-'}
handleShowDetails(drive)}
/>
))}
) : (
No SMART-capable drives detected.
)}
setDetailsOpen(false)}
/>
{
setUnmountConfirmOpen(false);
setUnmountTarget(null);
}}
onConfirm={handleUnmountConfirm}
confirmButton='Unmount'
/>
Refresh
);
}
function AdminControlsSection() {
const dockerized = useDockerized();
return (
{!dockerized && (
)}
);
}
function ControllerLink() {
return
You can view the Controller at {CONTROLLER_URI}
}
export function ControllerPage() {
return (
);
}
export default ControllerPage;