Files
2026-07-22 01:17:58 +09:00

119 lines
3.0 KiB
PHP

<?php
require_once __DIR__ . '/../common/auth.php';
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
custom_require_auth();
$config = custom_config();
$wakeConfig = $config['control']['wake_lan'] ?? [];
$controlBase = rtrim((string)($wakeConfig['base'] ?? ''), '/');
$controlToken = (string)($wakeConfig['token'] ?? '');
$targetMac = strtolower((string)($wakeConfig['mac'] ?? ''));
$timeout = max(2, (int)($wakeConfig['timeout'] ?? 8));
function wake_control_request(string $method, string $action, array $params): ?array
{
global $controlBase, $controlToken, $timeout;
if ($controlBase === '' || $controlToken === '') {
return null;
}
$url = $controlBase . '/api.php?action=' . rawurlencode($action);
$body = http_build_query($params, '', '&');
if ($method === 'GET' && $body !== '') {
$url .= '&' . $body;
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'X-Control-API-Token: ' . $controlToken,
],
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
'X-Control-API-Token: ' . $controlToken,
]);
}
$raw = curl_exec($ch);
$status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (!is_string($raw) || $raw === '') {
return null;
}
$decoded = json_decode($raw, true);
if (!is_array($decoded)) {
return null;
}
$decoded['_http_status'] = $status;
return $decoded;
}
if (isset($_GET['status'])) {
$res = wake_control_request('GET', 'wake_lan_status', [
'mac' => $targetMac,
]);
if (!$res || empty($res['ok'])) {
custom_json(['result' => 'error'], 502);
}
$wake = $res['data']['wake'] ?? [];
custom_json([
'result' => 'ok',
'state' => (string)($wake['state'] ?? 'unknown'),
'wake' => $wake,
]);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$res = wake_control_request('POST', 'wake_lan', [
'mac' => $targetMac,
]);
if (!$res) {
custom_json(['result' => 'error'], 502);
}
if (!empty($res['ok'])) {
custom_json([
'result' => 'sent',
'wake' => $res['data']['wake'] ?? null,
]);
}
if (($res['message'] ?? '') === 'device_already_online') {
custom_json([
'result' => 'already',
'state' => 'on',
]);
}
custom_json([
'result' => 'error',
'message' => $res['message'] ?? $res['error'] ?? 'control_wake_failed',
], 502);
}
custom_json(['result' => 'invalid_request'], 400);