summaryrefslogtreecommitdiff
path: root/scripts/socket.rb
blob: 2a9f31dda51b11c416de4dcac3b745b492e75e04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require "em-websocket"
require "em-hiredis"
require "json"

EM.run do
  @channels = Hash.new
  @redis = EM::Hiredis.connect("unix://#{File.expand_path('..')}/redis/redis.socket")
  pubsub = @redis.pubsub
  pubsub.subscribe "todos"
  pubsub.on(:message) do |redis_channel, message|
    message = JSON.parse(message)
    data = {
      channel: redis_channel,
      data: message
    }

    if redis_channel == "todos"
      channel = @channels[message["user_id"].to_s]
      channel[:channel].push data.to_json
    end
  end

  EM::WebSocket.start(host: "0.0.0.0", port: "8080", debug: false) do |socket|
    socket.onopen do |handshake|
      channel = channel_for_socket(handshake)

      sid = channel[:channel].subscribe do |msg|
        socket.send msg
      end

      socket.onclose do
        channel[:channel].unsubscribe(sid)
        @channels.delete(path(handshake))
      end
    end
  end

  def path(handshake)
    handshake.path.split("/").last
  end

  def channel_for_socket(handshake)
    channel_path = path(handshake)
    @channels[channel_path] ||= {
      channel: EM::Channel.new,
      user_id: channel_path,
      subscribed: ['todos']
    }
  end
end