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 //Criar uma funcao anonima para nao ser acessivel ao client
const KeypadSimplesIP = (function () { const KeypadSimplesIP = (function () {
const simplesipStateCall = (initialStateCall) => { const simplesipStateCall = (initialStateCall) => {
let stateCall = 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 = () => { const simplesipCreateContainer = () => {
let simplesipContainer = document.querySelector(".simplesipContainer"); let simplesipContainer = document.querySelector(".simplesipContainer");
@ -192,14 +197,14 @@ const KeypadSimplesIP = (function () {
const numberOutgoingCall = document.createElement("div"); const numberOutgoingCall = document.createElement("div");
numberOutgoingCall.classList.add("numberOutgoingCall"); numberOutgoingCall.classList.add("numberOutgoingCall");
numberOutgoingCall.id = "numberOutgoingCall"; numberOutgoingCall.id = "numberOutgoingCall";
numberOutgoingCall.textContent = "Recebendo chamada de " + "999000999"; numberOutgoingCall.textContent = "Recebendo chamada de " + incommingNumber;
container.appendChild(numberOutgoingCall); container.appendChild(numberOutgoingCall);
const simplesipIncomingCall = document.createElement("div"); const simplesipIncomingCall = document.createElement("div");
simplesipIncomingCall.classList.add("simplesipIncomingCall"); simplesipIncomingCall.classList.add("simplesipIncomingCall");
simplesipIncomingCall.id = "simplesipIncomingCall"; simplesipIncomingCall.id = "simplesipIncomingCall";
const bnAcceptCall = createButtonCall(handleAcceptCall); const bnAcceptCall = createButtonCall(handleAcceptCall);
const bnEndCall = createButtonEndCall(handleEndCall); const bnEndCall = createButtonEndCall(handleRejectCall);
bnAcceptCall.style.gridColumn = 1; bnAcceptCall.style.gridColumn = 1;
bnAcceptCall.style.animation = "pulse 1s infinite ease-in-out"; bnAcceptCall.style.animation = "pulse 1s infinite ease-in-out";
bnEndCall.style.gridColumn = 2; bnEndCall.style.gridColumn = 2;
@ -234,17 +239,35 @@ const KeypadSimplesIP = (function () {
container.appendChild(simplesipOutgoingCall); 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() { function handleEndCall() {
UASimplesIP.encerraChamada();
restartTimer(); restartTimer();
storedNumberCall = ""; storedNumberCall = "";
stateCurrent.setStateCall("home"); stateCurrent.setStateCall("home");
} }
function handleAcceptCall() { function handleAcceptCall() {
UASimplesIP.aceitarChamada();
startTimer(); startTimer();
stateCurrent.setStateCall("incall"); stateCurrent.setStateCall("incall");
} }
function handleRejectCall() {
UASimplesIP.rejeitarChamada();
stateCurrent.setStateCall("home");
restartTimer();
}
function handleMute() {} function handleMute() {}
const simplesipCreateDisplayContainer = (header) => { const simplesipCreateDisplayContainer = (header) => {
@ -472,15 +495,6 @@ const KeypadSimplesIP = (function () {
header.appendChild(simplesipTimer); header.appendChild(simplesipTimer);
}; };
let storedNumberCall = "";
const handleCall = () => {
const numberCall = document.getElementById("display").textContent;
if (numberCall) {
storedNumberCall = numberCall;
}
stateCurrent.setStateCall("outgoingcall");
};
let segundos = 0; let segundos = 0;
let minutos = 0; let minutos = 0;
let horas = 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 // Na Documentação incluir os sites da simplesip.com.br no Content-Security-Policy
// //
const UASimplesIP = (function() { const UASimplesIP = (function () {
function carregandoScriptSimpleSIP(url, callback) {
function carregandoScriptSimpleSIP(url, callback) { var script = document.createElement("script");
var script = document.createElement('script'); script.src = url;
script.src = url; script.async = true; // Asynchronous loading
script.async = true; // Asynchronous loading script.onload = function () {
script.onload = function() { if (typeof callback === "function") {
if (typeof callback === 'function') { callback();
callback(); }
} // Clean up after script execution
// Clean up after script execution script.onload = script.onerror = null;
script.onload = script.onerror = null; document.head.removeChild(script);
document.head.removeChild(script); };
}; script.onerror = function () {
script.onerror = function() { // Handle errors
// Handle errors console.error("Error loading script:", url);
console.error('Error loading script:', url); if (typeof callback === "function") {
if (typeof callback === 'function') { callback(new Error("Error loading script"));
callback(new Error('Error loading script')); }
} // Clean up after script execution
// Clean up after script execution script.onload = script.onerror = null;
script.onload = script.onerror = null; document.head.removeChild(script);
document.head.removeChild(script); };
}; document.head.appendChild(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 { function extrairNome(displayName) {
constructor() { // Expressão regular para extrair o nome entre aspas
this.events = {}; const regex = /"([^"]+)"/;
} // Executa a expressão regular na string de displayName
const match = regex.exec(displayName);
on(eventName, listener) { // Se houver correspondência, retorna o primeiro grupo capturado (o nome)
if (!this.events[eventName]) { if (match && match.length > 1) {
this.events[eventName] = []; return match[1];
} } else {
this.events[eventName].push(listener); // 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();
} }
session = newSession;
emit(eventName, ...args) { var completeSession = function () {
if (this.events[eventName]) { session = null;
this.events[eventName].forEach(listener => listener(...args)); 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));
} }
if (session.direction === "outgoing") {
off(eventName, listener) { console.log("::::::::::::::::::::::chamada realizada");
if (this.events[eventName]) { eventoSip.emit("outgoingcall");
this.events[eventName] = this.events[eventName].filter(fn => fn !== listener);
}
} }
} if (session.direction === "progress") {
eventoSip.emit("incall");
const meuEvento = new EventEmitter(); console.log("::::::::::::::::::::::chamada em progresso");
}
meuEvento.on("evento", (payload) => { });
console.log("hello eventos", payload); phone.start();
});
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;
} }
}
const _Autenticacao = new Autenticacao(); function ativaDebug(value) {
value === true
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'); ? SimpleSIP.debug.enable("SimpleSIP:*")
incomingCallAudio.loop = true; : SimpleSIP.debug.disable("SimpleSIP:*");
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:*')); } return {
config: _Autenticacao,
return {
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() { realizaUmaChamada: (numero) => {
if ( _Autenticacao.PROTOCOLO === undefined || _Autenticacao.SERVIDOR === undefined || _Autenticacao.RAMAL === undefined || _Autenticacao.SENHA === undefined ) { phone.call(numero);
console.error(":::: Configuração do Usuário Inválida para Autenticação no PBX !"); },
}else{
ativaDebug(true);
iniciandoAutenticacaonoPBX();
}
},
realizaUmaChamada: (numero) => { ativaDebug: (value) => {
phone.call(numero); ativaDebug(value);
}, },
ativaDebug: (value) => { encerraChamada: () => {
ativaDebug(value); if (session) {
}, session.terminate();
}
},
estouRegistradonoPBX: () => { aceitarChamada: () => {
console.log("estouRegistradonoPBX ::: " + phone.isRegistered()) if (session) {
}, session.accept();
}
},
myEvento: meuEvento, rejeitarChamada: () => {
if (session) {
session.reject();
}
},
help: function() { estouRegistradonoPBX: () => {
console.log("========================================================"); console.log("estouRegistradonoPBX ::: " + phone.isRegistered());
console.log("=== Unified Communications - Simples Ip - Versão 1.2 ==="); },
console.log("========================================================");
console.log("UASimplesIP.start() - Para iniciar o SDK");
}
}; 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.PROTOCOLO = "ws";
configuracao.SERVIDOR = "129.148.58.190"; configuracao.SERVIDOR = "129.148.58.190";
configuracao.PORTA = "8088"; configuracao.PORTA = "8088";
configuracao.NOME = "1003"; configuracao.NOME = "MATHEO BONUCIA";
configuracao.RAMAL = "1003"; configuracao.RAMAL = "1000";
configuracao.SENHA = "123"; configuracao.SENHA = "123";
</script> </script>
</body> </body>

Loading…
Cancel
Save