2015-07-21 14:10:24 +00:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Chatroom Controller
|
|
|
|
*
|
|
|
|
* Server API
|
|
|
|
* message:new - New message needs to be displayed
|
|
|
|
* message:refresh - Reload all messages
|
|
|
|
*
|
|
|
|
* Client API
|
|
|
|
* message:new - New message has been created
|
|
|
|
* message:refresh - Retrieve most recent messages
|
2015-08-07 00:53:52 +00:00
|
|
|
* message:delete - Deletes message by ID (Admin only)
|
2015-07-21 14:10:24 +00:00
|
|
|
*
|
|
|
|
*/
|
|
|
|
|
2015-08-07 00:14:36 +00:00
|
|
|
var mongoose = require("mongoose");
|
|
|
|
var Message = mongoose.model("message");
|
2015-07-21 14:10:24 +00:00
|
|
|
|
|
|
|
module.exports = function (namespace) {
|
|
|
|
|
|
|
|
var broadcastUpdate = function (message) {
|
|
|
|
namespace.emit("message:new", message.toJson());
|
|
|
|
};
|
|
|
|
|
2015-08-07 00:53:52 +00:00
|
|
|
var refreshMessages = function (socket) {
|
|
|
|
Message.list({}, function (error, messages) {
|
|
|
|
if (error) {
|
|
|
|
winston.error("Unable to retrieve messages. Error:", error);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var receiver = (socket === undefined) ? namespace : socket;
|
|
|
|
|
|
|
|
receiver.emit("message:refresh", {
|
|
|
|
chatHistory: messages
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2015-07-21 14:10:24 +00:00
|
|
|
namespace.on('connection', function (socket) {
|
|
|
|
|
|
|
|
socket.on('message:new', function (data) {
|
2015-08-07 00:14:36 +00:00
|
|
|
Message.create({
|
|
|
|
author: {
|
|
|
|
username: socket._user.username,
|
|
|
|
avatar: socket._user.avatar
|
|
|
|
},
|
2015-07-21 14:10:24 +00:00
|
|
|
content: data.content
|
2015-08-07 00:14:36 +00:00
|
|
|
}, function (error, newMessage) {
|
|
|
|
if (error) {
|
|
|
|
winston.error("Unable to store message. Error:", error);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
broadcastUpdate(newMessage)
|
|
|
|
});
|
2015-07-21 14:10:24 +00:00
|
|
|
});
|
|
|
|
|
2015-08-07 00:53:52 +00:00
|
|
|
socket.on('message:delete', function (data) {
|
|
|
|
var id = data.id;
|
|
|
|
if (id === undefined || !socket._user.admin) return;
|
|
|
|
|
|
|
|
Message.remove({_id: id}, function (error) {
|
2015-08-07 00:14:36 +00:00
|
|
|
if (error) {
|
2015-08-07 00:53:52 +00:00
|
|
|
winston.error("An error occurred when trying to delete message:", error);
|
2015-08-07 00:14:36 +00:00
|
|
|
return;
|
|
|
|
}
|
2015-08-07 00:53:52 +00:00
|
|
|
refreshMessages();
|
2015-07-21 14:10:24 +00:00
|
|
|
});
|
|
|
|
});
|
2015-08-07 00:53:52 +00:00
|
|
|
|
|
|
|
socket.on('message:refresh', function () {
|
|
|
|
refreshMessages(socket);
|
|
|
|
});
|
2015-07-21 14:10:24 +00:00
|
|
|
});
|
|
|
|
};
|