Files

78 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
function runPythonApi(string $action, array $args): array
{
$scriptPath = __DIR__ . '/py/api.py';
$pythonCandidates = PHP_OS_FAMILY === 'Windows'
? ['python', 'py']
: ['/usr/bin/python3', '/usr/bin/python', 'python3', 'python'];
$escapedArguments = array_map('escapeshellarg', array_merge([$scriptPath, $action], $args));
$lastError = 'Python konnte nicht gestartet werden.';
foreach ($pythonCandidates as $pythonBinary) {
$command = $pythonBinary . ' ' . implode(' ', $escapedArguments) . ' 2>&1';
$output = [];
$resultCode = 0;
exec($command, $output, $resultCode);
$joined = trim(implode("\n", $output));
$decoded = json_decode($joined, true);
if (is_array($decoded)) {
return [
'ok' => (bool) ($decoded['ok'] ?? false),
'data' => $decoded,
'raw' => $joined,
'command' => $command,
];
}
if ($joined !== '') {
$lastError = $joined;
} elseif ($resultCode !== 0) {
$lastError = 'Fehlercode ' . $resultCode . ' bei ' . $pythonBinary;
}
}
return [
'ok' => false,
'error' => $lastError,
];
}
function runPythonApiWithJsonPayloadFile(string $action, array $payload): array
{
$tempFile = tempnam(sys_get_temp_dir(), 'skyview_py_');
if ($tempFile === false) {
return [
'ok' => false,
'error' => 'Temporäre Datei für Python-Payload konnte nicht erstellt werden.',
];
}
$jsonPayload = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($jsonPayload === false) {
@unlink($tempFile);
return [
'ok' => false,
'error' => 'Python-Payload konnte nicht als JSON kodiert werden.',
];
}
if (file_put_contents($tempFile, $jsonPayload) === false) {
@unlink($tempFile);
return [
'ok' => false,
'error' => 'Temporäre Datei für Python-Payload konnte nicht geschrieben werden.',
];
}
try {
return runPythonApi($action, ['@' . $tempFile]);
} finally {
@unlink($tempFile);
}
}