update contests api

This commit is contained in:
themohooks 2025-02-16 04:37:06 +03:00
parent 3360b9d208
commit b5ff9d1998
4 changed files with 112 additions and 30 deletions

View file

@ -0,0 +1,4 @@
tasks:
- id: "ExecContests"
type: "cron"
handler: "/app/Controllers/Exec/Tasks/ExecContests.php"

View file

@ -81,6 +81,7 @@ class Routes
Router::any('/api/admin/geodb/load', 'ApiController@admingeodbload');
Router::any('/api/admin/contests/createtheme', 'ApiController@admincontestscreatetheme');
Router::any('/api/admin/contests/create', 'ApiController@admincontestscreate');
Router::any('/api/admin/settings/taskmanager', 'ApiController@admintaskmanager');
}
Router::get('/logout', 'MainController@logout');
Router::get('/404', 'ExceptionRegister@notfound');

View file

@ -1,5 +1,6 @@
<?php
namespace App\Services;
use InvalidArgumentException;
class Date
{
@ -65,5 +66,38 @@ class Date
);
return $formattedDate;
}
public static function addTime($timeString, int $baseTime = null)
{
if ($baseTime === null) {
$baseTime = time();
}
preg_match('/^(\d+)([smhdwMy])$/', $timeString, $matches);
if (!$matches) {
throw new InvalidArgumentException("Неверный формат времени: $timeString");
}
[$fullMatch, $amount, $unit] = $matches;
$amount = (int) $amount;
$multipliers = [
's' => 1, // секунды
'm' => 60, // минуты
'h' => 3600, // часы
'd' => 86400, // дни
'w' => 604800, // недели
'M' => 2629743, // месяцы (среднее значение)
'y' => 31556926 // годы (среднее значение)
];
if (!isset($multipliers[$unit])) {
throw new InvalidArgumentException("Неизвестная единица измерения: $unit");
}
return $baseTime + ($amount * $multipliers[$unit]);
}
}
?>

View file

@ -2,42 +2,44 @@
namespace App\Services;
class TaskScheduler {
private $taskName;
private $command;
private $interval;
public function __construct() {
// Конструктор теперь не принимает аргументы
}
public function __construct() {}
private function isWindows() {
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
// Метод для добавления задачи с параметрами
public function addTask($taskName, $command, $interval = "* * * * *") {
$this->taskName = $taskName;
$this->command = $command;
$this->interval = $interval;
return $this->isWindows() ? $this->addWindowsTask() : $this->addLinuxTask();
return $this->isWindows() ? $this->addWindowsTask($taskName, $command) : $this->addLinuxTask($command, $interval);
}
public function isTaskExists($taskName = null, $command = null) {
return $this->isWindows()
? $this->isWindowsTaskExists($taskName)
: $this->isLinuxTaskExists($command);
return $this->isWindows() ? $this->isWindowsTaskExists($taskName) : $this->isLinuxTaskExists($command);
}
public function removeTask($taskName = null, $command = null) {
return $this->isWindows()
? $this->removeWindowsTask($taskName)
: $this->removeLinuxTask($command);
return $this->isWindows() ? $this->removeWindowsTask($taskName) : $this->removeLinuxTask($command);
}
private function addLinuxTask() {
$cronJob = "{$this->interval} {$this->command}";
if ($this->isLinuxTaskExists($this->command)) {
public function getTaskStatus($taskName, $command = null) {
if (!$this->isTaskExists($taskName, $command)) {
return "Не работает (задача отсутствует)";
}
return $this->isWindows() ? $this->getWindowsTaskStatus($taskName) : $this->getLinuxTaskStatus($command);
}
public function findHandlerById($array, $id) {
foreach ($array as $item) {
if (isset($item['id']) && $item['id'] === $id) {
return $item['handler'] ?? null;
}
}
return null;
}
private function addLinuxTask($command, $interval) {
$cronJob = "{$interval} {$command}";
if ($this->isLinuxTaskExists($command)) {
return "✅ Cron-задача уже установлена.";
}
@ -57,7 +59,7 @@ class TaskScheduler {
private function isLinuxTaskExists($command = null) {
exec("crontab -l 2>&1", $output);
foreach ($output as $line) {
if (strpos($line, $command ?? $this->command) !== false) {
if (strpos($line, $command) !== false) {
return true;
}
}
@ -71,7 +73,7 @@ class TaskScheduler {
}
$filteredOutput = array_filter($output, function ($line) use ($command) {
return strpos($line, $command ?? $this->command) === false;
return strpos($line, $command) === false;
});
file_put_contents("/tmp/my_cron", implode(PHP_EOL, $filteredOutput) . PHP_EOL);
@ -81,19 +83,29 @@ class TaskScheduler {
return "✅ Cron-задача удалена!";
}
private function addWindowsTask() {
if ($this->isWindowsTaskExists($this->taskName)) {
private function getLinuxTaskStatus($command) {
exec("ps aux | grep '" . escapeshellarg($command) . "' | grep -v grep", $output, $return_code);
if (empty($output)) {
return "Не работает (ошибка: процесс не найден)";
}
return "✅ Работает корректно";
}
private function addWindowsTask($taskName, $command) {
if ($this->isWindowsTaskExists($taskName)) {
return "✅ Задача уже существует в Windows.";
}
$command = "schtasks /Create /SC MINUTE /MO 1 /TN \"{$this->taskName}\" /TR \"{$this->command}\" /F";
exec($command, $output, $return_code);
$cmd = "schtasks /Create /SC MINUTE /MO 1 /TN \"{$taskName}\" /TR \"{$command}\" /F";
exec($cmd, $output, $return_code);
return ($return_code === 0) ? "✅ Задача добавлена в Windows!" : "❌ Ошибка при добавлении задачи.";
}
private function isWindowsTaskExists($taskName = null) {
exec("schtasks /Query /TN \"". ($taskName ?? $this->taskName) ."\" 2>&1", $output, $return_var);
exec("schtasks /Query /TN \"". ($taskName) ."\" 2>&1", $output, $return_var);
return $return_var === 0;
}
@ -102,8 +114,39 @@ class TaskScheduler {
return "❌ Задача не найдена в Windows.";
}
exec("schtasks /Delete /TN \"". ($taskName ?? $this->taskName) ."\" /F", $output, $return_code);
exec("schtasks /Delete /TN \"". ($taskName) ."\" /F", $output, $return_code);
return ($return_code === 0) ? "✅ Задача удалена из Windows!" : "❌ Ошибка при удалении задачи.";
}
private function getWindowsTaskStatus($taskName) {
exec("schtasks /Query /TN \"{$taskName}\" /FO LIST /V", $output, $return_var);
if ($return_var !== 0) {
return "Не работает (задача отсутствует)";
}
$status = "Не работает (ошибка: неизвестно)";
$output = array_map(function($line) {
return iconv('Windows-1251', 'UTF-8', $line);
}, $output);
// Ищем статус задачи
foreach ($output as $line) {
if (strpos($line, "Статус:") !== false) {
if (stripos($line, "Выполняется") !== false) {
$status = "✅ Работает корректно";
} elseif (stripos($line, "Готово") !== false) {
$status = "Не работает (но активна)";
} elseif (stripos($line, "Не удалось запустить") !== false) {
$status = "Не работает (ошибка: не удалось запустить)";
}
break;
}
}
return $status;
}
}
?>