I have this form in my client.html file
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<link rel="stylesheet" type="text/css" href="/css/client.css">
</head>
<body>
<div class="wrapper">
<div class="chatBox">
<div class="chatBoxHead">Chat with Support</div>
<div class="contentArea" style="display: none">
<div class="formArea">
<div class="title">Please fill out this form</div>
<form class="loginForm" id="loginForm">
<div class="inputContainer">
<label for="name"></label>
<input class="nameInput" type="text" placeholder=" * Name" name="name" id="name" required />
</div>
<div class="inputContainer">
<label for="email"></label>
<input class="emailInput" name="email" id="email" type="email" placeholder=" * Email" required />
</div>
<button class="submit" >Submit</button>
</form>
</div>
<div class="chatArea" style="display: none">
<div class="messages">
<div class="oldMsg"></div>
<div class="newMsg"></div>
</div>
<div class='typing'></div>
<input class="inputMessage" rows="1" placeholder="Type here..."></input>
</div>
</div>
</div>
</div>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="../js/client.js"></script>
</body>
</html>
when I click on the submit button for the login form, it saves the data to the database and then reloads itself as opposed to saving the data and then displaying the chat area for messaging. Here is my client.js file
var $window = $(window);
var socket = io();
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $nameInput = $('.nameInput');
var $emailInput = $('.emailInput');
var $formArea = $('.formArea');
var $contentArea = $('.contentArea');
var $login = $('#loginForm');
var $chatArea = $('.chatArea');
var $typing = $(".typing");
var $oldMsg = $('.oldMsg');
var $newMsg = $('.newMsg');
var typing = false;
var timeout = undefined;
var id = localStorage.getItem("roomID");
var active = sessionStorage.getItem('active');
if (active && id) {
$formArea.hide();
$chatArea.show();
socket.emit('add user', {
isNewUser: false,
roomID: id
});
$contentArea.show();
}
$('.chatBoxHead').click(function() {
$contentArea.slideToggle('slow');
if (id != null && !active) {
socket.emit('add user', {
isNewUser: false,
roomID: id
});
$formArea.hide();
$chatArea.show();
$inputMessage.focus();
sessionStorage.setItem('active', true);
active = true;
}
});
$login.submit(function() {
$chatArea.show();
$formArea.hide();
$inputMessage.focus();
sessionStorage.setItem('active', true);
socket.emit('add user', {
isNewUser: true,
Name: $nameInput.val().trim(),
Email: $emailInput.val().trim()
});
});
$inputMessage.keypress(function(event) {
if (event.which !== 13) {
if (typing === false && $inputMessage.is(":focus")) {
typing = true;
socket.emit("typing", {
isTyping: true,
roomID: id,
person: "Client"
});
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 2000);
}
} else {
sendMessage();
clearTimeout(timeout);
timeoutFunction();
}
})
socket.on('chat message', function(data) {
var sender;
if (data.isAdmin){
sender = "msg_admin"
}
else{
sender = "msg_client"
}
var $messageBodyDiv = $('<div class="' + sender + '">' + data.message + '<span class="timestamp">' +
((data.timestamp).toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
});
function sendMessage() {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
var encodedMessage = $('<div />').text(message).html();
message = encodedMessage;
if (message) {
$inputMessage.val('');
var time = ("" + new Date().getTime());
socket.emit('chat message', {
roomID: "null",
message: message,
timestamp: time
});
var $messageBodyDiv = $('<div class="msg_client">' + message + '<span class="timestamp">' +
(time.toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
}
}
function timeoutFunction() {
typing = false;
socket.emit("typing", {
isTyping: false,
roomID: id,
person: "Client"
});
}
$messages.on("scroll", function() {
if ($messages.scrollTop() == 0)
socket.emit("more messages", {});
})
socket.on('roomID', function(roomID) {
id = roomID;
localStorage.setItem("roomID", roomID);
});
socket.on('typing', function(data) {
if (data.isTyping && data.person != 'Client')
$Typing.append("Support is typing...");
else
$Typing.text('');
});
socket.on('chat history', function(data) {
var len = data.history.length;
for (var i = len - 1; i >= 0; i--)
addMessages(data.history[i], false);
});
socket.on('more chat history', function(data) {
var len = data.history.length;
for (var i = 0; i < len; i++)
addMessages(data.history[i], true);
});
function addMessages(data, getMore) {
var sender;
if (data["who"]){
sender = "msg_admin"
}
else{
sender = "msg_client"
}
var $messageBodyDiv = $('<div class="' + sender + '">' + data["message"] + '<span class="timestamp">' +
(data["timeStamp"]).toLocaleString().substr(15, 6) + '</span></div>');
if (getMore) {
$messageBodyDiv.insertAfter($oldMsg);
$messages[0].scrollTop += $messageBodyDiv.outerHeight();
} else {
$messageBodyDiv.insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
}
}
socket.on('log message', function(text) {
var time = ("" + new Date().getTime());
var $messageDiv = $('<div class="msg_admin">' + text + '<span class="timestamp">' +
(time.toLocaleString().substr(15, 6)) + '</span></div>').insertBefore($newMsg);
$messages[0].scrollTop = $messages[0].scrollHeight;
});
socket.on('disconnect', function() {
console.log("Disconnected!");
$inputMessage.prop('disabled', true);
$inputMessage.prop('placeholder', "Connection Lost! Reconnecting..");
});
socket.on('reconnect_failed', function() {
console.log("Reconnection Failed!");
$inputMessage.prop('placeholder', "No active connection. Please refresh page.");
});
socket.on('reconnect', function() {
setTimeout(function() {
console.log("Reconnected!");
$inputMessage.prop('disabled', false);
$inputMessage.prop('placeholder', "Type here...");
if (active && id)
socket.emit('add user', {
isNewUser: false,
roomID: id
});
}, 10000);
});
Also here is my app.js file
var express = require('express');
var app = express();
var fs = require('fs');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var uuid = require('uuid');
var config = require(__dirname + "/config.js");
var r = require('rethinkdb');
var _ = require("underscore");
var db = require('./controllers/db');
var btoa = require('btoa');
var users = {};
var admins = {};
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(require("express-session")({
secret: "luxtag chat",
resave: false,
saveUninitialized: false
}));
// Setup rethinkDB database
db.setupDB();
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/client.html');
});
app.get(config.rethinkdb.admin_url, function(req, res) {
res.sendFile(__dirname + '/views/admin.html');
});
io.on('connection', function(socket){
console.log(`Socket ID: ${socket.id}`);
console.dir(socket.handshake, {colors: true});
//Admin login
socket.on('login', function(data) {
if (btoa(data.password) != config.rethinkdb.key)
socket.emit('login', {
login: false,
err: "Invalid Login"
})
else {
if (_.find(config.rethinkdb.admin_users, function(admin) {
return (admin == data.admin);
})) {
if (admins[data.admin]) {
socket.emit('login', {
login: false,
err: "Already Logged In"
})
} else {
socket.emit('login', {
login: true
})
}
} else {
socket.emit('login', {
login: false,
err: "Invalid Login"
})
}
}
});
socket.on('add admin', function(data) {
this.isAdmin = data.isAdmin;
socket.username = data.admin;
console.log('admins: ', admins);
console.log('users: ', users);
_.each(admins, function(adminSocket) {
adminSocket.emit("admin added", socket.username)
socket.emit("admin added", adminSocket.username)
});
admins[socket.username] = socket;
//If some user is already online on chat
if (Object.keys(users).length > 0) {
_.each(users, function(userSocket) {
db.getMessages(userSocket.roomID, 0)
.then(function(history) {
var len = history.length;
var userSocket = users[history[len - 1]];
history.splice(-1, 1);
socket.join(userSocket.roomID);
socket.emit("New Client", {
roomID: userSocket.roomID,
history: history,
details: userSocket.userDetails,
justJoined: true
})
})
});
}
});
socket.on('add user', function(data) {
socket.isAdmin = false;
if (data.isNewUser) {
data.roomID = uuid.v4();
var user = {
id: data.roomID,
name: data.Name,
email: data.Email
}
console.log(user);
db.saveUser(user, function (saved, err) {
if (saved) {
console.log('user saved...');
return;
}
if (err) {
console.log('There was an error creating the account');
}
else {
console.log("The account wasn't created");
}
});
socket.emit("roomID", data.roomID);
}
socket.roomID = data.roomID;
console.log('socket.roomID: ', socket.roomID);
//get user
db.findUserById(socket.roomID, function(err, details) {
if(err){
console.log("Line 60 : ", error);
}
else {
socket.userDetails = details;
console.log('socket.userDetails: ', socket.userDetails);
}
});
socket.join(socket.roomID);
var newUser = false;
if (!users[socket.roomID]) {
users[socket.roomID] = socket;
newUser = true;
}
//get message history
db.getMessages(socket.roomID, 0)
.then(function(history) {
history.splice(-1, 1)
socket.emit('chat history', {
history: history,
getMore: false
});
if (Object.keys(admins).length == 0) {
//Tell user he will be contacted asap
socket.emit('log message', "Thank you for reaching us." +
" Please leave your message here and we will get back to you shortly.");
} else {
if (newUser) {
socket.emit('log message', "Hello " + socket.userDetails['name'] + ", How can I help you?");
//Make all available admins join this users room.
_.each(admins, function(adminSocket) {
adminSocket.join(socket.roomID);
adminSocket.emit("New Client", {
roomID: socket.roomID,
history: history,
details: socket.userDetails,
justJoined: false
})
});
}
}
})
.catch(function(error) {
console.log("Line 113 : ", error)
})
.done();
db.getMsgLength(socket.roomID)
.then(function(len) {
socket.MsgHistoryLen = (len * -1) + 10;
socket.TotalMsgLen = (len * -1);
})
.catch(function(error) {
console.log("Line 121 : ", error)
})
.done();
});
socket.on('chat message', function(data){
if (data.roomID === "null"){
data.roomID = socket.roomID;
}
data.isAdmin = socket.isAdmin;
var msg = {
who: data.isAdmin,
message: data.message,
timestamp: data.timestamp
}
db.saveMessage(msg, function (err, saved) {
if (err || !saved) {
console.log('There was an error saving your message');
return;
}
socket.broadcast.to(data.roomID).emit('chat message', data);
});
});
socket.on("typing", function(data) {
socket.broadcast.to(data.roomID).emit("typing", {
isTyping: data.isTyping,
person: data.person,
roomID: data.roomID
});
});
socket.on("more messages", function() {
if (socket.MsgHistoryLen < 0) {
db.getMessages(socket.roomID, socket.MsgHistoryLen)
.then(function(history) {
history.splice(-1, 1)
socket.emit('more chat history', {
history: history
});
})
socket.MsgHistoryLen += 10;
}
});
socket.on('disconnect', function() {
if (socket.isAdmin) {
delete admins[socket.username];
_.each(admins, function(adminSocket) {
adminSocket.emit("admin removed", socket.username)
});
} else {
if (io.sockets.adapter.rooms[socket.roomID]) {
var total = io.sockets.adapter.rooms[socket.roomID]["length"];
var totAdmins = Object.keys(admins).length;
var clients = total - totAdmins;
if (clients == 0) {
//check if user reconnects in 10 seconds
setTimeout(function() {
if (io.sockets.adapter.rooms[socket.roomID]){
total = io.sockets.adapter.rooms[socket.roomID]["length"];
}
totAdmins = Object.keys(admins).length;
if (total <= totAdmins) {
delete users[socket.roomID];
socket.broadcast.to(socket.roomID).emit("User Disconnected", socket.roomID);
_.each(admins, function(adminSocket) {
adminSocket.leave(socket.roomID)
});
}
}, 10000);
}
} else {
if (socket.userDetails)
delete users[socket.roomID];
}
}
});
});
http.listen(config.express.port, function(){
console.log('listening on *:' + config.express.port);
});
any help would be greatly appreciated.
Setup a submit function in your js that does the POST request to the server and prevent the default behavior. jQuery example:
$( "#target" ).submit(function( event ) {
event.preventDefault();
// Do post request here
});
I supposing, you get a success promise after data stored in database successfully.
You need to prevent automatic form submission. Look out below code.
<!DOCTYPE html>
<html>
<body>
<form onsubmit="return toSubmit();">
First name:<br>
<input id="name" type="text" name="firstname" >
<br>
Last name:<br>
<input type="text" name="lastname" >
<br><br>
<button type="submit" >Submit</button>
</form>
<script>
function toSubmit(){
if(document.getElementById('name').value == "tushar"){
alert("success");
return true;
}
else{
alert("failed");
return false;
}
}
</script>
</body>
</html>
Related
In express-ntlm package i have added password attribute but i'm not able to get its value while i provide in private window of chrome. I always getting empty value.
My code is:
/* jshint node:true */
// node.js modules
var url = require('url');
// 3rd-party modules
var _ = require('underscore'),
async = require('async');
// Custom modules
var Cache = require('./Cache'),
NTLM_AD_Proxy = require('./NTLM_AD_Proxy'),
NTLM_No_Proxy = require('./NTLM_No_Proxy'),
utils = require('./utils');
const { Domain } = require('domain');
// Globals
var cache = new Cache();
module.exports = function(options) {
// Overwrite the default options by the user-defined
options = _.extend({
badrequest: function(request, response, next) {
response.sendStatus(400);
},
internalservererror: function(request, response, next) {
response.sendStatus(500);
},
forbidden: function(request, response, next) {
response.sendStatus(403);
},
unauthorized: function(request, response, next) {
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM');
response.end();
},
prefix: '[express-ntlm]',
debug: function() {
},
domaincontroller: null,
getConnectionId(request, response) {
return utils.uuidv4();
}
}, options);
function ntlm_message_type(msg) {
if (msg.toString('utf8', 0, 8) != 'NTLMSSP\0') {
return new Error('Not a valid NTLM message:', msg.toString('hex'));
}
var msg_type = msg.readUInt8(8);
if (!~[1, 2, 3].indexOf(msg_type)) {
return new Error('Incorrect NTLM message Type', msg_type);
}
return msg_type;
}
function parse_ntlm_authenticate(msg) {
var DomainNameLen = msg.readUInt16LE(0x1C),
DomainNameBufferOffset = msg.readUInt32LE(0x20),
DomainName = msg.slice(DomainNameBufferOffset, DomainNameBufferOffset + DomainNameLen),
UserNameLen = msg.readUInt16LE(0x24),
UserNameBufferOffset = msg.readUInt32LE(0x28),
UserName = msg.slice(UserNameBufferOffset, UserNameBufferOffset + UserNameLen),
PasswordLen = msg.readUInt16LE(0x34),
PasswordBufferOffset = msg.readUInt32LE(0x38),
Password = msg.slice(PasswordBufferOffset, PasswordBufferOffset + PasswordLen),
WorkstationLen = msg.readUInt16LE(0x2C),
WorkstationBufferOffset = msg.readUInt32LE(0x30),
Workstation = msg.slice(WorkstationBufferOffset, WorkstationBufferOffset + WorkstationLen);
if (utils.isFlagSet(msg.readUInt8(0x3C), utils.toBinary('00000001'))) {
DomainName = DomainName.toString('utf16le');
UserName = UserName.toString('utf16le');
Password = Password.toString('utf16le');
Workstation = Workstation.toString('utf16le');
} else {
DomainName = DomainName.toString();
UserName = UserName.toString();
Password = Password.toString();
Workstation = Workstation.toString();
}
return [UserName, Password, DomainName, Workstation];
}
function decode_http_authorization_header(auth) {
var ah = auth.split(' ');
if (ah.length === 2) {
if (ah[0] === 'NTLM') {
return ['NTLM', new Buffer(ah[1], 'base64')];
}
}
return false;
}
function connect_to_proxy(type1, callback) {
var domain = options.domain;
var proxy,
ntlm_challenge;
async.eachSeries(!options.domaincontroller ? [ -1 ] : typeof options.domaincontroller === 'string' ? [ options.domaincontroller ] : options.domaincontroller, function(server, eachDomaincontrollerCallback) {
if (!server || ntlm_challenge) return eachDomaincontrollerCallback();
if (server === -1) {
options.debug(options.prefix, 'No domaincontroller was specified, all Authentication messages are valid.');
proxy = new NTLM_No_Proxy();
} else if (!server.indexOf('ldap')) {
var serverurl = url.parse(server),
use_tls = serverurl.protocol === 'ldaps:',
decoded_path = decodeURI(serverurl.path);
options.debug(options.prefix, 'Initiating connection to Active Directory server ' + serverurl.host + ' (domain ' + domain + ') using base DN "' + decoded_path + '".');
proxy = new NTLM_AD_Proxy(serverurl.hostname, serverurl.port, domain, decoded_path, use_tls, options.tlsOptions);
} else {
return eachDomaincontrollerCallback(new Error('Domaincontroller must be an AD and start with ldap://'));
}
proxy.negotiate(type1, function(error, challenge) {
if (error) {
proxy.close();
proxy = null;
options.debug(options.prefix, error);
return eachDomaincontrollerCallback();
}
ntlm_challenge = challenge;
return eachDomaincontrollerCallback();
});
}, function(error) {
if (error) return callback(error);
if (!proxy) {
return callback(new Error('None of the Domain Controllers are available.'));
}
return callback(null, proxy, ntlm_challenge);
});
}
function handle_type1(request, response, next, ntlm_message, callback) {
cache.remove(request.connection.id);
cache.clean();
connect_to_proxy(ntlm_message, function(error, proxy, challenge) {
if (error) return callback(error);
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM ' + challenge.toString('base64'));
response.end();
cache.add(request.connection.id, proxy);
return callback();
});
}
function handle_type3(request, response, next, ntlm_message, callback) {
var proxy = cache.get_proxy(request.connection.id);
var userDomainWorkstation = parse_ntlm_authenticate(ntlm_message),
user = userDomainWorkstation[0],
pass = userDomainWorkstation[1],
domain = userDomainWorkstation[2],
workstation = userDomainWorkstation[3];
if (!domain) {
domain = options.domain;
}
proxy.authenticate(ntlm_message, function(error, result) {
if (error) return callback(error);
var userData = {
DomainName: domain,
UserName: user,
Password: pass,
Workstation: workstation,
Authenticated: false
};
request.ntlm = userData;
response.locals.ntlm = userData;
request.connection.ntlm = userData;
if (!result) {
cache.remove(request.connection.id);
options.debug(options.prefix, 'User ' + domain + '/' + user + ' authentication for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.forbidden(request, response, next);
} else {
userData.Authenticated = true;
return next();
}
});
}
return function(request, response, next) {
if (!request.connection.id) {
request.connection.id = options.getConnectionId(request, response);
}
var auth_headers = request.headers.authorization;
var user = request.connection.ntlm;
if (user && user.Authenticated) {
options.debug(options.prefix, 'Connection already authenticated ' + user.DomainName + '/' + user.UserName);
if (auth_headers) {
if (request.method != 'POST') {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
} else {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
}
if (!auth_headers) {
options.debug(options.prefix, 'No Authorization header present');
return options.unauthorized(request, response, next);
}
var ah_data = decode_http_authorization_header(auth_headers);
if (!ah_data) {
options.debug(options.prefix, 'Error when parsing Authorization header for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.badrequest(request, response, next);
}
var ntlm_version = ntlm_message_type(ah_data[1]);
if (ntlm_version instanceof Error) {
options.debug(options.prefix, ntlm_version.stack);
return options.badrequest(request, response, next);
}
if (ntlm_version === 1) {
return handle_type1(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
if (ntlm_version === 3) {
if (cache.get_proxy(request.connection.id) !== null) {
return handle_type3(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
options.debug(options.prefix, 'Unexpected NTLM message Type 3 in new connection for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.internalservererror(request, response, next);
}
options.debug(options.prefix, 'Type 2 message in client request');
return options.badrequest(request, response, next);
};
};
my response is
{"DomainName":"ijk","UserName":"xyz","Password":"","Workstation":"some","Authenticated":true}
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);
});
I have the below JavaScript code to develop an app in Fuse Tools. There is one last error that I cannot seem to understand and that is that my variable b64data should be a global variable and is not updating it's value from the capturePhoto function and letting me send the updated value in the submitPhoto function to the server. It should send the base64 encoded value as the picture variable in my POST function. Any help is appreciated!
var Observable = require("FuseJS/Observable");
let ImageTools = require("FuseJS/ImageTools");
var FileSystem = require("FuseJS/FileSystem");
var Base64 = require("FuseJS/Base64");
var Camera = _camera;
var b64data;
var captureMode = Observable();
var flashMode = Observable();
function getCameraInfo() {
Camera.getCameraInfo()
.then(function(info) {
console.log("captureMode: " + info[Camera.INFO_CAPTURE_MODE]);
console.log("flashMode: " + info[Camera.INFO_FLASH_MODE]);
console.log("cameraFacing: " + info[Camera.INFO_CAMERA_FACING]);
console.log("supportedFlashModes: " + info[Camera.INFO_SUPPORTED_FLASH_MODES].join());
captureMode.value = info[Camera.INFO_CAPTURE_MODE];
flashMode.value = info[Camera.INFO_FLASH_MODE];
if (Camera.INFO_PHOTO_RESOLUTIONS in info) {
var availableResolutions = info[Camera.INFO_PHOTO_RESOLUTIONS];
availableResolutions.forEach(function(e) {
console.log(e.width + "x" + e.height);
});
photoResolution = availableResolutions[Math.floor(availableResolutions.length * 0.4)];
var options = {};
options[Camera.OPTION_PHOTO_RESOLUTION] = photoResolution;
Camera.setPhotoOptions(options)
.then(function() {
console.log("New photo options set: " + JSON.stringify(options));
})
.catch(function(error) {
console.log("Failed to set photo options: " + error);
});
}
})
.catch(function(err) {
console.log("Failed to get camera info: " + err);
});
}
getCameraInfo();
function nextFlashMode() {
if (flashMode.value == Camera.FLASH_MODE_AUTO) return Camera.FLASH_MODE_ON;
else if (flashMode.value == Camera.FLASH_MODE_ON) return Camera.FLASH_MODE_OFF;
else if (flashMode.value == Camera.FLASH_MODE_OFF) return Camera.FLASH_MODE_AUTO;
else throw "Invalid flash mode";
}
function setCaptureMode(cm) {
Camera.setCaptureMode(cm)
.then(function(mode) {
captureMode.value = mode;
console.log("Capture mode set to: " + mode);
})
.catch(function(err) {
console.log("Failed to set capture mode: " + err);
});
}
function capturePhoto() {
Camera.capturePhoto()
.then(function (photo) {
photo.save()
.then(function(filePath) {
console.log("Photo saved to: " + filePath);
var arrayBuff = FileSystem.readBufferFromFileSync(filePath);
var b64data = Base64.encodeBuffer(arrayBuff); // send this to the backend
photo.release();
})
.catch(function(error) {
console.log("Failed to save photo: " + error);
photo.release();
});
})
.catch(function (error) {
console.log("Failed to capture photo: " + error);
});
}
var isRecording = Observable(false);
var recordingSession = null;
function startRecording() {
isRecording.value = true;
Camera.startRecording()
.then(function (session) {
recordingSession = session;
})
.catch(function (error) {
console.log("Failed to start recording: " + error);
isRecording.value = false;
});
}
function stopRecording() {
isRecording.value = false;
recordingSession.stop()
.then(function (recording) {
router.push("VideoPage", recording.filePath());
})
.catch(function (error) {
console.log("Failed to stop recording: " + error);
});
recordingSession = null;
}
var cameraBack = true;
function flipCameraFacing() {
var front = Camera.CAMERA_FACING_FRONT;
var back = Camera.CAMERA_FACING_BACK;
Camera.setCameraFacing(cameraBack ? front : back)
.then(function (newFacing) {
cameraBack = newFacing == back;
getCameraInfo();
console.log("Camera facing set to: " + (newFacing == back ? "back" : "front"));
})
.catch(function (err) {
console.log("Failed to set camera facing: " + err);
});
}
function changeFlashMode() {
Camera.setFlashMode(nextFlashMode())
.then(function(newFlashMode) {
flashMode.value = newFlashMode;
console.log("Flash mode set to: " + flashMode.value);
})
.catch(function(err) {
console.log("Failed to set flash mode: " + err);
});
}
var name = Observable();
var email = Observable();
var market = Observable();
module.exports = {
name: name,
email: email,
market: market,
b64data: b64data,
submitPhoto: submitPhoto,
captureMode: captureMode,
setCaptureModePhoto: function () { setCaptureMode(Camera.CAPTURE_MODE_PHOTO); },
setCaptureModeVideo: function () { setCaptureMode(Camera.CAPTURE_MODE_VIDEO); },
capturePhoto: capturePhoto,
startRecording: startRecording,
stopRecording: stopRecording,
isRecording: isRecording,
flipCameraFacing: flipCameraFacing,
flashMode: flashMode,
changeFlashMode: changeFlashMode,
}
function submitPhoto(){
console.log("name: "+name);
console.log("email: "+email);
console.log("market: "+market);
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
May be because of you are declaring b64data again in capturePhoto function on line 72 in your shared code.
try
b64data = ...
instead of
var b64data = ...
I am using Angular JS for my Front End and Express Server for backend.
I am trying to remove the init.html from my url.
I have read other post and I have not managed to fix it.
Now : http://localhost:3000/init.html#!/export
I want look like : http://localhost:3000/#!/export
I tried : $locationProvider.hashPrefix() and
locationProvider.html5Mode(true) but it is not working.
manager-app.js
angular.module("ManagerApp", ["angularUtils.directives.dirPagination", "ngRoute"]).config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/index.html"
})
.when("/export", {
templateUrl: "export/listExport.html",
controller: "ListCtrlExport"
});
index.html is a static html
init.html
<html ng-app="ManagerApp">
<head>
<title>
ManagerApp
</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css" type="text/css" />
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="/bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="/bower_components/angularUtils-pagination/dirPagination.js"></script>
<script type="text/javascript" src="/bower_components/bootbox.js/bootbox.js"></script>
<script type="text/javascript" src="/manager-app.js"></script>
<script type="text/javascript" src="/export/list-ctrl.js"></script>
<script type="text/javascript" src="/export/edit-ctrl.js"></script>
</head>
<body>
<ng-view></ng-view>
</header>
</body>
</html>
index.js
var express = require("express");
var bodyParser = require("body-parser");;
var helmet = require("helmet");
var path = require('path');
var app = express();
var folder = path.join(__dirname, '/public');
var MongoClient = require('mongodb').MongoClient;
var mURL = "mongodb://XXXXXXXXXXXXXXXXXxXXXXXXXX";
var port = (process.env.PORT || 10000);
var BASE_API_PATH = "/api/v2";
var moduleExport = require("./api/v2/exportModule.js");
var dbAlberto;
var dbUser;
app.use("/", express.static(path.join(__dirname, "public")));
app.use(bodyParser.json()); //use default json enconding/decoding
app.use(helmet()); //improve security
app.use("/",express.static(path.join(__dirname, 'public')));
app.use("/api/v2/tests", express.static(path.join(__dirname , "public/test.html")));
MongoClient.connect(mURL, {
native_parser: true
}, function(err, database) {
if (err) {
console.log("CANNOT connect to database" + err);
process.exit(1);
}
dbAlberto = database.collection("exports");
dbUser = database.collection("user");
moduleExport.register(app, dbAlberto, dbUser, BASE_API_PATH);
app.listen(port, () => {
console.log("Magic is happening on port " + port);
});
});
exportModule
var exports = module.exports = {};
exports.register = function(app, dbAlberto, dbUser, BASE_API_PATH) {
// Authentication apikey
var key = function(request, callback) {
var d;
dbUser.find({
apikey: request
}).toArray(function(err, sExport) {
if (sExport.length > 0) {
d = 1;
}
else {
d = 0;
}
callback(d);
});
}
function searchFrom(sExport,from,to){
var from = parseInt(from);
var to = parseInt(to);
var res=[];
sExport.forEach((filt)=>{
if(filt.year>=from && filt.year<=to){
res.push(filt);
}
});
return res;
// GET a collection and Search
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
var url = request.query;
var province = url.province;
var year = url.year;
var importS = url.importS;
var exportS = url.exportS;
var off = 0;
var limite = 100;
var res = request.query.apikey;
var from = url.from;
var to = url.to;
var resul = key(res, function(d) {
if (d > 0) {
if (url.limit != undefined) {
limite = parseInt(url.limit);
off = parseInt(url.offset);
}
if (from != undefined && to != undefined) {
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
var filted=searchFrom(sExport,from,to);
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
else {
dbAlberto.find({}).skip(off).limit(limite).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var filted = sExport.filter((stat) => {
if ((province == undefined || stat.province == province) && (year == undefined || stat.year == year) && (year == undefined || stat.year == year) && (importS == undefined || stat.importS == importS) && (exportS == undefined || stat.exportS == exportS)) {
return stat;
}
});
if (filted.length > 0) {
console.log("INFO: Sending stat: " + JSON.stringify(filted, 2, null));
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
// LoadInitialData
app.get(BASE_API_PATH + "/export-and-import/loadInitialData", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
dbAlberto.find({}).toArray(function(err, stats) {
if (err) {
console.error('WARNING: Error while getting initial data from DB');
return 0;
}
if (stats.length === 0) {
var initialStats = [{
"province": "jaen",
"year": "2013",
"oil": "375",
"importS": "802",
"exportS": "274"
}];
dbAlberto.insert(initialStats);
console.log("Date insert in db");
response.sendStatus(201, BASE_API_PATH + "/");
}
else {
console.log('INFO: DB has ' + stats.length + ' objects ');
response.sendStatus(200);
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
/*
// GET a collection
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
console.log("INFO: New GET request to /export-and-import");
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
console.log("INFO: Sending export and import stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
});
});
*/
// GET a single resource
app.get(BASE_API_PATH + "/export-and-import/:province", function(request, response) {
var province = request.params.province;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import-stats/" + province);
dbAlberto.find({
province: province
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//GET all stats of one year
app.get(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import/ without province, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import/" + province);
dbAlberto.find({
province: province,
year: year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province + " and " + year);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a collection
app.post(BASE_API_PATH + "/export-and-import", function(request, response) {
var newStats = request.body;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!newStats) {
console.log("WARNING: New POST request to /export-and-import without stats, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New POST request to /export-and-import with body: " + JSON.stringify(newStats, 2, null));
if (!newStats.province || !newStats.year || !newStats.oil || !newStats.importS || !newStats.exportS) {
console.log("WARNING: The stat " + JSON.stringify(newStats, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: newStats.province,
year: newStats.year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var sExportBefore = sExport.filter((result) => {
return (result.province.localeCompare(newStats.province, "en", {
'sensitivity': 'base'
}) === 0);
});
if (sExportBefore.length > 0) {
console.log("WARNING: The contact " + JSON.stringify(newStats, 2, null) + " already extis, sending 409...");
response.sendStatus(409); // conflict
}
else {
console.log("INFO: Adding contact " + JSON.stringify(newStats, 2, null));
dbAlberto.insert(newStats);
response.sendStatus(201); // created
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a single resource
app.post(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New POST request to /export-and-import-stats/" + province + " and " + year + ", sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a collection
app.put(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New PUT request to /export-and-import-stats, sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a single resource
app.put(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var updateExp = request.body;
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!updateExp) {
console.log("WARNING: New PUT request to /export-and-import-stats/ without contact, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New PUT request to /export-and-import-stats/" + province + " with data " + JSON.stringify(updateExp, 2, null));
if (!updateExp.province || !updateExp.year || !updateExp.oil || !updateExp.importS || !updateExp.exportS || updateExp.province !== province || updateExp.year !== year) {
console.log("WARNING: The contact " + JSON.stringify(updateExp, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: province,
$and: [{
year: year
}]
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
dbAlberto.update({
province: province,
year: year
}, updateExp);
console.log("INFO: Modifying contact with name " + province + " with data " + JSON.stringify(updateExp, 2, null));
response.send(updateExp); // return the updated contact
}
else {
console.log("WARNING: There are not any stats with provinc " + province);
response.sendStatus(404); // not found
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a collection
app.delete(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("INFO: New DELETE request to /export-and-import-stats");
dbAlberto.remove({}, {
multi: true
}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: Remove: " + n + " stats, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a single resource
app.delete(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province || !year) {
console.log("WARNING: New DELETE request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New DELETE request to /export-and-import-stats/" + province + " and " + year);
dbAlberto.remove({
province: province,
year: year
}, {}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: The stat with name " + province + " and year " + year + " has been succesfully deleted, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
}
Thanks in advance !
i need remove socket from server after execute socket.disconnect()
users = {}
ids_disconnect = []
io.of('/example')
.on('connection', function (socket) {
var user_id = socket.decoded_token.user;
if(users[user_id] === undefined){
users[user_id] = {"socket": socket};
} else {
ids_disconnect.push(users[user_id].socket.id);
users[user_id].socket.disconnect(true);
users[user_id] = {"socket": socket};
}
console.log("User Connect: " + user_id + " SocketID: " + socket.id);
//disconnect client
socket.on('disconnect', function () {
console.log('User Disconnect ' + user_id);
if(ids_disconnect.indexOf(socket.id) != -1){
console.log('Disconnect Force: ' + user_id );
ids_disconnect.splice(ids_disconnect.indexOf(socket.id),1)
} else {
delete users[user_id];
}
});
});
};
this my code but socket cant remove from server.
sorry for my english
You have to listen to the disconnect event before triggering it.
users = {}
ids_disconnect = []
io.of('/example')
.on('connection', function(socket) {
var user_id = socket.decoded_token.user;
//disconnect client
socket.on('disconnect', function() {
console.log('User Disconnect ' + user_id);
if (ids_disconnect.indexOf(socket.id) != -1) {
console.log('Disconnect Force: ' + user_id);
ids_disconnect.splice(ids_disconnect.indexOf(socket.id), 1)
} else {
delete users[user_id];
}
});
if (users[user_id] === undefined) {
users[user_id] = {
"socket": socket
};
} else {
ids_disconnect.push(users[user_id].socket.id);
users[user_id].socket.disconnect(true);
users[user_id] = {
"socket": socket
};
}
console.log("User Connect: " + user_id + " SocketID: " + socket.id);
});
};