Module: Nyoibo::Daemon

Included in:
Nyoibo
Defined in:
lib/nyoibo/daemon.rb

Constant Summary collapse

CMD_QUIT =
/^QUIT$/
CMD_JSON =
/^JSON: /
TYPE_BASE64 =
%r|^data:application/octet-stream;base64,|

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#pidObject (readonly)

Returns the value of attribute pid.



3
4
5
# File 'lib/nyoibo/daemon.rb', line 3

def pid
  @pid
end

Instance Method Details

#runObject



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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/nyoibo/daemon.rb', line 7

def run
  return if defined?(IRB)
  return unless Nyoibo.config
  daemon = lambda{
    EventMachine::WebSocket.start(:host => config.host, :port => config.port) do |ws|
      ws.onopen{
        ws.send "OK Ready"
      }
      ws.onclose{
        ws.close_websocket
      }
      ws.onmessage{|msg|
        @binary ||= ""
        @binary_type ||= 'binary'
        case msg
        when CMD_QUIT
          if @binary_type == 'base64'
            @binary = Base64.decode64(@binary)
          elsif @binary.encoding == Encoding::UTF_8
            @binary = @binary.unpack('U*').pack('c*')
          end
          Nyoibo.run_callback(:after, ws.request["path"], @json, @binary)
          @binary = @json = nil
          ws.send("OK Bye")
        when CMD_JSON
          msg.gsub!(CMD_JSON, '')
          @json = JSON.parse(msg)
          @json['size'] = @json['size'].to_i
          if Nyoibo.run_callback(:before, ws.request["path"], @json, @binary) == false
            ws.send("ABORT")
            ws.close_websocket
          else
            ws.send("NEXT")
          end
        else
          if msg =~ TYPE_BASE64
            msg.gsub!(TYPE_BASE64, '')
            @binary_type = 'base64'
          end

          if msg.length > 0
            @binary << msg
            ws.send("NEXT")
          else
            ws.send("EMPTY")
          end
        end
      }
    end
  }
  if ENV["NYOIBO_ENV"] == "test"
    daemon.call
  else
    @pid = Process.fork &daemon
    at_exit do
      Process.kill(:KILL, Nyoibo.pid) if Nyoibo.pid
    end
  end
end