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
);
}
// Mobile service row - simplified layout
// Exported so tests can mount a row directly: `Media` renders neither branch in jsdom,
// where no media query matches, so `ServicesSection` produces no rows at all there.
export function MobileServiceRow({service, onAction}) {
const {
loading, logsOpen, setLogsOpen, logs, logsLoading, linesCount, countdown, logsRef,
handleAction, fetchLogs, handleViewLogs, handleLinesChange, handleDownloadLogs,
isRunning, statusKind, viewUrl
} = useServiceRow(service, onAction);
return (
No services found. Services may not be available in this environment.
)}
);
}
// Helper to get health status color from SMART assessment
/**
* The severity of a SMART assessment.
*
* Roles, not hues: a drive's health is a severity and has to rank as one. All four
* branches together -- a helper where PASS and FAIL rank but WARN is an unranked hue is
* worse than either choice, and in night `--amber` is byte-identical to `--yellow`, so WARN
* would stop sitting between them.
*
* Exported and pure so the mapping can be tested as a mapping rather than scraped out of
* the source, which is what this needed before it was separated from the CSS wrapper.
*/
export const healthRole = (assessment) => {
if (!assessment) return 'neutral';
switch (assessment.toUpperCase()) {
case 'PASS':
return 'success';
case 'WARN':
return 'warning';
case 'FAIL':
return 'danger';
default:
return 'neutral';
}
};
const getHealthColor = (assessment) => `var(--${healthRole(assessment)})`;
// 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.health || drive.assessment);
return (
SMART Details: {drive.device}
Disk management is not available in Docker environments.
);
}
if (loading) {
return Disk Management;
}
return (
Disk Management
{error && Some disk information unavailable: {error}}
Disks
{disks.length > 0 ? (
This is the primary WROLPi drive. The WROLPi API service will
be stopped before unmounting, and your media will be
unavailable until a drive is mounted at {PRIMARY_MOUNT} and
the API service is started again.
setNewComment(e.target.value)}
/>
);
}
// Human labels for the hotspot protocols reported by the Controller.
const hotspotProtocolLabels = {
wpa2: 'WPA2 (most compatible)',
wpa3: 'WPA3',
};
function HotspotSettingsForm() {
const dockerized = useDockerized();
const [devices, setDevices] = React.useState([]);
const [protocols, setProtocols] = React.useState([]);
const [form, setForm] = React.useState({device: '', ssid: '', password: '', protocol: ''});
const [loading, setLoading] = React.useState(true);
const [saving, setSaving] = React.useState(false);
const [qrOpen, setQrOpen] = React.useState(false);
React.useEffect(() => {
const fetchSettings = async () => {
try {
const [settings, devicesResponse] = await Promise.all([getHotspotSettings(), getHotspotDevices()]);
setForm({
device: settings.device,
ssid: settings.ssid,
password: settings.password,
protocol: settings.protocol,
});
setDevices(devicesResponse.devices || []);
} catch (e) {
console.error('Failed to fetch hotspot settings', e);
} finally {
setLoading(false);
}
};
fetchSettings();
}, []);
// The supported protocols depend on the selected device's hardware.
React.useEffect(() => {
if (!form.device) {
return;
}
// Ignore out-of-order responses when the user switches devices quickly.
let cancelled = false;
const fetchProtocols = async () => {
try {
const response = await getHotspotProtocols(form.device);
if (cancelled) {
return;
}
const supported = response.protocols || [];
setProtocols(supported);
// Reset a selection the probed device does not support (e.g. WPA3 kept
// after switching to a WPA2-only adapter).
if (supported.length) {
setForm(f => supported.includes(f.protocol) ? f : {...f, protocol: supported[0]});
}
} catch (e) {
if (!cancelled) {
console.error('Failed to fetch hotspot protocols', e);
setProtocols([]);
}
}
};
fetchProtocols();
return () => {
cancelled = true;
};
}, [form.device]);
const handleSave = async () => {
setSaving(true);
try {
const settings = await updateHotspotSettings(form);
setForm(settings);
toast({type: 'success', title: 'Hotspot settings saved', time: 3000});
} catch (e) {
toast({type: 'error', title: 'Failed to save hotspot settings', description: e.message, time: 5000});
} finally {
setSaving(false);
}
};
if (loading) {
return Hotspot Settings;
}
// Keep the saved device selectable even if it is not currently present
// (e.g. a USB WiFi dongle is unplugged).
const deviceOptions = [...new Set([...devices, form.device].filter(Boolean))]
.map(device => ({value: device, label: device}));
// Keep the saved protocol selectable even if the device does not report it.
const protocolOptions = [...new Set([...protocols, form.protocol].filter(Boolean))]
.map(protocol => ({value: protocol, label: hotspotProtocolLabels[protocol] || protocol}));
// Special string which allows a mobile device to connect to a specific Wi-Fi.
// The WPA QR format requires backslash-escaping of \ ; , " in the SSID and password.
const escapeWifi = (s) => s.replace(/([\\;,"])/g, '\\$1');
const qrCodeValue = `WIFI:S:${escapeWifi(form.ssid)};T:WPA;P:${escapeWifi(form.password)};;`;
return Hotspot Settings setForm({...form, ssid: e.target.value})}
/>
setForm({...form, password: e.target.value})}
/>
setQrOpen(true)}
/>
setQrOpen(false)} closeIcon>
Scan this code to join the hotspot
{/* `media`: filtered as a unit by night mode; a QR code needs real black-on-white
contrast to scan, so it is exempted the same way DonatePage's and Share's are. */}
)}
);
}
export function ControllerPage() {
return (
// `wrolpi-stack`: these four sections are panels held in a wrapper of this page's own,
// so the stack on PageContainer does not reach them -- the same hole Settings had.