Class: Firering::Connection

Inherits:
Object
  • Object
show all
Includes:
Requests
Defined in:
lib/firering/connection.rb

Defined Under Namespace

Classes: HTTPError

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Requests

#authenticate, #room, #rooms, #search_messages, #star_message, #user

Constructor Details

#initialize(host, streaming_host = "https://streaming.campfirenow.com") {|_self| ... } ⇒ Connection

Returns a new instance of Connection.

Yields:

  • (_self)

Yield Parameters:



22
23
24
25
26
27
# File 'lib/firering/connection.rb', line 22

def initialize(host, streaming_host = "https://streaming.campfirenow.com")
  @retry_delay, @redirects, @max_retries, @performed_retries = 2, 1, -1, 0
  self.host, self.streaming_host = host, streaming_host
  self.user_agent = "firering library version #{VERSION}"
  yield self if block_given?
end

Instance Attribute Details

#hostObject

Returns the value of attribute host.



5
6
7
# File 'lib/firering/connection.rb', line 5

def host
  @host
end

#http_optionsObject

HTTP Options correspond to EM::HTTPRequest options: github.com/igrigorik/em-http-request/wiki/Issuing-Requests



18
19
20
# File 'lib/firering/connection.rb', line 18

def http_options
  @http_options
end

#loggerObject

Returns the value of attribute logger.



10
11
12
# File 'lib/firering/connection.rb', line 10

def logger
  @logger
end

#loginObject

Returns the value of attribute login.



13
14
15
# File 'lib/firering/connection.rb', line 13

def 
  @login
end

#max_retriesObject

Returns the value of attribute max_retries.



7
8
9
# File 'lib/firering/connection.rb', line 7

def max_retries
  @max_retries
end

#passwordObject

Returns the value of attribute password.



11
12
13
# File 'lib/firering/connection.rb', line 11

def password
  @password
end

#performed_retriesObject (readonly)

Returns the value of attribute performed_retries.



20
21
22
# File 'lib/firering/connection.rb', line 20

def performed_retries
  @performed_retries
end

#redirectsObject

Returns the value of attribute redirects.



9
10
11
# File 'lib/firering/connection.rb', line 9

def redirects
  @redirects
end

#retry_delayObject

Returns the value of attribute retry_delay.



8
9
10
# File 'lib/firering/connection.rb', line 8

def retry_delay
  @retry_delay
end

#streaming_hostObject

Returns the value of attribute streaming_host.



6
7
8
# File 'lib/firering/connection.rb', line 6

def streaming_host
  @streaming_host
end

#tokenObject

Returns the value of attribute token.



12
13
14
# File 'lib/firering/connection.rb', line 12

def token
  @token
end

#user_agentObject

Returns the value of attribute user_agent.



14
15
16
# File 'lib/firering/connection.rb', line 14

def user_agent
  @user_agent
end

Instance Method Details

#auth_headersObject



45
46
47
# File 'lib/firering/connection.rb', line 45

def auth_headers
  token ? {'authorization' => [token, "X"] } : {'authorization' => [, password] }
end

#http(method, path, data = nil, &callback) ⇒ Object



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
# File 'lib/firering/connection.rb', line 58

def http(method, path, data = nil, &callback)
  uri = host.join(path)
  logger.info("performing request to #{uri}")

  http = EventMachine::HttpRequest.new(uri, http_options || {}).send(method, parameters(data))

  http.errback do
    perform_retry(http) do
      http(method, path, data, &callback)
    end
  end

  http.callback {
    reset_retries_counter
    if callback
      begin
        data = Yajl::Parser.parse(http.response, :symbolize_keys => true)
        callback.call(data, http)
      rescue Yajl::ParseError
        perform_retry(http) do
          http(method, path, data, &callback)
        end
      end
    end
  }

  http
end

#max_retries_reached?Boolean

Returns:

  • (Boolean)


140
141
142
# File 'lib/firering/connection.rb', line 140

def max_retries_reached?
  @performed_retries && @max_retries >= 0 && @performed_retries >= @max_retries
end

#parameters(data = nil) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/firering/connection.rb', line 49

def parameters(data = nil)
  parameters = {
    :redirects => redirects,
    :head => auth_headers.merge("Content-Type" => "application/json").merge('User-Agent' => user_agent)
  }
  parameters.merge!(:body => data.is_a?(String) ? data : Yajl::Encoder.encode(data)) if data
  parameters
end

#stream(room, &callback) ⇒ Object

Streaming

The Streaming API allows you to monitor a room in real time. The authenticated user must already have joined the room in order to use this API.



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/firering/connection.rb', line 92

def stream(room, &callback)
  parser = Yajl::Parser.new(:symbolize_keys => true)

  parser.on_parse_complete = proc do |data|
    callback.call(Firering::Message.instantiate(self, data)) if callback
  end

  # timeout 5s because the campfire streaming API chunked connection sends
  # "1\r\n \r\n" every 3s, and we want to bail as soon as that stops
  options = {:keepalive => true, :timeout => 5}

  uri = streaming_host.join("/room/#{room.id}/live.json")
  logger.info("performing streaming request to #{uri.to_s}")
  http = EventMachine::HttpRequest.new(uri).get(options.merge(parameters))

  http.stream do |chunk|
    begin
      parser << chunk; reset_retries_counter
    rescue Yajl::ParseError
      perform_retry(http) do
        room.stream(&callback)
      end
    end
  end

  # Campfire servers will try to hold the streaming connections open indefinitely.
  # However, API clients must be able to handle occasional timeouts or
  # disruptions. Upon unexpected disconnection, API clients should wait for a
  # few seconds before trying to reconnect.
  http.errback do
    logger.error("http error #{http.error}. Trying again in #{retry_delay} seconds...")
    perform_retry(http) do
      room.stream(&callback)
    end
  end

  # Campfire will _also_ actively close the connection. Correctly. Presumably,
  # this only happens when they deploy, but it does actually happen.
  http.callback do
    logger.error("http connection closed. Trying again in #{retry_delay} seconds...")
    perform_retry(http) do
      room.stream(&callback)
    end
  end

  http
end

#subdomainObject



41
42
43
# File 'lib/firering/connection.rb', line 41

def subdomain
  host.host.split(".").first
end