PageRenderTime 42ms CodeModel.GetById 29ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/socketI0/socket.js

https://github.com/ajaylbsim/Me-You
JavaScript | 155 lines | 123 code | 23 blank | 9 comment | 16 complexity | 4ee18d4cf63d459fd9792776d2af235b MD5 | raw file
  1exports.startSocket = function () {
  2    //console.log('------------------------------------------- cool')
  3    var clients = {};
  4    var socketsOfClients = {};
  5    io.sockets.on('connection', function (socket) {
  6        socket.on('set username', function (userId) {
  7            if (clients[userId] === undefined) {
  8                // Does not exist ... so, proceed
  9                clients[userId] = socket.id;
 10                socketsOfClients[socket.id] = userId;
 11               // console.log('total users  =================  ', socketsOfClients);
 12                updateFrindsList(userId);
 13                userIdAvailable(socket.id, userId);
 14                userJoined(userId);
 15                broadcastOnline(userId);
 16            } else if (clients[userId] === socket.id) {
 17                // Ignore for now
 18            } else {
 19                userIdAlreadyInUse(socket.id, userId);
 20            }
 21        });
 22        socket.on('message', function (msg) {
 23            console.log('--------------------------------message found    -----------  ', msg)
 24            var srcUser;
 25            if (msg.inferSrcUser) {
 26                // Infer user name based on the socket id
 27                srcUser = socketsOfClients[socket.id];
 28            } else {
 29                srcUser = msg.source;
 30            }
 31
 32            if (msg.target == "All") {
 33                // broadcast
 34                io.sockets.emit('message',
 35                    {"source": srcUser,
 36                        "message": msg.message,
 37                        "target": msg.target,
 38                         "message": msg.message,
 39                       "deliveredTime": msg.deliveredTime});
 40            } else {
 41                // Look up the socket id
 42              if(clients[msg.target])
 43              {
 44                  io.sockets.sockets[clients[msg.target]].emit('message',
 45                      {   "source": srcUser,
 46                          "message": msg.message,
 47                          "target": msg.target,
 48                          "deliveredTime": msg.deliveredTime});
 49                  console.log("message is send   to ", clients[msg.target])
 50
 51              }else{
 52                  console.log("target is ofline so can't send message  ", clients[msg.target])
 53
 54              }
 55                var messageObj=new message();
 56                messageObj.To=msg.target;
 57                messageObj.From=srcUser;
 58                messageObj.data=msg.message;
 59                messageObj.deliveredTime=new Date();
 60                messageObj.save(function(err,msgObj){
 61                    if(err)console.log(err);
 62                });
 63            }
 64        })
 65        socket.on('disconnect', function () {
 66            var uName = socketsOfClients[socket.id];
 67            console.log('==================*****************************disconnected********',uName)
 68            broadcastOfline(uName)
 69            delete socketsOfClients[socket.id];
 70            delete clients[uName];
 71            // relay this message to all the clients
 72            userLeft(uName);
 73        })
 74    })
 75
 76    function userJoined(uName) {
 77        Object.keys(socketsOfClients).forEach(function (sId) {
 78            io.sockets.sockets[sId].emit('userJoined', { "userId": uName, "userList": socketsOfClients});
 79        })
 80    }
 81
 82
 83    function updateFrindsList(userId) {
 84        Object.keys(socketsOfClients).forEach(function (sId) {
 85            userService.findFriends(userId)
 86                .on('data', function (friends) {
 87                    if (friends.length && friends[0].friends.length) {
 88                        //initilizig status
 89                        friends[0].friends.forEach(function (obj) {
 90                            obj.status = false;
 91
 92                        });
 93
 94
 95                        for (var key in clients) {
 96                            friends[0].friends.forEach(function (obj) {
 97                                if (key == obj.id) {
 98                                    log.info(">>>>>>>>>>>>>>>>>>>>>>online is >>>>>>>>>>>>>>", obj.name);
 99
100                                    obj.status = true;
101                                }
102
103
104                            })
105                        }
106                    }
107                    io.sockets.sockets[sId].emit('updateFrindsList', {"userList": friends[0].friends});
108
109                })
110                .on('err', function () {
111
112                    log.error('error occured !!!!');
113
114                })
115        })
116    }
117
118    function userLeft(uName) {
119        io.sockets.emit('userLeft', { "userId": uName });
120    }
121
122    function userIdAvailable(sId, uName) {
123        setTimeout(function () {
124            console.log('Sending welcome msg to ' + uName + ' at ' + sId);
125            io.sockets.sockets[sId].emit('welcome', { "userId": uName, "currentUsers": JSON.stringify(Object.keys(clients)) });
126
127        }, 500);
128    }
129
130    function userIdAlreadyInUse(sId, uName) {
131        setTimeout(function () {
132            io.sockets.sockets[sId].emit('error', { "userIdInUse": true });
133        }, 500);
134    }
135
136    function broadcastOnline(sId) {
137        io.sockets.emit('catchOnlineFriends',
138            {
139                "id": sId
140            });
141        setTimeout(function () {
142
143        }, 500);
144    }
145    function broadcastOfline(sId) {
146        io.sockets.emit('catchOflineFriends',
147            {
148                "id": sId
149            });
150        setTimeout(function () {
151
152        }, 500);
153    }
154
155}