Active calls dashboard widget (#7411)

* Add context filter

* Add dashboard widget

* Add config for widget

* Add domain filter to service

* Fix websocket_service to get the class name

* Add new method get_service_name
This commit is contained in:
frytimo
2025-07-04 00:52:55 -03:00
committed by GitHub
parent e9fcc04d3f
commit a36e71ff2a
6 changed files with 609 additions and 8 deletions

View File

@@ -176,10 +176,21 @@ class active_calls_service extends service implements websocket_service_interfac
* @return filter
*/
public static function create_filter_chain_for(subscriber $subscriber): filter {
// Do not filter domain
if ($subscriber->has_permission('call_active_all') || $subscriber->is_service()) {
return filter_chain::and_link([
new event_filter(self::SWITCH_EVENTS),
new permission_filter(self::PERMISSION_MAP, $subscriber->get_permissions()),
new event_key_filter(self::EVENT_KEYS),
]);
}
// Filter on single domain name
return filter_chain::and_link([
new event_filter(self::SWITCH_EVENTS),
new permission_filter(self::PERMISSION_MAP, $subscriber->get_permissions()),
new event_key_filter(self::EVENT_KEYS),
new caller_context_filter([$subscriber->get_domain_name()]),
]);
}

View File

@@ -0,0 +1,56 @@
<?php
/*
* FusionPBX
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is FusionPBX
*
* The Initial Developer of the Original Code is
* Mark J Crane <markjcrane@fusionpbx.com>
* Portions created by the Initial Developer are Copyright (C) 2008-2025
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Mark J Crane <markjcrane@fusionpbx.com>
* Tim Fry <tim@fusionpbx.com>
*/
/**
* Description of caller_context_filter
*
* @author Tim Fry <tim@fusionpbx.com>
*/
class caller_context_filter implements filter {
private $domains;
public function __construct(array $domain_names) {
foreach ($domain_names as $name) {
$this->domains[$name] = true;
}
}
public function __invoke(string $key, $value): ?bool {
// return true when not on the event key caller_context to validate
if ($key !== 'caller_context') {
return true;
}
// Instruct the filter chain to drop the payload
if (!isset($this->domains[$value])) {
return null;
}
return true;
}
}

View File

@@ -0,0 +1,473 @@
<?php
/*
* The MIT License
*
* Copyright 2025 Tim Fry <tim@fusionpbx.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//set project root
$project_root = dirname(__DIR__, 4);
//includes files
require_once "$project_root/resources/require.php";
//check permisions
require_once "$project_root/resources/check_auth.php";
if (!permission_exists('call_active_view')) {
return;
}
//set the row style
$c = 0;
$row_style["0"] = "row_style0";
$row_style["1"] = "row_style1";
//connect to the database
if (!isset($database)) {
$database = database::new();
}
//set the dashboard icon to a solid color phone
$dashboard_icon = 'fa-solid fa-phone';
//add multi-lingual support
$text = (new text)->get($_SESSION['domain']['language']['code'], 'app/active_calls');
//show the widget
echo "<div class='hud_box'>\n";
//create a token
$token = (new token())->create($_SERVER['PHP_SELF']);
echo " <input id='current_context' type='hidden' name='current_context' value='" . $_SESSION['domain_name'] . "'>\n";
echo " <input id='token' type='hidden' name='" . $token['name'] . "' value='" . $token['hash'] . "'>\n";
//subscribe to service
subscriber::save_token($token, ['active.calls']);
//define row styles
$c = 0;
$row_style["0"] = "row_style0";
$row_style["1"] = "row_style1";
//icon and count
echo "<div class='hud_content' ".($dashboard_details_state == "disabled" ?: "onclick=\"$('#hud_active_calls_details').slideToggle('fast'); toggle_grid_row_end('".$dashboard_name."')\"").">\n";
echo "<span class='hud_title'><a onclick=\"document.location.href='".PROJECT_PATH."/app/active_calls/active_calls.php'\">".$text['title']."</a></span>\n";
echo "<div class='hud_content'>\n";
echo "<div style='position: relative; display: inline-block;'>\n";
echo "<span class='hud_stat'><i class=\"fas ".$dashboard_icon." \"></i></span>\n";
echo "<span id='calls_active_count' name='calls_active_count' style=\"background-color: ".(!empty($dashboard_number_background_color) ? $dashboard_number_background_color : '#03c04a')."; color: ".(!empty($dashboard_number_text_color) ? $dashboard_number_text_color : '#ffffff')."; font-size: 12px; font-weight: bold; text-align: center; position: absolute; top: 23px; left: 24.5px; padding: 2px 7px 1px 7px; border-radius: 10px; white-space: nowrap;\">0</span>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
//active call details
echo "<div class='hud_details hud_box' id='hud_active_calls_details'>\n";
if ($dashboard_details_state != 'disabled') {
echo "<table id='active_calls' name='active_calls' class='tr_hover' width='100%' cellpadding='0' cellspacing='0' border='0'>\n";
echo "<thead id='head_active_calls' name='head_active_calls'>\n";
echo "<tr>\n";
echo "<th class='hud_heading' width='50%'>".$text['label-cid-number']."</th>\n";
echo "<th class='hud_heading' width='50%'>".$text['label-destination']."</th>\n";
echo "<th class='hud_heading' width='50%'>".$text['label-status']."</th>\n";
echo "</tr>\n";
echo "</thead>\n";
echo "<tbody id='active_calls_body' name='active_calls_body'>\n";
echo "</tbody>\n";
echo "</table>\n";
}
echo "</div>\n";
//include arrows when not changed
$version = md5(file_get_contents($project_root, '/app/active_calls/resources/javascript/arrow.js'));
echo "<script src='/app/active_calls/resources/javascript/arrows.js?v=$version'></script>\n";
?>
<script>
const timers = [];
const callsMap = new Map();
var showAll = false;
const websockets_domain_name = '<?= $_SESSION['domain_name'] ?>';
// push PHP values into JS
const authToken = {
name: "<?= $token['name'] ?>",
hash: "<?= $token['hash'] ?>"
};
<?php
$user['extensions'] = [];
// translate the current users assigned extensions
if (!empty($_SESSION['user']['extension'])) {
echo "const extension = {\n";
foreach ($_SESSION['user']['extension'] as $user) {
echo " extension_uuid: '" . $user['extension_uuid'] . "',\n";
echo " extension: '" . $user['user'] . "',\n";
if (strlen($user['number_alias']) > 0) {
$user_contact = $user['number_alias'];
} else {
$user_contact = $user['user'];
}
echo " extension_destination: '$user_contact',\n";
$user['extensions'][$user['extension_uuid']] = $user_contact;
}
echo " last_entry_so_no_comma: '-100'";
echo " };\n";
}
?>
const colors = {
RINGING: 'blue',
CONNECTED: '<?php echo $settings->get('theme', 'heading_count_background_color', '#28a745'); ?>',
HANGUP: 'red',
INACTIVE: 'black'
}
// pre-cache arrows
const arrows = {
inbound: {
red: create_arrow('inbound', colors.HANGUP),
green: create_arrow('inbound', colors.CONNECTED),
blue: create_arrow('inbound', colors.RINGING),
black: create_arrow('inbound', colors.INACTIVE)
},
outbound: {
red: create_arrow('outbound', colors.HANGUP),
green: create_arrow('outbound', colors.CONNECTED),
blue: create_arrow('outbound', colors.RINGING),
black: create_arrow('outbound', colors.INACTIVE)
},
local: {
red: create_arrow('local', colors.HANGUP),
green: create_arrow('local', colors.CONNECTED),
blue: create_arrow('local', colors.RINGING),
black: create_arrow('local', colors.INACTIVE)
},
voicemail: {
red: create_arrow('voicemail', colors.HANGUP),
green: create_arrow('voicemail', colors.CONNECTED),
blue: create_arrow('voicemail', colors.RINGING),
black: create_arrow('voicemail', colors.INACTIVE)
},
missed: {
red: create_arrow('missed', colors.HANGUP),
green: create_arrow('missed', colors.CONNECTED),
blue: create_arrow('missed', colors.RINGING),
black: create_arrow('missed', colors.INACTIVE)
}
}
let active_calls_widget_client = null;
let reconnectAttempts = 0;
function connect_active_calls_widget() {
const maxReconnectDelay = 30000; // 30 seconds
const baseReconnectDelay = 1000; // 1 second
active_calls_widget_client = new ws_client(`wss://${window.location.hostname}/websockets/`, authToken);
if (!active_calls_widget_client) {
console.error('Unable to connect to web socket server');
}
// CONNECTED
active_calls_widget_client.ws.addEventListener("open", async () => {
try {
console.log('Connected');
console.log('Requesting authentication');
//set the status as inactive while waiting
const status = document.getElementById('calls_active_count');
status.style.backgroundColor = colors.INACTIVE;
//wait to be authenticated
await active_calls_widget_client.request('authentication');
reconnectAttempts = 0;
//bind active call event to function
active_calls_widget_client.onEvent("CHANNEL_CALLSTATE", channel_callstate_event);
console.log('Sent request for calls in progress');
//get the in progress calls
active_calls_widget_client.request('active.calls', 'in.progress');
//display green circle for connected
status.style.backgroundColor = colors.CONNECTED;
} catch (err) {
console.error("WS setup failed: ", err);
return;
}
});
// DISCONNECTED
active_calls_widget_client.ws.addEventListener("close", async () => {
const status = document.getElementById('calls_active_count');
status.style.background = '#cc0033';
console.warn("Websocket Disconnected");
});
}
/////////////////////
// Event Functions //
/////////////////////
// Ringing, Answer, Hangup
function channel_callstate_event(call) {
const state = call.answer_state;
//update color
const uuid = call.unique_id;
//console.log(call.event_name, call.unique_id, state, call);
let row = document.getElementById(uuid) || null;
//create a row for the call
if (row === null) {
new_call(call);
}
const other_leg_rdnis = call.other_leg_rdnis ?? '';
const other_leg_unique_id = call.other_leg_unique_id ?? '';
switch (state) {
case 'ringing':
update_call(call);
replace_arrow_color(uuid, colors.RINGING);
//enforce a local arrow for eavesdrop
if (call.caller_caller_id_name === '<?= $text['label-eavesdrop'] ?>') {
replace_arrow_icon(uuid, 'local');
row.dataset.forced_direction = 'local';
}
//calls with an rdnis means that it came from an outside source
if (other_leg_rdnis !== '') {
replace_arrow_icon(uuid, 'inbound');
} else {
if (other_leg_unique_id !== '') {
const matched_call = document.getElementById(other_leg_unique_id);
if (matched_call.dataset.forced_direction) {
replace_arrow_icon(uuid, matched_call.dataset.forced_direction);
}
} else {
replace_arrow_icon(uuid, call.call_direction);
}
}
break;
case 'answered':
update_call(call);
//console.log('ANSWERED', call);
if (row !== null) {
replace_arrow_color(uuid, colors.CONNECTED);
}
break;
case 'hangup':
if (row !== null)
replace_arrow_color(uuid, colors.HANGUP);
hangup_call(call);
break;
}
}
//////////////////////
// Helper functions //
//////////////////////
function replace_arrow_color(uuid, color) {
const row = document.getElementById(uuid);
if (!row) {
return;
}
//get the table cell
const span = document.getElementById(`arrow_${uuid}`) ?? null;
if (!span) {
return;
}
const icon = span.dataset.icon ?? 'local';
//nothing to do
if (color === span.dataset.color) {
return;
}
span.dataset.icon = icon;
span.dataset.color = color;
//copy the cached arrow
const cached_arrow = arrows[icon][color];
const arrow = cached_arrow.cloneNode(true);
//check for exiting arrow and add or replace
const span_arrow = span.firstChild ?? null;
if (span_arrow !== null) {
span.replaceChild(arrow, span_arrow);
} else {
span.appendChild(arrow);
}
}
function replace_arrow_icon(uuid, icon) {
const row = document.getElementById(uuid);
if (!row) {
return;
}
//get the table cell
const span = document.getElementById(`arrow_${uuid}`) ?? null;
if (!span) {
return;
}
const color = span.dataset.color ?? colors.RINGING;
if (span.dataset.icon === null) {
throw Exception('icon empty');
}
//nothing to do
if (icon === span.dataset.icon) {
return;
}
span.dataset.icon = icon;
span.dataset.color = color;
//copy the cached arrow
const cached_arrow = arrows[icon][color];
const arrow = cached_arrow.cloneNode(true);
const span_arrow = span.firstChild ?? null;
if (span_arrow !== null) {
span.replaceChild(arrow, span_arrow);
} else {
span.appendChild(create_arrow(icon, color));
}
}
function new_call(call) {
//console.log(call);
const tbody = document.getElementById("active_calls_body");
if (!callsMap.has(call.unique_id)) {
// create the row
const uuid = call.unique_id;
//create or get the row
let row = document.getElementById(uuid);
if (!row) {
row = document.createElement("tr");
}
row.id = uuid;
row.className = 'list-row';
row.dataset.color = colors.RINGING;
// start string block
row.innerHTML = `<?php
echo '<td id="caller_id_number_${uuid}">${call.caller_caller_id_number}</td>' . PHP_EOL;
echo '<td id="destination_${uuid}">${call.caller_destination_number}</td>' . PHP_EOL;
echo '<td id="answer_state_${uuid}">${call.answer_state}</td>' . PHP_EOL;
?>`;
//end string block
row.style.display = 'table-row';
// add the row to the table
tbody.appendChild(row);
console.log('NEW ROW ADDED', row.id);
// add the uuid to the map
callsMap.set(call.unique_id, row);
}
updateCount();
}
function update_call(call) {
const tbody = document.getElementById("active_calls_body");
if (callsMap.has(call.unique_id)) {
//set values
const uuid = call.unique_id;
const row = document.getElementById(uuid);
const caller_caller_id_number = call.caller_caller_id_number ?? '';
const caller_destination_number = call.caller_destination_number ?? '';
const answer_state = call.answer_state ?? '';
//update table cells
update_call_element(`caller_id_number_${uuid}`, caller_caller_id_number);
update_call_element(`destination_${uuid}`, caller_destination_number);
update_call_element(`answer_state_${uuid}`, answer_state);
}
}
// Only updates the field when the data is not empty and has changed
function update_call_element(element_name, value) {
if (typeof value === 'undefined')
return;
const element = document.getElementById(element_name);
if (element !== null && value !== null && value.length > 0 && element.textContent !== value) {
element.textContent = value;
}
}
function basename(path) {
return path.replace(/^.*[\\\/]/, '')
}
function updateCount() {
const calls_active_count = document.getElementById('calls_active_count');
let visibleCount = 0;
callsMap.forEach((row) => {
if (row.style.display !== 'none') {
visibleCount++;
}
});
const totalCount = callsMap.size;
calls_active_count.textContent = `${visibleCount}`;
}
function hangup_call(call) {
const row = callsMap.get(call.unique_id);
if (row) {
const uuid = call.unique_id;
callsMap.delete(uuid);
const calls_active_count = document.getElementById('calls_active_count');
let visibleCount = 0;
callsMap.forEach((row) => {
if (row.style.display !== 'none') {
visibleCount++;
}
});
const totalCount = callsMap.size;
calls_active_count.textContent = `${visibleCount}`;
row.remove();
}
}
//////////////////////////
// Start the connection //
//////////////////////////
connect_active_calls_widget();
</script>
<?php echo "</div>\n"; ?>

View File

@@ -0,0 +1,38 @@
<?php
$x++;
$array['dashboard'][$x]['dashboard_uuid'] = '4c63234b-e5d2-4232-9787-4734d342557b';
$array['dashboard'][$x]['dashboard_name'] = 'Active Calls';
$array['dashboard'][$x]['dashboard_path'] = 'active_calls/active_calls';
$array['dashboard'][$x]['dashboard_icon'] = 'fa-solid fa-phone';
$array['dashboard'][$x]['dashboard_icon_color'] = '';
$array['dashboard'][$x]['dashboard_url'] = '';
$array['dashboard'][$x]['dashboard_target'] = '';
$array['dashboard'][$x]['dashboard_width'] = '';
$array['dashboard'][$x]['dashboard_height'] = '';
$array['dashboard'][$x]['dashboard_content'] = '';
$array['dashboard'][$x]['dashboard_content_text_align'] = '';
$array['dashboard'][$x]['dashboard_content_details'] = '';
$array['dashboard'][$x]['dashboard_chart_type'] = 'number';
$array['dashboard'][$x]['dashboard_label_enabled'] = 'true';
$array['dashboard'][$x]['dashboard_label_text_color'] = '#444444';
$array['dashboard'][$x]['dashboard_label_text_color_hover'] = '';
$array['dashboard'][$x]['dashboard_label_background_color'] = '';
$array['dashboard'][$x]['dashboard_label_background_color_hover'] = '';
$array['dashboard'][$x]['dashboard_number_text_color'] = '#ffffff';
$array['dashboard'][$x]['dashboard_number_text_color_hover'] = '';
$array['dashboard'][$x]['dashboard_number_background_color'] = '';
$array['dashboard'][$x]['dashboard_background_color'] = '#ffffff';
$array['dashboard'][$x]['dashboard_background_color_hover'] = '';
$array['dashboard'][$x]['dashboard_detail_background_color'] = '#ffffff';
$array['dashboard'][$x]['dashboard_column_span'] = '1';
$array['dashboard'][$x]['dashboard_row_span'] = '2';
$array['dashboard'][$x]['dashboard_details_state'] = 'hidden';
$array['dashboard'][$x]['dashboard_order'] = '90';
$array['dashboard'][$x]['dashboard_enabled'] = 'true';
$array['dashboard'][$x]['dashboard_description'] = 'System information like Disk usage.';
$y = 0;
$array['dashboard'][$x]['dashboard_groups'][$y]['dashboard_group_uuid'] = 'c5205a44-1eb7-4294-86a8-8b0d2b9ece98';
$array['dashboard'][$x]['dashboard_groups'][$y]['dashboard_uuid'] = '4c63234b-e5d2-4232-9787-4734d342557b';
$array['dashboard'][$x]['dashboard_groups'][$y]['group_name'] = 'user';

View File

@@ -434,7 +434,13 @@ class subscriber {
return $this->authenticated;
}
/**
* Allows overriding the token authentication
* @param bool $authenticated
* @return self
*/
public function set_authenticated(bool $authenticated): self {
$this->authenticated = $authenticated;
return $this;
}
@@ -452,6 +458,14 @@ class subscriber {
return $this->service;
}
/**
* Alias of service_name without the parameters
* @return string
*/
public function get_service_name(): string {
return $this->service_name;
}
/**
* Get or set the service_name
* @param string|null $service_name
@@ -495,6 +509,11 @@ class subscriber {
return isset($this->services[$service_name]);
}
/**
* Subscribe to a service by ensuring this subscriber has the appropriate permissions
* @param string $service_name
* @return self
*/
public function subscribe(string $service_name): self {
$this->services[$service_name] = true;
return $this;

View File

@@ -193,24 +193,29 @@ class websocket_service extends service {
// Authenticate their token
if ($subscriber->authenticate_token($message->token)) {
$subscriber->send(websocket_message::request_authenticated($message->request_id, $message->service));
// Check for service authenticated
if ($subscriber->is_service()) {
$this->info("Service $subscriber->id authenticated");
$this->services[$subscriber->service_name()] = $subscriber;
} else {
// Subscriber authenticated
$this->info("Client $subscriber->id authenticated");
$this->info("Setting permissions on $subscriber->id");
$subscriptions = $subscriber->subscribed_to();
foreach ($subscriber->subscribed_to() as $subscribed_to) {
foreach ($subscriptions as $subscribed_to) {
if (isset($this->services[$subscribed_to])) {
$service = $this->services[$subscribed_to];
if (is_a($service, 'websocket_service_interface', true)) {
$class = $service->get_service_name();
$filter = $class::create_filter_chain_for($subscriber);
$subscriber_service = $this->services[$subscribed_to];
$class_name = $subscriber_service->service_class();
// Make sure we can call the 'create_filter_chain_for' method
if (is_a($class_name, 'websocket_service_interface', true)) {
// Call the service class method to validate the subscriber
$filter = $class_name::create_filter_chain_for($subscriber);
if ($filter !== null) {
// Log the filter has been set for the subscriber
$this->info("Set filter for " . $subscriber->id());
$subscriber->set_filter($filter);
}
}
$this->info("Set permissions for $subscriber->id for service " . $service->service_name());
$this->info("Set permissions for $subscriber->id for service " . $subscriber_service->service_name());
}
}
}
@@ -256,7 +261,6 @@ class websocket_service extends service {
try {
// Notify of the message we are broadcasting
$this->debug("Broadcasting message '" . $message->payload['event_name'] . "' for service '" . $message->service_name . "' to subscriber $subscriber->id");
$message->apply_filter($subscriber->get_filter());
$subscriber->send_message($message);
} catch (subscriber_token_expired_exception $ste) {
$this->info("Subscriber $ste->id token expired");