You've already forked Atomcms-edit
Remove all auto-update functionality (commands, services, widgets, blades, translations)
This commit is contained in:
@@ -1,272 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Emulator;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
|
||||
class EmulatorBuildService
|
||||
{
|
||||
use EmulatorConfiguration;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->loadConfiguration();
|
||||
}
|
||||
|
||||
public function buildFromSource(bool $force = false): array
|
||||
{
|
||||
$repo = $this->sourceRepo ?: $this->githubRepo;
|
||||
$branch = $this->sourceBranch ?: $this->githubBranch ?: 'main';
|
||||
|
||||
if (! $repo) {
|
||||
return ['success' => false, 'error' => 'Geen source repo geconfigureerd'];
|
||||
}
|
||||
|
||||
$sourcePath = $this->emulatorSourcePath;
|
||||
$serviceName = $this->emulatorService;
|
||||
|
||||
Log::info('[EmulatorBuild] Starting source build', [
|
||||
'repo' => $repo,
|
||||
'branch' => $branch,
|
||||
'path' => $sourcePath,
|
||||
]);
|
||||
|
||||
$this->ensureJavaInstalled();
|
||||
|
||||
Process::timeout(10)->run('mkdir -p ' . escapeshellarg(dirname((string) $sourcePath)));
|
||||
Process::timeout(10)->run('mkdir -p ' . escapeshellarg((string) $this->jarPath));
|
||||
Process::timeout(10)->run('chown -R www-data:www-data ' . escapeshellarg(dirname((string) $sourcePath)));
|
||||
|
||||
$maxRetries = 2;
|
||||
$lastError = '';
|
||||
|
||||
for ($retry = 0; $retry <= $maxRetries; $retry++) {
|
||||
Process::timeout(10)->run('chown -R www-data:www-data ' . escapeshellarg(dirname((string) $sourcePath)) . ' 2>/dev/null || true');
|
||||
Process::timeout(10)->run('chown -R www-data:www-data ' . escapeshellarg((string) $sourcePath) . ' 2>/dev/null || true');
|
||||
|
||||
if ($retry > 0) {
|
||||
Log::info('[EmulatorBuild] Retry attempt', ['attempt' => $retry]);
|
||||
Process::timeout(30)->run('rm -rf ' . escapeshellarg((string) $sourcePath));
|
||||
}
|
||||
|
||||
try {
|
||||
$existsCheck = Process::timeout(5)->run('[ -d ' . escapeshellarg((string) $sourcePath) . " ] && echo 'exists'");
|
||||
$sourceExists = $existsCheck->successful() && trim($existsCheck->output()) === 'exists';
|
||||
|
||||
$gitCheck = Process::timeout(5)->run('[ -d ' . escapeshellarg((string) $sourcePath) . "/.git ] && echo 'git'");
|
||||
$isGitRepo = $gitCheck->successful() && trim($gitCheck->output()) === 'git';
|
||||
|
||||
if ($sourceExists && $isGitRepo) {
|
||||
Log::info('[EmulatorBuild] Pulling latest changes');
|
||||
$commands = [
|
||||
'cd ' . escapeshellarg((string) $sourcePath) . ' && git fetch origin',
|
||||
'cd ' . escapeshellarg((string) $sourcePath) . ' && git checkout ' . escapeshellarg($branch),
|
||||
'cd ' . escapeshellarg((string) $sourcePath) . ' && git pull origin ' . escapeshellarg($branch),
|
||||
];
|
||||
} else {
|
||||
Log::info('[EmulatorBuild] Cloning repository');
|
||||
$commands = [
|
||||
'sudo rm -rf ' . escapeshellarg((string) $sourcePath) . ' 2>/dev/null || rm -rf ' . escapeshellarg((string) $sourcePath),
|
||||
'mkdir -p ' . escapeshellarg(dirname((string) $sourcePath)),
|
||||
'git clone --branch ' . escapeshellarg($branch) . ' --depth 1 https://github.com/' . escapeshellarg($repo) . '.git ' . escapeshellarg((string) $sourcePath),
|
||||
'chown -R www-data:www-data ' . escapeshellarg((string) $sourcePath),
|
||||
];
|
||||
}
|
||||
|
||||
$command = implode(' && ', $commands);
|
||||
$result = Process::timeout(300)->run($command);
|
||||
|
||||
if ($result->failed()) {
|
||||
$lastError = 'Git clone/pull failed: ' . substr($result->errorOutput(), 0, 300);
|
||||
Log::warning('[EmulatorBuild] Git operation failed', ['error' => $lastError, 'attempt' => $retry]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$buildCommands = $this->getBuildCommands($sourcePath);
|
||||
|
||||
Log::info('[EmulatorBuild] Running build', ['command' => $buildCommands]);
|
||||
$buildResult = Process::timeout(600)->run('cd ' . escapeshellarg((string) $sourcePath) . ' && ' . $buildCommands);
|
||||
|
||||
$hasSignalError = str_contains($buildResult->errorOutput(), 'signal') || str_contains($buildResult->output(), 'signal');
|
||||
|
||||
if ($hasSignalError) {
|
||||
Log::warning('[EmulatorBuild] Build process received signal, checking if JAR was built anyway');
|
||||
}
|
||||
|
||||
$jarPath = $this->findBuiltJar($sourcePath);
|
||||
|
||||
if ($jarPath) {
|
||||
Log::info('[EmulatorBuild] JAR found despite build status', ['jar' => $jarPath]);
|
||||
} elseif ($buildResult->failed() && ! $hasSignalError) {
|
||||
$lastError = 'Build failed: ' . substr($buildResult->errorOutput(), 0, 500);
|
||||
Log::warning('[EmulatorBuild] Build failed', ['error' => $lastError, 'attempt' => $retry]);
|
||||
|
||||
if ($retry < $maxRetries) {
|
||||
$cleanCommands = [
|
||||
'cd ' . escapeshellarg((string) $sourcePath) . ' && mvn clean 2>/dev/null || ./gradlew clean 2>/dev/null || true',
|
||||
];
|
||||
Process::timeout(60)->run(implode(' && ', $cleanCommands));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $jarPath) {
|
||||
$lastError = 'Build succeeded but JAR not found. Check build output.';
|
||||
Log::warning('[EmulatorBuild] JAR not found', ['attempt' => $retry]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
return $this->deployJar($jarPath, $serviceName);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$lastError = $e->getMessage();
|
||||
Log::error('[EmulatorBuild] Source build exception', ['error' => $lastError, 'attempt' => $retry]);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => 'Build mislukt na ' . ($maxRetries + 1) . ' pogingen. Laatste fout: ' . $lastError,
|
||||
];
|
||||
}
|
||||
|
||||
public function getBuildCommands(string $sourcePath): string
|
||||
{
|
||||
$pomPath = $sourcePath;
|
||||
$pomCheck = Process::timeout(5)->run("[ -f {$pomPath}/pom.xml ] && echo 'pom'");
|
||||
|
||||
if (! $pomCheck->successful() || trim($pomCheck->output()) !== 'pom') {
|
||||
$pomPath = $sourcePath . '/Emulator';
|
||||
$pomCheck = Process::timeout(5)->run("[ -f {$pomPath}/pom.xml ] && echo 'pom'");
|
||||
}
|
||||
|
||||
$gradlewPath = $sourcePath . '/gradlew';
|
||||
$gradlewCheck = Process::timeout(5)->run("[ -f {$gradlewPath} ] && echo 'gradlew'");
|
||||
|
||||
$gradlePath = $sourcePath . '/build.gradle';
|
||||
$gradleCheck = Process::timeout(5)->run("[ -f {$gradlePath} ] && echo 'gradle'");
|
||||
|
||||
if ($pomCheck->successful() && trim($pomCheck->output()) === 'pom') {
|
||||
return "cd {$pomPath} && mvn clean package -DskipTests 2>&1";
|
||||
}
|
||||
|
||||
if ($gradlewCheck->successful() && trim($gradlewCheck->output()) === 'gradlew') {
|
||||
return "cd {$sourcePath} && chmod +x gradlew && ./gradlew clean build -x test 2>&1";
|
||||
}
|
||||
|
||||
if ($gradleCheck->successful() && trim($gradleCheck->output()) === 'gradle') {
|
||||
return "cd {$sourcePath} && gradle clean build -x test 2>&1";
|
||||
}
|
||||
|
||||
return "cd {$sourcePath} && ls -la";
|
||||
}
|
||||
|
||||
public function findBuiltJar(string $sourcePath): ?string
|
||||
{
|
||||
$patterns = [
|
||||
$sourcePath . '/target/*.jar',
|
||||
$sourcePath . '/build/libs/*.jar',
|
||||
$sourcePath . '/*/*.jar',
|
||||
$sourcePath . '/*.jar',
|
||||
$sourcePath . '/Emulator/target/*.jar',
|
||||
$sourcePath . '/Emulator/build/libs/*.jar',
|
||||
$sourcePath . '/Emulator/*/*.jar',
|
||||
];
|
||||
|
||||
foreach ($patterns as $pattern) {
|
||||
$result = Process::timeout(10)->run('ls -t ' . $pattern . ' 2>/dev/null | head -1');
|
||||
if ($result->successful()) {
|
||||
$jarPath = trim($result->output());
|
||||
if ($jarPath !== '' && $jarPath !== '0' && str_contains($jarPath, '.jar')) {
|
||||
return $jarPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function deployJar(string $jarPath, string $serviceName): array
|
||||
{
|
||||
$jarName = basename($jarPath);
|
||||
$version = $this->extractVersionFromFilename($jarName);
|
||||
if ($version === '' || $version === '0') {
|
||||
$version = date('Y.m.d');
|
||||
}
|
||||
|
||||
$deployCommands = [
|
||||
'mkdir -p ' . escapeshellarg((string) $this->jarPath),
|
||||
'chown -R www-data:www-data ' . escapeshellarg((string) $this->jarPath),
|
||||
'if ls ' . escapeshellarg((string) $this->jarPath) . '/*.jar 1>/dev/null 2>&1; then mkdir -p ' . escapeshellarg((string) $this->jarPath) . '/backup && mv ' . escapeshellarg((string) $this->jarPath) . '/*.jar ' . escapeshellarg((string) $this->jarPath) . '/backup/; fi',
|
||||
'cp -f ' . escapeshellarg($jarPath) . ' ' . escapeshellarg((string) $this->jarPath) . '/' . escapeshellarg($jarName),
|
||||
'chown www-data:www-data ' . escapeshellarg((string) $this->jarPath) . '/' . escapeshellarg($jarName),
|
||||
'chmod 755 ' . escapeshellarg((string) $this->jarPath) . '/' . escapeshellarg($jarName),
|
||||
'ls -la ' . escapeshellarg((string) $this->jarPath) . '/',
|
||||
'systemctl restart ' . escapeshellarg((string) $serviceName) . ' 2>&1 || service ' . escapeshellarg((string) $serviceName) . ' restart 2>&1 || true',
|
||||
];
|
||||
|
||||
$deployCommand = implode(' && ', $deployCommands);
|
||||
|
||||
Log::info('[EmulatorBuild] Deploying jar', [
|
||||
'source' => $jarPath,
|
||||
'destination' => "{$this->jarPath}/{$jarName}",
|
||||
]);
|
||||
|
||||
$deployResult = Process::timeout(60)->run($deployCommand);
|
||||
|
||||
if (! $deployResult->successful()) {
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => 'Deploy failed: ' . substr($deployResult->errorOutput(), 0, 300),
|
||||
];
|
||||
}
|
||||
|
||||
$sourceService = new EmulatorSourceService;
|
||||
$sourceInfo = $sourceService->checkForUpdates();
|
||||
$installedDate = $sourceInfo['latest_timestamp'] ?? time();
|
||||
|
||||
$this->settings->set('emulator_version', $version);
|
||||
$this->settings->set('emulator_jar_installed_date', (string) $installedDate);
|
||||
$this->settings->set('emulator_source_commit', $sourceInfo['latest_sha'] ?? 'unknown');
|
||||
$this->settings->set('emulator_source_date', (string) $installedDate);
|
||||
|
||||
$currentBranch = $this->sourceBranch ?: $this->githubBranch ?: 'main';
|
||||
$this->settings->set('emulator_installed_branch', $currentBranch);
|
||||
|
||||
$sqlService = new EmulatorSqlService;
|
||||
$sqlService->runUpdates();
|
||||
|
||||
Log::info('[EmulatorBuild] Source build successful');
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'version' => $version,
|
||||
'jar' => $jarName,
|
||||
'built' => true,
|
||||
'message' => "✅ Emulator vanaf source gebouwd!\n📦 {$jarName}\n🔄 Service herstart",
|
||||
];
|
||||
}
|
||||
|
||||
private function ensureJavaInstalled(): void
|
||||
{
|
||||
$javaCheck = Process::timeout(5)->run('java -version 2>&1');
|
||||
if (! $javaCheck->successful()) {
|
||||
Log::warning('[EmulatorBuild] Java not found, attempting to install');
|
||||
Process::timeout(180)->run('apt-get update && apt-get install -y default-jdk 2>&1');
|
||||
}
|
||||
|
||||
$mavenCheck = Process::timeout(5)->run('which mvn');
|
||||
if (! $mavenCheck->successful()) {
|
||||
Log::warning('[EmulatorBuild] Maven not found, attempting to install');
|
||||
Process::timeout(180)->run('apt-get install -y maven 2>&1');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,509 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Emulator;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EmulatorJarService
|
||||
{
|
||||
use EmulatorConfiguration;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->loadConfiguration();
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return ! in_array($this->githubUrl, [null, '', '0'], true) || ! in_array($this->jarDirectUrl, [null, '', '0'], true);
|
||||
}
|
||||
|
||||
public function checkForUpdates(): array
|
||||
{
|
||||
if (! $this->isConfigured()) {
|
||||
return [
|
||||
'update_available' => false,
|
||||
'error' => 'Configureer een GitHub URL of directe .jar URL',
|
||||
];
|
||||
}
|
||||
|
||||
$sourceService = new EmulatorSourceService;
|
||||
$sourceInfo = $sourceService->checkForUpdates();
|
||||
$hasSourceUpdates = $sourceInfo && $sourceInfo['has_update'];
|
||||
|
||||
if (! in_array($this->jarDirectUrl, [null, '', '0'], true)) {
|
||||
return $this->checkDirectUrlUpdates($sourceInfo, $hasSourceUpdates);
|
||||
}
|
||||
|
||||
return $this->checkGitHubFolderUpdates($sourceInfo, $hasSourceUpdates);
|
||||
}
|
||||
|
||||
public function performUpdate(array $check): array
|
||||
{
|
||||
$jarUrl = $check['jar_url'];
|
||||
$jarName = $check['jar_name'];
|
||||
$version = $check['latest_version'];
|
||||
$serviceName = $this->emulatorService;
|
||||
|
||||
$tempDir = '/tmp/emulator-update-' . Str::random(8);
|
||||
$tempJar = $tempDir . '/' . $jarName;
|
||||
|
||||
$updateScript = $this->buildUpdateScript($jarUrl, $jarName, $tempDir, $tempJar, $serviceName);
|
||||
|
||||
$scriptPath = '/tmp/emulator_update_' . uniqid() . '.sh';
|
||||
file_put_contents($scriptPath, $updateScript);
|
||||
chmod($scriptPath, 0755);
|
||||
|
||||
Log::info('[EmulatorJar] Starting update', [
|
||||
'version' => $version,
|
||||
'jar' => $jarName,
|
||||
'url' => $jarUrl,
|
||||
]);
|
||||
|
||||
try {
|
||||
$result = Process::timeout(600)->run('bash ' . $scriptPath . ' 2>&1');
|
||||
@unlink($scriptPath);
|
||||
|
||||
if ($result->exitCode() !== 0) {
|
||||
Log::error('[EmulatorJar] Update failed', [
|
||||
'output' => $result->output(),
|
||||
'error' => $result->errorOutput(),
|
||||
]);
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => 'Update mislukt: ' . substr($result->output(), 0, 300),
|
||||
];
|
||||
}
|
||||
|
||||
$this->storeUpdateInfo($version, $check);
|
||||
|
||||
Log::info('[EmulatorJar] Update successful');
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'version' => $version,
|
||||
'jar' => $jarName,
|
||||
'message' => "✅ Emulator geüpdatet naar v{$version}!\n📦 {$jarName}\n🔄 Service herstart",
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
Log::error('[EmulatorJar] Exception', ['error' => $e->getMessage()]);
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => $e->getMessage(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function findLatestJar(): ?array
|
||||
{
|
||||
if (! $this->githubRepo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$branch = $this->githubBranch ?: 'main';
|
||||
|
||||
$commonNames = ['arcturus.jar', 'Arcturus.jar', 'emulator.jar', 'habbo.jar', 'hotel.jar'];
|
||||
|
||||
foreach ($commonNames as $name) {
|
||||
try {
|
||||
$apiUrl = "https://api.github.com/repos/{$this->githubRepo}/contents/Latest_Compiled_Version/{$name}?ref={$branch}";
|
||||
$response = Http::timeout(10)
|
||||
->withHeaders([
|
||||
'Accept' => 'application/vnd.github.v3+json',
|
||||
'User-Agent' => 'AtomCMS-Emulator-Updater',
|
||||
])
|
||||
->get($apiUrl);
|
||||
|
||||
if (! $response->successful()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$data = json_decode($response->body(), true);
|
||||
|
||||
if (! isset($data['sha']) || ! isset($data['download_url'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$commitDate = null;
|
||||
$commitSha = $data['sha'];
|
||||
|
||||
try {
|
||||
$commitsResponse = Http::timeout(10)
|
||||
->withHeaders([
|
||||
'Accept' => 'application/vnd.github.v3+json',
|
||||
'User-Agent' => 'AtomCMS-Emulator-Updater',
|
||||
])
|
||||
->get("https://api.github.com/repos/{$this->githubRepo}/commits", [
|
||||
'path' => "Latest_Compiled_Version/{$name}",
|
||||
'sha' => $branch,
|
||||
'per_page' => 1,
|
||||
]);
|
||||
|
||||
if ($commitsResponse->successful()) {
|
||||
$commits = $commitsResponse->json();
|
||||
if (! empty($commits) && isset($commits[0]['commit']['committer']['date'])) {
|
||||
$commitDate = strtotime($commits[0]['commit']['committer']['date']);
|
||||
$commitSha = $commits[0]['sha'] ?? $data['sha'];
|
||||
}
|
||||
}
|
||||
} catch (\Exception) {
|
||||
Log::debug('[EmulatorJar] Could not fetch commit date for ' . $name);
|
||||
}
|
||||
|
||||
$installedDate = $this->settings->getOrDefault('emulator_jar_installed_date', null);
|
||||
$installedJarCommit = $this->settings->getOrDefault('emulator_jar_commit', null);
|
||||
|
||||
$isUpdate = false;
|
||||
if ($installedJarCommit !== null) {
|
||||
$isUpdate = $installedJarCommit !== $commitSha;
|
||||
} elseif ($installedDate !== null && $commitDate !== null) {
|
||||
$isUpdate = (int) $installedDate < $commitDate;
|
||||
} elseif ($installedDate === null && $commitDate !== null) {
|
||||
$isUpdate = true;
|
||||
}
|
||||
|
||||
$version = $this->extractVersionFromFilename($name);
|
||||
if ($version === '' || $version === '0') {
|
||||
$version = $commitDate ? date('Y.m.d', $commitDate) : date('Y.m.d');
|
||||
}
|
||||
|
||||
return [
|
||||
'name' => $name,
|
||||
'url' => $data['download_url'],
|
||||
'version' => $version,
|
||||
'commit' => $commitSha,
|
||||
'commit_date' => $commitDate,
|
||||
'is_update' => $isUpdate,
|
||||
'installed_date' => $installedDate,
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('[EmulatorJar] Error checking JAR file ' . $name, ['error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function checkDirectUrlUpdates(?array $sourceInfo, bool $hasSourceUpdates): array
|
||||
{
|
||||
$jarInfo = $this->validateDirectUrl($this->jarDirectUrl);
|
||||
|
||||
if ($jarInfo) {
|
||||
if (! empty($jarInfo['version'])) {
|
||||
$currentVersion = $this->settings->getOrDefault('emulator_version', '0.0.0');
|
||||
if ($jarInfo['version'] !== $currentVersion) {
|
||||
$this->settings->set('emulator_version', $jarInfo['version']);
|
||||
}
|
||||
}
|
||||
|
||||
$hasJarUpdates = $jarInfo['is_update'] ?? false;
|
||||
|
||||
if ($hasSourceUpdates && ! $hasJarUpdates) {
|
||||
return [
|
||||
'update_available' => true,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'latest_version' => $sourceInfo['latest_timestamp'] ? date('Y.m.d', $sourceInfo['latest_timestamp']) : $jarInfo['version'],
|
||||
'release_name' => 'Source Update',
|
||||
'jar_url' => null,
|
||||
'jar_name' => null,
|
||||
'jar_size' => 'Onbekend',
|
||||
'type' => 'source_build',
|
||||
'source_info' => $sourceInfo,
|
||||
'message' => 'Nieuwe commits beschikbaar - build vanaf source nodig',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'update_available' => $hasJarUpdates,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'latest_version' => $jarInfo['version'],
|
||||
'release_name' => $hasSourceUpdates ? 'Source Update' : 'Direct URL',
|
||||
'jar_url' => $this->jarDirectUrl,
|
||||
'jar_name' => $jarInfo['name'],
|
||||
'jar_size' => 'Onbekend',
|
||||
'type' => $hasSourceUpdates ? 'source_build' : 'direct_url',
|
||||
'commit' => $jarInfo['commit_sha'] ?? null,
|
||||
'source_info' => $sourceInfo,
|
||||
'has_source_updates' => $hasSourceUpdates,
|
||||
];
|
||||
}
|
||||
|
||||
if ($hasSourceUpdates) {
|
||||
return [
|
||||
'update_available' => true,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'latest_version' => $sourceInfo['latest_timestamp'] ? date('Y.m.d', $sourceInfo['latest_timestamp']) : 'Onbekend',
|
||||
'release_name' => 'Source Update',
|
||||
'jar_url' => null,
|
||||
'jar_name' => null,
|
||||
'jar_size' => 'Onbekend',
|
||||
'type' => 'source_build',
|
||||
'source_info' => $sourceInfo,
|
||||
'message' => 'Nieuwe commits beschikbaar - build vanaf source nodig',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'update_available' => false,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'error' => 'Directe .jar URL is niet bereikbaar',
|
||||
];
|
||||
}
|
||||
|
||||
private function checkGitHubFolderUpdates(?array $sourceInfo, bool $hasSourceUpdates): array
|
||||
{
|
||||
$jarInfo = $this->findLatestJar();
|
||||
|
||||
if (! $jarInfo) {
|
||||
if ($hasSourceUpdates) {
|
||||
return [
|
||||
'update_available' => true,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'latest_version' => $sourceInfo['latest_timestamp'] ? date('Y.m.d', $sourceInfo['latest_timestamp']) : 'Onbekend',
|
||||
'release_name' => 'Source Update',
|
||||
'jar_url' => null,
|
||||
'jar_name' => null,
|
||||
'jar_size' => 'Onbekend',
|
||||
'type' => 'source_build',
|
||||
'source_info' => $sourceInfo,
|
||||
'message' => 'Nieuwe commits beschikbaar - build vanaf source nodig',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'update_available' => false,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'latest_version' => 'Onbekend',
|
||||
'error' => 'Kon geen .jar bestand vinden',
|
||||
'type' => 'not_found',
|
||||
'source_available' => $sourceInfo !== null,
|
||||
];
|
||||
}
|
||||
|
||||
$version = $jarInfo['version'];
|
||||
$hasJarUpdates = $jarInfo['is_update'] ?? false;
|
||||
|
||||
if ($hasSourceUpdates && ! $hasJarUpdates) {
|
||||
return [
|
||||
'update_available' => true,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'latest_version' => $sourceInfo['latest_timestamp'] ? date('Y.m.d', $sourceInfo['latest_timestamp']) : $version,
|
||||
'release_name' => 'Source Update',
|
||||
'jar_url' => null,
|
||||
'jar_name' => null,
|
||||
'jar_size' => 'Onbekend',
|
||||
'type' => 'source_build',
|
||||
'source_info' => $sourceInfo,
|
||||
'message' => 'Nieuwe commits beschikbaar - build vanaf source nodig',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'update_available' => $hasJarUpdates,
|
||||
'current_version' => $this->settings->getOrDefault('emulator_version', '0.0.0'),
|
||||
'latest_version' => $hasSourceUpdates ? ($sourceInfo['latest_timestamp'] ? date('Y.m.d', $sourceInfo['latest_timestamp']) : $version) : $version,
|
||||
'release_name' => $hasSourceUpdates ? 'Source Update' : 'Latest from GitHub',
|
||||
'jar_url' => $jarInfo['url'],
|
||||
'jar_name' => $jarInfo['name'],
|
||||
'jar_size' => 'Onbekend',
|
||||
'type' => $hasSourceUpdates ? 'source_build' : 'github_folder',
|
||||
'commit' => $jarInfo['commit'] ?? null,
|
||||
'commit_date' => $jarInfo['commit_date'] ?? null,
|
||||
'source_info' => $sourceInfo,
|
||||
'has_source_updates' => $hasSourceUpdates,
|
||||
];
|
||||
}
|
||||
|
||||
private function validateDirectUrl(string $url): ?array
|
||||
{
|
||||
if ($url === '' || $url === '0' || ! str_ends_with(strtolower($url), '.jar')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$jarName = basename(parse_url($url, PHP_URL_PATH));
|
||||
$version = $this->extractVersionFromFilename($jarName);
|
||||
$storedVersion = $this->settings->getOrDefault('emulator_version', '0.0.0');
|
||||
|
||||
$lastModified = null;
|
||||
$commitSha = null;
|
||||
$gitHubInfoAvailable = false;
|
||||
|
||||
if (preg_match('/github\.com\/([^\/]+)\/([^\/]+)\/raw\/refs\/heads\/([^\/]+)\/(.+)/', $url, $matches)) {
|
||||
$owner = $matches[1];
|
||||
$repo = $matches[2];
|
||||
$branch = $matches[3];
|
||||
$path = $matches[4];
|
||||
|
||||
try {
|
||||
$apiResponse = Http::timeout(10)
|
||||
->withHeaders([
|
||||
'Accept' => 'application/vnd.github.v3+json',
|
||||
'User-Agent' => 'AtomCMS-Emulator-Updater',
|
||||
])
|
||||
->get("https://api.github.com/repos/{$owner}/{$repo}/contents/{$path}", [
|
||||
'ref' => $branch,
|
||||
]);
|
||||
|
||||
if ($apiResponse->successful()) {
|
||||
$data = $apiResponse->json();
|
||||
|
||||
if (isset($data['sha']) && ! isset($data['message'])) {
|
||||
$gitHubInfoAvailable = true;
|
||||
$commitSha = $data['sha'];
|
||||
|
||||
if (isset($data['commit']['committer']['date'])) {
|
||||
$lastModified = strtotime($data['commit']['committer']['date']);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Exception) {
|
||||
Log::debug('[EmulatorJar] Could not fetch GitHub commit info for direct URL');
|
||||
}
|
||||
}
|
||||
|
||||
if ($lastModified === null) {
|
||||
$response = Http::timeout(10)->head($url);
|
||||
if ($response->successful()) {
|
||||
$modifiedSince = $response->header('Last-Modified');
|
||||
if ($modifiedSince) {
|
||||
$lastModified = strtotime($modifiedSince);
|
||||
if ($lastModified === false) {
|
||||
$lastModified = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$isUpdate = false;
|
||||
$installedDate = $this->settings->getOrDefault('emulator_jar_installed_date', null);
|
||||
|
||||
$storedData = $this->settings->getOrDefault('emulator_direct_url_info_' . md5($url));
|
||||
if ($storedData !== null && is_string($storedData)) {
|
||||
$storedDataArray = json_decode($storedData, true);
|
||||
if (is_array($storedDataArray)) {
|
||||
if ($gitHubInfoAvailable && $commitSha !== null && isset($storedDataArray['commit_sha'])) {
|
||||
$isUpdate = $commitSha !== $storedDataArray['commit_sha'];
|
||||
} elseif ($lastModified !== null && $installedDate !== null) {
|
||||
$isUpdate = (int) $installedDate < $lastModified;
|
||||
} elseif ($lastModified !== null && isset($storedDataArray['last_modified'])) {
|
||||
$isUpdate = $lastModified > $storedDataArray['last_modified'];
|
||||
} elseif (! in_array($version, ['', '0', $storedVersion], true)) {
|
||||
$isUpdate = version_compare($version, $storedVersion) > 0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$isUpdate = true;
|
||||
}
|
||||
|
||||
$infoToStore = [
|
||||
'last_checked' => time(),
|
||||
'version' => $version,
|
||||
];
|
||||
if ($lastModified) {
|
||||
$infoToStore['last_modified'] = $lastModified;
|
||||
}
|
||||
if ($commitSha) {
|
||||
$infoToStore['commit_sha'] = $commitSha;
|
||||
}
|
||||
$this->settings->set('emulator_direct_url_info_' . md5($url), json_encode($infoToStore));
|
||||
|
||||
return [
|
||||
'name' => $jarName,
|
||||
'version' => $version,
|
||||
'last_modified' => $lastModified,
|
||||
'commit_sha' => $commitSha,
|
||||
'is_update' => $isUpdate,
|
||||
'gitHub_rate_limited' => ! $gitHubInfoAvailable && preg_match('/github\.com/', $url),
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('[EmulatorJar] Direct URL not reachable', ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function buildUpdateScript(string $jarUrl, string $jarName, string $tempDir, string $tempJar, string $serviceName): string
|
||||
{
|
||||
return <<<BASH
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
JAR_URL='{$jarUrl}'
|
||||
JAR_NAME='{$jarName}'
|
||||
JAR_PATH='{$this->jarPath}'
|
||||
SERVICE='{$serviceName}'
|
||||
TEMP_DIR='{$tempDir}'
|
||||
TEMP_JAR='{$tempJar}'
|
||||
|
||||
mkdir -p "\$TEMP_DIR" "\$JAR_PATH"
|
||||
|
||||
if ls "\$JAR_PATH"/*.jar 1>/dev/null 2>&1; then
|
||||
mkdir -p "\$JAR_PATH/backup"
|
||||
mv "\$JAR_PATH"/*.jar "\$JAR_PATH/backup/" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
download_success=false
|
||||
for attempt in 1 2 3; do
|
||||
if curl -L --max-time 300 --retry 3 --retry-delay 5 -o "\$TEMP_JAR" "\$JAR_URL" 2>&1; then
|
||||
FILE_TYPE=\$(file -b "\$TEMP_JAR" 2>/dev/null)
|
||||
JAR_SIZE=\$(stat -c%s "\$TEMP_JAR" 2>/dev/null || echo 0)
|
||||
|
||||
if echo "\$FILE_TYPE" | grep -qi "zip\|jar\|archive" && [ "\$JAR_SIZE" -gt 1000 ]; then
|
||||
download_success=true
|
||||
break
|
||||
else
|
||||
rm -f "\$TEMP_JAR" 2>/dev/null || true
|
||||
sleep 3
|
||||
fi
|
||||
else
|
||||
sleep 5
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "\$download_success" = false ]; then
|
||||
if ls "\$JAR_PATH/backup"/*.jar 1>/dev/null 2>&1; then
|
||||
mv "\$JAR_PATH/backup"/*.jar "\$JAR_PATH/" 2>/dev/null || true
|
||||
fi
|
||||
rm -rf "\$TEMP_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mv "\$TEMP_JAR" "\$JAR_PATH/"
|
||||
chown -R www-data:www-data "\$JAR_PATH"
|
||||
chmod 755 "\$JAR_PATH/\$JAR_NAME"
|
||||
|
||||
systemctl restart "\$SERVICE" 2>&1 || service "\$SERVICE" restart 2>&1 || true
|
||||
|
||||
rm -rf "\$TEMP_DIR" 2>/dev/null || true
|
||||
BASH;
|
||||
}
|
||||
|
||||
private function storeUpdateInfo(string $version, array $check): void
|
||||
{
|
||||
setting('emulator_version', $version);
|
||||
|
||||
$commitDate = $check['commit_date'] ?? time();
|
||||
$this->settings->set('emulator_jar_installed_date', (string) $commitDate);
|
||||
$this->settings->set('emulator_jar_commit', $check['commit'] ?? null);
|
||||
|
||||
$sourceSha = $check['source_info']['latest_sha'] ?? $check['commit'] ?? null;
|
||||
$sourceDate = $check['source_info']['latest_timestamp'] ?? ($check['commit_date'] ?? time());
|
||||
if ($sourceSha) {
|
||||
$this->settings->set('emulator_source_commit', $sourceSha);
|
||||
}
|
||||
if ($sourceDate) {
|
||||
$this->settings->set('emulator_source_date', (string) $sourceDate);
|
||||
}
|
||||
|
||||
$currentBranch = $this->sourceBranch ?: $this->githubBranch ?: 'main';
|
||||
$this->settings->set('emulator_installed_branch', $currentBranch);
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Emulator;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EmulatorSourceService
|
||||
{
|
||||
use EmulatorConfiguration;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->loadConfiguration();
|
||||
}
|
||||
|
||||
public function checkForUpdates(): ?array
|
||||
{
|
||||
$repo = $this->sourceRepo ?: $this->githubRepo;
|
||||
$branch = $this->sourceBranch ?: $this->githubBranch ?: 'main';
|
||||
|
||||
if (! $repo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$localCheck = $this->checkLocalSourceUpdates();
|
||||
if ($localCheck !== null) {
|
||||
return $localCheck;
|
||||
}
|
||||
|
||||
return $this->checkRemoteSourceUpdates($repo, $branch);
|
||||
}
|
||||
|
||||
public function isSourceBuildAvailable(): bool
|
||||
{
|
||||
$hasRepo = ! in_array($this->sourceRepo, [null, '', '0'], true) || ! in_array($this->githubRepo, [null, '', '0'], true);
|
||||
$hasPath = ! in_array($this->emulatorSourcePath, [null, '', '0'], true);
|
||||
|
||||
if (! $hasRepo || ! $hasPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = Process::timeout(5)->run("[ -d {$this->emulatorSourcePath} ] && echo 'exists' || echo 'not_exists'");
|
||||
|
||||
return trim($result->output()) === 'exists';
|
||||
} catch (\Exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function checkLocalSourceUpdates(): ?array
|
||||
{
|
||||
$sourcePath = $this->emulatorSourcePath;
|
||||
|
||||
$existsCheck = Process::timeout(5)->run("[ -d {$sourcePath} ] && echo 'exists'");
|
||||
if (! $existsCheck->successful() || trim($existsCheck->output()) !== 'exists') {
|
||||
return $this->checkSourceByCloning();
|
||||
}
|
||||
|
||||
try {
|
||||
$gitCheck = Process::timeout(5)->run("cd {$sourcePath} && git rev-parse --is-inside-work-tree 2>/dev/null");
|
||||
if (! $gitCheck->successful()) {
|
||||
return $this->checkSourceByCloning();
|
||||
}
|
||||
|
||||
$currentCommitResult = Process::timeout(5)->run("cd {$sourcePath} && git rev-parse HEAD");
|
||||
if (! $currentCommitResult->successful()) {
|
||||
return null;
|
||||
}
|
||||
$currentSha = trim($currentCommitResult->output());
|
||||
|
||||
$fetchResult = Process::timeout(30)->run("cd {$sourcePath} && git fetch origin 2>&1");
|
||||
if ($fetchResult->failed()) {
|
||||
Log::debug('[EmulatorSource] Git fetch failed, trying local check only');
|
||||
}
|
||||
|
||||
$branch = $this->sourceBranch ?: $this->githubBranch ?: 'main';
|
||||
$latestResult = Process::timeout(5)->run("cd {$sourcePath} && git rev-parse origin/{$branch} 2>/dev/null || git rev-parse HEAD");
|
||||
if (! $latestResult->successful()) {
|
||||
return null;
|
||||
}
|
||||
$latestSha = trim($latestResult->output());
|
||||
|
||||
$dateResult = Process::timeout(5)->run("cd {$sourcePath} && git log -1 --format='%ci' {$latestSha}");
|
||||
$latestDate = null;
|
||||
$latestTimestamp = time();
|
||||
if ($dateResult->successful()) {
|
||||
$latestDate = trim($dateResult->output(), "'");
|
||||
if ($latestDate !== '' && $latestDate !== '0') {
|
||||
$latestTimestamp = strtotime($latestDate);
|
||||
}
|
||||
}
|
||||
|
||||
$this->persistSourceCommitInfo($latestSha, $latestTimestamp);
|
||||
|
||||
$msgResult = Process::timeout(5)->run("cd {$sourcePath} && git log -1 --format='%s' {$latestSha}");
|
||||
$latestMessage = $msgResult->successful() ? trim($msgResult->output()) : '';
|
||||
|
||||
$authorResult = Process::timeout(5)->run("cd {$sourcePath} && git log -1 --format='%an' {$latestSha}");
|
||||
$latestAuthor = $authorResult->successful() ? trim($authorResult->output()) : '';
|
||||
|
||||
$storedSha = $this->settings->getOrDefault('emulator_source_commit', null);
|
||||
$storedDate = $this->settings->getOrDefault('emulator_source_date', null);
|
||||
|
||||
$isUpdate = $storedSha !== null && $storedSha !== $latestSha;
|
||||
if ($storedSha === null) {
|
||||
$isUpdate = true;
|
||||
}
|
||||
|
||||
return [
|
||||
'has_update' => $isUpdate,
|
||||
'latest_sha' => $latestSha,
|
||||
'latest_date' => $latestDate,
|
||||
'latest_timestamp' => $latestTimestamp,
|
||||
'latest_message' => $latestMessage,
|
||||
'latest_author' => $latestAuthor,
|
||||
'stored_sha' => $storedSha,
|
||||
'stored_date' => $storedDate,
|
||||
'source' => 'local',
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
Log::debug('[EmulatorSource] Local source check failed: ' . $e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function checkSourceByCloning(): ?array
|
||||
{
|
||||
$repo = $this->sourceRepo ?: $this->githubRepo;
|
||||
$branch = $this->sourceBranch ?: $this->githubBranch ?: 'main';
|
||||
|
||||
if (! $repo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$repo = preg_replace('#/tree/[^/]+/.*$#', '', $repo);
|
||||
$repo = str_replace(['https://github.com/', 'http://github.com/'], '', $repo);
|
||||
$repo = rtrim($repo, '/');
|
||||
|
||||
try {
|
||||
$tempDir = '/tmp/emulator-source-check-' . Str::random(8);
|
||||
|
||||
$cloneResult = Process::timeout(120)->run(
|
||||
"git clone --branch {$branch} --depth 1 https://github.com/{$repo}.git {$tempDir} 2>&1",
|
||||
);
|
||||
|
||||
if ($cloneResult->failed()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$shaResult = Process::timeout(5)->run("cd {$tempDir} && git rev-parse HEAD");
|
||||
$latestSha = $shaResult->successful() ? trim($shaResult->output()) : '';
|
||||
|
||||
$dateResult = Process::timeout(5)->run("cd {$tempDir} && git log -1 --format='%ci'");
|
||||
$latestDate = null;
|
||||
$latestTimestamp = time();
|
||||
if ($dateResult->successful()) {
|
||||
$latestDate = trim($dateResult->output());
|
||||
if ($latestDate !== '' && $latestDate !== '0') {
|
||||
$latestTimestamp = strtotime($latestDate);
|
||||
}
|
||||
}
|
||||
|
||||
$this->persistSourceCommitInfo($latestSha, $latestTimestamp);
|
||||
|
||||
$msgResult = Process::timeout(5)->run("cd {$tempDir} && git log -1 --format='%s'");
|
||||
$latestMessage = $msgResult->successful() ? trim($msgResult->output()) : '';
|
||||
|
||||
$authorResult = Process::timeout(5)->run("cd {$tempDir} && git log -1 --format='%an'");
|
||||
$latestAuthor = $authorResult->successful() ? trim($authorResult->output()) : '';
|
||||
|
||||
Process::timeout(10)->run("rm -rf {$tempDir}");
|
||||
|
||||
$storedSha = $this->settings->getOrDefault('emulator_source_commit', null);
|
||||
$storedDate = $this->settings->getOrDefault('emulator_source_date', null);
|
||||
|
||||
$isUpdate = $storedSha !== null && $storedSha !== $latestSha;
|
||||
if ($storedSha === null) {
|
||||
$isUpdate = true;
|
||||
}
|
||||
|
||||
return [
|
||||
'has_update' => $isUpdate,
|
||||
'latest_sha' => $latestSha,
|
||||
'latest_date' => $latestDate,
|
||||
'latest_timestamp' => $latestTimestamp,
|
||||
'latest_message' => $latestMessage,
|
||||
'latest_author' => $latestAuthor,
|
||||
'stored_sha' => $storedSha,
|
||||
'stored_date' => $storedDate,
|
||||
'source' => 'cloned',
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
Log::debug('[EmulatorSource] Source clone check failed: ' . $e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function checkRemoteSourceUpdates(string $repo, string $branch): ?array
|
||||
{
|
||||
try {
|
||||
$response = Http::timeout(10)
|
||||
->withHeaders([
|
||||
'Accept' => 'application/vnd.github.v3+json',
|
||||
'User-Agent' => 'AtomCMS-Emulator-Updater',
|
||||
])
|
||||
->get("https://api.github.com/repos/{$repo}/commits", [
|
||||
'sha' => $branch,
|
||||
'per_page' => 1,
|
||||
]);
|
||||
|
||||
if (! $response->successful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$commits = $response->json();
|
||||
|
||||
if (empty($commits) || ! isset($commits[0]['sha'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$latestCommit = $commits[0];
|
||||
$latestSha = $latestCommit['sha'];
|
||||
$latestDate = $latestCommit['commit']['committer']['date'] ?? null;
|
||||
$latestTimestamp = $latestDate ? strtotime((string) $latestDate) : time();
|
||||
|
||||
$this->persistSourceCommitInfo($latestSha, $latestTimestamp);
|
||||
|
||||
$installedDate = $this->settings->getOrDefault('emulator_jar_installed_date', null);
|
||||
$storedSha = $this->settings->getOrDefault('emulator_source_commit', null);
|
||||
$storedDate = $this->settings->getOrDefault('emulator_source_date', null);
|
||||
|
||||
if ($storedSha !== null && $storedSha === $latestSha) {
|
||||
$isUpdate = false;
|
||||
} elseif ($storedSha !== null && $storedSha !== $latestSha) {
|
||||
$isUpdate = true;
|
||||
} elseif ($installedDate !== null) {
|
||||
$installedTimestamp = is_numeric($installedDate) ? (int) $installedDate : strtotime((string) $installedDate);
|
||||
$isUpdate = $installedTimestamp < $latestTimestamp;
|
||||
} else {
|
||||
$isUpdate = false;
|
||||
}
|
||||
|
||||
return [
|
||||
'has_update' => $isUpdate,
|
||||
'latest_sha' => $latestSha,
|
||||
'latest_date' => $latestDate,
|
||||
'latest_timestamp' => $latestTimestamp,
|
||||
'latest_message' => $latestCommit['commit']['message'] ?? '',
|
||||
'latest_author' => $latestCommit['commit']['author']['name'] ?? '',
|
||||
'stored_sha' => $storedSha,
|
||||
'stored_date' => $storedDate,
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('[EmulatorSource] Could not check source updates via GitHub API', ['error' => $e->getMessage()]);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function persistSourceCommitInfo(string $sha, int $timestamp): void
|
||||
{
|
||||
$this->settings->set('emulator_source_commit', $sha);
|
||||
$this->settings->set('emulator_source_date', (string) $timestamp);
|
||||
}
|
||||
}
|
||||
@@ -1,510 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Emulator;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class EmulatorSqlService
|
||||
{
|
||||
use EmulatorConfiguration;
|
||||
|
||||
private const string SQL_TABLE = 'emulator_sql_updates';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->loadConfiguration();
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return ! in_array($this->githubUrl, [null, '', '0'], true) || ! in_array($this->jarDirectUrl, [null, '', '0'], true);
|
||||
}
|
||||
|
||||
public function checkForUpdates(bool $recentOnly = true): array
|
||||
{
|
||||
if (! $this->githubRepo) {
|
||||
return [
|
||||
'has_updates' => false,
|
||||
'error' => 'Geen GitHub repo geconfigureerd',
|
||||
];
|
||||
}
|
||||
|
||||
$this->ensureSqlTableExists();
|
||||
|
||||
$result = $this->fetchSqlFilesFromGitHub($recentOnly);
|
||||
|
||||
if (isset($result['error'])) {
|
||||
return [
|
||||
'has_updates' => false,
|
||||
'error' => $result['error'],
|
||||
];
|
||||
}
|
||||
|
||||
$sqlFiles = $result;
|
||||
|
||||
if ($sqlFiles === []) {
|
||||
return [
|
||||
'has_updates' => false,
|
||||
'message' => $recentOnly
|
||||
? 'Geen SQL updates van de afgelopen week gevonden'
|
||||
: 'Geen SQL updates gevonden',
|
||||
];
|
||||
}
|
||||
|
||||
$appliedHashes = $this->getAppliedSqlHashes();
|
||||
$newSqlFiles = [];
|
||||
$alreadyApplied = [];
|
||||
|
||||
foreach ($sqlFiles as $file) {
|
||||
$hash = $file['sha'] ?? md5((string) $file['name']);
|
||||
if (in_array($hash, $appliedHashes)) {
|
||||
$alreadyApplied[] = $file['name'];
|
||||
|
||||
continue;
|
||||
}
|
||||
$newSqlFiles[] = $file;
|
||||
}
|
||||
|
||||
if ($newSqlFiles === []) {
|
||||
return [
|
||||
'has_updates' => false,
|
||||
'message' => 'Alle SQL updates zijn al toegepast (' . count($alreadyApplied) . ' stuks)',
|
||||
'applied_count' => count($alreadyApplied),
|
||||
];
|
||||
}
|
||||
|
||||
usort($newSqlFiles, fn ($a, $b) => strcmp((string) $a['name'], (string) $b['name']));
|
||||
|
||||
return [
|
||||
'has_updates' => true,
|
||||
'count' => count($newSqlFiles),
|
||||
'files' => $newSqlFiles,
|
||||
'message' => count($newSqlFiles) . ' nieuwe SQL update(s) van deze week',
|
||||
'applied_count' => count($alreadyApplied),
|
||||
];
|
||||
}
|
||||
|
||||
public function runUpdates(): array
|
||||
{
|
||||
$sqlCheck = $this->checkForUpdates(false);
|
||||
|
||||
if (! ($sqlCheck['has_updates'] ?? false)) {
|
||||
return ['success' => true, 'sql_updated' => false, 'message' => 'Geen nieuwe SQL updates'];
|
||||
}
|
||||
|
||||
$results = [
|
||||
'success' => true,
|
||||
'sql_updated' => true,
|
||||
'files_run' => [],
|
||||
'errors' => [],
|
||||
];
|
||||
|
||||
foreach ($sqlCheck['files'] as $file) {
|
||||
$sqlResult = $this->downloadAndRunSql($file);
|
||||
|
||||
if ($sqlResult['success']) {
|
||||
$results['files_run'][] = $file['name'];
|
||||
$this->markSqlAsApplied($file);
|
||||
} else {
|
||||
$results['errors'][] = $file['name'] . ': ' . $sqlResult['error'];
|
||||
}
|
||||
}
|
||||
|
||||
if (count($results['errors']) > 0) {
|
||||
$results['message'] = count($results['files_run']) . ' SQL updates succesvol, ' . count($results['errors']) . ' met fouten';
|
||||
} else {
|
||||
$results['message'] = count($results['files_run']) . ' SQL updates succesvol uitgevoerd!';
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
public function getAppliedUpdates(): array
|
||||
{
|
||||
$this->ensureSqlTableExists();
|
||||
|
||||
return DB::table(self::SQL_TABLE)
|
||||
->orderBy('applied_at', 'desc')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
public function diagnose(): array
|
||||
{
|
||||
$diagnosis = [
|
||||
'table_exists' => false,
|
||||
'applied_count' => 0,
|
||||
'pending_count' => 0,
|
||||
'error' => null,
|
||||
];
|
||||
|
||||
try {
|
||||
$diagnosis['table_exists'] = Schema::hasTable(self::SQL_TABLE);
|
||||
|
||||
if ($diagnosis['table_exists']) {
|
||||
$diagnosis['applied_count'] = DB::table(self::SQL_TABLE)->count();
|
||||
}
|
||||
|
||||
if ($this->githubRepo && $diagnosis['table_exists']) {
|
||||
$sqlCheck = $this->checkForUpdates(false);
|
||||
if (isset($sqlCheck['count'])) {
|
||||
$diagnosis['pending_count'] = $sqlCheck['count'];
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$diagnosis['error'] = $e->getMessage();
|
||||
}
|
||||
|
||||
return $diagnosis;
|
||||
}
|
||||
|
||||
public function repair(): array
|
||||
{
|
||||
$actions = [];
|
||||
$errors = [];
|
||||
|
||||
try {
|
||||
$this->ensureSqlTableExists();
|
||||
$actions[] = 'SQL update tabel gecontroleerd';
|
||||
|
||||
$appliedCount = DB::table(self::SQL_TABLE)->count();
|
||||
$actions[] = "SQL updates tabel OK ({$appliedCount} records)";
|
||||
|
||||
if ($this->githubRepo) {
|
||||
$sqlCheck = $this->checkForUpdates(false);
|
||||
|
||||
if (isset($sqlCheck['error'])) {
|
||||
$actions[] = 'SQL update check: ' . $sqlCheck['error'];
|
||||
} elseif (! ($sqlCheck['has_updates'] ?? false)) {
|
||||
$actions[] = 'SQL updates: ' . ($sqlCheck['message'] ?? 'Allemaal up-to-date');
|
||||
} else {
|
||||
$count = $sqlCheck['count'] ?? 0;
|
||||
$actions[] = "{$count} nieuwe SQL updates beschikbaar";
|
||||
|
||||
if ($this->isConfigured()) {
|
||||
$actions[] = 'SQL updates worden toegepast...';
|
||||
$runResult = $this->runUpdates();
|
||||
|
||||
if ($runResult['success'] ?? false) {
|
||||
$filesRun = count($runResult['files_run'] ?? []);
|
||||
$actions[] = "{$filesRun} SQL updates toegepast";
|
||||
} else {
|
||||
$errors[] = 'SQL updates: ' . ($runResult['error'] ?? 'Onbekende fout');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$errors[] = 'SQL repair: ' . $e->getMessage();
|
||||
Log::error('[EmulatorSql] Repair failed', ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => $errors === [],
|
||||
'actions' => $actions,
|
||||
'errors' => $errors,
|
||||
];
|
||||
}
|
||||
|
||||
private function ensureSqlTableExists(): void
|
||||
{
|
||||
if (Schema::hasTable(self::SQL_TABLE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Schema::create(self::SQL_TABLE, function ($table) {
|
||||
$table->id();
|
||||
$table->string('file_name');
|
||||
$table->string('file_hash')->unique();
|
||||
$table->timestamp('applied_at');
|
||||
$table->text('sql_content')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
private function getAppliedSqlHashes(): array
|
||||
{
|
||||
$this->ensureSqlTableExists();
|
||||
|
||||
return DB::table(self::SQL_TABLE)
|
||||
->pluck('file_hash')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
private function markSqlAsApplied(array $file): void
|
||||
{
|
||||
$this->ensureSqlTableExists();
|
||||
|
||||
$hash = $file['sha'] ?? md5((string) $file['name']);
|
||||
|
||||
DB::table(self::SQL_TABLE)->updateOrInsert(
|
||||
['file_hash' => $hash],
|
||||
[
|
||||
'file_name' => $file['name'],
|
||||
'applied_at' => now(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
private function fetchSqlFilesFromGitHub(bool $recentOnly = false): array
|
||||
{
|
||||
if (! $this->githubRepo) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$branch = $this->githubBranch ?: 'main';
|
||||
|
||||
$folderNames = [
|
||||
'Database%20Updates',
|
||||
'Database Updates',
|
||||
'database_updates',
|
||||
'database/updates',
|
||||
'sql/updates',
|
||||
'sql',
|
||||
'updates',
|
||||
];
|
||||
|
||||
$knownSqlFiles = [
|
||||
'07012026_UpdateDatabase_to_4-0-1.sql',
|
||||
'09012026_UpdateDatabase_to_4-0-2.sql',
|
||||
'12012026_Battle Banzai.sql',
|
||||
'12012026_Breeding Fixes.sql',
|
||||
'12012026_ChatBubbles.sql',
|
||||
'16032026_updateall_command.sql',
|
||||
'17032026_allow_underpass.sql',
|
||||
'19032026_hotel_timezone.sql',
|
||||
'21022026_user_prefixes.sql',
|
||||
'Default_Camera.sql',
|
||||
'UpdateDatabase_Allow_diagonale.sql',
|
||||
'UpdateDatabase_BOT.sql',
|
||||
'UpdateDatabase_Banners.sql',
|
||||
'UpdateDatabase_DanceCMD.sql',
|
||||
'UpdateDatabase_Happiness.sql',
|
||||
'UpdateDatabase_Websocket.sql',
|
||||
'UpdateDatabase_unignorable.sql',
|
||||
];
|
||||
|
||||
try {
|
||||
if ($recentOnly) {
|
||||
return $this->fetchRecentSqlFiles($branch);
|
||||
}
|
||||
|
||||
$sqlFiles = [];
|
||||
|
||||
foreach ($knownSqlFiles as $filename) {
|
||||
foreach ($folderNames as $folderName) {
|
||||
$encodedFilename = str_replace(' ', '%20', $filename);
|
||||
$url = "https://raw.githubusercontent.com/{$this->githubRepo}/{$branch}/{$folderName}/{$encodedFilename}";
|
||||
$response = Http::timeout(10)->get($url);
|
||||
|
||||
if ($response->successful()) {
|
||||
$sqlFiles[] = [
|
||||
'name' => $filename,
|
||||
'url' => $url,
|
||||
'sha' => md5($response->body()),
|
||||
];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($sqlFiles !== []) {
|
||||
usort($sqlFiles, fn ($a, $b) => strcmp($a['name'], $b['name']));
|
||||
|
||||
return $sqlFiles;
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('[EmulatorSql] Could not fetch SQL files', ['error' => $e->getMessage()]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private function fetchRecentSqlFiles(string $branch): array
|
||||
{
|
||||
$weekAgo = now()->subDays(7)->toIso8601String();
|
||||
|
||||
$githubToken = setting('github_token', '');
|
||||
$headers = [
|
||||
'Accept' => 'application/vnd.github+json',
|
||||
'User-Agent' => 'AtomCMS-EmulatorUpdate/1.0',
|
||||
];
|
||||
if (! empty($githubToken)) {
|
||||
$headers['Authorization'] = 'Bearer ' . $githubToken;
|
||||
}
|
||||
|
||||
$folderNames = ['Database Updates', 'database_updates', 'sql', 'updates'];
|
||||
|
||||
try {
|
||||
foreach ($folderNames as $folderName) {
|
||||
$response = Http::withHeaders($headers)->timeout(30)->get("https://api.github.com/repos/{$this->githubRepo}/commits", [
|
||||
'path' => $folderName,
|
||||
'sha' => $branch,
|
||||
'since' => $weekAgo,
|
||||
'per_page' => 100,
|
||||
]);
|
||||
|
||||
if ($response->successful()) {
|
||||
$commits = $response->json();
|
||||
|
||||
if (! is_array($commits) || $commits === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sqlFiles = [];
|
||||
|
||||
foreach ($commits as $commit) {
|
||||
$sha = $commit['sha'] ?? null;
|
||||
$commitDate = $commit['commit']['committer']['date'] ?? null;
|
||||
|
||||
if (! $sha) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$commitResponse = Http::withHeaders($headers)->timeout(30)->get("https://api.github.com/repos/{$this->githubRepo}/commits/{$sha}");
|
||||
|
||||
if (! $commitResponse->successful()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$commitData = $commitResponse->json();
|
||||
$files = $commitData['files'] ?? [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
$filename = $file['filename'] ?? '';
|
||||
|
||||
if (! str_ends_with(strtolower((string) $filename), '.sql')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = basename((string) $filename);
|
||||
$sqlFiles[] = [
|
||||
'name' => $name,
|
||||
'url' => $file['raw_url'] ?? "https://raw.githubusercontent.com/{$this->githubRepo}/{$sha}/{$filename}",
|
||||
'sha' => $sha,
|
||||
'date' => $commitDate,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($sqlFiles !== []) {
|
||||
usort($sqlFiles, fn ($a, $b) => strcmp($a['name'], $b['name']));
|
||||
|
||||
return $sqlFiles;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('[EmulatorSql] Could not fetch recent SQL files', ['error' => $e->getMessage()]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private function downloadAndRunSql(array $file): array
|
||||
{
|
||||
try {
|
||||
$response = Http::timeout(60)->get($file['url']);
|
||||
|
||||
if (! $response->successful()) {
|
||||
return ['success' => false, 'error' => 'Download mislukt'];
|
||||
}
|
||||
|
||||
$sql = $this->cleanSql($response->body());
|
||||
|
||||
if (in_array(trim($sql), ['', '0'], true)) {
|
||||
return ['success' => true, 'message' => 'Lege SQL file overgeslagen'];
|
||||
}
|
||||
|
||||
$host = setting('emulator_database_host', config('database.connections.emulator.host', '127.0.0.1'));
|
||||
$port = setting('emulator_database_port', config('database.connections.emulator.port', '3306'));
|
||||
$name = setting('emulator_database_name', config('database.connections.emulator.database', ''));
|
||||
$username = setting('emulator_database_username', config('database.connections.emulator.username', ''));
|
||||
$password = setting('emulator_database_password', config('database.connections.emulator.password', ''));
|
||||
|
||||
if (empty($name) || empty($username)) {
|
||||
return ['success' => false, 'error' => 'Emulator database niet geconfigureerd'];
|
||||
}
|
||||
|
||||
$pdo = new \PDO(
|
||||
"mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4",
|
||||
$username,
|
||||
$password,
|
||||
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION],
|
||||
);
|
||||
|
||||
$statements = $this->splitSqlStatements($sql);
|
||||
$successCount = 0;
|
||||
$skipCount = 0;
|
||||
|
||||
foreach ($statements as $statement) {
|
||||
$statement = trim((string) $statement);
|
||||
if ($statement === '' || $statement === '0') {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$pdo->exec($statement);
|
||||
$successCount++;
|
||||
} catch (\PDOException $e) {
|
||||
if ($this->isDuplicateError($e)) {
|
||||
$skipCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
Log::warning('[SQL Update] Statement error: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
Log::info('[SQL Update] Successfully ran: ' . $file['name'] . " ({$successCount} statements, {$skipCount} skipped)");
|
||||
|
||||
return ['success' => true, 'message' => "SQL uitgevoerd ({$successCount} statements, {$skipCount} duplicate)"];
|
||||
} catch (\Exception $e) {
|
||||
Log::error('[SQL Update] Failed: ' . $file['name'], ['error' => $e->getMessage()]);
|
||||
|
||||
return ['success' => false, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
private function cleanSql(string $sql): string
|
||||
{
|
||||
$sql = preg_replace('/--.*$/m', '', $sql);
|
||||
$sql = preg_replace('/#.*$/m', '', (string) $sql);
|
||||
$sql = preg_replace('/SET FOREIGN_KEY_CHECKS.*?;/i', '', (string) $sql);
|
||||
|
||||
return preg_replace('/SET @@SESSION.SQL_MODE.*?;/i', '', (string) $sql);
|
||||
}
|
||||
|
||||
private function splitSqlStatements(string $sql): array
|
||||
{
|
||||
$parts = explode(';', $sql);
|
||||
|
||||
return array_filter($parts, fn ($part) => trim((string) $part) !== '');
|
||||
}
|
||||
|
||||
private function isDuplicateError(\PDOException $e): bool
|
||||
{
|
||||
$message = strtolower($e->getMessage());
|
||||
$patterns = [
|
||||
'duplicate entry',
|
||||
"table '",
|
||||
'already exists',
|
||||
"can't create",
|
||||
'duplicate key',
|
||||
'duplicate index',
|
||||
'error 1061',
|
||||
'error 1062',
|
||||
'error 1826',
|
||||
];
|
||||
|
||||
return array_any($patterns, fn ($pattern) => str_contains($message, (string) $pattern));
|
||||
}
|
||||
}
|
||||
@@ -1,407 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Miscellaneous\WebsiteSetting;
|
||||
use App\Services\Emulator\EmulatorBackupService;
|
||||
use App\Services\Emulator\EmulatorBuildService;
|
||||
use App\Services\Emulator\EmulatorJarService;
|
||||
use App\Services\Emulator\EmulatorSourceService;
|
||||
use App\Services\Emulator\EmulatorSqlService;
|
||||
use App\Services\Emulator\EmulatorStatusService;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
|
||||
class EmulatorUpdateService
|
||||
{
|
||||
private readonly EmulatorStatusService $statusService;
|
||||
|
||||
private readonly EmulatorJarService $jarService;
|
||||
|
||||
private readonly EmulatorSourceService $sourceService;
|
||||
|
||||
private readonly EmulatorBuildService $buildService;
|
||||
|
||||
private readonly EmulatorSqlService $sqlService;
|
||||
|
||||
private readonly EmulatorBackupService $backupService;
|
||||
|
||||
private readonly SettingsService $settings;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->statusService = new EmulatorStatusService;
|
||||
$this->jarService = new EmulatorJarService;
|
||||
$this->sourceService = new EmulatorSourceService;
|
||||
$this->buildService = new EmulatorBuildService;
|
||||
$this->sqlService = new EmulatorSqlService;
|
||||
$this->backupService = new EmulatorBackupService;
|
||||
$this->settings = app(SettingsService::class);
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return $this->statusService->isConfigured();
|
||||
}
|
||||
|
||||
public function getStatus(): array
|
||||
{
|
||||
$status = $this->statusService->getStatus();
|
||||
$updateCheck = $this->jarService->checkForUpdates();
|
||||
$sourceInfo = $this->sourceService->checkForUpdates();
|
||||
|
||||
return array_merge($status, [
|
||||
'update_available' => $updateCheck['update_available'] ?? false,
|
||||
'current_version' => $updateCheck['current_version'] ?? setting('emulator_version', 'N/A'),
|
||||
'latest_version' => $updateCheck['latest_version'] ?? 'N/A',
|
||||
'update_type' => $updateCheck['type'] ?? 'unknown',
|
||||
'has_source_updates' => $sourceInfo['has_update'] ?? false,
|
||||
'latest_sha' => $sourceInfo['latest_sha'] ?? null,
|
||||
'latest_message' => $sourceInfo['latest_message'] ?? null,
|
||||
'latest_author' => $sourceInfo['latest_author'] ?? null,
|
||||
'latest_date' => $sourceInfo['latest_date'] ?? null,
|
||||
'stored_sha' => $sourceInfo['stored_sha'] ?? null,
|
||||
'stored_date' => $sourceInfo['stored_date'] ?? null,
|
||||
'source_info' => $sourceInfo,
|
||||
]);
|
||||
}
|
||||
|
||||
public function checkForUpdates(): array
|
||||
{
|
||||
return $this->jarService->checkForUpdates();
|
||||
}
|
||||
|
||||
public function checkForSqlUpdates(bool $recentOnly = true): array
|
||||
{
|
||||
return $this->sqlService->checkForUpdates($recentOnly);
|
||||
}
|
||||
|
||||
public function runSqlUpdates(): array
|
||||
{
|
||||
return $this->sqlService->runUpdates();
|
||||
}
|
||||
|
||||
public function getAppliedSqlUpdates(): array
|
||||
{
|
||||
return $this->sqlService->getAppliedUpdates();
|
||||
}
|
||||
|
||||
public function updateEmulator(): array
|
||||
{
|
||||
if (! $this->isConfigured()) {
|
||||
return ['success' => false, 'error' => 'Geen GitHub URL geconfigureerd'];
|
||||
}
|
||||
|
||||
$check = $this->checkForUpdates();
|
||||
|
||||
if (! ($check['update_available'] ?? false)) {
|
||||
if ($check['type'] === 'not_found' && ($check['source_available'] ?? false)) {
|
||||
return $this->buildFromSource();
|
||||
}
|
||||
|
||||
return ['success' => false, 'error' => 'Emulator is al up-to-date'];
|
||||
}
|
||||
|
||||
$hasSourceUpdates = ($check['has_source_updates'] ?? false) || ($check['type'] ?? '') === 'source_build';
|
||||
|
||||
if ($hasSourceUpdates && $this->sourceService->isSourceBuildAvailable()) {
|
||||
return $this->buildFromSource();
|
||||
}
|
||||
|
||||
if ($check['type'] === 'source_build') {
|
||||
return $this->buildFromSource();
|
||||
}
|
||||
|
||||
if (! ($check['jar_url'] ?? null)) {
|
||||
return ['success' => false, 'error' => 'Geen .jar gevonden'];
|
||||
}
|
||||
|
||||
$result = $this->jarService->performUpdate($check);
|
||||
|
||||
if ($result['success']) {
|
||||
$this->runSqlUpdates();
|
||||
|
||||
if ($this->restartEmulator()) {
|
||||
$result['restarted'] = true;
|
||||
$result['message'] = ($result['message'] ?? '') . ' | 🔄 Emulator herstart';
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function performUpdate(array $check): array
|
||||
{
|
||||
return $this->jarService->performUpdate($check);
|
||||
}
|
||||
|
||||
public function buildFromSource(bool $force = false): array
|
||||
{
|
||||
return $this->buildService->buildFromSource($force);
|
||||
}
|
||||
|
||||
public function restartEmulator(): bool
|
||||
{
|
||||
$serviceName = $this->settings->getOrDefault('emulator_service_name', 'emulator');
|
||||
|
||||
try {
|
||||
Log::info('[EmulatorUpdate] Restarting emulator service: ' . $serviceName);
|
||||
|
||||
$result = Process::timeout(30)->run("systemctl restart {$serviceName} 2>&1");
|
||||
if ($result->successful()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$result = Process::timeout(30)->run("service {$serviceName} restart 2>&1");
|
||||
|
||||
return $result->successful();
|
||||
} catch (\Exception $e) {
|
||||
Log::error('[EmulatorUpdate] Failed to restart emulator', ['error' => $e->getMessage()]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function getBackupList(): array
|
||||
{
|
||||
return $this->backupService->getList();
|
||||
}
|
||||
|
||||
public function restoreBackup(string $backupName): array
|
||||
{
|
||||
return $this->backupService->restore($backupName);
|
||||
}
|
||||
|
||||
public function getInstalledVersion(): string
|
||||
{
|
||||
return $this->statusService->getInstalledVersion();
|
||||
}
|
||||
|
||||
public function getInstalledJar(): ?string
|
||||
{
|
||||
return $this->statusService->getInstalledJar();
|
||||
}
|
||||
|
||||
public function getInstalledJarInfo(): array
|
||||
{
|
||||
return $this->statusService->getInstalledJarInfo();
|
||||
}
|
||||
|
||||
public function getLastSqlUpdate(): ?string
|
||||
{
|
||||
return setting('emulator_last_sql_update');
|
||||
}
|
||||
|
||||
public function debugStatus(): array
|
||||
{
|
||||
return Cache::remember('emulator_debug_status', 120, function () {
|
||||
$installedDate = $this->settings->getOrDefault('emulator_jar_installed_date', null);
|
||||
$sourceCommit = $this->settings->getOrDefault('emulator_source_commit', null);
|
||||
$sourceDate = $this->settings->getOrDefault('emulator_source_date', null);
|
||||
$emulatorVersion = $this->settings->getOrDefault('emulator_version', null);
|
||||
$jarFiles = $this->statusService->getInstalledJarInfo();
|
||||
|
||||
return [
|
||||
'github_url' => $this->settings->getOrDefault('emulator_github_url', ''),
|
||||
'github_repo' => $this->settings->getOrDefault('emulator_source_repo', ''),
|
||||
'github_branch' => $this->settings->getOrDefault('emulator_github_branch', 'main'),
|
||||
'source_repo' => $this->settings->getOrDefault('emulator_source_repo', ''),
|
||||
'source_branch' => $this->settings->getOrDefault('emulator_github_branch', 'main'),
|
||||
'installed_date' => $installedDate,
|
||||
'installed_date_formatted' => $installedDate ? date('Y-m-d H:i:s', (int) $installedDate) : null,
|
||||
'source_commit' => $sourceCommit,
|
||||
'source_date' => $sourceDate,
|
||||
'source_date_formatted' => $sourceDate ? date('Y-m-d H:i:s', (int) $sourceDate) : null,
|
||||
'emulator_version' => $emulatorVersion,
|
||||
'jar_files' => $jarFiles,
|
||||
'installed_branch' => $this->settings->getOrDefault('emulator_installed_branch', null),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public function resetInstalledDate(): void
|
||||
{
|
||||
WebsiteSetting::where('key', 'emulator_jar_installed_date')->delete();
|
||||
WebsiteSetting::where('key', 'emulator_source_commit')->delete();
|
||||
WebsiteSetting::where('key', 'emulator_source_date')->delete();
|
||||
}
|
||||
|
||||
public function clearAllLogs(): array
|
||||
{
|
||||
$cleared = [];
|
||||
$paths = [
|
||||
storage_path('logs') => 'Laravel Logs',
|
||||
storage_path('logs/emulator.log') => 'Emulator Log',
|
||||
'/tmp/emulator-update-*' => 'Emulator Update Temp',
|
||||
'/tmp/nitro-switch-*' => 'Nitro Switch Logs',
|
||||
'/tmp/nitro_*' => 'Nitro Temp',
|
||||
'/var/www/Emulator/logs' => 'Emulator Folder Logs',
|
||||
];
|
||||
|
||||
foreach ($paths as $path => $label) {
|
||||
try {
|
||||
if (str_contains($path, '*')) {
|
||||
Process::timeout(10)->run("rm -f {$path} 2>/dev/null || true");
|
||||
$cleared[] = $label;
|
||||
} elseif (is_dir($path)) {
|
||||
Process::timeout(10)->run("find {$path} -name '*.log' -mtime +1 -delete 2>/dev/null || true");
|
||||
$cleared[] = $label;
|
||||
} elseif (is_file($path)) {
|
||||
@unlink($path);
|
||||
$cleared[] = $label;
|
||||
}
|
||||
} catch (\Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$laravelLog = storage_path('logs/laravel.log');
|
||||
if (is_file($laravelLog)) {
|
||||
file_put_contents($laravelLog, '');
|
||||
$cleared[] = 'laravel.log';
|
||||
}
|
||||
} catch (\Exception) {
|
||||
}
|
||||
|
||||
Process::timeout(10)->run("find /tmp -name 'emulator_*' -mtime +1 -delete 2>/dev/null || true");
|
||||
Process::timeout(10)->run("find /tmp -name 'nitro_*' -mtime +1 -delete 2>/dev/null || true");
|
||||
Process::timeout(10)->run("find /tmp -name 'deploy_*' -mtime +1 -delete 2>/dev/null || true");
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'cleared' => $cleared,
|
||||
'message' => count($cleared) . ' log locaties geleegd',
|
||||
];
|
||||
}
|
||||
|
||||
public function repairEmulator(): array
|
||||
{
|
||||
$actions = [];
|
||||
$errors = [];
|
||||
|
||||
Log::info('[EmulatorUpdate] Starting repair process');
|
||||
|
||||
try {
|
||||
$status = $this->getStatus();
|
||||
|
||||
if (! ($status['jar_exists'] ?? false)) {
|
||||
$actions[] = 'JAR bestand ontbreekt - downloaden...';
|
||||
$updateResult = $this->updateEmulator();
|
||||
if (! $updateResult['success']) {
|
||||
$errors[] = 'Kon JAR niet herstellen: ' . ($updateResult['error'] ?? 'Onbekende fout');
|
||||
} else {
|
||||
$actions[] = 'JAR bestand hersteld';
|
||||
}
|
||||
}
|
||||
|
||||
if (! ($status['service_running'] ?? false)) {
|
||||
$actions[] = 'Emulator service niet actief - starten...';
|
||||
if ($this->restartEmulator()) {
|
||||
$actions[] = 'Emulator service gestart';
|
||||
} else {
|
||||
$errors[] = 'Kon emulator service niet starten';
|
||||
}
|
||||
}
|
||||
|
||||
$sqlRepairResult = $this->sqlService->repair();
|
||||
if (! empty($sqlRepairResult['actions'])) {
|
||||
$actions = array_merge($actions, $sqlRepairResult['actions']);
|
||||
}
|
||||
if (! empty($sqlRepairResult['errors'])) {
|
||||
$errors = array_merge($errors, $sqlRepairResult['errors']);
|
||||
}
|
||||
|
||||
if ($errors !== []) {
|
||||
return [
|
||||
'success' => false,
|
||||
'actions' => $actions,
|
||||
'errors' => $errors,
|
||||
'error' => implode('; ', $errors),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'actions' => $actions,
|
||||
'message' => count($actions) . ' acties uitgevoerd',
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
Log::error('[EmulatorUpdate] Repair exception', ['error' => $e->getMessage()]);
|
||||
|
||||
return [
|
||||
'success' => false,
|
||||
'actions' => $actions,
|
||||
'error' => $e->getMessage(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function diagnoseSqlUpdates(): array
|
||||
{
|
||||
return $this->sqlService->diagnose();
|
||||
}
|
||||
|
||||
public function diagnose(): array
|
||||
{
|
||||
$diagnosis = [
|
||||
'timestamp' => now()->toIso8601String(),
|
||||
'checks' => [],
|
||||
'issues' => [],
|
||||
'recommendations' => [],
|
||||
];
|
||||
|
||||
try {
|
||||
$status = $this->getStatus();
|
||||
|
||||
$diagnosis['checks']['jar_exists'] = $status['jar_exists'] ?? false;
|
||||
$diagnosis['checks']['jar_files'] = $status['jar_files'] ?? [];
|
||||
$diagnosis['checks']['service_running'] = $status['service_running'] ?? false;
|
||||
$diagnosis['checks']['source_exists'] = $status['source_exists'] ?? false;
|
||||
$diagnosis['checks']['emulator_db_connected'] = $status['emulator_db_connected'] ?? false;
|
||||
$diagnosis['checks']['is_configured'] = $this->isConfigured();
|
||||
$diagnosis['checks']['update_available'] = $status['update_available'] ?? false;
|
||||
|
||||
$sqlDiagnosis = $this->sqlService->diagnose();
|
||||
$diagnosis['checks']['sql_table_exists'] = $sqlDiagnosis['table_exists'] ?? false;
|
||||
$diagnosis['checks']['sql_updates_applied'] = $sqlDiagnosis['applied_count'] ?? 0;
|
||||
$diagnosis['checks']['sql_pending'] = $sqlDiagnosis['pending_count'] ?? 0;
|
||||
|
||||
if (! ($status['jar_exists'] ?? false)) {
|
||||
$diagnosis['issues'][] = 'JAR bestand ontbreekt';
|
||||
$diagnosis['recommendations'][] = 'Voer emulator:update uit om de JAR te downloaden';
|
||||
}
|
||||
|
||||
if (! ($status['service_running'] ?? false)) {
|
||||
$diagnosis['issues'][] = 'Emulator service draait niet';
|
||||
$diagnosis['recommendations'][] = 'Start de service met: sudo systemctl start ' . $this->settings->getOrDefault('emulator_service_name', 'emulator');
|
||||
}
|
||||
|
||||
if (! ($status['emulator_db_connected'] ?? false)) {
|
||||
$diagnosis['issues'][] = 'Emulator database niet bereikbaar';
|
||||
$diagnosis['recommendations'][] = 'Controleer de database credentials in de settings';
|
||||
}
|
||||
|
||||
if (! ($status['source_exists'] ?? false) && $this->sourceService->isSourceBuildAvailable()) {
|
||||
$diagnosis['issues'][] = 'Source code niet gevonden';
|
||||
$diagnosis['recommendations'][] = 'Voer emulator:update --rebuild uit om vanaf source te bouwen';
|
||||
}
|
||||
|
||||
if (! ($sqlDiagnosis['table_exists'] ?? false)) {
|
||||
$diagnosis['issues'][] = 'SQL update tabel ontbreekt';
|
||||
$diagnosis['recommendations'][] = 'Reparatie zal de tabel aanmaken';
|
||||
}
|
||||
|
||||
if (($sqlDiagnosis['pending_count'] ?? 0) > 0) {
|
||||
$diagnosis['issues'][] = $sqlDiagnosis['pending_count'] . ' SQL updates pending';
|
||||
$diagnosis['recommendations'][] = 'Voer reparatie uit om SQL updates toe te passen';
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$diagnosis['error'] = $e->getMessage();
|
||||
}
|
||||
|
||||
return $diagnosis;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,186 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class UpdateHistoryService
|
||||
{
|
||||
private const string TABLE = 'update_history';
|
||||
|
||||
public function ensureTableExists(): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
Schema::create(self::TABLE, function ($table) {
|
||||
$table->id();
|
||||
$table->string('type'); // nitro, emulator, sql, config
|
||||
$table->string('action'); // update, build, deploy, fix
|
||||
$table->string('item')->nullable(); // filename, version, etc
|
||||
$table->string('status'); // success, failed, pending
|
||||
$table->text('message')->nullable();
|
||||
$table->string('user')->nullable();
|
||||
$table->string('ip')->nullable();
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
$table->index(['type', 'created_at']);
|
||||
$table->index('status');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function log(string $type, string $action, ?string $item = null, string $status = 'success', ?string $message = null): void
|
||||
{
|
||||
$this->ensureTableExists();
|
||||
|
||||
DB::table(self::TABLE)->insert([
|
||||
'type' => $type,
|
||||
'action' => $action,
|
||||
'item' => $item,
|
||||
'status' => $status,
|
||||
'message' => $message,
|
||||
'user' => auth()->user()?->name ?? 'System',
|
||||
'ip' => request()->ip(),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function getRecent(int $limit = 50): array
|
||||
{
|
||||
$this->ensureTableExists();
|
||||
|
||||
return DB::table(self::TABLE)
|
||||
->orderBy('created_at', 'desc')
|
||||
->limit($limit)
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
public function getByType(string $type, int $limit = 50): array
|
||||
{
|
||||
$this->ensureTableExists();
|
||||
|
||||
return DB::table(self::TABLE)
|
||||
->where('type', $type)
|
||||
->orderBy('created_at', 'desc')
|
||||
->limit($limit)
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
public function getByStatus(string $status, int $limit = 50): array
|
||||
{
|
||||
$this->ensureTableExists();
|
||||
|
||||
return DB::table(self::TABLE)
|
||||
->where('status', $status)
|
||||
->orderBy('created_at', 'desc')
|
||||
->limit($limit)
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
public function getStats(): array
|
||||
{
|
||||
$this->ensureTableExists();
|
||||
|
||||
$total = DB::table(self::TABLE)->count();
|
||||
$success = DB::table(self::TABLE)->where('status', 'success')->count();
|
||||
$failed = DB::table(self::TABLE)->where('status', 'failed')->count();
|
||||
|
||||
$lastUpdate = DB::table(self::TABLE)
|
||||
->orderBy('created_at', 'desc')
|
||||
->first();
|
||||
|
||||
$byType = DB::table(self::TABLE)
|
||||
->select('type', DB::raw('count(*) as count'))
|
||||
->groupBy('type')
|
||||
->pluck('count', 'type')
|
||||
->toArray();
|
||||
|
||||
return [
|
||||
'total' => $total,
|
||||
'success' => $success,
|
||||
'failed' => $failed,
|
||||
'success_rate' => $total > 0 ? round(($success / $total) * 100) : 100,
|
||||
'last_update' => $lastUpdate,
|
||||
'by_type' => $byType,
|
||||
];
|
||||
}
|
||||
|
||||
public function getHtml(): string
|
||||
{
|
||||
$this->ensureTableExists();
|
||||
|
||||
$updates = $this->getRecent(20);
|
||||
$stats = $this->getStats();
|
||||
|
||||
$html = '<div style="font-family: -apple-system, BlinkMacSystemFont, sans-serif;">';
|
||||
|
||||
// Stats
|
||||
$html .= '<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 16px;">';
|
||||
$html .= '<div style="background: rgba(255,255,255,0.05); padding: 12px; border-radius: 8px; text-align: center;">';
|
||||
$html .= '<div style="font-size: 24px; font-weight: 700; color: #4ade80;">' . $stats['total'] . '</div>';
|
||||
$html .= '<div style="font-size: 10px; color: #64748b; text-transform: uppercase;">Totaal</div></div>';
|
||||
$html .= '<div style="background: rgba(255,255,255,0.05); padding: 12px; border-radius: 8px; text-align: center;">';
|
||||
$html .= '<div style="font-size: 24px; font-weight: 700; color: #4ade80;">' . $stats['success'] . '</div>';
|
||||
$html .= '<div style="font-size: 10px; color: #64748b; text-transform: uppercase;">Geslaagd</div></div>';
|
||||
$html .= '<div style="background: rgba(255,255,255,0.05); padding: 12px; border-radius: 8px; text-align: center;">';
|
||||
$html .= '<div style="font-size: 24px; font-weight: 700; color: #f87171;">' . $stats['failed'] . '</div>';
|
||||
$html .= '<div style="font-size: 10px; color: #64748b; text-transform: uppercase;">Mislukt</div></div>';
|
||||
$html .= '<div style="background: rgba(255,255,255,0.05); padding: 12px; border-radius: 8px; text-align: center;">';
|
||||
$html .= '<div style="font-size: 24px; font-weight: 700; color: #60a5fa;">' . $stats['success_rate'] . '%</div>';
|
||||
$html .= '<div style="font-size: 10px; color: #64748b; text-transform: uppercase;">Succes</div></div>';
|
||||
$html .= '</div>';
|
||||
|
||||
// History list
|
||||
if ($updates === []) {
|
||||
$html .= '<div style="text-align: center; padding: 24px; color: #64748b;">';
|
||||
$html .= '<div style="font-size: 32px; margin-bottom: 8px;">📋</div>';
|
||||
$html .= 'Nog geen update geschiedenis</div>';
|
||||
} else {
|
||||
$html .= '<div style="max-height: 400px; overflow-y: auto;">';
|
||||
foreach ($updates as $update) {
|
||||
$icon = match ($update->status) {
|
||||
'success' => '✅',
|
||||
'failed' => '❌',
|
||||
'pending' => '⏳',
|
||||
default => '⚪'
|
||||
};
|
||||
|
||||
$typeColor = match ($update->type) {
|
||||
'nitro' => '#4ade80',
|
||||
'emulator' => '#60a5fa',
|
||||
'sql' => '#fbbf24',
|
||||
'config' => '#a78bfa',
|
||||
default => '#94a3b8'
|
||||
};
|
||||
|
||||
$time = Carbon::parse($update->created_at)->diffForHumans();
|
||||
|
||||
$html .= '<div style="display: flex; align-items: center; gap: 12px; padding: 10px 12px; background: rgba(255,255,255,0.03); border-radius: 8px; margin-bottom: 6px;">';
|
||||
$html .= '<div style="font-size: 16px;">' . $icon . '</div>';
|
||||
$html .= '<div style="flex: 1;">';
|
||||
$html .= '<div style="display: flex; align-items: center; gap: 8px;">';
|
||||
$html .= '<span style="background: ' . $typeColor . '20; color: ' . $typeColor . '; padding: 2px 8px; border-radius: 12px; font-size: 10px; font-weight: 600; text-transform: uppercase;">' . e($update->type) . '</span>';
|
||||
$html .= '<span style="color: #e2e8f0; font-size: 13px;">' . e($update->action) . '</span>';
|
||||
if ($update->item) {
|
||||
$html .= '<span style="color: #94a3b8; font-size: 12px;">' . e($update->item) . '</span>';
|
||||
}
|
||||
$html .= '</div>';
|
||||
if ($update->message) {
|
||||
$html .= '<div style="color: #64748b; font-size: 11px; margin-top: 2px;">' . e($update->message) . '</div>';
|
||||
}
|
||||
$html .= '</div>';
|
||||
$html .= '<div style="text-align: right;">';
|
||||
$html .= '<div style="color: #64748b; font-size: 10px;">' . e($update->user) . '</div>';
|
||||
$html .= '<div style="color: #475569; font-size: 9px;">' . e($time) . '</div>';
|
||||
$html .= '</div>';
|
||||
$html .= '</div>';
|
||||
}
|
||||
$html .= '</div>';
|
||||
}
|
||||
|
||||
return $html . '</div>';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user