PortIO/app/Models/Tunnel.php

89 lines
1.8 KiB
PHP
Raw Normal View History

2023-03-15 13:45:41 +00:00
<?php
namespace App\Models;
2023-05-14 07:42:18 +00:00
use App\Support\Frp;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;
2023-03-15 13:45:41 +00:00
use Illuminate\Database\Eloquent\Model;
2023-05-14 07:42:18 +00:00
use App\Http\Controllers\Admin\ServerController;
use App\Http\Controllers\Admin\TunnelController;
2023-03-16 13:44:01 +00:00
use Illuminate\Database\Eloquent\Relations\BelongsTo;
2023-03-15 13:45:41 +00:00
class Tunnel extends Model
{
protected $fillable = [
'name',
'protocol',
'custom_domain',
'local_address',
'remote_port',
'client_token',
'sk',
'status',
'server_id',
'user_id',
2023-05-14 07:42:18 +00:00
'locked_reason',
'run_id'
2023-03-15 13:45:41 +00:00
];
2023-03-16 13:44:01 +00:00
protected $with = [
'server',
];
public function server(): BelongsTo
2023-03-15 13:45:41 +00:00
{
return $this->belongsTo(Server::class);
2023-05-14 07:42:18 +00:00
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function getConfig()
{
return (new TunnelController)->generateConfig($this);
}
public function close()
{
if ($this->run_id) {
$frp = new Frp($this->server);
$closed = $frp->close($this->run_id);
if ($closed) {
$cache_key = 'frpTunnel_data_' . $this->client_token;
Cache::forget($cache_key);
$this->run_id = null;
$this->saveQuietly();
}
return true;
}
return false;
}
protected static function boot()
{
parent::boot();
static::creating(function (self $tunnel) {
$tunnel->client_token = Str::random(18);
});
static::updated(function (self $tunnel) {
if ($tunnel->locked_reason) {
$tunnel->close();
}
});
2023-03-15 13:45:41 +00:00
2023-05-14 07:42:18 +00:00
static::deleted(function (self $tunnel) {
$tunnel->close();
});
2023-03-15 13:45:41 +00:00
}
}