added chat 2

This commit is contained in:
2026-07-30 18:06:53 +03:30
parent abb778e090
commit dcc6ffb3ca
@@ -12,13 +12,6 @@ class ChatController extends Controller
{
$user = Customer::findOrFail(auth('customer')->id());
if (!empty($user->chat_room_id)) {
return response()->json([
'message' => 'چت از قبل ساخته شده',
'user' => $user,
]);
}
$chatApi = self::Config('chat_api');
$chatApiKey = self::Config('chat_api_key');
@@ -29,11 +22,33 @@ class ChatController extends Controller
}
$host = preg_replace('#^https?://#', '', rtrim((string) $chatApi, '/'));
$userChatId = 'user_'.$user->id;
$userChatId = !empty($user->chat_user_id)
? (string) $user->chat_user_id
: 'user_'.$user->id;
if (!empty($user->chat_room_id)) {
if ($this->chatRoomIsAccessible($host, (string) $chatApiKey, (string) $user->chat_room_id, $userChatId)) {
if (empty($user->chat_user_id) || $user->chat_user_id !== $userChatId) {
$user->chat_user_id = $userChatId;
$user->save();
}
return response()->json([
'message' => 'چت از قبل ساخته شده',
'user' => $user,
]);
}
// روم در سرویس چت نامعتبر/بدون عضویت است — از نو می‌سازیم
$user->chat_room_id = null;
$user->chat_user_id = null;
$user->save();
}
$url = 'https://'.$host.'/api/rooms/create';
try {
$response = Http::post($url, [
$response = Http::timeout(12)->post($url, [
'api_key' => $chatApiKey,
'name' => $user->name,
'type' => 'SUPPORT',
@@ -65,4 +80,29 @@ class ChatController extends Controller
], 422);
}
}
private function chatRoomIsAccessible(
string $host,
string $apiKey,
string $roomId,
string $userChatId
): bool {
if ($host === '' || $apiKey === '' || $roomId === '' || $userChatId === '') {
return false;
}
try {
$response = Http::timeout(8)->acceptJson()->get('https://'.$host.'/api/messages', [
'api_key' => $apiKey,
'room_id' => $roomId,
'user_id' => $userChatId,
'limit' => 1,
'offset' => 0,
]);
return $response->successful();
} catch (\Throwable $e) {
return false;
}
}
}