Server crash, sending message at restart (Node.js / Socket.io) - javascript

Hey guys i am doing a message system all is working fine but now i want to add the thing that if the server crash and restart the message that have been send during this time will be send at the restart of the server. I am trying to save the information of the message in the client side and make a "waiting" system that will wait to a server response. So i wanted to know how can i do that "waiting" system because now i am doing like that :
while (socket.connected === false) {
}
But that make bug the client because the infinit loop is way too fast ... so is that possible to set a timer ? (i have already tried but i dind't find how to make a good timer in a loop).
Or maybe i am totaly wrong and i haven't to do a waiting system but an other thing so tell me if my technic will not work or if there is one better :)
So here is my code :
Client.js (startTchat is called when someone is connected)
(function($){
var socket = io.connect('http://localhost:1337');
var lastmsg = [];
var me_id = [];
var friend_ = [];
var conv_ = [];
var isPlace_ = [];
var isLocation_ = [];
var me_ = [];
var my_id;
startTchat = function(user_id, username, friend_id, conv_id, isPlace, isLocalisation) {
my_id = user_id;
socket.emit('login_chat', {
id : user_id,
username : username,
friend : friend_id,
conv : conv_id,
isPlace : isPlace,
isLocalisation : isLocalisation,
})
};
/**
* Error
*/
socket.on('error', function(err){
alert(err);
});
/**
* Messages
*/
$('#chat_form').submit(function(event){
var a = 0;
while (socket.connected === false) {
}
event.preventDefault();
console.log('ME', my_id, 'TAB', me_id);
socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
if (a === 1) {
console.log('HEYYYYYYYYYY', my_id);
}
$('#message').val('');
$('#message').focus();
});
socket.on('new_msg', function(message, me, id_receiver, id_transmiter){
if (me.id === id_receiver || me.id === id_transmiter) {
if (lastmsg != message.user.id) {
$('#new_message').append('<span class="time_date"> ' + message.h + ' : ' + message.m + ' | ' + message.y + '-' + message.m + '-' + message.d + ' | ' + message.user.username + '</span>'
+ '<p>' + message.message + '</p>\n'
);
lastmsg = message.user.id;
} else {
$('#new_message').append('<p>' + message.message + '</p>'
);
}
}
});
/**
* Login
*/
socket.on('new_user', function(user, friend, conv, isPlace, isLocation){
me_id[user.id] = user.id;
friend_[user.id] = friend;
conv_[user.id] = conv;
isPlace_[user.id] = isPlace;
me_[user.id] = user;
isLocation_[user.id] = isLocation;
$('#new_user').append('<div class="chat_list active_chat" id="' + user.id + '">\n' +
' <div class="chat_people">\n' +
' <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>\n' +
' <div class="chat_ib">\n' +
' <h5>' + user.username + ' <span class="chat_date">Id : ' + user.id + '</span></h5>\n' +
' </div>\n' +
' </div>\n' +
' </div>');
});
/**
* Disconnect
*/
socket.on('disc_user', function(user){
$('#' + user.id).remove();
})
})(jQuery);
And server.js :
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'msg';
MongoClient.connect(url, function(err, client) {
if (err)
throw err;
console.log('MongoDB connected ...');
httpServer = http.createServer(function(req, res) {
console.log('This is a test');
res.end('Hello World');
});
httpServer.listen(1337);
var io = require('socket.io').listen(httpServer);
var users = {};
var messages = [];
io.sockets.on('connection', function (socket) {
const collection = client.db(dbName).collection('MessageUser');
var me = false;
var friend = false;
var conv = false;
var isPlace = false;
var room = false;
var isLocalisation = false;
for(var k in users) {
socket.emit('new_user', users[k]);
}
/**
* Login
*/
socket.on('login_chat', function (user) {
me = user;
friend = user.friend;
isPlace = user.isPlace;
conv = user.conv;
isLocalisation = user.isLocalisation;
if (isPlace === 0) {
room = user.conv;
} else {
room = user.conv + '-Place';
}
socket.join(room);
//console.log('New user : ', me.username, ' - id : ', me.id);
users[me.id] = me;
io.sockets.emit('new_user', me, friend, conv, isPlace, isLocalisation);
});
/**
* Disconnect
*/
socket.on('disconnect', function() {
if (!me) {
return false;
}
delete users[me.id];
io.sockets.emit('disc_user', me);
});
/**
* Message receive
*/
socket.on('new_msg', function(message, me_id, friend_, conv_, isPlace_, isLocalisation_, me_){
if (message.message !== '') {
message.user = me;
date = new Date();
message.h = date.getHours();
message.m = date.getMinutes();
message.y = date.getFullYear();
message.m = date.getMonth();
message.d = date.getDate();
console.log(message);
messages.push(message);
msg = {};
msg.content = message.message;
msg.sendAt = new Date();
msg.idTransmitter = me.id;
if (isPlace === 0) {
msg.idReceiver = friend;
} else {
msg.idReceiver = conv;
}
msg.idConversation = conv;
msg.isPlace = isPlace;
msg.isLocalisation = isLocalisation;
collection.insertOne(msg);
console.log('---1---', msg.idReceiver, '---2---', msg.idTransmitter, '---3---', me);
io.to(room).emit('new_msg', message, me, msg.idReceiver, msg.idTransmitter);
}
});
});
});
ps : Tell me if you need more info, sorry if i forget something that my first time using js, node and socket.io :)

while (socket.connected === false) {
}
Don't do that, it will block your page and hold your processor to 100%.
Instead, use setTimeout. It's the equivalent of sleep in javascript. You need to refactor your code to call setTimeout in a recursive fashion, and count the number of "retries" (if you want to stop at some point).
Code:
$('#chat_form').submit(function(event){
var retries = 0, max_retries = 10;
function tryNewMessage() {
if (socket.connected === false) {
if (retries >= max_retries) return; //handle max_retries properly in your code
//this is where you sleep for 1 second, waiting for the server to come online
setTimeout(tryNewMessage, 1000);
retries++;
}
else {
var a = 0;
event.preventDefault();
console.log('ME', my_id, 'TAB', me_id);
socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
if (a === 1) {
console.log('HEYYYYYYYYYY', my_id);
}
$('#message').val('');
$('#message').focus();
}
}
tryNewMessage();
});

Related

Delay for messages in node-telegram-bot-api

I am working on a telegram bot with the node-telegram-bot-api library. I made 2 buttons using keyboard. But when you click on them a lot, the bot will spam and sooner or later it will freeze. Is it possible to somehow put a delay for the user on messages.
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
export const keyboardMain = {
reply_markup: JSON.stringify({
keyboard: [
[{
text: '/start',
},
],
resize_keyboard: true
})
};
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use:
You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
I tried using this code, put the function code in my function file, connected everything to the required file, and I don’t understand what to do next and where to insert the last code and what to do with it. I'm new to JavaScript and just learning.
import {
bot
} from '../token.js';
import {
throttler
} from '../functions/functions.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
const throttle = throttler(10);
if (text === '/start') {
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
return bot.sendMessage(chatId, 'hello', keyboardMain);
} else {
// dont reply
}
}
return bot.sendMessage(chatId, 'error');
});
}
Get the time when he pressed the button
Get the time of the next click
Take away the difference and set the condition (if, for example, more than 3 seconds have passed between clicks, then the user will not be frozen).
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILLINYOUR GOOGLEWEBAPPADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e){
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var msgbegan = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A7").getValue();
var msginfo = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A9").getValue();
var answer = "%0A" + msgbegan + "%0A" ;
///////////////////////
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
// global 10 second throttler
const throttle = throttler(500) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
///////////////////////////////////////
if(text == "/start"){
sendText(id, answer);
} else if (text == "/info"){
sendText(id, msginfo);
}else{
if (text.length == 10){
var found = false;
var total_rows = SpreadsheetApp.openById(ssId).getSheets()[0].getMaxRows();
for(i=1; i<=total_rows; i++){
var loop_id = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(i,2).getValue();
if(text == loop_id){
found = true;
found_at = i; // employee row
break;
}
}
if(found){
sendText(id, work_message);
}else{
var msgerrror = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A6").getValue();
var not_found = "%0A" + msgerrror+ "%0A" ;
sendText(id, not_found);
}
} else {
sendText(id, "eroor");
}
}
/////////////
var emp_name = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,1).getValue();
var emp_work = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,3).getValue();
var homeloc = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,4).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var emp_data = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,5).getValue();
var emp_day = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,6).getValue();
var emp_clock = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,7).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var welcome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A2").getValue();
var msgemp = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A3").getValue();
var msgloc = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A4").getValue();
var msgbay = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A5").getValue();
var msghome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A8").getValue();
var msmobil = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A11").getValue();
var mstoday = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A13").getValue();
var msdata = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A14").getValue();
var msclock = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A15").getValue();
var work_message = welcome + emp_name +
"%0A" + msgemp + emp_work +
"%0A" + mstoday + emp_day +
"%0A" + msdata + emp_data +
"%0A" + msclock + emp_clock +
"%0A" + msghome + homeloc +
"%0A" + msgloc+ emp_location +
"%0A" + msgbay +
"%0A" + msmobil ;
}
Excuse me . I am a beginner
Is this the correct way

Join multiple room in kurento

I want to create an application that allows a user to join multiple video call rooms in kurento.
I wrote the following code:
function joinRooms() {
var userId = document.getElementById('expertid').value;
console.log("UserID = " + userId);
var roomIds = document.getElementById('roomids').value.split(",");//Assume that we have 2 rooms r1 & r2
var userIdAlias = [];
for (var i = 0; i < roomIds.length; i++) {
userIdAlias[i] = userId + "(" + i + ")";
console.log("User alias = " + userIdAlias[i]);
}
var wsUri = 'wss://' + location.host + '/room';
kurento = KurentoRoom(wsUri, function(error, kurento) {
if (error)
return console.log(error);
for (let i = 0; i < roomIds.length; i++) {
//console.log("Start loop Roomid = " + roomId);
rooms[i] = kurento.Room({
room : roomIds[i],
user : userIdAlias[i],
subscribeToStreams : true
});
localStreams[i] = kurento.Stream(rooms[i], {
audio : true,
video : true,
data : true
});
localStreams[i].addEventListener("access-accepted", function() {
var playVideo = function(stream) {
var participantId = stream.getParticipant().getID();
var userId = document.getElementById('expertid').value;
console.log("userId = " + userId + ", participantId = " + participantId);
if (!userIdAlias.includes(participantId)) {
var elementId = "video-" + stream.getGlobalID();
var div = document.createElement('div');
div.setAttribute("id", elementId);
document.getElementById("participants").appendChild(div);
stream.playThumbnail(elementId);
// Check color
var videoTag = document.getElementById("native-" + elementId);
var userId = stream.getGlobalID();
var canvas = document.createElement('CANVAS');
checkColor(videoTag, canvas, userId);
}
}
rooms[i].addEventListener("room-connected", function(){
var j = i;
return function(roomEvent) {
document.getElementById('room-header').innerText = 'ROOM \"'
+ roomIds[j] + '\"';
//document.getElementById('join').style.display = 'none';
document.getElementById('room').style.display = 'block';
localStreams[j].publish();
var streams = roomEvent.streams;
for (var streamsIdx = 0; streamsIdx < streams.length; streamsIdx++) {
playVideo(streams[streamsIdx]);
}
}
});
rooms[i].addEventListener("stream-added", function(streamEvent) {
playVideo(streamEvent.stream);
});
rooms[i].addEventListener("stream-removed", function(streamEvent) {
var element = document.getElementById("video-"
+ streamEvent.stream.getGlobalID());
if (element !== undefined) {
element.parentNode.removeChild(element);
}
});
playVideo(localStreams[i]);
rooms[i].connect();
});
localStreams[i].init();
}
});
}
However, the code does not work. The log in server said that there is only one user request to join room r2 but not r1.
I think the reason is Javascript works with too many asynchronous task so it worked incorrectly.
Can you give some advice about the way to joining multiple rooms in kurento?

angularJs data binding issue to capture and display status

I am trying to get and display Total Sent, Total Success and Total Error using AngularJs. So far, I have been able to retrieve the information Total Sent, Total Success and Total Error inside the code. However, I am not convinced that the approach (using global variables) I have taken to bind and display those status is correct.
Here are my controller and associated services.
var sent = 0;
var succ = 0;
var err = 0;
myApp.service('ParseMessageService', function() {
this.myFunc = function(message) {
var res = message.match(/Success/g);
if (res !== null) {
//console.log(res);
TSent = message.match(/Total Sent: (\d+)/);
if (TSent) {
sent = TSent[1];
//parsedMsg.push(TSent[1]);
//console.log(TSent[1]); //replace with $scope and display on Gui
}
TSucc = message.match(/Total Success: (\d+)/);
if (TSucc) {
succ = TSucc[1];
//parsedMsg.push(TSucc[1]);
// console.log(TSucc[1]); //replace with $scope and display on Gui
}
TErr = message.match(/Total Errors: (\d+)/);
if (TErr) {
err = TErr[1];
//parsedMsg.push(TErr[1]);
//console.log(TErr[1]); //replace with $scope and display on Gui
}
}
}
//}
});
myApp.factory('WebSocketService', function() {
var service = {};
service.connect = function() {
if (service.ws) {
return;
}
var ws = new WebSocket("ws://127.0.0.1:8000");
ws.onopen = function() {
service.callback("Succeeded to open a connection");
//display webSocket connected status
};
ws.onerror = function() {
service.callback("Failed to open a connection");
}
ws.onmessage = function(message) {
service.callback(message.data);
};
service.ws = ws;
}
service.send = function(message) {
service.ws.send(message);
}
service.subscribe = function(callback) {
service.callback = callback;
}
return service;
});
angular.module('myApp')
.controller('PingTestController', function($scope, WebSocketService, ParseMessageService) {
$scope.messages = [];
$scope.TSent = [];
$scope.TSucc = [];
$scope.TErr = [];
$scope.parsedSent = 0;
$scope.parsedSucc =0;
$scope.parsedErr =0;
$scope.pingStr = "Ping"
$scope.define = "Definitions";
$scope.url = "www.google.com"
$scope.size = "1";
$scope.TTL = "10"
$scope.pause = "3";
$scope.paraStr = "[,]";
$scope.cmdStartStr = "[;]";
($scope.trueStr) = "TRUE";
($scope.falseStr) = "FALSE";
($scope.PfalseStr) = "False";
($scope.cmdEndStr) = "[/]";
//($scope.newLineStr) = "\r\n";
($scope.startCmd) = "Start";
($scope.stopCmd) = "Stop";
($scope.clearCmd) = "Clear";
$scope.updatePing = function() {
$scope.pingCmd = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.define) + ($scope.cmdStartStr) +
($scope.url) + ($scope.paraStr) + ($scope.PfalseStr) + ($scope.paraStr) +
($scope.TTL) + ($scope.paraStr) +
($scope.size) + ($scope.paraStr) +
($scope.pause) + ($scope.cmdEndStr);
}
WebSocketService.subscribe(function(message) {
ParseMessageService.myFunc(message);
$scope.parsedSent = (sent);
$scope.parsedSucc = (succ);
$scope.parsedErr= (err);
$scope.messages.push(message);
$scope.$apply();
});
$scope.connect = function() {
WebSocketService.connect();
}
$scope.send = function() {
WebSocketService.send($scope.pingCmd);
$scope.text = "";
}
//[;]Ping[;]Stop[;]TRUE[/]
$scope.stopPing = function() {
$scope.pingStop = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.stopCmd) + ($scope.cmdStartStr) +
($scope.trueStr) + ($scope.cmdEndStr);
WebSocketService.send($scope.pingStop);
}
// [;]Ping[;]Start[;]TRUE[/]
$scope.startPing = function() {
$scope.pingStart = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.startCmd) + ($scope.cmdStartStr) +
($scope.trueStr) + ($scope.cmdEndStr);
WebSocketService.send($scope.pingStart);
}
// [;]Ping[;]Clear;]TRUE[/]
$scope.clearPing = function() {
$scope.pingClear = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.clearCmd) + ($scope.cmdStartStr) +
($scope.trueStr) + ($scope.cmdEndStr);
WebSocketService.send($scope.pingClear);
}
});
Here is relevant part of html code.
<br/>
<button ng-click="send()" class="btn"> Add new Ping</button>
<button ng-click="startPing()" class="btn"> StartPing</button>
<button ng-click="stopPing()" class="btn">Stop Ping</button>
<button ng-click="clearPing()" class="btn">Clear Ping</button>
<br />
<div ng-repeat = "message in messages track by $index">
{{parsedSent}} {{parsedSucc}} {{parsedErr}}
</div>
Eventually, I would like to have a clean way to get those statistics and display with on a webpage i.e. Total success with green background, Total Error with Red and Total Sent with Blue background.
You can move the global variables to the service an use them from there. You could also use this answer: Static javascript variable to be used as counter in Angularjs controller

TypeError: Cannot read property 'toString' of undefined - why?

Here is the line (50) where this is happening:
var meetingId = meeting._id.toString(),
And here is the full, relevant code:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var config = require('./config'),
xlsx = require('./xlsx'),
utils = require('./utils'),
_ = require('lodash'),
url = config.DB_URL;
var meetings = [];
function findNumberOfNotesByMeeting(db, meeting, callback) {
var meetingId = meeting._id.toString(),
meetingName = meeting.name.displayValue,
attendees = meeting.attendees;
host = meeting.host;
var count = 1, pending = 0, accepted = 0;
console.log("==== Meeting: " + meetingName + '====');
_.each(attendees, function(item) {
console.log(count++ + ': ' + item.email + ' (' + item.invitationStatus + ')');
if (item.invitationStatus == 'pending') { pending++; }
else if (item.invitationStatus == 'accepted') { accepted++; }
});
console.log("*** " + attendees.length + ", " + pending + "," + accepted);
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
console.log(meetingName + ': ' + count + ',' + attendees.length + ' (' + email + ')');
meetings.push([ meetingName, count, email, attendees.length, pending, accepted ]);
}
callback();
});
}
});
}
function findMeetings(db, meeting, callback) {
var meetingId = meeting._id.toString(),
host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (!err && doc && doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
var cursor = db.collection('meetings').find({
'email': {'$regex': 'agu', '$options': 'i' }
});
}
callback();
});
}
cursor.count(function(err, count) {
console.log('count: ' + count);
var cnt = 0;
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
findNumberOfNotesByMeeting(db, doc, function() {
cnt++;
if (cnt >= count) { callback(); }
});
}
});
});
});
}
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findMeetings(db, function() {
var newMeetings = meetings.sort(function(m1, m2) { return m2[1] - m1[1]; });
newMeetings.splice(0, 0, [ 'Meeting Name', 'Number of Notes', 'Emails' ]);
xlsx.writeXLSX(newMeetings, config.xlsxFileNameMeetings);
db.close();
});
});
As you can see, the meeting variable (which I am almost 100% sure is the problem, not the _id property) is passed in just fine as a parameter to the earlier function findNumberOfNotesByMeeting. I have found some information here on SO about the fact that my new function may be asynchronous and needs a callback, but I've attempted to do this and am not sure how to get it to work, or even if this is the right fix for my code.
You're not passing the meeting object to findMeetings, which is expecting it as a second parameter. Instead of getting the meeting object, the function receives the callback function in its place, so trying to do meeting._id is undefined.
In fact, what is the purpose of the findMeetings function? It's name indicates it can either find all meetings in the database, or all meetings with a specific id. You're calling it without a meeting id indicating you might be trying to find all meetings, but its implementation takes a meeting object. You need to clear that up first.

Use TripleSec encryption with Node.js Socket.io Chat

I am new to Node.js and I've created a simple chat application using Socket.io. I am trying to encrypt the messages using the triplesec library but I am having some issues. What would be the best approach to add this encryption/decryption:
var triplesec = require('triplesec');
// Encrypt Function
triplesec.encrypt({
key: new triplesec.Buffer('secretkey'),
data: new triplesec.Buffer('secretthings'),
}, function (err, buff) {
if(!err) {
var ciphertext = buff.toString('hex')
console.log(buff.toString('hex'))
}
// Decrypt Function
triplesec.decrypt({
data: new triplesec.Buffer(ciphertext, "hex"),
key: new triplesec.Buffer('secretkey')
}, function (err, buff) {
if(!err) {
console.log(buff.toString());
}
});
});
To this client: (All encryption on the messages coming in and going out will be handled client side, assuming this is the best approach?)
// imports
var readline = require('readline');
var socketio = require('socket.io-client');
var util = require('util');
var clc = require("cli-color");
var async = require("async");
// globals
var nick;
var serverAddress;
var serverPort;
var socket;
var rl = readline.createInterface(process.stdin, process.stdout);
// message types
var chat = clc.green;
var pm = clc.yellow;
var notice = clc.cyan;
var emote = clc.blue;
var error = clc.red;
// function definitions
function consoleOut (msg) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
console.log(msg);
rl.prompt(true);
}
// handle a command that the user has entered
function handleCommand (commandType, arg) {
switch (commandType) {
case 'nick': // set the nickname and send a message with the updated nickname
var notice = nick + " changed their name to " + arg;
nick = arg;
socket.emit('send', { type: 'notice', message: notice });
break;
case 'pm': // private message another user
var to = arg.match(/[a-z]+\b/)[0];
var message = arg.substr(to.length, arg.length);
socket.emit('send', { type: 'pm', message: message, to: to, from: nick });
break;
case 'me': // the user performs some emote
var emote = nick + " " + arg;
socket.emit('send', { type: 'emote', message: emote });
break;
default: // invalid command type
consoleOut(error("That is not a valid command."));
}
}
// start of execution
async.series([
function(callback) {
// get the address
rl.question("Please enter the address of the server, such as 192.168.0.10: ", function(address) {
serverAddress = address;
callback();
});
},
function(callback) {
// get the port
rl.question("Please enter the port the server is listening on, such as 8080: ", function(port) {
serverPort = port;
socket = socketio.connect('http://' + serverAddress + ':' + serverPort);
// register the sockets on message event handler
socket.on('message', function (data) {
var leader;
// process message, these are pretty self explainitory
if (data.type == 'chat' && data.nick != nick) {
leader = chat("<" + data.nick + "> ");
consoleOut(leader + data.message);
}
else if (data.type == "notice") {
consoleOut(notice(data.message));
}
else if (data.type == "pm" && data.to == nick) {
leader = pm("["+data.from+"->"+data.to+"]");
consoleOut(leader + data.message);
}
else if (data.type == "emote") {
consoleOut(emote(data.message));
}
});
callback();
});
},
function(callback) {
// get the users nickname
rl.question("Please enter a nickname: ", function(name) {
nick = name;
var msg = nick + " has joined the chat";
socket.emit('send', { type: 'notice', message: msg });
rl.prompt(true);
callback();
});
}
]);
// called when the user hits enter on the command line
// parses what ever they typed into either a command or a chat message
rl.on('line', function (line) {
if (line[0] == "/" && line.length > 1) {
var cmd = line.match(/[a-z]+\b/)[0];
var arg = line.substr(cmd.length+2, line.length);
handleCommand(cmd, arg);
rl.prompt(true);
} else {
// send chat message
socket.emit('send', { type: 'chat', message: line, nick: nick });
rl.prompt(true);
}
});

Categories

Resources