getPeer(); $extension = explode('/',$extension); $extension = trim(end($extension)); $status = $event->getPeerStatus(); $status = trim($status); if (substr($extension, 0, 2) == '99' && strlen($extension) > 3){ $extension = substr($extension, 2); } $this->handleQueueMembership($extension, $status); // $user = User::find($extension); if($status == 'Reachable'){ $this->createLoginEvent($extension); }else{ $this->updateLoginEvent($extension); } } // if ($event instanceof HangupEvent) { // $linkedId = $event->getKey('linkedid'); // $maxAttempts = 5; // 5 × 2 = 10 ثواني // $attempt = 0; // while ($attempt < $maxAttempts) { // $exists = \DB::table('inbound_reports') // ->where('linkedid', $linkedId) // ->exists(); // if ($exists) { // \Log::info("Inbound report already created for {$linkedId} on attempt {$attempt}"); // return; // } // sleep(2); // $attempt++; // } // Artisan::call('reports:inbound:process-call', [ // 'linkedid' => $linkedId // ]); // \Log::info("Inbound report created for call {$linkedId}"); // } // if ($event instanceof HangupEvent) { // $linkedId = $event->getKey('linkedid'); // ProcessInboundReportJob::dispatch($linkedId); // \Log::info("Inbound report job dispatched for {$linkedId}"); // } } private function getAgentStatus($userId) { $process = new Process(['asterisk', '-x', 'queue show']); $process->run(); $output = $process->getOutput(); // Search for the line that contains the user preg_match_all("/Local\/{$userId}@from-queue[^\n]*/", $output, $matches); if (empty($matches[0])) { return [ 'status' => 'not_found', 'reason' => null, ]; } // Take the first match (first queue) $line = $matches[0][0]; // Determine status and reason if (preg_match('/\(paused:(.*?)\)/', $line, $pausedMatch)) { $status = 'paused'; // Take only the first word from the reason $reasonFull = trim($pausedMatch[1]); $reasonParts = explode(' ', $reasonFull); $reason = $reasonParts[0] ?? null; } else { $status = 'unpaused'; $reason = null; } return [ 'status' => $status, 'reason' => $reason, ]; } /** * Handle adding/removing user from queues based on reachability status * * @param string $extension User's extension * @param string $status Peer status (Reachable/Unreachable) * @return void */ private function handleQueueMembership($extension, $status) { try { // Find the user by extension (id) $user = User::find($extension); $time = date('Y-m-d H:i:s'); if (!$user) { \Log::debug("AsteriskEventsHandler: User with extension {$extension} not found"); return; } // Get all groups (queues) the user belongs to $groups = $user->groups; if ($groups->isEmpty()) { \Log::debug("AsteriskEventsHandler: User {$extension} has no assigned groups/queues"); return; } $log_name = 'phone-status'; $asteriskGroup = new UserAsteriskGroup(); if ($status == 'Reachable') { foreach ($groups as $group) { $queueId = $group->queue_id ?? $group->id; // User's phone is online - add them to their queues $result = $asteriskGroup->RealtimeAddUserToQueue($extension, $queueId); if ($result) { \Log::info("AsteriskEventsHandler: Added extension {$extension} to queue {$queueId} (status: Reachable)"); } else { \Log::warning("AsteriskEventsHandler: Failed to add extension {$extension} to queue {$queueId}"); } $isPaused = $asteriskGroup->isUserOnPause($extension, $queueId); if ($isPaused) { $asteriskGroup->PauseUser($extension, $queueId, $isPaused); $log_name = $isPaused; $status = 'pause'; } } } else { foreach ($groups as $group) { $queueId = $group->queue_id ?? $group->id; // User's phone is offline - remove them from their queues $result = $asteriskGroup->RealtimeRemoveUserFromQueue($extension, $queueId); if ($result) { \Log::info("AsteriskEventsHandler: Removed extension {$extension} from queue {$queueId} (status: {$status})"); } else { \Log::warning("AsteriskEventsHandler: Failed to remove extension {$extension} from queue {$queueId}"); } } } $insertions = [ [ 'log_name' => $log_name, 'description' => $status, 'subject_id' => $extension, 'subject_type' => 'Modules\Platform\User\Entities\User', 'causer_id' => $extension, 'causer_type' => 'Modules\Platform\User\Entities\User', 'properties' => '[]', 'created_at' => $time, 'updated_at' => $time ] ]; // $lastLog = \DB::table('activity_log') // ->where('subject_id', $extension) // ->orderByDesc('id') // ->first(); // // \Log::debug(["activity_log" => $insertions[0]]); // // Handle queue membership based on reachability status // if($lastLog && $lastLog->log_name == $log_name && $lastLog->description == $status){ // \Log::info("Duplicate status for extension $extension skipped"); // } else { \DB::table('activity_log')->insert($insertions); // } } catch (\Exception $e) { \Log::error("AsteriskEventsHandler: Error handling queue membership for extension {$extension} - " . $e->getMessage()); } } public function createLoginEvent($extension) { $calendarId = $this->getOrCreateDefaultCalendar(); $event = Event::where('owned_by_id', $extension)->where('owned_by_type', User::class) ->where('calendar_id', $calendarId) ->where('updated_at','>', Carbon::now()->subHours(8)->format('Y-m-d H:i:s')) ->whereRaw('start_date = DATE_SUB(end_date, INTERVAL 1 SECOND)') ->where('event_status_id', 2) ->where('description', 'LogIn') ->first(); if(!$event){ try { $start_date = Carbon::now()->format('Y-m-d H:i:s'); $end_date = Carbon::now()->addSecond()->format('Y-m-d H:i:s'); $event = new Event(); $event->name = $extension.' LogIn'; $event->start_date = $start_date; $event->end_date = $end_date; $event->full_day = false; $event->event_color = '#7fc82b'; // $event->changeOwnerTo($user); $event->owned_by_id = $extension; $event->owned_by_type = 'Modules\Platform\User\Entities\User'; $event->calendar_id = $calendarId; $event->event_priority_id = 1; $event->event_status_id = 2; $event->description = 'LogIn'; $event->company_id = 1; $event->save(); } catch (\Throwable $th) { echo $th; } } } public function updateLoginEvent($extension) { $calendar = Calendar::where('name', 'Attendees Calendar') ->first(); $time = date('Y-m-d H:i:s'); try { $event = Event::where('owned_by_id', $extension)->where('owned_by_type', 'Modules\Platform\User\Entities\User') ->where('calendar_id', $calendar->id) // ->whereRaw('start_date = DATE_SUB(end_date, INTERVAL 1 SECOND)') // ->where('event_status_id', 2) // ->where('description', 'LogIn') ->orderBy('updated_at', 'DESC') ->first(); $event->end_date = $time; $event->event_color = '#6d0d0d'; $event->description = 'LogIn - LogOut'; $event->event_status_id = 4; $event->save(); } catch (\Throwable $th) { // echo $th; } } public function getOrCreateDefaultCalendar() { $calendar = Calendar::where('name', 'Attendees Calendar') ->first(); if (empty($calendar)) { $calendar = new Calendar(); $calendar->name = 'Attendees Calendar'; $calendar->is_public = false; $calendar->default_view = Calendar::MONT_VIEW; $calendar->first_day = Calendar::WEEK_START_AT_MONDAY; $calendar->day_start_at = Calendar::DEFAULT_DAT_START_AT; $calendar->company_id = Landlord::getTenants()->first(); $calendar->save(); } return $calendar->id; } public function separate(){ echo PHP_EOL.PHP_EOL.'-----------------------------'.PHP_EOL.PHP_EOL; } // just add (linkedid) and (direction_id) to calls After Hung Up public function insertCallRecord($data){ if(!empty($data)){ $call = new Call; $call->linkedid = $data['linkedid']; $call->direction_id = \DB::table('calls_dict_direction') ->select('id') ->where('name',$data['direction_text']) ->first()->id; if($call->save()){ return true; } return false; // // var_dump($data); // // sleep(1); // $db_data = \DB::table('asteriskcdrdb.cdr') // ->select('duration','billsec','src','dst','cnum','cnam','calldate') // ->where('linkedid',$data['linkedid']) // // ??????? // ->where('lastapp','Dial') // ->first(); // $user_object = User::select('company_id','id') // // +++++++ // ->where('id', $db_data->cnum); // if($data['direction_text'] == 'Incoming'){ // $user_object->where('id',$db_data->dst); // $call->phone_number = $db_data->src; // }elseif($data['direction_text'] == 'Outgoing'){ // $user_object->where('id',$db_data->cnum); // $call->phone_number = $db_data->dst; // } // $user_object = $user_object->first(); // $company_id = $user_object->company_id; // $user_id = $user_object->id; // $direction_id = \DB::table('calls_dict_direction') // ->select('id') // ->where('company_id',$company_id) // ->where('name',$data['direction_text']) // ->first(); // if(!is_null($direction_id)){ // $direction_id = $direction_id; // }else{ // // $direction_id = 1;??????? // // +++++++++++ // $direction_id = \DB::table('calls_dict_direction') // ->select('id') // ->where('name',$data['direction_text']) // ->first(); // } // $lead_id = NULL; // $possible_lead_id = Lead::where('phone',$call->phone_number)->orWhere('mobile',$call->phone_number)->first(); // if(!is_null($possible_lead_id)){ // $lead_id = $possible_lead_id->id; // } // $contact_id = NULL; // $possible_contact_id = Contact::where('phone',$call->phone_number)->orWhere('mobile',$call->phone_number)->first(); // if(!is_null($possible_contact_id)){ // $contact_id = $possible_contact_id->id; // } // $call->duration = $db_data->duration; // $call->talktime = $db_data->billsec; // $call->ringtime = (int)$db_data->duration-$db_data->billsec; // $call->linkedid = $data['linkedid']; // $call->call_date = $db_data->calldate; // $call->company_id = $company_id; // // ??????? // $call->status_id = 1; // $call->lead_id = $lead_id; // $call->contact_id = $contact_id; // $call->direction_id = $direction_id; // $call->owned_by_type = 'Modules\Platform\User\Entities\test'; // $call->owned_by_id = $user_id; // if($call->save()){ // // echo 'yes '.PHP_EOL; // return true; // } // // try { // // if($call->save()){ // // return true; // // } // // } catch (\Throwable $th) { // // throw $th; // // } // return false; } } /* var_dump($a->send(new DongleSendUSSDAction('dongle01', '*101#'))); var_dump($a->send(new DongleSendPDUAction('dongle01', 'AT+CSMS=0 '))); var_dump($a->send(new DongleRestartAction('now', 'dongle01'))); var_dump($a->send(new DongleResetAction('dongle01'))); var_dump($a->send(new DongleReloadAction('now'))); var_dump($a->send(new DongleStopAction('now', 'dongle01'))); var_dump($a->send(new DongleStartAction('dongle01'))); var_dump($a->send(new DongleSendSMSAction('dongle01', '+666666666', 'a message'))); var_dump($a->send(new ListCommandsAction())); var_dump($a->send(new QueueStatusAction())); var_dump($a->send(new QueueStatusAction())); var_dump($a->send(new QueueStatusAction())); var_dump($a->send(new CoreShowChannelsAction())); var_dump($a->send(new SIPPeersAction())); var_dump($a->send(new StatusAction())); var_dump($a->send(new CommandAction('sip show peers'))); var_dump($a->send(new SIPShowRegistryAction())); var_dump($a->send(new CoreSettingsAction())); var_dump($a->send(new ListCategoriesAction('sip.conf'))); var_dump($a->send(new CoreStatusAction())); var_dump($a->send(new GetConfigAction('extensions.conf'))); var_dump($a->send(new GetConfigAction('sip.conf', 'general'))); var_dump($a->send(new GetConfigJSONAction('extensions.conf'))); var_dump($a->send(new DAHDIShowChannelsAction())); var_dump($a->send(new AgentsAction())); var_dump($a->send(new MailboxStatusAction('marcelog@gmail'))); var_dump($a->send(new MailboxCountAction('marcelog@gmail'))); var_dump($a->send(new VoicemailUsersListAction())); var_dump($a->send(new DBPutAction('something', 'a', 'a'))); var_dump($a->send(new DBGetAction('something', 'a'))); var_dump($a->send(new DBDelAction('something', 'a'))); var_dump($a->send(new DBDelTreeAction('something', 'a'))); var_dump($a->send(new SetVarAction('foo', 'asd'))); var_dump($a->send(new SetVarAction('foo', 'asd', 'SIP/a-1'))); var_dump($a->send(new GetVarAction('foo'))); var_dump($a->send(new ParkedCallsAction())); var_dump($a->send(new GetVarAction('foo', 'SIP/a-1'))); var_dump($a->send(new PingAction())); var_dump($a->send(new ExtensionStateAction('1', 'default'))); var_dump($a->send(new ModuleCheckAction('chan_sip'))); var_dump($a->send(new SIPShowPeerAction('marcelog'))); var_dump($a->send(new QueuePauseAction('Agent/123'))); var_dump($a->send(new QueueUnpauseAction('Agent/123'))); var_dump($a->send(new QueueStatusAction())); $notify = new SIPNotifyAction('marcelog'); $notify->setVariable('a', 'b'); var_dump($a->send($notify)); var_dump($a->send(new ShowDialPlanAction())); var_dump($a->send(new QueueSummaryAction())); var_dump($a->send(new QueueLogAction('a', 'asdasd'))); var_dump($a->send(new QueuePenaltyAction('Agent/123', '123'))); var_dump($a->send(new QueueResetAction('a'))); var_dump($a->send(new QueueRuleAction('a'))); */ //var_dump($a->send(new QueueReloadAction('a', true, true, true))); // // The following are commented just in case you run it in the wrong box ;) // //var_dump($a->send(new QueueRemoveAction('a', 'Agent/123'))); //var_dump($a->send(new MeetmeListAction('asd'))); //var_dump($a->send(new MeetmeMuteAction('asd', 'asd'))); //var_dump($a->send(new MeetmeUnmuteAction('asd', 'asd'))); //var_dump($a->send(new ParkAction('a', 'b'))); //var_dump($a->send(new JabberSendAction('a', 'b', 'c'))); //var_dump($a->send(new QueuesAction())); //var_dump($a->send(new MonitorAction('DAHDI/1-1', 'monitor'))); //var_dump($a->send(new PauseMonitorAction('DAHDI/1-1'))); //var_dump($a->send(new UnpauseMonitorAction('DAHDI/1-1'))); //var_dump($a->send(new StopMonitorAction('DAHDI/1-1'))); //var_dump($a->send(new SipQualifyPeerAction('marcelog'))); //var_dump($a->send(new AgentLogoffAction('a', true))); //var_dump($a->send(new PlayDTMFAction('DAHDI/1-1', '1'))); //var_dump($a->send(new CreateConfigAction('foo.conf'))); //var_dump($a->send(new DAHDIDNDOnAction('1'))); //var_dump($a->send(new DAHDIDNDOffAction('1'))); //var_dump($a->send(new DAHDIDialOffHookAction(1, '113'))); //var_dump($a->send(new DAHDIRestartAction())); //var_dump($a->send(new RedirectAction('SIP/a-1', '51992266', 'netlabs', '1'))); //var_dump($a->send(new AttendedTransferAction('SIP/a-1', '51992266', 'netlabs', '1'))); //var_dump($a->send(new ModuleReloadAction('chan_sip.so'))); //var_dump($a->send(new ModuleLoadAction('chan_sip.so'))); //var_dump($a->send(new ModuleUnloadAction('chan_sip.so'))); //$originateMsg = new OriginateAction('SIP/marcelog'); //$originateMsg->setContext('netlabs'); //$originateMsg->setPriority('1'); //$originateMsg->setExtension('51992266'); //var_dump($a->send($originateMsg)); //var_dump($a->send(new AbsoluteTimeoutAction('SIP/XXXX-123123', 10))); //var_dump($a->send(new BridgeAction('SIP/a-1', 'SIP/a-2', true))); //var_dump($a->send(new LogoffAction())); //var_dump($a->send(new HangupAction('SIP/XXXX-123123'))); //var_dump($a->send(new DAHDIHangupAction('1'))); //var_dump($a->send(new ReloadAction())); //var_dump($a->send(new ReloadAction('chan_sip'))); //var_dump($a->send(new LocalOptimizeAwayAction('SIP/a-1'))); //var_dump($a->send(new EventsAction())); //var_dump($a->send(new QueuesAction()) // // SMS //$sms = new VGMSMSTxAction(); //$sms->setContentType('text/plain; charset=ASCII'); //$sms->setContent($msg); //$sms->setCellPhone($phone); //$a->send($sms); }