Files
nabeh/backend/app/Models/WhatsAppSession.php
T

230 lines
7.0 KiB
PHP

<?php
namespace App\Models;
use App\Core\Security;
use App\Core\Database;
use App\Core\Cache;
/**
* WhatsAppSession Model
* Handles the whatsapp_sessions table with encryption for phone and QR code,
* Redis caching of connected sessions, and Round-Robin distribution for outbound messages.
*/
class WhatsAppSession extends BaseModel
{
protected static string $table = 'whatsapp_sessions';
/**
* Clear cached connected sessions for a company
*/
public static function clearSessionsCache(int $companyId): void
{
Cache::delete("connected_sessions:company_{$companyId}");
}
/**
* Get all active connected sessions for a company (cached via Redis if available)
*/
public static function getConnectedSessionsForCompany(int $companyId): array
{
$cacheKey = "connected_sessions:company_{$companyId}";
$cached = Cache::get($cacheKey);
if ($cached !== null && is_array($cached)) {
return $cached;
}
$sessions = Database::select(
"SELECT * FROM " . static::$table . " WHERE company_id = ? AND status = 'connected' ORDER BY id ASC",
[$companyId]
);
foreach ($sessions as &$session) {
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
}
Cache::set($cacheKey, $sessions, 3000); // Cache for 50 minutes
return $sessions;
}
/**
* Get next connected session using Round-Robin strategy via Redis
*/
public static function getRoundRobinSession(int $companyId): ?array
{
$connectedSessions = static::getConnectedSessionsForCompany($companyId);
if (empty($connectedSessions)) {
// Fallback to legacy single session if no connected sessions are found
return static::findByCompany($companyId, false);
}
$count = count($connectedSessions);
if ($count === 1) {
return $connectedSessions[0];
}
$rrKey = "rr_index:company_{$companyId}";
$currentIndex = Cache::get($rrKey);
if ($currentIndex === null || !is_numeric($currentIndex)) {
$currentIndex = 0;
} else {
$currentIndex = (int)$currentIndex;
}
$selectedIndex = $currentIndex % $count;
$nextIndex = ($selectedIndex + 1) % $count;
Cache::set($rrKey, $nextIndex, 86400);
return $connectedSessions[$selectedIndex];
}
/**
* Get the session for a specific company (defaults to Round-Robin among connected sessions)
*/
public static function findByCompany(int $companyId, bool $useRoundRobin = true)
{
if ($useRoundRobin) {
$session = static::getRoundRobinSession($companyId);
if ($session) {
return $session;
}
}
$session = Database::selectOne(
"SELECT * FROM " . static::$table . " WHERE company_id = ? LIMIT 1",
[$companyId]
);
if ($session) {
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
}
return $session;
}
/**
* Find secure session by ID
*/
public static function findSecure(int $id)
{
$session = Database::selectOne(
"SELECT * FROM " . static::$table . " WHERE id = ? LIMIT 1",
[$id]
);
if ($session) {
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
}
return $session;
}
/**
* Get all WhatsApp sessions for a company
*/
public static function findAllByCompany(int $companyId): array
{
$sessions = Database::select(
"SELECT * FROM " . static::$table . " WHERE company_id = ? ORDER BY id ASC",
[$companyId]
);
foreach ($sessions as &$session) {
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
}
return $sessions;
}
/**
* Get a session by session_key (used by webhooks)
*/
public static function findBySessionKey(string $sessionKey)
{
$session = Database::selectOne(
"SELECT * FROM " . static::$table . " WHERE session_key = ? LIMIT 1",
[$sessionKey]
);
if ($session) {
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
}
return $session;
}
/**
* Find session by phone number (useful to prevent duplicates across companies)
*/
public static function findByPhone(string $phone)
{
$phoneHash = Security::blindIndex($phone);
$session = Database::selectOne(
"SELECT * FROM " . static::$table . " WHERE phone_hash = ? LIMIT 1",
[$phoneHash]
);
if ($session) {
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
}
return $session;
}
/**
* Create or retrieve a new session for a company
*/
public static function findOrCreate(int $companyId, string $name = 'Main WhatsApp')
{
$session = static::findByCompany($companyId, false);
if ($session) {
return $session;
}
$sessionKey = 'cmp_' . $companyId . '_' . bin2hex(random_bytes(4));
$id = static::create([
'company_id' => $companyId,
'name' => $name,
'session_key' => $sessionKey,
'status' => 'disconnected'
]);
static::clearSessionsCache($companyId);
return static::findByCompany($companyId, false);
}
/**
* Update session state securely and clear Redis cache
*/
public static function updateState(int $id, array $data)
{
if (isset($data['phone'])) {
$data['phone_hash'] = Security::blindIndex($data['phone']);
$data['phone'] = Security::encrypt($data['phone']);
}
if (isset($data['qr_code'])) {
$data['qr_code'] = Security::encrypt($data['qr_code']);
}
$session = Database::selectOne("SELECT company_id FROM " . static::$table . " WHERE id = ? LIMIT 1", [$id]);
$result = static::update($id, $data);
if ($session && !empty($session['company_id'])) {
static::clearSessionsCache((int)$session['company_id']);
}
return $result;
}
}