Related
I wrote a mqtt client.js, but realized I need multiple instances of this script so I rewrote it into a class.
Now I ended up with a lot of 'this.foo' references vor my variables, which made me wonder, is this the correct way of using classes in javascript?
Here´s how part of my class looks like:
this.client = mqtt.connect("mqtts://" + this.host, options); // mqtts for tls connection
// client event handling
this.client.on("connect", () => {
log.write("LOG_INFO", "PubClient connected to Broker: " + this.host + ":" + this.settings.port);
this.client.publish("client/publisher/status", "online", { qos: 1, retain: true });
this.clientToSocket.pubConnect(true);
});
this.client.on("close", () => {
//log.write("LOG_INFO", "PubClient close");
});
this.client.on("disconnect", (packet) => {
log.write("LOG_INFO", "PubClient disconnected. Reasoncode: " + packet.reasoncode);
});
this.client.on("offline", () => {
log.write("LOG_INFO", "PubClient offline");
this.clientToSocket.pubConnect(false);
});
this.client.on("error", (err) => {
//log.write("LOG_ERR", "PubClient Error: " + err.message);
});
this.client.on("packetreceive", (packet) => {
//log.write("LOG_INFO", "PubClient packet received: " + packet.cmd);
});
}
}
publish(topic, qos, msg) {
if(this.client !== undefined) {
this.client.publish(topic, msg, { qos: parseInt(qos), retain: true });
//log.write("LOG_INFO", "Publishing Message with: topic: " + topic + " payload: " + msg);
} else {
log.write("LOG_ERR", "Error: Publish not possible because client undefined");
}
}
close() {
if(this.client !== undefined) {
this.client.end();
log.write("LOG_INFO", "PubClient closing");
}
}
}
You can simplify it, using local variables. When work is done can assign to this. You can also use restructure to use the variables.
Local Var
constructor() {
const client = mqtt.connect("mqtts://" + host, options); // mqtts for tls connection
client.on("close", () => {
//log.write("LOG_INFO", "PubClient close");
});
this.client = client;
}
De-Structure:
doSomthingOnClient() {
const {client} = this // destrcuture
client.get() // use it
}
Whole class:
class Client {
constructor() {
const client = mqtt.connect("mqtts://" + host, options); // mqtts for tls connection
client.on("connect", () => {
log.write(
"LOG_INFO",
"PubClient connected to Broker: " + host + ":" + settings.port
);
client.publish("client/publisher/status", "online", {
qos: 1,
retain: true,
});
clientToSocket.pubConnect(true);
});
client.on("close", () => {
//log.write("LOG_INFO", "PubClient close");
});
client.on("disconnect", (packet) => {
log.write(
"LOG_INFO",
"PubClient disconnected. Reasoncode: " + packet.reasoncode
);
});
this.client = client;
}
getClient() {
return this.client;
}
doSomthingOnClient() {
const {client} = this // destrcuture
client.get() // use it
}
}
I am new to JS.
I am trying to build API server, this server must received data from other server using socket.
Currently I am using net library, I am facing a problem.
I should get data to check whether hardware worked or not, but I only get
undefiend(empty array).
I found some sources making async function to get called, but still I can't get it.
here is my code.
router.post("/Updated", async function(req, res, next) {
.....
//connect to station server for locking
var data = {
cmd: "lockStationQuery",
stationId: STATION_ID,
powerBankId: POWER_BANK_ID,
userId: USER_ID,
number: channelValue
};
var stringData = JSON.stringify(data);
var jsonData = JSON.parse(stringData);
var [client, recvData] = await getConnectionSocket(
USER_ID,
res,
merchant_uid,
amount
);
let successToWriteData = await writeData(client, stringData);
//Fail to send data to lock the Station
if (!successToWriteData) {
res.status(500).json({
RESULT: "FAIL",
REASON:
"error code 504"
});
res.end();
return;
}
console.log("received data", recvData); //this is empty array
jsonData = JSON.parse(recvData[0]);
Here is my getConnectionSocket function.
async function getConnectionSocket(USER_ID, res, merchant_uid, amount) {
//서버에 해당 포트로 접속
var client = "";
var recvData = [];
var local_port = "";
let status = {};
client = net.connect({ port: 8999, host: "localhost" }, function() {
console.log(
"connect log======================================================================"
);
console.log("connect success");
console.log("local = " + this.localAddress + ":" + this.localPort);
console.log("remote = " + this.remoteAddress + ":" + this.remotePort);
local_port = this.localPort;
this.setEncoding("utf8");
this.setTimeout(300000); // timeout : 10분
console.log("client setting Encoding:binary, timeout:300000");
console.log("client connect localport : " + local_port);
});
// 접속 종료 시 처리
client.on("close", function() {
console.log("client Socket Closed : " + " localport : " + local_port);
});
// 데이터 수신 후 처리
await client.on("data", function(data) {
console.log(
"data recv log======================================================================"
);
recvData.push(data);
console.log(recvData); //I want this data
console.log("data.length : " + data.length);
console.log("data recv : " + data);
let jsonData = JSON.parse(data);
if (jsonData.cmd === "removedPowerBank") {
if (jsonData.errorCode !== 0) {
//환불
console.log("환불 시작");
let cancel = cancelOrder(merchant_uid, USER_ID, res);
//여기서 환불 purchase db에 쓰기
} else {
console.log("PURCHASE 성공후 디비에 씀");
//구매 purchase db에 쓰기(getRentId에 썼음)
let purchased = writePurchaseDataInDB(
USER_ID,
res,
merchant_uid,
amount
);
console.log(purchased);
}
}
client.end();
});
client.on("end", function() {
console.log("client Socket End");
});
client.on("error", function(err) {
console.log("client Socket Error: " + JSON.stringify(err));
});
client.on("timeout", function() {
console.log("client Socket timeout: ");
});
client.on("drain", function() {
console.log("client Socket drain: ");
});
client.on("lookup", function() {
console.log("client Socket lookup: ");
});
return [client, recvData]; //recvData is always empty array
}
which way is best to address to resolve this?
Need some clarification on below point
are you getting correct value(s) in below log ? Or you undefined in them too.
console.log("data.length : " + data.length);
console.log("data recv : " + data);
also add this one
console.log("data type : " + typeof(data));
im trying to create a chat using nodejs for a project, the problem is that when i send a message and there is more than 1 user on the chat it repeats the message, for example (visual example), if i have 4 users in the chat it prints the message 4 times.
This is the code im using
socketio.js
var Messages = require('../controllers/chat_message')
var socket_io = require('socket.io');
var io = socket_io();
var socketio = {};
socketio.io = io;
var users = [];
io.on('connection', function(socket){
console.log('A user connected');
console.log(`Socket connected ${socket.id}`)
Messages.getpreviousMsgs()
.then(dados =>socket.emit('previousMessage', dados))
.catch(erro =>res.status(500).jsonp(erro))
socket.on('sendMessage', data => {
console.log(data);
Messages.create(data)
.then(dados =>console.log("Saved"))
.catch(erro =>res.status(500).jsonp(erro))
});
socket.on('join', function (user){
socket.username = user.username;
users.push(socket.username);
io.emit('user joined', { 'username': user.username, users:users });
});
socket.on('typing', function (msg) {
io.emit('typing', { 'message': msg.message, 'username': msg.username });
});
socket.on('new_message', function (msg) {
io.emit('chat message', { 'message': msg.message, 'username': msg.username });
});
socket.on('disconnect', function(){
console.log('user disconnected');
users.splice(users.indexOf(socket.username), 1);
io.emit('user disconnected', { 'username': socket.username });
});
});
module.exports = socketio;
chat_script.js
var username = Math.random().toString(36).substr(2,8);
socket.emit('join', { username: username });
socket.on('user joined', function (data) {
$(".js-userjoined").html(data.username + ' Joined chat room');
console.log(data.users);
$.each(data.users, function(index, user) {
console.log(user);
$(".js-usersinchat").append('<span id ='+user+'> <strong>'+user+'</strong></span>');
});
});
socket.on('user disconnected', function (data) {
$("#"+data.username).remove();
});
socket.on('previousMessage', function(messages){
for(message of messages){
$('#messages').append('<div class="row message-bubble"><p class="text-muted">'+message.author+'</p><p>'+ message.message+' </p> </div>');
}
});
//an event emitted from server
socket.on('chat message', function (data) {
var string = '<div class="row message-bubble"><p class="text-muted">' + data.username+'</p><p>'+data.message+'</p></div>';
if (data.username.length && data.message.length){
var messageObject = {
author:data.username,
message: data.message,
};
socket.emit('sendMessage',messageObject);
}
$('#messages').append(string);
});
$(function () {
var timeout;
function timeoutFunction() {
typing = false;
socket.emit("typing", { message: '', username: '' });
}
$("#sendmessage").on('click', function () {
var message = $("#txtmessage").val();
$("#txtmessage").val('');
$('.typing').html("");
socket.emit('new_message', { message: message, username: username });
});
$('#txtmessage').keyup(function () {
console.log('happening');
typing = true;
socket.emit('typing', { message: 'typing...', username: username});
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 2000);
});
});
socket.on('typing', function (data) {
if (data.username && data.message) {
$('.typing').html("User: " + data.username + ' ' + data.message);
} else {
$('.typing').html("");
}
});
var typing = false;
var timeout = undefined;
function timeoutFunction(){
typing = false;
socket.emit(noLongerTypingMessage);
}
I hope i was clear
Try remove this line:
socket.emit('sendMessage',messageObject);
Here on chat_script.js:
//an event emitted from server
socket.on('chat message', function (data) {
var string = '<div class="row message-bubble"><p class="text-muted">' + data.username+'</p><p>'+data.message+'</p></div>';
if (data.username.length && data.message.length){
var messageObject = {
author:data.username,
message: data.message,
};
// THIS LINE BELOW:
socket.emit('sendMessage',messageObject);
}
$('#messages').append(string);
});
Frontend code:-
let socket = io();
socket.on(`connect`, () => {
console.log(`new User Connected`);
});
jQuery(`#video-form`).on(`submit`, (event) => {
event.preventDefault();
socket.emit(`offer`, () => {
console.log(`Starting call`);
});
});
/////////////////////////////
'use strict';
let isChannelReady = false;
let isInitiator = false;
let isStarted = false;
let localStream;
let pc;
let remoteStream;
let turnReady;
let pcConfig = {
'iceServers': [{
'url': 'stun:stun.1.google.com:19302'
}]
};
// Set up audio and video regardless of what devices are present.
let sdpConstraints = {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
};
/////////////////////////////////////////////
let room = 'foo';
// Could prompt for room name:
// room = prompt('Enter room name:');
if (room !== '') {
socket.emit('create or join', room);
console.log('Attempted to create or join room', room);
}
socket.on('created', function (room) {
console.log('Created room ' + room);
isInitiator = true;
});
socket.on('full', function (room) {
console.log('Room ' + room + ' is full');
});
socket.on('join', function (room) {
console.log('Another peer made a request to join room ' + room);
console.log('This peer is the initiator of room ' + room + '!');
isChannelReady = true;
});
socket.on('joined', function (room) {
console.log('joined: ' + room);
isChannelReady = true;
});
socket.on('log', function (array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
function sendMessage(message) {
console.log('Client sending message: ', message);
socket.emit('message', message);
}
// This client receives a message
socket.on('message', function (message) {
console.log('Client received message:', message);
if (message === 'got user media') {
//isStarted = true;
isInitiator = true;
isChannelReady = true;
maybeStart(message);
} else if (message.type === 'offer') {
if (!isInitiator && !isStarted) {
maybeStart(message);
}
pc.setRemoteDescription(new RTCSessionDescription(message));
doAnswer(message);
} else if (message.type === 'answer' && isStarted) {
pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate' && isStarted) {
let candidate = new RTCIceCandidate({
sdpMLineIndex: message.label,
candidate: message.candidate
});
pc.addIceCandidate(candidate);
} else if (message === 'bye' && isStarted) {
handleRemoteHangup();
}
});
////////////////////////////////////////////////////
let localVideo = document.querySelector('#localVideo');
let remoteVideo = document.querySelector('#remoteVideo');
navigator.getUserMedia = navigator.getUserMedia || navigator.mediaDevices.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
let constraints = {
audio: false,
video: true
};
navigator.mediaDevices.getUserMedia(constraints)
.then(gotStream)
.catch(function (e) {
alert('getUserMedia() error: ' + e.name);
});
function gotStream(stream) {
console.log('Adding local stream.');
// if (navigator.webkitGetUserMedia) {
localVideo.src = window.URL.createObjectURL(stream);
// }
// else {
// localStream.src = stream;
// }
localStream = stream;
sendMessage('got user media');
if (isInitiator) {
maybeStart();
}
}
console.log('Getting user media with constraints', constraints);
if (location.hostname !== 'localhost') {
requestTurn();
}
function maybeStart(message) {
// isChannelReady = true;
// isInitiator = true;
console.log('>>>>>>> maybeStart() ', isStarted, localStream, isChannelReady);
if (!isStarted && typeof localStream !== 'undefined' && isChannelReady) {
console.log('>>>>>> creating peer connection');
createPeerConnection(message);
pc.addStream(localStream);
isStarted = true;
console.log('isInitiator', isInitiator);
if (isInitiator) {
doCall();
}
}
}
window.onbeforeunload = function () {
sendMessage('bye');
};
/////////////////////////////////////////////////////////
function createPeerConnection(message) {
try {
//let msg = JSON.parse(message.data);
pc = new RTCPeerConnection(pcConfig) || webkitRTCPeerConnection(pcConfig) || mozRTCPeerConnection(pcConfig);
pc.setRemoteDescription(new RTCSessionDescription(message));
console.log(`SetRemomteDescription`);
pc.onicecandidate = handleIceCandidate;
console.log(`handleIceCandidate`);
pc.onaddstream = handleRemoteStreamAdded;
console.log(`handleRemoteStreamAdde`);
pc.onremovestream = handleRemoteStreamRemoved;
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
}
}
function handleIceCandidate(event) {
console.log('icecandidate event: ', event);
if (event.candidate) {
sendMessage({
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
});
} else {
console.log('End of candidates.');
}
}
function handleRemoteStreamAdded(event) {
//if (navigator.webkitGetUserMedia) {
console.log('Remote stream added.');
remoteVideo.src = window.URL.createObjectURL(event.stream);
// }
// else {
// remoteStream.srcObject = event.stream;
// }
remoteStream = event.stream;
}
function handleCreateOfferError(event) {
console.log('createOffer() error: ', event);
}
function doCall() {
console.log('Sending offer to peer');
pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}
function doAnswer(message) {
console.log('Sending answer to peer.');
pc.createAnswer(message.id).then(
setLocalAndSendMessage).catch(
onCreateSessionDescriptionError);
}
function setLocalAndSendMessage(sessionDescription) {
// Set Opus as the preferred codec in SDP if Opus is present.
// sessionDescription.sdp = preferOpus(sessionDescription.sdp);
pc.setLocalDescription(sessionDescription);
console.log('setLocalAndSendMessage sending message', sessionDescription);
sendMessage(sessionDescription);
}
function onCreateSessionDescriptionError(error) {
trace('Failed to create session description: ' + error.toString());
}
function requestTurn(turnURL) {
let turnExists = false;
for (let i in pcConfig.iceServers) {
if (pcConfig.iceServers[i].url.substr(0, 5) === 'turn:') {
turnExists = true;
turnReady = true;
break;
}
}
if (!turnExists) {
console.log('Getting TURN server from ', turnURL);
// No TURN server. Get one from computeengineondemand.appspot.com:
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let turnServer = JSON.parse(xhr.responseText);
console.log('Got TURN server: ', turnServer);
pcConfig.iceServers.push({
'url': 'turn:192.158.29.39:3478?transport=tcp', //+ turnServer.username + '#' + turnServer.turn,
'username':'28224511:1379330808',
'credential': 'JZEOEt2V3Qb0y27GRntt2u2PAYA='
});
turnReady = true;
}
};
//xhr.open('GET', turnURL, true);
//xhr.send();
}
}
// function handleRemoteStreamAdded(event) {
// console.log('Remote stream added.');
// remoteVideo.src = window.URL.createObjectURL(event.stream);
// remoteStream = event.stream;
// }
function handleRemoteStreamRemoved(event) {
console.log('Remote stream removed. Event: ', event);
}
function hangup() {
console.log('Hanging up.');
stop();
sendMessage('bye');
}
function handleRemoteHangup() {
console.log('Session terminated.');
stop();
isInitiator = false;
}
function stop() {
isStarted = false;
// isAudioMuted = false;
// isVideoMuted = false;
pc.close();
pc = null;
}
///////////////////////////////////////////
// Set Opus as the default audio codec if it's present.
function preferOpus(sdp) {
let sdpLines = sdp.split('\r\n');
let mLineIndex;
// Search for m line.
for (let i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('m=audio') !== -1) {
mLineIndex = i;
break;
}
}
if (mLineIndex === null) {
return sdp;
}
// If Opus is available, set it as the default in m line.
for (let i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('opus/48000') !== -1) {
let opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
if (opusPayload) {
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex],
opusPayload);
}
break;
}
}
// Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
return sdp;
}
function extractSdp(sdpLine, pattern) {
let result = sdpLine.match(pattern);
return result && result.length === 2 ? result[1] : null;
}
// Set the selected codec to the first in m line.
function setDefaultCodec(mLine, payload) {
let elements = mLine.split(' ');
let newLine = [];
let index = 0;
for (let i = 0; i < elements.length; i++) {
if (index === 3) { // Format of media starts from the fourth.
newLine[index++] = payload; // Put target payload to the first.
}
if (elements[i] !== payload) {
newLine[index++] = elements[i];
}
}
return newLine.join(' ');
}
// Strip CN from sdp before CN constraints is ready.
function removeCN(sdpLines, mLineIndex) {
let mLineElements = sdpLines[mLineIndex].split(' ');
// Scan from end for the convenience of removing an item.
for (let i = sdpLines.length - 1; i >= 0; i--) {
let payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
if (payload) {
let cnPos = mLineElements.indexOf(payload);
if (cnPos !== -1) {
// Remove CN payload from m line.
mLineElements.splice(cnPos, 1);
}
// Remove CN line in sdp
sdpLines.splice(i, 1);
}
}
sdpLines[mLineIndex] = mLineElements.join(' ');
return sdpLines;
}
Backend Code:
const path = require(`path`);
const http = require(`http`);
const express = require(`express`);
const socketIO = require(`socket.io`);
const {generateMessage} = require(`./utils/message`);
const {isRealString} = require(`./utils/validation`);
const publicPath = path.join(__dirname,`../public`);
let app = express();
let server = http.createServer(app);
let io = socketIO(server);
app.use(express.static(publicPath));
app.get(`/video`,(req,res)=>{
res.sendFile(path.join(__dirname,`../public/videochat.html`));
});
io.on(`connection`,(socket)=>{
console.log(`New User Connected`);
socket.emit(`newMessage`,generateMessage(`Admin`, `Welcome to Chat App`));
socket.broadcast.emit(`newMessage`,generateMessage(`Admin`,`New User Joined`));
socket.on(`join`,(params,callback)=>{
if(!isRealString(params.name) || !isRealString(params.room)){
callback(`Name and Room name is required`);
}
callback();
});
socket.on('createMessage',(message,callback)=>{
console.log(`create Message`,message);
io.emit(`newMessage`,generateMessage(message.from,message.text));
callback();
});
socket.on(`offer`,(callback)=>{
console.log(`Call is Starting`);
callback();
});
/////////////////////////////////////////
function log() {
let array = ['Message from server:'];
array.push.apply(array, arguments);
socket.emit('log', array);
}
socket.on('message', function (message) {
log('Client said: ', message);
// for a real app, would be room-only (not broadcast)
socket.emit('message', message);
});
socket.on(`sdp`,(data)=>{
console.log('Received SDP from ' + socket.id);
socket.emit('sdp received', data.sdp);
});
socket.on('create or join', function (room) {
log('Received request to create or join room ' + room);
let numClients = io.sockets.sockets.length;
log('Room ' + room + ' now has ' + numClients + ' client(s)');
if (numClients === 1) {
socket.join(room);
log('Client ID ' + socket.id + ' created room ' + room);
socket.emit('created', room, socket.id);
} else if (numClients === 2) {
log('Client ID ' + socket.id + ' joined room ' + room);
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room, socket.id);
io.sockets.in(room).emit('ready');
} else { // max two clients
socket.emit('full', room);
}
});
socket.on('ipaddr', function () {
let ifaces = os.networkInterfaces();
for (let dev in ifaces) {
ifaces[dev].forEach(function (details) {
if (details.family === 'IPv4' && details.address !== '127.0.0.1') {
socket.emit('ipaddr', details.address);
}
});
}
});
socket.on('bye', function () {
console.log('received bye');
});
});
server.listen(3000,`192.168.0.105`,()=>{
console.log(`Server is Up`)
});
I'm getting this Error:- Failed to create PeerConnection, exception: Failed to construct 'RTCSessionDescription': parameter 1 ('descriptionInitDict') is not an object.
Also getting
Uncaught (in promise) DOMException: Failed to set remote offer sdp: Called in wrong state: kHaveLocalOffer
This line:
function doCall() {
console.log('Sending offer to peer');
pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}
Change to:
pc.createOffer().then(setDescription).catch(errorHandler);
function setDescription(description) {
console.log('Got description', description);
pc.setLocalDescription(description).then(function() {
console.log("Sending SDP");
socket.emit('signal', {'sdp': description});
}).catch(errorHandler);
}
You should than handle the emitted SDP:
function gotMessageFromServer(signal) {
console.log('Got message', signal);
if(signal.sdp) {
console.log("Set remote description: ", signal);
pc.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(function() {
// Only create answers in response to offers
if(signal.sdp.type === 'offer') {
console.log("Sending answer");
pc.createAnswer().then(setDescription).catch(errorHandler);
}
}).catch(errorHandler);
} else if(signal.ice) {
console.log('Got remote ice candidate: ', signal);
pc.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler);
}
}
Having difficulty with this working at seemingly random times. When I go into the chat page, the controller activates, and immediately after that the before addlistener and after addlistener console.logs fire, and then sometimes when I send a message, it is received with a console printout of the package contents, but more often it isn't. And sometimes, it is printed on the console of the computer that fires off the send message instead of the receiving end.
At the very least, though, whenever I send a message, even if I don't get a console printout of the package, I get a corresponding [QBChat RECV]:, [object Object] - hit the button ten times, get ten QBChat RECVs.
.controller('ChatCtrl', function($scope, $stateParams, $timeout, $rootScope, $ionicLoading) {
console.log("Inside ChatCtrl");
QB.createSession(function(err,result){
console.log('Session create callback', err, result);
console.log('Session create callback' + JSON.stringify(result));
});
$scope.settings = {};
$scope.user = {};
$scope.error = {};
$scope.signInClick = function() {
console.log('Login was clicked');
$scope.loading = $ionicLoading.show({
content: 'Logging in',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
var params = {'login': ($scope.user.username), 'password': ($scope.user.password)}
console.log("params... " + JSON.stringify(params));
QB.users.create(params, function(err, user){
if (user) {
console.log("successful user.create... " + JSON.stringify(user));
var jid = user.id + "-#####" + "#chat.quickblox.com";
var chatparams = {'jid': jid, 'password': ($scope.user.password)};
QB.chat.connect(chatparams, function(err, roster) {
console.log("err from qb.chat.connect... " + JSON.stringify(err));
console.log("roster from qb.chat.connect .... " + JSON.stringify(roster));
});
} else {
if (err.message == "Unprocessable Entity"){
QB.login(params, function(err, user){
if (user) {
console.log("Logged into QB with " + JSON.stringify(user));
var jid = user.id + "-#####" + "#chat.quickblox.com";
console.log(user.login + "'s jid is......" + jid);
var chatparams = {'jid': jid, 'password': ($scope.user.password)};
QB.chat.connect(chatparams, function(err, roster) {
console.log("stringifying the roster... " + JSON.stringify(roster));
});
}
else {
console.log(JSON.stringify(err));
}
});
}
}
});
// var chatparams = {'jid': jid, 'password': ($scope.user.password)};
// console.log("the jid is......" + jid);
// console.log("chatparams is ......" + JSON.stringify)
Parse.User.logIn(($scope.user.username) , $scope.user.password, {
success: function(_user) {
console.log('Login Success');
console.log('user = ' + _user.attributes.username);
console.log('email = ' + _user.attributes.email);
$ionicLoading.hide();
$rootScope.user = _user;
$rootScope.isLoggedIn = true;
// $state.go('tab.home');
},
error: function(user, err) {
$ionicLoading.hide();
// The login failed. Check error to see why.
if (err.code === 101) {
$scope.error.message = 'Invalid login credentials';
} else {
$scope.error.message = 'An unexpected error has ' +
'occurred, please try again.';
}
$scope.$apply();
}
});
// $state.go('tab.profile');
};
$scope.sendMessageClick = function() {
var user = $rootScope.user.attributes.username;
console.log("user = " + user);
console.log('sendMessageclick');
var countchew = "3354163-######chat.quickblox.com"; //countchew
var starshipenterprise = "3354099-######chat.quickblox.com"; //starshipenterprise
QB.chat.roster.get(function(roster) {
console.log("roster.get before if block " + JSON.stringify(roster));
});
if (user == "countchew"){
QB.chat.roster.confirm(starshipenterprise, function(){
console.log("roster.confirm called");
});
QB.chat.roster.add(starshipenterprise, function() {
console.log("roster.add called");
});
QB.chat.send(starshipenterprise, {
type: 'chat',
name: 'testmessage',
body: 'Hello world!',
extension: {save_to_history: 1}
});
// QB.chat.roster.remove(starshipenterprise, function() {
// console.log("roster.remove starship ... ");
// });
QB.chat.roster.get(function(roster) {
console.log("end of if statement " + JSON.stringify(roster));
});
} else if (user == "starshipenterprise"){
QB.chat.roster.confirm(countchew, function() {
console.log("roster.confirm called");
});
QB.chat.roster.add(countchew, function() {
console.log("roster.add called");
});
QB.chat.send(countchew, {
type: 'chat',
body: 'Hello world!'
});
}
};
console.log("before addlistener");
QB.chat.addListener({from: '3354163-######chat.quickblox.com'}, function() {
QB.chat.onMessageListener = function(userId, message) {
console.log('userId ..... ' + userId);
console.log('message .... ' + JSON.stringify(message));
};
});
console.log("after addlistener");
var chatparams1 = {from: '3354099-######chat.quickblox.com'};
console.log("before addlistener");
QB.chat.addListener(chatparams1, function() {
QB.chat.onMessageListener = function(userId, message) {
console.log('userId ..... ' + userId);
console.log('message .... ' + JSON.stringify(message));
};
});
console.log("after addlistener");
})
Great! Figured it out.
You need to pay attention to the XML packages that it sends. What was happening is that somehow, when it first got up and running and was working well with the corresponding QB chat addresses for the account, after that, at some point it started appending a string of numbers-quickblox-numbers (35896363-quickblox-20942 or whatever) in the 'from' field for the address, which is what I had my listener listening to. The confusing thing is that this worked sporadically.
You can't hardcode the addresses because this string of numbers at the end changes with every login.
Instead, it is working for the time being to just listen for messages with the parameters {name: 'message', type: 'chat'}.
A better way could be:
QB.chat.addListener( {name: 'message'}, function() {
$log.debug(" main: QB listener by filter was triggered");
});
Or just:
QB.chat.onMessageListener = showMessage;
That code has to be run once (at first init, on system loading).
onMessageListener will be triggered every time.
addListener will be triggered only if msg is with name'message'. (filter of listener)
Then you need a function with such a signature:
function showMessage(userId, msg) {
console.log('main.showMessage:: on message', msg)
}