Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- io = require 'socket.io'
- jwt = require 'jsonwebtoken'
- clientManager = require 'client-manager'
- SocketManager = require './SocketManager'
- module.exports = class Sockets
- constructor: (@app, @server) ->
- @loaded = false
- @app.io = io @server
- @manager = clientManager()
- @socketManager = new SocketManager @manager
- @app.socketManager = @socketManager
- @listenEvents()
- @app.logger.info '✓ '.bold.green + 'Started sockets handler.'
- listenEvents: () ->
- usersController = require('../../api/users/index')(@app, @app.Sequelize, @app.db);
- @app.sockets_channels = {}
- @app.joinChannel = (name, userId) =>
- if typeof @app.sockets_channels[name] == 'undefined'
- @app.sockets_channels[name] = []
- @app.sockets_channels[name].push userId
- sock = @app.socketManager.getClientSocket(userId)
- sock.join name if sock
- @app.unsubscribeChannel = (channel, socket) =>
- if typeof socket.user != 'undefined'
- for own key, value of @app.sockets_channels
- if key.match(new RegExp "#{channel}_") and Array.isArray value
- @app.sockets_channels[key] = value.filter (u) => u != socket.user.id
- socket.leave key
- delete @app.sockets_channels[key] if @app.sockets_channels[key].length == 0
- @app.unsubscribeAllChannels = (socket) =>
- if typeof socket.user != 'undefined'
- for own key, value of @app.sockets_channels
- if Array.isArray value
- @app.sockets_channels[key] = value.filter (u) => u != socket.user.id
- socket.leave key
- delete @app.sockets_channels[key] if @app.sockets_channels[key].length == 0
- @app.io.on 'connection', (socket) =>
- socket.on 'join', (data) =>
- jwt.verify data.authorization, @app.config.jwt_secret, (err, user) =>
- if err is null
- socket.user = user;
- @manager.addClient user.id, socket
- usersController.getFriends(user.id).then (friends) =>
- user.status = 'online'
- friends.forEach (friend) =>
- c = @socketManager.getClientSocket friend.friend_id
- if c
- @app.io.to(c.id).emit 'onUserStatus', user
- .catch (error) =>
- console.log error
- socket.on 'unsubscribe_channel', (channel) =>
- @app.unsubscribeChannel channel, socket
- socket.on 'disconnect', =>
- client = @socketManager.getClientBySocketId socket.id
- if client isnt null
- client.status = 'offline'
- @app.unsubscribeAllChannels(socket);
- usersController.getFriends(client.id).then (friends) =>
- friends.forEach (friend) =>
- c = @socketManager.getClientSocket friend.friend_id
- if c
- @app.io.to(c.id).emit 'onUserStatus', client
- @manager.removeClient client.id
- @app.logger.info "#{client.firstname} #{client.lastname} has disconnected"
- @manager.on 'add', (client) =>
- @app.logger.info "#{client.user.firstname} #{client.user.lastname} is connected"
- @manager.on 'empty', =>
- @app.logger.info 'No more sockets connected'
- @loaded = true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement