fedi-feed-router/app/Models/PlatformAccount.php

102 lines
2.9 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Crypt;
use App\Enums\PlatformEnum;
/**
* @property int $id
* @property PlatformEnum $platform
* @property string $instance_url
* @property string $username
* @property string $password
* @property string $settings
* @property bool $is_active
* @property Carbon $last_tested_at
* @property string $status
* @property Carbon $created_at
* @property Carbon $updated_at
* @property Collection $activeChannels
* @method static where(string $string, PlatformEnum $platform)
* @method static orderBy(string $string)
* @method static create(array $validated)
*/
class PlatformAccount extends Model
{
protected $fillable = [
'platform',
'instance_url',
'username',
'password',
'api_token',
'settings',
'is_active',
'last_tested_at',
'status'
];
protected $casts = [
'platform' => PlatformEnum::class,
'settings' => 'array',
'is_active' => 'boolean',
'last_tested_at' => 'datetime'
];
// Encrypt password when storing
protected function password(): Attribute
{
return Attribute::make(
get: fn ($value) => $value ? Crypt::decryptString($value) : null,
set: fn ($value) => $value ? Crypt::encryptString($value) : null,
);
}
// Encrypt API token when storing
protected function apiToken(): Attribute
{
return Attribute::make(
get: fn ($value) => $value ? Crypt::decryptString($value) : null,
set: fn ($value) => $value ? Crypt::encryptString($value) : null,
);
}
// Get the active accounts for a platform (returns collection)
public static function getActive(PlatformEnum $platform): Collection
{
return static::where('platform', $platform)
->where('is_active', true)
->get();
}
// Set this account as active (deactivates others for same platform)
public function setAsActive(): void
{
// Deactivate other accounts for this platform
static::where('platform', $this->platform)
->where('id', '!=', $this->id)
->update(['is_active' => false]);
// Activate this account
$this->update(['is_active' => true]);
}
public function channels(): BelongsToMany
{
return $this->belongsToMany(PlatformChannel::class, 'platform_account_channels')
->withPivot(['is_active', 'priority'])
->withTimestamps();
}
public function activeChannels(): BelongsToMany
{
return $this->channels()
->wherePivot('is_active', true)
->orderByPivot('priority', 'desc');
}
}