Class: AbsenteeCamper::Monitor

Inherits:
Object
  • Object
show all
Includes:
Campfire, Logger
Defined in:
lib/absentee_camper/monitor.rb

Instance Method Summary collapse

Methods included from Logger

#log

Constructor Details

#initializeMonitor

Returns a new instance of Monitor.



6
7
8
9
10
11
# File 'lib/absentee_camper/monitor.rb', line 6

def initialize
  @room = Room.new(Config.room_id)
  @room.join

  trap_signals
end

Instance Method Details

#startObject



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
# File 'lib/absentee_camper/monitor.rb', line 21

def start
  log "monitoring room #{Config.room_id} at #{API.base_uri} ..."

  url = URI.parse("http://#{Config.token}:[email protected]/room/#{Config.room_id}/live.json")

  begin
    Yajl::HttpStream.get(url) do |message|
      if message['type'] == 'TextMessage'
        body = message['body']
        log body

        body.scan(/@\w+/).each do |mention|
          mentioned = mention[1..-1]
          if Config.users.keys.include? mentioned
            begin
              # If the user isn't in the room, fire off an email to them
              unless users_in_room(@room).map { |u| u['id'] }.include? user_id_from_config(mentioned)
                @room.message("[Notified #{mentioned}.]")
                NotificationManager.new(Config.users[mentioned]).send_notifications body
              end
            rescue
              log $!
            end
          end
        end
      end
    end

    # If the stream ends, try to reconnect
    retry_connection
  rescue Yajl::HttpStream::HttpError => e
    log "Error connecting to campfire: #{e.message}"
  end
end

#users_in_room(room) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/absentee_camper/monitor.rb', line 13

def users_in_room(room)
  response = room.info
  raise "Error while retrieving room info: #{response.message}" if response.code != 200

  room = JSON.parse(response.body)
  room['room']['users']
end