'use strict';
var mongoose = require('mongoose');
var logger, core, user, saveNotif, notificationChannel;
var socket = require('../../../ws/mobile.js');
var context = require('../../../../../../context');
function sayHello(req, res) {
logger.info('Welcome to c2net!');
return res.json(200, {message: core.getMessage()});
}
function createUserNotification(notification){
for(var i=0; i<notification.userEmail.length; i++){
console.log(notification.userEmail[i]);
user.findByEmail(notification.userEmail[i],function(err, u){
if(!u || err)
{
logger.info('User not found ...');
logger.debug(err);
return;
}
u.objectType = 'user';
logger.info("ID found by Email :" + u._id)
var data = {
title: notification.title,
author: u.id,
action: notification.body.substring(0,25)+'...',
object: notification.body,
link: notification.link,
level: "notification.level",
timestamps: new Date(),
target: [u],
data: {},
context: "context",
icon : notification.icon
};
saveNotif.save(data,function(err,notifData){
if(err)
{
console.log(err);
return;
}
});
var notif = {
title : notification.title,
body : notification.body,
component : notification.component,
link : notification.link,
userEmail : notification.userEmail[i],
icon : notification.icon,
type : notification.type
};
try{socket.emit(u._id, notif);
console.log("notification Handled by controller and emmited to socket.")
}
catch(err){
console.log("----emiter error:-----")
console.log(err)
}
});
}
}
function sendNotification(req, res){
createUserNotification(req.body);
//console.log(User.findById(req.user._id));
//console.log(saveNotif);
/*
var notif = {
title:req.body.title,
msg: req.body.msg,
status: 'unread',
type: req.body.type
};
user.newNotification(req.user._id, notif);
socket.emit(req.user._id, notif);
return res.json(204, {message:"User is notified!"});
*/
return res.json(204, {message:"User is notified!"});
}
module.exports = function(dependencies) {
var PubSub = dependencies('pubsub').local;
var PubSubG = dependencies('pubsub').global;
saveNotif = dependencies('notification').notification;
user = dependencies('user');
logger = context.logger;
core = require('./core')(dependencies);
notificationChannel = context.requires.send_notifications;
console.log(notificationChannel);
notificationChannel.subscribe('C2NET_Notification');
notificationChannel.on('message', function(data){
createUserNotification(JSON.parse(data.toString()));
});
// User login ------------------------------------------------------------------------------
PubSub.topic('login:success').subscribe(function(data) {
logger.info("Login successfully!");
var notif = {
title:'Login successfully',
msg: 'Welcome to C2NET!',
status: 'unread',
type: 'login'
};
// console.log(data)
// user.newNotification(data._id, notif);
// socket.emit(data._id, notif);
});
return {
sayHello: sayHello,
sendNotification:sendNotification
}
};