Created
July 7, 2017 06:03
-
-
Save jhony112/532cb7decdb3bb27419e1e59d909c1b7 to your computer and use it in GitHub Desktop.
socket js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require("http"); | |
const https = require("https"); | |
const co = require("co"); | |
const fs = require("fs"); | |
const url = require("url"); | |
const querystring = require("querystring"); | |
const MongoClient = require("mongodb").MongoClient; | |
const ObjectID = require("mongodb").ObjectID; | |
let config, db, deployment, io, server; | |
co(function *() { | |
config = yield JSON.parse(fs.readFileSync("config.json", "UTF-8")); | |
deployment = config[config.env]; | |
db = yield MongoClient.connect(deployment.database); | |
if (config.env === "PRODUCTION") { | |
let ssl = {key: fs.readFileSync(config.ssl.key), cert: fs.readFileSync(config.ssl.cert)}; | |
server = https.createServer(ssl); | |
} | |
else server = http.createServer(); | |
server.listen(config.microservices.socket); | |
console.log("Socket Chat service listening on port", `${config.microservices.socket}.`); | |
io = require("socket.io").listen(server); | |
io.on('connection', function (socket) { | |
'use strict'; | |
socket.on("login", function (uid) { | |
"use strict"; | |
if (app.getUserBySocketID(socket.id)) return socket.emit("login_status", { | |
status: 201, | |
message: "You are already connected." | |
}); | |
else users.push({uid: uid, socket: socket.id}); | |
console.log(uid, "connected."); | |
let messageObj = []; | |
co(app.getUserGroups(uid, function (lists) { | |
for (var group of lists) { | |
socket.join(group.id); | |
console.log(group.id); | |
let result = app.getOldMessages(group.id); | |
if (result !== null) messageObj.push(result); | |
} | |
console.log("messages" + messageObj); | |
})).catch(err => console.log(err.stack)); | |
return socket.emit("login_status", {status: 200, socket: socket.id, data: messageObj}); | |
}); | |
socket.on("send_message", function (gid, uid, msg) { | |
"use strict"; | |
console.log(gid); | |
let user = app.getUserBySocketID(socket.id); | |
// console.log(user); | |
if (!user) return socket.emit("message_error", "SESSION_EXPIRED", "You're not logged in."); | |
co(app.saveMessage(gid, uid, msg)).catch(err => console.log(err.stack)); | |
return socket.broadcast.to(gid).emit("message_received", {gid: gid, msg: msg}); | |
}); | |
}) | |
}).catch(function (err) { | |
console.log(err.stack); | |
}); | |
let users = []; | |
let app = { | |
/** | |
* @param {Number} socketID | |
*/ | |
getUserBySocketID: function (socketID) { | |
"use strict"; | |
let total = users.length; | |
for (let i = 0; i < total; i++) { | |
if (users[i].socket === socketID) { | |
let user = users[i]; | |
user.index = i; | |
return user; | |
} | |
} | |
return false; | |
}, | |
/** | |
* @param {String} uid | |
* @return {Array} | |
*/ | |
formatDate: function (date, timestamp) { | |
"use strict"; | |
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; | |
let hours = date.getHours(); | |
let minutes = date.getMinutes(); | |
minutes = minutes < 10 ? '0' + minutes : minutes; | |
if (timestamp) { | |
let seconds = date.getSeconds(); | |
return months[date.getMonth()].toUpperCase() + "/" + date.getDate() + " " + | |
(hours < 10 ? "0" + hours : hours) + ':' + minutes + ':' + (seconds < 10 ? "0" + seconds : seconds); | |
} | |
let ampm = hours >= 12 ? 'pm' : 'am'; | |
hours = hours % 12; | |
hours = hours ? hours : 12; | |
return months[date.getMonth()] + " " + date.getDate() + ", " + hours + ':' + minutes + ' ' + ampm; | |
}, | |
getUserGroups: function *(uid, callback) { | |
let list = []; | |
let members = yield db.collection("groups_members").find({uid: uid.toString()}).toArray(); | |
for (let member of members) { | |
let groupID = member.groupID; | |
let group = yield app.getGroupInfo(groupID); | |
if (group === false) continue; | |
list.push({ | |
id: groupID, | |
ownerID: group.ownerID, | |
name: group.name, | |
photo: group.photo, | |
members: group.members, | |
admins: group.admins, | |
balance: group.balance, | |
date: app.formatDate(group.timestamp) | |
}); | |
} | |
callback(list) | |
// return list; | |
}, | |
getOldMessages: function *(gid) { | |
let messages = yield db.collection("messages").find({gid: gid}).limit(1).toArray(); | |
if (messages.length) { | |
return messages[0]; | |
} else { | |
return null; | |
} | |
}, | |
saveMessage: function *(gid, uid, msg) { | |
let message = {text: msg, sender: uid, timestamp: new Date()}; | |
let old = yield db.collection("messages").find({gid: gid}).limit(1).toArray(); | |
console.log("oldmsg",old); | |
if (old.length > 0) { | |
old[0].messages.push(message); | |
let newMessages = old[0].messages; | |
console.log(newMessages); | |
db.collection("messages").updateOne({gid: gid}, {$set: {messages: newMessages}}); | |
} | |
else { | |
db.collection("messages").insertOne( | |
{ | |
gid: gid, | |
messages: [message] | |
}); | |
} | |
}, | |
/** | |
* @param {String} uid | |
* @return {Array} | |
*/ | |
getUserByUID: function *(uid, basicInfo) { | |
"use strict"; | |
let query = yield db.collection("accounts").find({uid: uid}).hint("UID").limit(1).toArray(); | |
if (query.length) return app.displayUserInfo(query[0], basicInfo); | |
else return []; | |
}, | |
/** | |
* @param {Object} user | |
* @param {Boolean} basicInfo | |
* @return {Object} | |
*/ | |
displayUserInfo: function (user, basicInfo) { | |
"use strict"; | |
user.photo = `${config.bucket.url}/${user.photo}.jpg`; | |
if (basicInfo) return { | |
uid: user.uid, | |
username: user.username, | |
name: user.name, | |
photo: user.photo, | |
level: user.level | |
} | |
else return user; | |
} | |
, | |
getGroupInfo: function *(groupID) { | |
"use strict"; | |
let group = yield db.collection("groups").find({_id: groupID}).toArray(); | |
if (!group.length) return false; | |
else group = group[0]; | |
let photo = (!group.photo) ? `images/groups/${group.type.toLowerCase()}.jpg` : `${config.bucket.url}/${group.photo}.jpg`; | |
return { | |
id: groupID, | |
name: group.name, | |
type: group.type, | |
circle: group.circle, | |
owner: yield app.getUserByUID(group.ownerID), | |
members: group.members, | |
balance: group.balance, | |
info: group.info, | |
photo: photo, | |
timestamp: group.timestamp | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment