ctrlpanel/app/Models/Server.php

146 lines
2.9 KiB
PHP
Raw Normal View History

2021-06-05 09:26:32 +00:00
<?php
namespace App\Models;
use App\Classes\Pterodactyl;
use Exception;
use GuzzleHttp\Promise\PromiseInterface;
use Hidehalo\Nanoid\Client;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Http\Client\Response;
use Spatie\Activitylog\Traits\LogsActivity;
/**
* Class Server
* @package App\Models
*/
class Server extends Model
{
use HasFactory;
use LogsActivity;
/**
* @var bool
*/
public $incrementing = false;
/**
* @var string[]
*/
2021-06-06 20:04:46 +00:00
protected static $ignoreChangedAttributes = ['pterodactyl_id', 'identifier', 'updated_at'];
2021-06-05 09:26:32 +00:00
/**
* @var string[]
*/
protected static $logAttributes = ['name', 'description'];
/**
* @var string[]
*/
protected $fillable = [
"name",
"description",
"suspended",
"identifier",
"product_id",
"pterodactyl_id",
];
/**
* @var string[]
*/
protected $dates = [
'suspended'
];
/**
*
*/
2021-06-06 20:04:46 +00:00
public static function boot()
{
2021-06-05 09:26:32 +00:00
parent::boot();
2021-06-06 20:04:46 +00:00
static::creating(function (Server $server) {
2021-06-05 09:26:32 +00:00
$client = new Client();
$server->{$server->getKeyName()} = $client->generateId($size = 21);
});
2021-06-06 20:04:46 +00:00
static::deleting(function (Server $server) {
$response = Pterodactyl::client()->delete("/application/servers/{$server->pterodactyl_id}");
2021-08-02 17:44:14 +00:00
if ($response->failed() && !is_null($server->pterodactyl_id)) throw new Exception($response['errors'][0]['code']);
2021-06-05 09:26:32 +00:00
});
}
/**
* @return bool
*/
2021-06-06 20:04:46 +00:00
public function isSuspended()
{
2021-06-05 09:26:32 +00:00
return !is_null($this->suspended);
}
/**
* @return PromiseInterface|Response
*/
2021-06-06 20:04:46 +00:00
public function getPterodactylServer()
{
2021-06-05 09:26:32 +00:00
return Pterodactyl::client()->get("/application/servers/{$this->pterodactyl_id}");
}
/**
*
* @throws Exception
*/
2021-06-06 20:04:46 +00:00
public function suspend()
{
2021-06-05 09:26:32 +00:00
$response = Pterodactyl::suspendServer($this);
if ($response->successful()) {
$this->update([
'suspended' => now()
]);
}
return $this;
}
/**
* @throws Exception
*/
public function unSuspend()
{
$response = Pterodactyl::unSuspendServer($this);
if ($response->successful()) {
$this->update([
'suspended' => null
]);
}
return $this;
}
2021-06-25 21:42:53 +00:00
2021-06-05 09:26:32 +00:00
/**
* @return HasOne
*/
2021-06-06 20:04:46 +00:00
public function product()
{
return $this->hasOne(Product::class, 'id', 'product_id');
2021-06-05 09:26:32 +00:00
}
/**
* @return BelongsTo
*/
2021-06-06 20:04:46 +00:00
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
2021-06-05 09:26:32 +00:00
}
}