aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_cable/channel/base.rb
blob: 8ee99649f40a4741b2a20e28912fbec2e7095e14 (plain) (blame)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
module ActionCable
  module Channel

    class Base
      include Callbacks
      include Redis

      on_subscribe   :start_periodic_timers
      on_unsubscribe :stop_periodic_timers

      on_unsubscribe :disconnect

      attr_reader :params, :connection

      class_attribute :channel_name

      class << self
        def matches?(identifier)
          raise "Please implement #{name}#matches? method"
        end

        def find_name
          @name ||= channel_name || to_s.demodulize.underscore
        end
      end

      def initialize(connection, channel_identifier, params = {})
        @connection = connection
        @channel_identifier = channel_identifier
        @_active_periodic_timers = []
        @params = params

        connect

        subscribe
      end

      def receive_data(data)
        if authorized?
          if respond_to?(:receive)
            receive(data)
          else
            logger.error "[ActionCable] #{self.class.name} received data (#{data}) but #{self.class.name}#receive callback is not defined"
          end
        else
          unauthorized
        end
      end

      def subscribe
        self.class.on_subscribe_callbacks.each do |callback|
          send(callback)
        end
      end

      def unsubscribe
        self.class.on_unsubscribe_callbacks.each do |callback|
          send(callback)
        end
      end

      protected
        # Override in subclasses
        def authorized?
          true
        end

        def unauthorized
          logger.error "[ActionCable] Unauthorized access to #{self.class.name}"
        end

        def connect
          # Override in subclasses
        end

        def disconnect
          # Override in subclasses
        end

        def broadcast(data)
          if authorized?
            connection.broadcast({ identifier: @channel_identifier, message: data }.to_json)
          else
            unauthorized
          end
        end

        def start_periodic_timers
          self.class.periodic_timers.each do |callback, options|
            @_active_periodic_timers << EventMachine::PeriodicTimer.new(options[:every]) do
              worker_pool.async.run_periodic_timer(self, callback)
            end
          end
        end

        def stop_periodic_timers
          @_active_periodic_timers.each {|t| t.cancel }
        end

        def worker_pool
          connection.worker_pool
        end

        def logger
          connection.logger
        end

    end

  end
end