JS Gist
o.sockets.on('connection', function (socket) {
socket.on('leave route', function (room_id) {
socket.broadcast.to(room_id).emit('leave route', info.id);
util.log('123');
});
rq({
uri: config.Services.MobileService.Url + 'user/me',
method: "GET",
headers: {
XAuthToken: socket.handshake.query.XAuthToken
}
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var userModel = JSON.parse(body);
var user = {};
var room_id = false;
if (socket.handshake.query.UserID) {
sendChat = function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
var flag = 0;
for (var __room in rooms) {
_room = rooms[__room];
if (_room.id == info.id && flag == 0) {
room_id = _room.id;
flag = 1;
}
}
if (flag == 0) {
var room = {};
room.id = room_id = info.id;
room.users = {};
for (var member in info.members) {
room.users[info.members[member].userId] = info.members[member];
users[info.members[member].userId] = info.members[member];
}
rooms[info.id] = room;
}
} else {
console.log(error);
console.log(body);
}
socket.join(room_id);
};
rq({
uri: config.Services.MobileService.Url + 'chat',
method: "POST",
form: {
fromUserId: userModel.id,
toUsers: [socket.handshake.query.UserID]
}
}, sendChat);
}
socket.on('user message', function (msg) {
util.log(room_id + " " + msg);
if (room_id) {
msg = sanitize.toString(msg);
socket.broadcast.to(room_id).emit('user message', {
timestamp: 1453362268,
user_id: userModel.id,
message: msg
});
saveToDatabase(userModel.id, msg);
}
});
function saveToDatabase(fromUserId, msg) {
rq({
uri: config.Services.MobileService.Url + 'messages/' + socket.handshake.query.UserID,
method: "POST",
headers: {
XAuthToken: socket.handshake.query.XAuthToken
},
form: {
message: msg,
userId: fromUserId
}
}, function (error, response, body) {
util.log("save: "+room_id + " " + body);
if (error) {
util.log(body);
}
});
}
socket.on('disconnect', function () {
socket.leave(room_id);
delete rooms[room_id];
util.log('disconnect');
});
} else if (!error && response.statusCode == 401) {
util.log('401');
socket.disconnect();
} else {
util.log(body);
}
});
});