Class: Lita::Adapters::Gitter::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/lita/adapters/gitter/connection.rb

Overview

Connection adapter to RestAPI and Stream API

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(robot, config) ⇒ Connection

Returns a new instance of Connection.



15
16
17
18
# File 'lib/lita/adapters/gitter/connection.rb', line 15

def initialize(robot, config)
  @robot = robot
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



13
14
15
# File 'lib/lita/adapters/gitter/connection.rb', line 13

def config
  @config
end

#robotObject (readonly)

Returns the value of attribute robot.



12
13
14
# File 'lib/lita/adapters/gitter/connection.rb', line 12

def robot
  @robot
end

Instance Method Details

#get_message(text, from_id, room_id) ⇒ Object (private)

Handle new message

Parameters:

  • text (String)

    Message text.

  • from_id (String)

    ID of user who sent this message.

  • room_id (String)

    Room ID.



108
109
110
111
112
113
114
115
116
117
# File 'lib/lita/adapters/gitter/connection.rb', line 108

def get_message(text, from_id, room_id)
  user = User.new(from_id)
  source = Source.new(user: user, room: room_id)
  message = Message.new(robot, text, source)

  return if from_id == @user_id

  message.command!
  robot.receive(message)
end

#httpObject (private)

HTTP Request initializer



127
128
129
130
131
132
133
134
# File 'lib/lita/adapters/gitter/connection.rb', line 127

def http
  @http ||= EventMachine::HttpRequest.new(
    stream_url,
    keepalive: true,
    connect_timeout: 0,
    inactivity_timeout: 0,
  )
end

#logObject (private)

Helper method to access Lita logger



121
122
123
# File 'lib/lita/adapters/gitter/connection.rb', line 121

def log
  Lita.logger
end

#parse(body) ⇒ Object (private)

Parse received message

Parameters:

  • text (String)

    Received body content.



89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/lita/adapters/gitter/connection.rb', line 89

def parse(body)
  response = MultiJson.load(body)

  text = response['text']
  from_id = response['fromUser']['id']
  room_id = config.room_id

  get_message(text, from_id, room_id)

rescue MultiJson::ParseError => e
  log.error "Failed to decode: #{body.inspect} - #{e}"
end

#runObject

The main loop. Listens for incoming messages, creates Message objects from them, and dispatches them to the robot.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lita/adapters/gitter/connection.rb', line 24

def run
  EventMachine.run do
    log.debug("Connecting to Gitter Stream API (room: #{config.room_id}).")

    buffer = ''
    start_request.stream do |chunk|
      body = buffer + chunk

      # Keep alive packet, ignore!
      next if body.strip.empty?

      if body.end_with?("}\n")
        # End of chunk, let's process it!
        received = body.dup
        buffer = ''

        EM.defer { parse(received) }
      else
        # Chunk too big, buffering!
        buffer = body
      end
    end
  end
end

#send_message(_target, text) ⇒ Object

Sends one message to a user or room.

Parameters:

  • target (Lita::Source)

    The user or room to send message to.

  • text (String)

    Messages to send.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/lita/adapters/gitter/connection.rb', line 54

def send_message(_target, text) # rubocop:disable Metrics/AbcSize
  url = "https://api.gitter.im/v1/rooms/#{config.room_id}/chatMessages"
  uri = URI.parse(url)

  Net::HTTP.start(
    uri.host,
    uri.port,
    use_ssl: true,
    verify_mode: OpenSSL::SSL::VERIFY_NONE,
  ) do |http|
    request = Net::HTTP::Post.new(uri.path)
    request.add_field('Content-Type', 'application/json')
    request.add_field('Accept', 'application/json')
    request.add_field('Authorization', "Bearer #{config.token}")
    request.body = { 'text' => text }.to_json
    response = http.request(request)

    @user_id = MultiJson.load(response.body)['fromUser']['id']
  end
end

#shut_downObject

Shutdown connection



77
78
79
80
81
# File 'lib/lita/adapters/gitter/connection.rb', line 77

def shut_down
  log.debug('Closing connection to Gitter Stream API.') if http

  EM.stop if EM.reactor_running?
end

#start_requestObject (private)



136
137
138
139
140
141
142
143
# File 'lib/lita/adapters/gitter/connection.rb', line 136

def start_request
  http.get(
    head: {
      'Accept' => 'application/json',
      'Authorization' => "Bearer #{config.token}",
    }
  )
end

#stream_urlString (private)

Stream URL for configured Room

Returns:

  • (String)

    stream url



149
150
151
# File 'lib/lita/adapters/gitter/connection.rb', line 149

def stream_url
  "https://stream.gitter.im/v1/rooms/#{@config.room_id}/chatMessages"
end