Browse Source

adicionado opcao de realizar chamadas, adicioando reacao aao receber chamada e mostrar quem esta te ligando, adicionado listeners tanto no keypad quanto no sdk'

master
Matheo Bonucia 6 months ago
parent
commit
c3239f6865
  1. 38
      keypad.js
  2. 412
      simplesipsdk.js
  3. 4
      vazio.html

38
keypad.js

@ -1,5 +1,4 @@
//Criar uma funcao anonima para nao ser acessivel ao client
const KeypadSimplesIP = (function () {
const simplesipStateCall = (initialStateCall) => {
let stateCall = initialStateCall;
@ -57,6 +56,12 @@ const KeypadSimplesIP = (function () {
});
});
//==================================================================
let incommingNumber = "Indefinido";
UASimplesIP.simplesipEvento.on("incomingcall", function (callerNumber) {
incommingNumber = callerNumber;
stateCurrent.setStateCall("incomingcall");
});
const simplesipCreateContainer = () => {
let simplesipContainer = document.querySelector(".simplesipContainer");
@ -192,14 +197,14 @@ const KeypadSimplesIP = (function () {
const numberOutgoingCall = document.createElement("div");
numberOutgoingCall.classList.add("numberOutgoingCall");
numberOutgoingCall.id = "numberOutgoingCall";
numberOutgoingCall.textContent = "Recebendo chamada de " + "999000999";
numberOutgoingCall.textContent = "Recebendo chamada de " + incommingNumber;
container.appendChild(numberOutgoingCall);
const simplesipIncomingCall = document.createElement("div");
simplesipIncomingCall.classList.add("simplesipIncomingCall");
simplesipIncomingCall.id = "simplesipIncomingCall";
const bnAcceptCall = createButtonCall(handleAcceptCall);
const bnEndCall = createButtonEndCall(handleEndCall);
const bnEndCall = createButtonEndCall(handleRejectCall);
bnAcceptCall.style.gridColumn = 1;
bnAcceptCall.style.animation = "pulse 1s infinite ease-in-out";
bnEndCall.style.gridColumn = 2;
@ -234,17 +239,35 @@ const KeypadSimplesIP = (function () {
container.appendChild(simplesipOutgoingCall);
};
let storedNumberCall = "";
const handleCall = () => {
const numberCall = document.getElementById("display").textContent;
if (numberCall) {
storedNumberCall = numberCall;
}
stateCurrent.setStateCall("outgoingcall");
UASimplesIP.realizaUmaChamada(numberCall);
};
function handleEndCall() {
UASimplesIP.encerraChamada();
restartTimer();
storedNumberCall = "";
stateCurrent.setStateCall("home");
}
function handleAcceptCall() {
UASimplesIP.aceitarChamada();
startTimer();
stateCurrent.setStateCall("incall");
}
function handleRejectCall() {
UASimplesIP.rejeitarChamada();
stateCurrent.setStateCall("home");
restartTimer();
}
function handleMute() {}
const simplesipCreateDisplayContainer = (header) => {
@ -472,15 +495,6 @@ const KeypadSimplesIP = (function () {
header.appendChild(simplesipTimer);
};
let storedNumberCall = "";
const handleCall = () => {
const numberCall = document.getElementById("display").textContent;
if (numberCall) {
storedNumberCall = numberCall;
}
stateCurrent.setStateCall("outgoingcall");
};
let segundos = 0;
let minutos = 0;
let horas = 0;

412
simplesipsdk.js

@ -2,194 +2,262 @@
//
// Na Documentação incluir os sites da simplesip.com.br no Content-Security-Policy
//
const UASimplesIP = (function() {
function carregandoScriptSimpleSIP(url, callback) {
var script = document.createElement('script');
script.src = url;
script.async = true; // Asynchronous loading
script.onload = function() {
if (typeof callback === 'function') {
callback();
}
// Clean up after script execution
script.onload = script.onerror = null;
document.head.removeChild(script);
};
script.onerror = function() {
// Handle errors
console.error('Error loading script:', url);
if (typeof callback === 'function') {
callback(new Error('Error loading script'));
}
// Clean up after script execution
script.onload = script.onerror = null;
document.head.removeChild(script);
};
document.head.appendChild(script);
const UASimplesIP = (function () {
function carregandoScriptSimpleSIP(url, callback) {
var script = document.createElement("script");
script.src = url;
script.async = true; // Asynchronous loading
script.onload = function () {
if (typeof callback === "function") {
callback();
}
// Clean up after script execution
script.onload = script.onerror = null;
document.head.removeChild(script);
};
script.onerror = function () {
// Handle errors
console.error("Error loading script:", url);
if (typeof callback === "function") {
callback(new Error("Error loading script"));
}
// Clean up after script execution
script.onload = script.onerror = null;
document.head.removeChild(script);
};
document.head.appendChild(script);
}
carregandoScriptSimpleSIP("simplesiplib.js", (error) => {
if (!error) {
console.log("::: Script loaded successfully!");
} else {
console.error(":::: Failed to load script:", error);
}
carregandoScriptSimpleSIP("simplesiplib.js", (error) => {
if (!error) {
console.log("::: Script loaded successfully!");
} else {
console.error(":::: Failed to load script:", error);
}
});
});
class EventEmitter {
constructor() {
this.events = {};
}
on(eventName, listener) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(listener);
function extrairNome(displayName) {
// Expressão regular para extrair o nome entre aspas
const regex = /"([^"]+)"/;
// Executa a expressão regular na string de displayName
const match = regex.exec(displayName);
// Se houver correspondência, retorna o primeiro grupo capturado (o nome)
if (match && match.length > 1) {
return match[1];
} else {
// Se não houver correspondência, retorna null ou uma string vazia, dependendo do seu caso
return null;
}
}
class EventEmitter {
constructor() {
this.events = {};
}
on(eventName, listener) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(listener);
}
emit(eventName, ...args) {
if (this.events[eventName]) {
this.events[eventName].forEach((listener) => listener(...args));
}
}
off(eventName, listener) {
if (this.events[eventName]) {
this.events[eventName] = this.events[eventName].filter(
(fn) => fn !== listener
);
}
}
}
const eventoSip = new EventEmitter();
eventoSip.on("evento", (payload) => {
console.log(payload);
});
setInterval(() => {
eventoSip.emit("evento", _Autenticacao);
}, 5000);
//const PROTOCOLO = "ws|wss"
function passa(nome) {
console.log(SimpleSIP.settings);
}
function Autenticacao(PROTOCOLO, SERVIDOR, PORTA, NOME, RAMAL, SENHA) {
this.PROTOCOLO = PROTOCOLO;
this.SERVIDOR = SERVIDOR;
this.PORTA = PORTA;
this.NOME = NOME;
this.RAMAL = RAMAL;
this.SENHA = SENHA;
}
const _Autenticacao = new Autenticacao();
const incomingCallAudio = new window.Audio(
"https://cdn.pixabay.com/download/audio/2021/08/04/audio_bb630cc098.mp3?filename=short-success-sound-glockenspiel-treasure-video-game-6346.mp3"
);
incomingCallAudio.loop = true;
var remoteAudio = new window.Audio();
remoteAudio.autoplay = true;
var phone;
var session;
var isIncomingCall = false; // Flag para controlar o estado de chamada recebida
function iniciandoAutenticacaonoPBX() {
const configuration = {
uri: "sip:" + _Autenticacao.RAMAL + "@" + _Autenticacao.SERVIDOR,
password: _Autenticacao.SENHA,
sockets: new SimpleSIP.WebSocketInterface(
_Autenticacao.PROTOCOLO +
"://" +
_Autenticacao.SERVIDOR +
":" +
_Autenticacao.PORTA +
"/ws"
),
display_name:
_Autenticacao.NOME !== null ? _Autenticacao.NOME : _Autenticacao.RAMAL,
user_agent: "UASimpleSIP 1.2.0",
};
if (configuration.uri && configuration.password) {
phone = new SimpleSIP.UA(configuration);
phone.on("registrationFailed", function (ev) {
console.log("Registering on SIP server failed with error: " + ev.cause);
configuration.uri = null;
configuration.password = null;
});
phone.on("newRTCSession", function (ev) {
const newSession = ev.session;
if (session) {
// Encerrar qualquer chamada existente antes de aceitar uma nova
session.terminate();
}
emit(eventName, ...args) {
if (this.events[eventName]) {
this.events[eventName].forEach(listener => listener(...args));
session = newSession;
var completeSession = function () {
session = null;
isIncomingCall = false;
};
session.on("ended", completeSession);
session.on("failed", completeSession);
session.on("accepted", (accepted) => {
console.log(accepted);
});
session.on("confirmed", function (confirmed) {
console.log(
"confirmed ::::::::::::::::::::::::::::::::::::::::::::::::::::",
confirmed
);
const remoteStreams = session.connection.getRemoteStreams()[0];
remoteAudio.srcObject = remoteStreams;
});
session.on("icecandidate", function (event) {
if (
event.candidate.type === "srflx" &&
event.candidate.relatedAddress !== null &&
event.candidate.relatedPort !== null
) {
event.ready();
}
});
session.on("addstream", function (e) {
incomingCallAudio.pause();
remoteAudio.src = window.URL.createObjectURL(e.stream);
});
if (session.direction === "incoming") {
incomingCallAudio.play();
console.log("::::::::::::::::::::::chamada recebida");
isIncomingCall = true;
eventoSip.emit("incomingcall", extrairNome(session.remote_identity));
}
off(eventName, listener) {
if (this.events[eventName]) {
this.events[eventName] = this.events[eventName].filter(fn => fn !== listener);
}
if (session.direction === "outgoing") {
console.log("::::::::::::::::::::::chamada realizada");
eventoSip.emit("outgoingcall");
}
}
const meuEvento = new EventEmitter();
meuEvento.on("evento", (payload) => {
console.log("hello eventos", payload);
});
setInterval(() => {
//meuEvento.emit("evento", _Autenticacao);
}, 5000);
//const PROTOCOLO = "ws|wss"
function passa(nome) {
console.log(SimpleSIP.settings);
}
function Autenticacao(PROTOCOLO, SERVIDOR, PORTA, NOME, RAMAL, SENHA) {
this.PROTOCOLO = PROTOCOLO;
this.SERVIDOR = SERVIDOR;
this.PORTA = PORTA;
this.NOME = NOME;
this.RAMAL = RAMAL;
this.SENHA = SENHA;
if (session.direction === "progress") {
eventoSip.emit("incall");
console.log("::::::::::::::::::::::chamada em progresso");
}
});
phone.start();
}
}
const _Autenticacao = new Autenticacao();
const incomingCallAudio = new window.Audio('https://cdn.pixabay.com/download/audio/2021/08/04/audio_bb630cc098.mp3?filename=short-success-sound-glockenspiel-treasure-video-game-6346.mp3');
incomingCallAudio.loop = true;
var remoteAudio = new window.Audio();
remoteAudio.autoplay = true;
var phone;
var session;
function iniciandoAutenticacaonoPBX() {
const configuration = {
uri: "sip:" + _Autenticacao.RAMAL + "@" + _Autenticacao.SERVIDOR,
password: _Autenticacao.SENHA,
sockets: new SimpleSIP.WebSocketInterface(_Autenticacao.PROTOCOLO + "://" + _Autenticacao.SERVIDOR + ":" + _Autenticacao.PORTA + "/ws"),
display_name: (_Autenticacao.NOME !== null?_Autenticacao.NOME:_Autenticacao.RAMAL),
user_agent: "UASimpleSIP 1.2.0"
};
if (configuration.uri && configuration.password) {
phone = new SimpleSIP.UA(configuration);
phone.on('registrationFailed', function(ev){
console.log('Registering on SIP server failed with error: ' + ev.cause);
configuration.uri = null;
configuration.password = null;
});
phone.on('newRTCSession',function(ev){
const newSession = ev.session;
if (session) {
session.terminate();
}
session = newSession;
var completeSession = function(){
session = null;
};
session.on('ended', completeSession);
session.on('failed', completeSession);
session.on('accepted', (accepted) => {
console.log(accepted);
});
session.on('confirmed', function(confirmed){
console.log('confirmed ::::::::::::::::::::::::::::::::::::::::::::::::::::', confirmed)
const remoteStreams = session.connection.getRemoteStreams()[0];
remoteAudio.srcObject = remoteStreams;
});
session.on("icecandidate", function (event) {
if (event.candidate.type === "srflx" &&
event.candidate.relatedAddress !== null &&
event.candidate.relatedPort !== null) {
event.ready();
}
});
session.on('addstream', function(e){
incomingCallAudio.pause();
remoteAudio.src = window.URL.createObjectURL(e.stream);
});
if(session.direction === 'incoming'){
incomingCallAudio.play();
}
});
phone.start();
}
}
function ativaDebug(value) {
value === true
? SimpleSIP.debug.enable("SimpleSIP:*")
: SimpleSIP.debug.disable("SimpleSIP:*");
}
function ativaDebug(value) { ( value === true?SimpleSIP.debug.enable('SimpleSIP:*'):SimpleSIP.debug.disable('SimpleSIP:*')); }
return {
return {
config: _Autenticacao,
config: _Autenticacao,
start: function () {
if (
_Autenticacao.PROTOCOLO === undefined ||
_Autenticacao.SERVIDOR === undefined ||
_Autenticacao.RAMAL === undefined ||
_Autenticacao.SENHA === undefined
) {
console.error(
":::: Configuração do Usuário Inválida para Autenticação no PBX !"
);
} else {
ativaDebug(true);
iniciandoAutenticacaonoPBX();
}
},
start: function() {
if ( _Autenticacao.PROTOCOLO === undefined || _Autenticacao.SERVIDOR === undefined || _Autenticacao.RAMAL === undefined || _Autenticacao.SENHA === undefined ) {
console.error(":::: Configuração do Usuário Inválida para Autenticação no PBX !");
}else{
ativaDebug(true);
iniciandoAutenticacaonoPBX();
}
},
realizaUmaChamada: (numero) => {
phone.call(numero);
},
realizaUmaChamada: (numero) => {
phone.call(numero);
},
ativaDebug: (value) => {
ativaDebug(value);
},
ativaDebug: (value) => {
ativaDebug(value);
},
encerraChamada: () => {
if (session) {
session.terminate();
}
},
estouRegistradonoPBX: () => {
console.log("estouRegistradonoPBX ::: " + phone.isRegistered())
},
aceitarChamada: () => {
if (session) {
session.accept();
}
},
myEvento: meuEvento,
rejeitarChamada: () => {
if (session) {
session.reject();
}
},
help: function() {
console.log("========================================================");
console.log("=== Unified Communications - Simples Ip - Versão 1.2 ===");
console.log("========================================================");
console.log("UASimplesIP.start() - Para iniciar o SDK");
}
estouRegistradonoPBX: () => {
console.log("estouRegistradonoPBX ::: " + phone.isRegistered());
},
};
simplesipEvento: eventoSip,
help: function () {
console.log("========================================================");
console.log("=== Unified Communications - Simples Ip - Versão 1.2 ===");
console.log("========================================================");
console.log("UASimplesIP.start() - Para iniciar o SDK");
},
};
})();

4
vazio.html

@ -47,8 +47,8 @@
configuracao.PROTOCOLO = "ws";
configuracao.SERVIDOR = "129.148.58.190";
configuracao.PORTA = "8088";
configuracao.NOME = "1003";
configuracao.RAMAL = "1003";
configuracao.NOME = "MATHEO BONUCIA";
configuracao.RAMAL = "1000";
configuracao.SENHA = "123";
</script>
</body>

Loading…
Cancel
Save