/********server.js***********/
/*
* @author Anil Yadav * @Description Create server and implemnt route front and socket for chat server
* @create-date 28-09-2017 12:12pm
*/
var express = require('express');
var path = require('path');
require('dotenv').load();
var app = express();
// allow CORS
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
app.use(express.static(__dirname + '/uploads'))
app.use('/uploads', express.static(path.join(__dirname, '/uploads')));
var httpServer = require('http').createServer(app);
var io = require('socket.io').listen(httpServer)
var ss = require('socket.io-stream');
var routes = require('./chat-server/routes');
//front end routes
app.use('/', routes);
//implement chat server
require('./chat-server/controller/socketController')(io)
//require('./chat-server/controller/socketGroupController')(io)
//assign port
var port = process.env.PORT || 8888;
httpServer.listen(port, function() {
console.log('Chat Server running on port ' + port + '.');
});
/************************models.js****************/
/*
* Use : Model Logic
* @author Anil Yadav<ayadav@clavax.us>
* @create-date 03-10-2017 06:42pm
*/
//create model for room
var Room = require('./../include/roomSchema')
var config = require('./../include/config');
var notification = require('./../include/pushnotification');
var customJs = require('./../include/custom');
//create model for user
var User = require('./../include/userSchema')
var RoomUser = require('./../include/roomUserSchema')
var Chat = require('./../include/chatSchema')
var DeviceToken = require('./../include/deviceToken')
//define schema
var Schema = require('./getSchema')
//get user schema
var userget = Schema.users;
//get group list data
var grouplist = Schema.grouplist;
//get group user list data
var groupuserlist = Schema.groupuserlist;
//get default api response
var apiResponse = Schema.apiResponse;
var Promise = require('bluebird');
var fs = require('fs');
var formidable = require('formidable');
var multer = require('multer');
exports.addDeviceToken = function addDeviceToken(request, callback) {
/*
* Use : Save device token for push notification
* Description : Save device token for push notification
*/
var user_id = request.user_id;
var device_token = request.device_token;
var token_type = request.token_type;
DeviceToken.findOne({user_id: user_id, }, function (err, data) {
if (err) {
apiResponse.data = [];
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Error!";
} else if (data) {
data.device_token = device_token;
data.save(function (err1, data1) {
// console.log("device token update successfully");
apiResponse.data = [];
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "device token update successfully";
callback(apiResponse)
})
} else {
var insertData = {'user_id': user_id, device_token: device_token, token_type: token_type};
var saveDeviceToken = new DeviceToken(insertData);
saveDeviceToken.save(function (err, data) {
apiResponse.data = [];
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "device token insert successfully";
callback(apiResponse)
// console.log("device token saved successfully");
});
}
})
};
exports.removeDeviceToken = function removeDeviceToken(request, callback) {
/*
* Use : Save device token for push notification
* Description : Save device token for push notification
*/
var user_id = request.user_id;
var device_token = request.device_token;
DeviceToken.findOne({user_id: user_id, device_token: device_token}, function (err, data) {
data.remove(function (err, data) {
callback("success")
});
})
};
exports.addRoom = function addRoom(request, callback) {
/*
* Use : Add room for chat
* Description : Add room for chat create room code for chat user.
*/
genCode(function (data) {
try {
//get user request
var randomcode = data;
var code_type = request.code_type || 1;
var userid = request.user_id;
var language = request.language;
// console.log("=======send data for get user details======")
getUserData(userid, function (userData) {
// console.log("=====after get user data ===========")
if (userData) {
var userid = userData._id;
//change title according to language when it create
var suffix = (language === "fr") ? "Groupe " : " Group";
var title = (language === "fr") ? suffix + userData.firstName : userData.firstName + suffix;
Room.find({}, function (err, dd) {
var gsno = dd.length + 1;
var data = {gsno: gsno, code: randomcode, valid: 1, code_type: code_type, creator: userid, title: title}
var saveCode = new Room(data);
saveCode.save(function (err) {
var roomId = saveCode._id
if (err) {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "got error " + err;
callback(apiResponse)
} else {
var nickname = userData.nickname;
//save user to room
var dataRoomUser = {user_id: userid, group_id: roomId, nickname: nickname};
saveUserRoom(dataRoomUser, function (data) {
getGroupDetails(roomId, function (gdata) {
var groupData = {};
groupData['room_code'] = randomcode;
groupData['group_id'] = roomId;
groupData['user_id'] = userid;
groupData['members'] = gdata.members;
groupData['group_details'] = gdata.group_details;
apiResponse.data = groupData;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Group Created SuccessFully";
callback(apiResponse)
})
});
}
});
//call back to socket
})
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "user not found";
}
});
} catch (e) {
callback(apiResponse)
}
});
};
function getGroupDetails(group_id, callback) {
var groupdetails = Schema.groupdetails;
var members = [];
var groupDetails = {};
Room.findOne({_id: group_id, is_deleted: 0}, groupdetails, function (err, data) {
if (data && data.length != 0) {
groupDetails['group_details'] = data;
RoomUser.find({group_id: group_id, is_deleted: 0, }, groupuserlist).sort('-created_at').limit(5).exec(function (err, data2) {
var count = data2.length;
var countInc = 0;
data2.forEach(function (value) {
getUserData(value.user_id, function (userData) {
var temp_obj = {};
temp_obj['room_user_id'] = value._id;
temp_obj['user_id'] = value.user_id;
temp_obj['nickname'] = value.nickname;
temp_obj['user_image'] = (userData.imageFile) ? userData.imageFile : "";
members.push(temp_obj);
countInc++;
if (count == countInc) {
groupDetails['members'] = members;
callback(groupDetails)
}
})
});
});
} else {
callback([]);
}
})
}
exports.checkCode = function checkCode(request, callback) {
/*
* Use : Check Code
* Description : check code vailid or not.
*/
var userid = request.user_id;
var code = request.code;
// console.log("=======send data for get user details======")
getUserData(userid, function (userData) {
// console.log("=====after get user data ===========")
Room.findOne({code: code, valid: 1, is_deleted: 0}, function (err, data) {
if (data) {
var checkCode = 0;
var code_type = data.code_type;
var createdDate = data.created_at;
var roomcode = data.code;
var creator = data.creator;
if (code_type == 1) {
var gettime = new Date(createdDate);
var curtime = new Date();
gettime.setSeconds(gettime.getSeconds() + 25);
if (curtime > gettime) {
//store status
checkCode = 1;
}
} else {
var curtime = new Date();
var newDate = addDays(new Date(), 5);
if (curtime > newDate) {
//store status
checkCode = 1;
}
}
//check code active or not
if (checkCode) {
data.valid = 0;
data.save();
apiResponse.data = {user_id: userid}
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Invalid code or Expired";
callback(apiResponse)
} else {
var nickname = userData.nickname;
//save user to room
var group_id = data._id;
//action if code is active
var dataRoomUser = {user_id: userid, group_id: group_id, nickname: nickname};
// console.log("////checkkkkkkkcodeeeee")
saveUserRoom(dataRoomUser, function (data) {
getGroupDetails(group_id, function (gdata) {
var groupData = {};
groupData['room_code'] = roomcode;
groupData['group_id'] = group_id;
groupData['exist'] = data;
groupData['user_id'] = creator;
groupData['members'] = gdata.members;
groupData['group_details'] = gdata.group_details;
apiResponse.data = groupData;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Check code SuccessFully";
callback(apiResponse)
})
});
}
} else {
apiResponse.data = {user_id: userid}
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Invalid code or Expired";
//return to call back socket
callback(apiResponse)
}
});
});
};
exports.getCode = function getCode(request, callback) {
/*
* Use : getCode
* Description : getCode.
*/
var group_id = request.group_id;
groupdetails = Schema.groupdetails;
// console.log("=====after get user data ===========")
Room.findOne({_id: group_id}, groupdetails, function (err, data) {
if (data) {
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Error Group id not found";
// console.log(apiResponse)
callback(apiResponse)
}
});
};
exports.updateCode = function updateCode(request, callback) {
/*
* Use :updateCode
* Description :updateCode.
*/
groupdetails = Schema.groupdetails;
// console.log("=====after get user data ===========")
genCode(function (data) {
try {
//get user request
var group_id = request.group_id;
var randomcode = data;
var code_type = request.code_type || 1;
Room.findOne({_id: group_id}, groupdetails, function (err, data) {
if (data) {
data.code = randomcode;
data.code_type = code_type;
data.code_date = new Date();
data.save(function (err, dataCode) {
// console.log(err)
if (err) {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Got an issue please try after some time";
// console.log(apiResponse)
callback(apiResponse)
} else {
getGroupDetails(group_id, function (gdata) {
var groupData = {};
groupData['room_code'] = randomcode;
groupData['exist'] = "1";
groupData['group_id'] = group_id;
groupData['user_id'] = data.creator;
groupData['members'] = gdata.members;
groupData['group_details'] = gdata.group_details;
apiResponse.data = groupData;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Group Created SuccessFully";
callback(apiResponse)
})
}
})
} else {
}
});
} catch (e) {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "error!!!";
// console.log(apiResponse)
callback(apiResponse)
}
});
};
exports.deleteCode = function deleteCode(request, callback) {
/*
* Use :deleteCode
* Description :deleteCode.
*/
var group_id = request.group_id;
groupdetails = Schema.groupdetails;
// console.log("=====after get user data ===========")
Room.findOne({_id: group_id}, groupdetails, function (err, data) {
// console.log(data);
// console.log(err)
if (data) {
data.code = -1;
data.code_type = -1;
data.valid = 0;
data.save(function (err, dataCode) {
// console.log(err);
// console.log(dataCode)
if (err) {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Got an issue please try after some time";
// console.log(apiResponse)
callback(apiResponse)
} else {
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
}
})
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Error Group id not found";
// console.log(apiResponse)
callback(apiResponse)
}
});
};
exports.changeNickname = function changeNickname(request, callback) {
/*
* Use :changeNickname
* Description :changeNickname.
*/
var group_id = request.group_id;
var user_id = request.user_id;
var nickname = request.nickname;
groupdetails = Schema.groupdetails;
// console.log("=====after get user data ===========")
RoomUser.findOne({group_id: group_id, user_id: user_id}, groupuserlist, function (err, data) {
if (data) {
data.nickname = nickname;
data.save(function (err, dataCode) {
// console.log(err)
if (err) {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Got an issue please try after some time";
// console.log(apiResponse)
callback(apiResponse)
} else {
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
}
})
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Error Group id not found";
// console.log(apiResponse)
callback(apiResponse)
}
});
};
exports.groupDetails = function groupDetails(request, callback) {
/*
* Use : groupDetails
* Description : groupDetails
*/
var group_id = request.group_id;
var userid = request.user_id;
groupdetails = Schema.groupdetails;
Room.findOne({_id: group_id, is_deleted: 0}, groupdetails, function (err, data) {
// console.log("=====room user====")
if (data) {
RoomUser.find({group_id: group_id, is_deleted: 0}, function (err1, dataRU) {
if (dataRU) {
var count = dataRU.length;
data = data.toObject();
data['count'] = count;
// getUserData(function(err2,data2){
//
// })
//return to call back socket
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
callback(apiResponse)
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Error Group id not found";
callback(apiResponse)
}
})
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Error Group id not found";
callback(apiResponse)
}
});
};
exports.groupDelete = function groupDelete(request, callback) {
/*
* Use : groupDelete
* Description : groupDelete
*/
var group_id = request.group_id;
var userid = request.user_id;
groupdetails = Schema.groupdetails;
// console.log(request)
Room.findOne({_id: group_id}, function (err, data) {
// console.log(err)
// console.log(data)
// console.log("=====remove room user====")
if (data && data.creator == userid) {
// console.log("hello how are you")
//set delete and disable status
data.is_deleted = 1;
data.is_disable = 1;
// console.log("hello how are you")
data.save(function (err1, data) {
// console.log("hellooooo")
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
});
} else {
// console.log("as")
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Invalid user for delete group";
callback(apiResponse)
}
});
};
exports.exitRoom = function exitRoom(request, callback) {
/*
* Use : exitRoom
* Description : exitRoom
*/
var group_id = request.group_id;
var userid = request.user_id;
groupdetails = Schema.groupdetails;
RoomUser.findOne({group_id: group_id, user_id: userid}, function (err, data) {
// console.log("=====remove room user====")
if (data) {
//set delete and disable status
data.is_deleted = 1;
data.is_disable = 1;
data.save(function (err1, data) {
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
});
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "room not found";
callback(apiResponse)
}
});
};
exports.deleteChat = function deleteChat(request, callback) {
/*
* Use : exitRoom
* Description : exitRoom
*/
var id = request.chat_id;
var user_id = request.user_id
var groupdetails = Schema.groupdetails;
Chat.findOne({_id: id, user_id: user_id}, function (err, data) {
// console.log("=====remove chat user====")
if (data) {
//set delete and disable status
data.is_deleted = 1;
data.is_disable = 1;
data.save(function (err1, data) {
Room.findOne({_id: data.group_id}, function (dataGroup) {
Chat.find({group_id: data.group_id, is_deleted: 0}).sort('-sno').exec(function (err, dataChat) {
// console.log(dataChat)
if (dataChat.length) {
var dataC = dataChat[0];
updateGroupChatMsg(data.group_id, dataC.message, dataC.message_type)
} else {
updateGroupChatMsg(data.group_id, "", 0)
// console.log("77777777888888888888888")
}
});
})
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
});
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "chat not found";
callback(apiResponse)
}
});
};
exports.chatList = function chatList(request, callback) {
/*
* Use : chatList
* Description : chatList
*/
var group_id = request.group_id;
var user_id = request.user_id;
var page = parseInt(request.page);
var limit = parseInt(request.limit);
var user_id = request.user_id;
var appendData = [];
var chatlist = Schema.chatlist;
page = page * limit;
Chat.find({group_id: group_id, is_deleted: 0}).sort('-sno').limit(5000).exec(chatlist, function (err, data) {
// console.log("hello")
// console.log(data)
if (data && data.length != 0) {
var count = data.length;
var countInc = 0;
data.forEach(function (value) {
getUserRoomData(value.user_id, value.group_id, function (dataList) {
var temp_obj = {};
temp_obj['group_id'] = value.group_id;
temp_obj['sno'] = value.sno;
temp_obj['_id'] = value._id;
temp_obj['user_id'] = value.user_id;
temp_obj['message'] = value.message;
temp_obj['mime_type'] = value.mime_type;
temp_obj['thumbnail_key'] = value.thumbnail_key;
temp_obj['message_type'] = value.message_type;
temp_obj['created_at'] = value.created_at;
temp_obj['nickname'] = dataList.nickname;
temp_obj['user_image'] = dataList.user_image;
appendData.push(temp_obj)
countInc++;
if (count == countInc) {
apiResponse.data = sortBy(appendData, {prop: "sno"});
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "chat List Success";
callback(apiResponse)
}
})
})
} else {
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "success";
callback(apiResponse)
}
});
};
function msgCountInc(data) {
RoomUser.update({group_id: data.group_id}, {$inc: {unread_msg: 1}}, {"multi": true}, function (err, num) {
});
}
exports.chatTack = function chatTack(data) {
RoomUser.update({group_id: data.group_id, user_id: data.user_id}, {unread_msg: 0}, function (err, num) {
});
}
//sorted list by given data like number string or date
var sortBy = (function () {
//cached privated objects
var _toString = Object.prototype.toString,
//the default parser function
_parser = function (x) {
return x;
},
//gets the item to be sorted
_getItem = function (x) {
return this.parser((x !== null && typeof x === "object" && x[this.prop]) || x);
};
// Creates a method for sorting the Array
// @array: the Array of elements
// @o.prop: property name (if it is an Array of objects)
// @o.desc: determines whether the sort is descending
// @o.parser: function to parse the items to expected type
return function (array, o) {
if (!(array instanceof Array) || !array.length)
return [];
if (_toString.call(o) !== "[object Object]")
o = {};
if (typeof o.parser !== "function")
o.parser = _parser;
o.desc = !!o.desc ? -1 : 1;
return array.sort(function (a, b) {
a = _getItem.call(o, a);
b = _getItem.call(o, b);
return o.desc * (a < b ? -1 : +(a > b));
});
};
}());
exports.groupEdit = function groupEdit(request, callback) {
/*
* Use : groupEdit
* Description :groupEdit.
*/
var user_id = request.user_id;
var group_id = request.group_id;
groupdetails = Schema.groupdetails;
Room.findOne({_id: group_id, creator: user_id, is_deleted: 0}, function (err, data) {
//return to call back socket
if (data) {
if (request.title) {
data.title = request.title;
}
if (request.description) {
data.room_description = request.description;
}
data.save(function (err, data) {
if (!err) {
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
}
callback(apiResponse)
})
} else {
apiResponse.data = [];
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Error Invalid user";
// console.log(apiResponse)
callback(apiResponse)
}
});
};
exports.groupEditAll = function groupEditAll(request, callback) {
/*
* Use : groupEdit
* Description :groupEdit.
*/
var user_id = request.user_id;
var group_id = request.group_id;
groupdetails = Schema.groupdetails;
try {
RoomUser.findOne({user_id: user_id, group_id: group_id}, function (err, docs) {
if (docs) {
// console.log(request)
if (request.nickname) {
docs.nickname = request.nickname;
docs.save();
}
}
Room.findOne({_id: group_id, creator: user_id, is_deleted: 0}, function (err, data) {
//return to call back socket
if (data) {
// console.log(request)
//for seprate save nickname
if (request.title) {
data.title = request.title;
}
if (request.description) {
data.room_description = request.description;
}
data.save(function (err, data) {
if (!err) {
data = data.toObject();
data['user_id'] = data.creator;
delete data.creator;
apiResponse.data = data;
apiResponse.is_creator = 1;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
}
callback(apiResponse)
})
} else if (docs) {
apiResponse.data = docs;
apiResponse.is_creator = 0;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse);
callback(apiResponse);
} else {
apiResponse.data = [];
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Error Invalid user";
// console.log(apiResponse)
callback(apiResponse)
}
});
});
} catch (e) {
console.log(e)
}
};
exports.groupImageUpdate = function groupImageUpdate(request, callback) {
/*
* Use : groupImageUpdate Code
* Description : groupImageUpdate.
*/
var user_id = request.user_id;
var group_id = request.group_id;
groupdetails = Schema.groupdetails;
Room.findOne({_id: group_id, creator: user_id, is_deleted: 0}, function (err, data) {
if (data) {
imageUploadGroup(request, function (imagename) {
data.group_image = imagename;
data.save(function (err, data) {
// console.log(err)
// console.log(data)
if (!err) {
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
}
callback(apiResponse)
})
})
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "Invalid user for update group";
callback(apiResponse)
}
});
};
/*
* @Description Save Room id and user id in callection roomUser
* @param {type} dataRoomUser
* @returns {undefined}
*/
function saveUserRoom(dataRoomUser, callback) {
// console.log("===save record add room before==========")
var msg = 0
RoomUser.findOne({user_id: dataRoomUser.user_id, group_id: dataRoomUser.group_id}, function (err, docs) {
if (docs) {
if (docs.is_deleted) {
docs.is_deleted = 0;
docs.save();
callback(0)
} else {
callback(1)
}
} else {
var saveRoomUser = new RoomUser(dataRoomUser);
saveRoomUser.save(function (err, data) {
// console.log(err)
// console.log(data)
msg = 0;
callback(msg)
});
}
});
// console.log("===save record add room after==========")
}
/*
* @Description list group
* @param {type} listGroup
* @returns {listGroup}
*/
exports.listGroup = function listGroup(request, callback) {
var userid = request.user_id;
var appendData = []
getUserData(userid, function (userData) {
// console.log("==============================================")
if (userData) {
RoomUser.find({user_id: userid, is_deleted: 0, }, groupuserlist).sort('-created_at').limit(5000).exec(function (err, data) {
if (data && data.length != 0) {
var count = data.length;
var countInc = 0;
data.forEach(function (value) {
// console.log("hello")
getGroupDetails(value.group_id, function (dataList) {
countInc++;
// console.log(dataList)
// console.log(countInc)
var temp_obj = {};
try {
if (dataList && dataList.length != 0) {
temp_obj['group_id'] = value.group_id;
temp_obj['nickname'] = value.nickname;
temp_obj['unread_msg'] = value.unread_msg;
temp_obj['user_id'] = value.user_id;
temp_obj['user_image'] = userData.imageFile;
temp_obj['group_details'] = dataList.group_details;
temp_obj['created_at'] = dataList.group_details.created_at;
temp_obj['members'] = dataList.members;
appendData.push(temp_obj)
}
} catch (e) {
}
if (count == countInc) {
apiResponse.data = sortBy(appendData, {prop: "created_at"});
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Group List Success";
callback(apiResponse)
}
})
})
} else {
apiResponse.data = [];
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Error";
callback(apiResponse)
}
})
}
});
}
/*
*
* @Description Display list group user
* @returns {listGroupUser}
*/
exports.listGroupUser = function listGroupUser(request, callback) {
var group_id = request.group_id;
var appendData = []
groupOrderSet(request, function (onwerData) {
console.log(onwerData);
RoomUser.find({group_id: group_id, is_deleted: 0, }, groupuserlist).sort('-created_at').limit(5).exec(function (err, data) {
if (data && data.length != 0) {
// console.log(data)
// console.log(err)
var count = data.length;
var countInc = 0;
data.forEach(function (value) {
getUserData(value.user_id, function (userData) {
// console.log(userData)
getRoomList(value.group_id, function (dataList) {
try {
// console.log(dataList)
var temp_obj = {};
temp_obj['group_id'] = value.group_id;
temp_obj['nickname'] = value.nickname;
temp_obj['user_id'] = value.user_id;
temp_obj['user_image'] = (userData.imageFile) ? userData.imageFile : "";
temp_obj['group_details'] = dataList;
appendData.push(temp_obj)
} catch (e) {
}
countInc++;
if (count == countInc) {
apiResponse.data = appendData
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Group List Success";
callback(apiResponse)
}
})
})
})
} else {
apiResponse.data = [];
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Error";
callback(apiResponse)
}
})
});
}
function groupOrderSet(request, callback) {
/*
* Yogesh Work on byte array / binary
*/
var group_id = request.group_id;
Room.findOne({_id: group_id}, function (err, data) {
callback(data.creator);
});
}
/*
*@description send chat data
*
*/
exports.chatSend = function chatSend(request, callback) {
var userid = request.user_id;
var groupid = request.group_id;
var message = request.message;
getUserData(userid, function (userData) {
saveChat(request, function (data) {
getUserRoomData(userid, groupid, function (dataList) {
try {
data = data.toObject();
data['user_image'] = dataList.user_image;
data['nickname'] = dataList.nickname;
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse);
callback(apiResponse);
} catch (e) {
callback(apiResponse)
}
});
})
});
}
/*
* Use : chatImageSend
* Description : chatImageSend
*/
exports.chatImageSend = function chatImageSend(request, callback) {
// console.log("---------------------------yogesh-----------------");
imageUpload(request, function (imagename) {
// console.log(imagename);
thumbnailCreate(request, function (thumbname) {
// console.log("---------------------------yogesh thumb-----------------");
// console.log(thumbname);
request.message = imagename.url;
request.mime_type = imagename.mime_type;
request.thumbnail_key = thumbname;
// console.log(request);
var userid = request.user_id;
var groupid = request.group_id;
saveChatImage(request, function (data) {
getUserRoomData(userid, groupid, function (dataList) {
try {
data = data.toObject();
data['user_image'] = dataList.user_image;
data['nickname'] = dataList.nickname;
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
} catch (e) {
callback(apiResponse)
}
});
});
});
});
};
/*
* Use : chatImageSend
* Description : chatImageSend
*/
exports.chatImageSendBefore = function chatImageSendBefore(request, callback) {
thumbnailCreate(request, function (thumbname) {
var ext = request.image_name.substr(request.image_name.lastIndexOf('.') + 1);
request.message = "";
request.mime_type = ext;
request.thumbnail_key = thumbname;
// console.log(request);
var userid = request.user_id;
var groupid = request.group_id;
saveChatBeforeImage(request, function (data) {
getUserRoomData(userid, groupid, function (dataList) {
try {
data = data.toObject();
data['user_image'] = dataList.user_image;
data['nickname'] = dataList.nickname;
data['check'] = request.check;
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse)
callback(apiResponse)
} catch (e) {
callback(apiResponse)
}
});
});
});
};
/*
*@description get room user data
*/
function getUserRoomData(user_id, group_id, callback) {
// console.log(group_id);
// console.log(user_id);
RoomUser.findOne({user_id: user_id, group_id: group_id, }, groupuserlist, function (err, data) {
getUserData(user_id, function (dataArr) {
data = data.toObject();
data['user_image'] = dataArr.imageFile;
callback(data);
})
})
}
/*
* @description save chat data
* 0 for text
*/
function saveChat(data, callback) {
var userid = data.user_id;
var groupid = data.group_id;
var message = data.message;
var message_type = 0;
updateGroupChatMsg(groupid, message, message_type);
Chat.find({}, function (err, dd) {
var sno = dd.length + 1;
// console.log(sno)
var data = {sno: sno, user_id: userid, group_id: groupid, message: message, message_type: message_type}
//increment unread message
msgCountInc(data);
var saveChat = new Chat(data);
saveChat.save(function (err, data) {
// console.log(data)
// console.log(err)
sendPushNotification(groupid, data.toObject())
callback(data)
})
});
}
/*
* @Description update last message in group
* @param {type} group_id
* @param {type} message
* @param {type} message_type
* @returns NUll
*/
function updateGroupChatMsg(group_id, message, message_type, mime_type, thumbnail_key) {
// console.log("------------------------mime-----------------------")
// console.log(mime_type);
try {
if (mime_type) {
} else {
mime_type = "";
}
if (thumbnail_key) {
} else {
thumbnail_key = "";
}
// console.log(mime_type);
// console.log(thumbnail_key);
Room.findOne({_id: group_id}, function (err, data) {
data.message_type = message_type
data.mime_type = mime_type
data.thumbnail_key = thumbnail_key
data.last_message = message
data.msg_date = new Date();
data.save();
})
} catch (e) {
console.log(e)
}
}
/*
*
*@Description Send Push notification
*@author <ayadav@clavax.us>
*/
function sendPushNotification(groupid, message1) {
RoomUser.find({group_id: groupid, is_deleted: 0}, groupuserlist, function (err, data) {
if (data.length) {
// console.log("---------------send Push Notification-------------------------")
// console.log("----------------------------------------")
data.forEach(function (dataVal) {
User.findOne({_id: dataVal.user_id}, function (errUser, dataUser) {
if (!errUser) {
dataUser = dataUser.toObject();
// console.log("---------------User data list-------------------------")
// console.log(dataUser);
if (dataUser.enabledNotification) {
DeviceToken.findOne({user_id: dataVal.user_id}, function (err, dataDev) {
try {
// delete message1.message_type;
var deviceId = dataDev.device_token;
// message1.user_image = dataUser.imageFile;
// message1.nickname = dataVal.nickname;
// var message = {
// to: deviceId,
// collapse_key: '',
// data: message1,
// notification: message1
// };
var message = {
to: deviceId,
collapse_key: '',
data: {
created_at: '"' + message1.created_at + '"',
sno: message1.sno,
user_id: message1.user_id,
group_id: message1.group_id.toString(),
message: '"' + message1.message + '"',
mime_type: '"' + message1.mime_type + '"',
thumbnail_key: '"' + message1.thumbnail_key + '"',
message_type_id: message1.message_type,
//_id: message1._id,
//user_image: '"' + dataUser.imageFile + '"',
//nickname: '"' + dataVal.nickname + '"',
unread_msg: dataVal.unread_msg
},
notification: {
created_at: '"' + message1.created_at + '"',
sno: message1.sno,
user_id: message1.user_id,
group_id: message1.group_id.toString(),
message: message1.message,
mime_type: '"' + message1.mime_type + '"',
thumbnail_key: '"' + message1.thumbnail_key + '"',
message_type_id: message1.message_type,
// _id: message1._id,
// user_image: '"' + dataUser.imageFile + '"',
// nickname: '"' + dataVal.nickname + '"',
unread_msg: dataVal.unread_msg
},
};
// console.log(message);
// console.log("---------------Push notific end msg -------------------------")
var notific = notification.Notification(message)
} catch (e) {
console.log(e)
}
});
}
}
});
});
}
})
}
/*
* @description save chat data
*/
function saveChatImageUpdate(data, callback) {
var userid = data.user_id;
var groupid = data.group_id;
var message = data.message;
var message_type = 1;
var mime_type = data.mime_type;
var thumbnail_key = data.thumbnail_key;
Chat.findOne({_id: data.id}, function (err2, data2) {
data2.message = message;
data2.message_type = message_type;
data2.mime_type = mime_type;
data2.thumbnail_key = thumbnail_key;
data2.save(function (err, data) {
// console.log(data)
// console.log(err)
updateGroupChatMsg(groupid, message, message_type, mime_type, thumbnail_key);
sendPushNotification(groupid, data.toObject())
callback(data2)
})
});
}
/*
* @description save chat data
*/
function saveChatBeforeImage(data, callback) {
var userid = data.user_id;
var groupid = data.group_id;
var message = data.message;
var message_type = 1;
var mime_type = data.mime_type;
var thumbnail_key = data.thumbnail_key;
Chat.find({}, function (err, dd) {
var sno = dd.length + 1;
// console.log(sno)
var data = {sno: sno, user_id: userid, group_id: groupid, message: message, message_type: message_type, mime_type: mime_type, thumbnail_key: thumbnail_key, is_deleted: 1}
//increment unread message
var saveChat = new Chat(data);
saveChat.save(function (err, data) {
callback(data)
})
});
}
/*
* @description save chat data
*/
function saveChatImage(data, callback) {
var userid = data.user_id;
var groupid = data.group_id;
var message = data.message;
var message_type = 1;
var mime_type = data.mime_type;
var thumbnail_key = data.thumbnail_key;
updateGroupChatMsg(groupid, message, message_type, mime_type, thumbnail_key);
Chat.find({}, function (err, dd) {
var sno = dd.length + 1;
// console.log(sno)
var data = {sno: sno, user_id: userid, group_id: groupid, message: message, message_type: message_type, mime_type: mime_type, thumbnail_key: thumbnail_key}
//increment unread message
msgCountInc(data);
var saveChat = new Chat(data);
saveChat.save(function (err, data) {
// console.log(data)
// console.log(err)
sendPushNotification(groupid, data.toObject())
callback(data)
})
});
}
/*
*@Description Get room user list data single
*/
function getRoomList(roomid, callback) {
Room.findOne({is_deleted: 0, _id: roomid}, function (err, data) {
callback(data)
})
}
/*
*@Descripiton Add days functionality in current days
*/
function addDays(theDate, days) {
return new Date(theDate.getTime() + days * 24 * 60 * 60 * 1000);
}
/*
* Use : Genrate code
* Description : generate code for group user
*/
function genCode(callback) {
// console.log("=====genCode()=========")
var Randdom = Math.floor(Math.random() * 89999 + 10000);
try {
//check code exist or not
Room.find({code: Randdom}, function (err, data) {
//disable for right now will enable when it required
if (0) {
genCode()
} else {
callback(Randdom);
}
});
} catch (e) {
console.log(e)
}
}
//get user data
function getUserData(userid, callback) {
// console.log("==========enter user get data getUserData function=========")
var data = "";
User.findOne({_id: userid}, userget, function (err, users) {
data = users;
// console.log('getuserdata')
// console.log(users)
callback(data);
});
}
/*
*@Descripiton Image upload with base 64
*/
function imageUpload(request, callback) {
//image upload with binary data
/*fs.writeFile(request.image, request.image, "binary", function(err,data){
console.log(data)
console.log("hello this is the test message")
console.log(err)
});*/
//image upload with base64 data
/*var ext = request.image_name.substr(request.image_name.lastIndexOf('.') + 1);
var b64string = request.image;
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64');
} else {
// older Node versions
buf = new Buffer(b64string, 'base64');
}
var filename = 'img-' + Date.now() + '.' + ext;
var uploadedImagePath = config.uploadImage + filename;
try
{
fs.writeFile(uploadedImagePath, buf, function (e) {
callback(imageName = config.showImagePath + filename)
});
} catch (e) {
callback(imageName = "")
}
*/
/*
* Yogesh Work on byte array / binary
*/
// console.log("-------------------------------imageUpload------------------------------------------------------");
// console.log(request);
// console.log("-------------------------------end imageUpload------------------------------------------------------");
var ext = request.image_name.substr(request.image_name.lastIndexOf('.') + 1);
//
// var filename = 'media-' + Date.now() + '.' + ext;
var uploadedImagePath = config.uploadImage + request.image_name;
// var uploadedImagePath = config.uploadImage + filename;
// console.log(uploadedImagePath);
try {
console.log("fgf99999000000000000000000000000000000000000000")
fs.writeFile(uploadedImagePath, request.image, "binary");
} catch (e) {
// console.log("file errror");
// console.log(e.message);
callback({"url": "", "mime_type": ""});
}
}
/*
*@Descripiton Image upload with base 64
*/
function imageUploadGroup(request, callback) {
//image upload with binary data
/*fs.writeFile(request.image, request.image, "binary", function(err,data){
console.log(data)
console.log("hello this is the test message")
console.log(err)
});*/
//image upload with base64 data
var ext = request.image_name.substr(request.image_name.lastIndexOf('.') + 1);
var b64string = request.image;
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64');
} else {
// older Node versions
buf = new Buffer(b64string, 'base64');
}
var filename = 'img-' + Date.now() + '.' + ext;
var uploadedImagePath = config.uploadImage + filename;
try
{
fs.writeFile(uploadedImagePath, buf, function (e) {
callback(imageName = config.showImagePath + filename)
});
} catch (e) {
callback(imageName = "")
}
}
exports.pushtest = function pushtest(request, callback) {
try {
var deviceId = 'cDVJ-dc0nxU:APA91bGxXbdm9wPOQvv2mmBkd8xQ5y-TcQRe_UabUu8dFS8MEfhrdOAQ7kPqcL3gBXEKA6yLjzLk35T2Q6SYVR9VT21LZ_RqP3HBnwoNp5Onr0G_jHER2m9uf8SMLKEd9_64mrwPSjcZ';
var message = {
to: deviceId,
collapse_key: 'your_collapse_key',
notification: {
title: 'Title of your push notification',
body: 'Body of your push notification'
},
data: {//you can send only notification or only data(or include both)
my_key: 'my value',
my_another_key: 'my another value'
}
};
var notific = notification.Notification(message)
callback('testy')
} catch (e) {
console.log(e)
}
}
function thumbnailCreate(request, callback) {
/*
* Yogesh Work on byte array / binary
*/
if (!request.thumb_name) {
callback(thumbName = "")
} else if (!request.thumb_name.trim()) {
callback(thumbName = "")
} else {
var uploadedImagePath = config.uploadImage + request.thumb_name;
try {
fs.writeFile(uploadedImagePath, request.thumb_image, "binary", function (err, data) {
// console.log(data);
// console.log("hello this is the Thumbnail create");
// console.log(err);
callback(thumbName = config.showImagePath + request.thumb_name)
});
} catch (e) {
callback(thumbName = "")
}
}
}
/*
* Use : chatImageSend
* Description : chatImageSend
*/
exports.multiplartFile = function multiplartFile(request, callback) {
// console.log(request);
var ext = request.image_name.substr(request.image_name.lastIndexOf('.') + 1);
// var filename = 'img-' + Date.now() + '.' + ext;
var uploadedImagePath = config.uploadImage + request.image_name;
// console.log(uploadedImagePath);
// imageUpload(request, function (imagename) {
fs.writeFile(uploadedImagePath, request.image, "binary", function (err, data) {
// console.log(data);
// console.log("hello this is the test message");
// console.log(err);
// callback(uploadedImagePath);
callback(imageName = config.showImagePath + request.image_name)
});
// });
};
/*
*@description send chat data
*
*/
exports.chatSendGlobles = function chatSendGlobles(request, callback) {
var chat_id = request.chat_id;
Chat.findOne({_id: chat_id}, function (err, data) {
if (!err) {
getUserRoomData(data.user_id, data.group_id, function (dataList) {
try {
data = data.toObject();
data['user_image'] = dataList.user_image;
data['nickname'] = dataList.nickname;
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
sendPushNotification(data.group_id, data)
callback(apiResponse);
} catch (e) {
apiResponse.data = [];
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Error";
callback(apiResponse);
}
})
} else {
apiResponse.data = [];
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.message = "Error";
callback(apiResponse);
}
})
}
/*
*@description send chat data
*
*/
exports.chatSendImageData = function chatSendImageData(request, callback) {
// console.log("chatSendImageData");
// console.log(request);
Chat.findOne({_id: request.chatid}, function (err, data) {
// console.log("=====remove chat user====")
if (data) {
//set delete and disable status
data.is_deleted = 0;
// data.mime_type = request.extension;
data.message = config.showImagePath + "" + request.message;
data.save(function (err1, data) {
getUserRoomData(data.user_id, data.group_id, function (dataList) {
try {
data = data.toObject();
data['user_image'] = dataList.user_image;
data['nickname'] = dataList.nickname;
apiResponse.data = data;
apiResponse.error = 0;
apiResponse.status = 200;
apiResponse.message = "Success";
// console.log(apiResponse);
callback(apiResponse);
} catch (e) {
callback(apiResponse)
}
});
});
} else {
apiResponse.error = 1;
apiResponse.status = 200;
apiResponse.data = [];
apiResponse.message = "chat not found";
callback(apiResponse)
}
});
}
/**schema**********/
/*
* Use : Set Model Schema
* @author Anil Yadav<ayadav@clavax.us>
* @create-date 03-10-2017 06:42pm
*/
var dbSchema = {
users: {
'_id': 1,
'email': 1,
'username': 1,
'firstName': 1,
'lastName': 1,
'imageFile': 1,
'nickname':1,
},
groupuserlist: {
'_id': 1,
'user_id':1,
'group_id':1,
'nickname':1,
'unread_msg':1,
},
grouplist: {
'_id': 1,
'room_description':1,
'group_image':1,
'is_deleted':1,
'title':1,
'last_message':1,
'message_type':1,
'code_type':1,
'code':1,
'created_at': 1,
'updated_at': 1,
'creator':1,
//'gsno':1,
},
groupdetails: {
'_id': 1,
'room_description':1,
'group_image':1,
'is_deleted':1,
'valid':1,
'title':1,
'last_message':1,
'mime_type':1,
'thumbnail_key':1,
'message_type':1,
'code_type':1,
'code':1,
'code_date':1,
'msg_date':1,
'created_at': 1,
'updated_at': 1,
'creator':1,
//'gsno':1,
},
chatlist: {
'_id': 1,
'user_id':1,
'group_id':1,
'message_type':1,
'mime_type':1,
'message':1,
'created_at': 1,
'updated_at': 1,
'sno':1,
},
apiResponse: {
'error': 1,
'message': 'Internal server error',
'data': [],
'status': 500
}
,
};
module.exports = dbSchema;
/*************************************************************
/*
* Use : Set Chat Schema
* @author Anil Yadav<ayadav@clavax.us>
* @create-date 03-10-2017 06:42pm
*/
// grab the things we need
var db = require('./db')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var chatSchema = new Schema({
message: String,
user_id: {type: String, required: true},
group_id: {type: String, required: true},
message_type: String,
mime_type : String,
thumbnail_key : String,
is_deleted: Number,
is_disable: Number,
sno: Number,
created_at: Date,
updated_at: Date,
__v: { type: Number, select: false}
});
//for save date time
chatSchema.pre('save', function (next) {
now = new Date();
this.updated_at = now;
if (!this.created_at) {
this.created_at = now;
}
if (!this.message) {
this.message = "";
}
if (!this.message_type) {
this.message_type = "1";
}
if (!this.mime_type) {
this.mime_type = "";
}
if (!this.thumbnail_key) {
this.thumbnail_key = "";
}
if (!this.is_deleted) {
this.is_deleted = "0";
}
if (!this.is_disable) {
this.is_disable = "0";
}
next();
});
// the schema is useless so far
// we need to create a model using it
var Chat = mongoose.model('Chat', chatSchema);
// make this available to our Chat in our Node applications
module.exports = Chat;
/*******db config****************/
/*
* Use : Connect to database
* @author Anil Yadav<ayadav@clavax.us>
* @create-date 03-10-2017 06:42pm
*/
var databaseUri = process.env.DATABASE_URI || 'mongodb://localhost:27017/sdsds';
var mongodb = require('mongodb');
var mongoose=require('mongoose');
mongoose.Promise = require('bluebird');
var db = mongoose.connect(databaseUri,{useMongoClient: true },function(error){
if(error){
console.log("error"+error);
}else{
console.log("open done")
}
});
module.exports = db;
/**********route*************/
/*
* @author Anil Yadav<ayadav@clavax.us>
* @Description Create route front
* @create-date 28-09-2017 12:12pm
*/
var express = require('express');
var frontCtrl = require('./controller/frontController');
var router = express.Router();
var roomss = require('./models/Models');
var config = require('./include/config');
router.route('/addgroup').get(frontCtrl.createGroup);
router.route('/checkcode').get(frontCtrl.checkCode);
router.route('/updatecode').get(frontCtrl.updateCode);
router.route('/getlist').get(frontCtrl.getList);
router.route('/getgroupuser').get(frontCtrl.getGroupUser)
router.route('/chat').get(frontCtrl.groupChat);
router.route('/chat1').get(frontCtrl.groupChat1);
router.route('/chat2').get(frontCtrl.groupChat2);
router.route('/chatstart').get(frontCtrl.startChat);
router.route('/updategroup').get(frontCtrl.updateGroup);
router.route('/demo').get(frontCtrl.demoChat);
router.route('/yogesh').get(frontCtrl.yogesh);
router.route('/multipart').get(frontCtrl.filemultipart);
router.route('/multer_upload').get(frontCtrl.multer_upload);
//group chat routes
var multer = require('multer');
//var upload = multer({dest: '/tmp/'});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, config.uploadImageMultipart )
},
filename: function (req, file, cb) {
// var extension = originalname.split(".");
// filename = Date.now() + '.' + extension[extension.length-1];
cb(null, file.originalname)
// cb(null, Date.now() + '-' + file.originalname)
}
})
//var upload = multer({storage: storage}).any();
var upload = multer({storage: storage}).single('profileimage');
/* POST saveblog router. */
router.post('/save_file', function (req, res, next) {
upload(req, res, function (err) {
var chatid = req.body.chat_id;
// console.log(req.body, 'Body');
// console.log(req.file, 'files');
// console.log(req.file.filename);
if (err) {
console.log("errr" + err);
res.send({error: 1, status: 200, data: []});
} else {
console.log("Success");
console.log(chatid);
if (req.file) {
console.log('uploading File...')
console.log(req.file.path)
console.log(req.file)
// File Info
// var profileImageOriginalName = req.file.originalname;
var profileImageName = req.file.filename;
// var profileImageMime = req.file.mimetype;
// var profileImagePath = req.file.path;
// var profileImageExt = req.file.extension;
// var profileImageSize = req.file.size;
var extension = profileImageName.split(".");
extension = extension[extension.length - 1];
request = {};
request.message = profileImageName;
// request.extension = extension;
request.is_deleted = 0;
request.chatid = chatid;
roomss.chatSendImageData(request, function (req) {
console.log("response -------------------------- chatSendImageData");
console.log(req);
res.send(req);
});
console.log(profileImageName);
} else {
res.send({error: 1, status: 200, data: []});
}
}
});
});
router.route('/').get(frontCtrl.startServer);
module.exports = router;