Initial work

This commit is contained in:
2025-08-30 16:11:06 +02:00
parent 4e5f154492
commit 774d1cf45f
41 changed files with 1217 additions and 281 deletions

9
app/Bots/BotContract.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
namespace App\Bots;
interface BotContract
{
public function run(): void;
public static function configSchema(): array;
}

73
app/Bots/Mattermost.php Normal file
View File

@@ -0,0 +1,73 @@
<?php
namespace App\Bots;
use App\Bots\BotContract;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
class Mattermost implements BotContract
{
protected Client $client;
public function __construct(private ?array $config = [])
{
$this->client = new Client([
'base_uri' => rtrim(config('scheduler.mattermost.server_url'), '/') . '/api/v4/',
'headers' => [
'Authorization' => 'Bearer ' . config('scheduler.mattermost.access_token'),
'Accept' => 'application/json',
'Content-Type' => 'application/json',
],
]);
}
public function run(): void
{
try {
$request = new \GuzzleHttp\Psr7\Request(
$this->config['method'] ?? 'POST',
$this->config['endpoint'],
['Content-Type' => 'application/json'],
json_encode($this->config['body'] ?? [])
);
$res = $this->client->send($request);
// $res = $this->client->put('users/me/status/custom', [
// 'json' => [
// 'emoji' => 'house',
// 'text' => 'Working Home',
// 'status' => 'online',
// ]
// ]);
if ($res->getStatusCode() === 200) {
Log::info("Mattermost home status updated successfully.");
} else {
Log::error("Failed to update Mattermost status. HTTP Status: " . $res->getStatusCode());
}
} catch (\Exception $e) {
Log::error("Error updating Mattermost status: " . $e->getMessage());
}
}
public static function configSchema(): array
{
return [
'endpoint' => ['type' => 'string', 'label' => 'API Endpoint', 'rules' => [
'required',
'string',
'max:255',
]],
'method' => ['type' => 'string', 'label' => 'HTTP Method', 'default' => 'POST', 'rules' => [
'required',
'in:GET,POST,PUT,DELETE,PATCH',
]],
'body' => ['type' => 'array', 'label' => 'Request Body (JSON)', 'rules' => [
'nullable',
'array',
]],
];
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Bots\Mattermost;
use App\Bots\BotContract;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
class RemoveStatus implements BotContract
{
protected Client $client;
public function __construct(private ?array $config = [])
{
$this->client = new Client([
'base_uri' => rtrim(config('scheduler.mattermost.server_url'), '/') . '/api/v4/',
'headers' => [
'Authorization' => 'Bearer ' . config('scheduler.mattermost.access_token'),
],
]);
}
public function run(): void
{
try {
$res = $this->client->delete('users/me/status/custom');
if ($res->getStatusCode() === 200) {
Log::info("Mattermost status cleared");
} else {
Log::error("Failed to update Mattermost status. HTTP Status: " . $res->getStatusCode());
}
} catch (\Exception $e) {
Log::error("Error updating Mattermost status: " . $e->getMessage());
}
}
public static function configSchema(): array
{
return [
'endpoint' => ['type' => 'string', 'label' => 'API Endpoint'],
'method' => ['type' => 'string', 'label' => 'HTTP Method', 'default' => 'POST'],
'body' => ['type' => 'array', 'label' => 'Request Body (JSON)'],
];
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace App\Bots\Mattermost;
use App\Bots\BotContract;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
class WednesdayHomeStatus implements BotContract
{
protected Client $client;
public function __construct(private ?array $config = [])
{
$this->client = new Client([
'base_uri' => rtrim(config('scheduler.mattermost.server_url'), '/') . '/api/v4/',
'headers' => [
'Authorization' => 'Bearer ' . config('scheduler.mattermost.access_token'),
'Accept' => 'application/json',
'Content-Type' => 'application/json',
],
]);
}
public function run(): void
{
try {
$res = $this->client->put('users/me/status/custom', [
'json' => [
'emoji' => 'house',
'text' => 'Working Home',
'status' => 'online',
]
]);
if ($res->getStatusCode() === 200) {
Log::info("Mattermost home status updated successfully.");
} else {
Log::error("Failed to update Mattermost status. HTTP Status: " . $res->getStatusCode());
}
} catch (\Exception $e) {
Log::error("Error updating Mattermost status: " . $e->getMessage());
}
}
public static function configSchema(): array
{
return [
'endpoint' => ['type' => 'string', 'label' => 'API Endpoint'],
'method' => ['type' => 'string', 'label' => 'HTTP Method', 'default' => 'POST'],
'body' => ['type' => 'array', 'label' => 'Request Body (JSON)'],
];
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class BotController extends Controller
{
public function create()
{
return view('bots.create');
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index()
{
$bots = \App\Models\Bot::all();
return view('dashboard', compact('bots'));
}
}

32
app/Livewire/BotsList.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace App\Livewire;
use Livewire\Component;
class BotsList extends Component
{
public $bots;
public function mount()
{
$this->bots = \App\Models\Bot::all();
}
public function toggleBot($botId)
{
$bot = \App\Models\Bot::find($botId);
if ($bot) {
$bot->enabled = !$bot->enabled;
$bot->save();
$this->bots = \App\Models\Bot::all(); // Refresh the list
flash()->success("Bot '{$bot->name}' has been " . ($bot->enabled ? 'enabled' : 'disabled') . ".");
}
}
public function render()
{
return view('livewire.bots-list');
}
}

View File

@@ -0,0 +1,164 @@
<?php
namespace App\Livewire;
use App\Bots\BotContract;
use Cron\CronExpression;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\URL;
use Illuminate\Validation\Rule;
use Livewire\Component;
use Lorisleiva\CronTranslator\CronParsingException;
use Lorisleiva\CronTranslator\CronTranslator;
class CreateEditBot extends Component
{
public string $name = '';
public string $class = '';
public string $schedule = '* * * * *';
public bool $enabled = true;
public string $cron_text = 'Every minute';
public string $config = '{}';
public array $classList = [];
public array $configSchema = [];
public string $routeName = '';
public function mount(?int $bot = null)
{
$this->routeName = URL::current() === route('bots.create') ? 'Create Bot' : 'Edit Bot';
$bot = \App\Models\Bot::find($bot);
if ($bot) {
$this->name = $bot->name;
$this->class = $bot->class;
$this->schedule = $bot->schedule;
$this->enabled = $bot->enabled;
$this->cron_text = \Lorisleiva\CronTranslator\CronTranslator::translate($bot->schedule);
}
$basePath = $basePath ?? app_path('Bots');
$baseNamespace = $baseNamespace ?? 'App\\Bots';
foreach (File::allFiles($basePath) as $file) {
// Convert file path → class name
$relativePath = str_replace([$basePath . DIRECTORY_SEPARATOR, '.php'], '', $file->getPathname());
$relativeNamespace = str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath);
$class = $baseNamespace . '\\' . $relativeNamespace;
// Make sure class exists and implements BotContract
if (class_exists($class) && in_array(BotContract::class, class_implements($class))) {
$label = method_exists($class, 'label')
? $class::label()
: class_basename($class);
$this->classList[$label] = $class;
}
}
}
public function updatedClass($value)
{
$this->class = $this->classList[$value];
$this->configSchema = $this->classList[$value]::configSchema();
}
protected function rules(): array
{
$schemaRules = [];
foreach ($this->configSchema as $field => $meta) {
$schemaRules["config.$field"] = $meta['rules'] ?? [];
}
return array_merge([
'name' => [
'required',
'string',
'max:255',
Rule::unique('bots', 'name')->ignore($this->name, 'name'),
],
'class' => [
'required',
'string',
'max:255',
],
'schedule' => [
'required',
'string',
'max:255',
function ($attribute, $value, $fail) {
if (!CronExpression::isValidExpression($value)) {
$fail('The ' . $attribute . ' is not a valid cron expression.');
}
},
],
'enabled' => ['boolean'],
], $schemaRules);
}
public function save(): void
{
$this->validate();
if (!class_exists($this->class)) {
$this->addError('class', 'The specified class does not exist.');
return;
}
if (!in_array(\App\Bots\BotContract::class, class_implements($this->class))) {
$this->addError('class', 'The specified class does not exist.');
return;
}
if (URL::current() !== route('bots.create')) {
$bot = \App\Models\Bot::where('name', $this->name)->first();
if ($bot) {
$bot->update([
'name' => $this->name,
'class' => $this->class,
'enabled' => $this->enabled,
'schedule' => $this->schedule,
]);
flash()->success('Bot updated successfully.');
return;
}
} else {
\App\Models\Bot::create([
'name' => $this->name,
'class' => $this->class,
'enabled' => $this->enabled,
'schedule' => $this->schedule,
]);
}
flash()->success('Bot created successfully.');
$this->reset(['name', 'namespace', 'class', 'enabled', 'schedule']);
}
public function updatedSchedule($value)
{
try {
$this->cron_text = CronTranslator::translate($value);
$this->resetErrorBag('schedule');
} catch (CronParsingException $e) {
$this->cron_text = '';
}
}
public function render()
{
return view('livewire.create-edit-bot');
}
}

39
app/Models/Bot.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
namespace App\Models;
use Cron\CronExpression;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Lorisleiva\CronTranslator\CronTranslator;
class Bot extends Model
{
protected $fillable = [
'name',
'class',
'config',
'schedule',
'enabled'
];
protected $casts = [
'config' => 'array',
];
public function nextDue(): Attribute
{
return Attribute::make(
get: function () {
$cron = new CronExpression($this->schedule);
return $cron->getNextRunDate()->format('Y-m-d H:i:s');
}
);
}
public function cronToHuman(): Attribute
{
return Attribute::make(
get: fn () => CronTranslator::translate($this->schedule));
}
}

View File

@@ -11,7 +11,9 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
app()->singleton(\App\Services\BotService::class, function ($app) {
return new \App\Services\BotService();
});
}
/**

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Services;
use App\Models\Bot;
use App\Bots\BotContract;
use Cron\CronExpression;
use Illuminate\Support\Facades\Log;
class BotService
{
public function run(): void
{
$bots = Bot::where('enabled', 1)->get();
foreach ($bots as $bot) {
$cron = new CronExpression($bot->schedule);
if ($cron->isDue()) {
try {
$instance = app($bot->class, ['config' => $bot->config]);
if ($instance instanceof BotContract) {
$instance->run();
}
} catch (\Throwable $e) {
Log::error("Bot [{$bot->name}] failed: " . $e->getMessage());
}
Log::info("Bot [{$bot->name}] executed successfully.");
}
}
}
}