Class: Sparks

Inherits:
Object
  • Object
show all
Defined in:
lib/sparks.rb,
lib/sparks/version.rb

Overview

Usage:

c = Sparks.new('subdomain', 'abc123')
r = c.room "Room Name"
c.say r["id"], "hi there"
c.paste r["id"], "class Foo\nend"

Constant Summary collapse

VERSION =
"0.4"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subdomain, token, opts = {}) ⇒ Sparks

Returns a new instance of Sparks.



15
16
17
18
19
20
21
22
# File 'lib/sparks.rb', line 15

def initialize subdomain, token, opts = {}
  @base   = URI("https://#{subdomain}.campfirenow.com")
  @token  = token
  @logger = opts[:logger] || Logger.new(STDOUT)
  @http   = Net::HTTP::Persistent.new("sparks")
  @http.ca_file = opts[:ca_file] if opts[:ca_file]
  @rooms ||= {}
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



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

def logger
  @logger
end

Instance Method Details

#join(id) ⇒ Object



42
43
44
# File 'lib/sparks.rb', line 42

def join(id)
  req("/room/#{id}/join", :post)
end

#leave(id) ⇒ Object



46
47
48
# File 'lib/sparks.rb', line 46

def leave(id)
  req("/room/#{id}/leave", :post)
end

#meObject



24
25
26
# File 'lib/sparks.rb', line 24

def me
  user("me")
end

#paste(id, message) ⇒ Object



57
58
59
# File 'lib/sparks.rb', line 57

def paste(id, message)
  speak id, message, 'PasteMessage'
end

#play(id, message) ⇒ Object



61
62
63
# File 'lib/sparks.rb', line 61

def play(id, message)
  speak id, message, 'SoundMessage'
end

#req(uri, body = nil) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/sparks.rb', line 115

def req(uri, body = nil)
  uri = @base + (uri + ".json") unless uri.is_a?(URI)
  logger.debug "#{body ? 'POST' : 'GET'} #{uri}"

  if body
    request = Net::HTTP::Post.new(uri.path)
    request.body = body unless body == :post
  else
    request = Net::HTTP::Get.new(uri.path)
  end
  request.content_type = "application/json"
  request.basic_auth @token, "x"

  retries ||= 0
  response = @http.request(uri, request)
  response.value   # raises if response is not 2xx
  parse_response(response)

rescue Net::HTTPRetriableError => e # response was 3xx
  location = URI(response['location'])
  logger.info "Request redirected to #{location}"
  sleep 2
  req(location, body)

rescue Net::HTTPServerException => e # response was 4xx
  msg = "Authorization failed: HTTP #{response.code}"
  msg << ": " << request.body if request.body && !request.body.empty?
  raise msg

rescue SystemCallError,           # All Errno errors
    Net::HTTP::Persistent::Error, # Timeout, SSL, or connection error
    Net::HTTPBadResponse,         # response wasn't 2xx
    Net::HTTPHeaderSyntaxError,   # response header issue
    Net::ProtocolError => e       # not http
  # Retry if something goes wrong
  retries += 1
  logger.info "Request failed: #{e.class}: #{e.message}"
  logger.info "Going to retry request in #{retries * 2}s"
  sleep retries * 2
  retry
end

#room(id) ⇒ Object



36
37
38
39
40
# File 'lib/sparks.rb', line 36

def room(id)
  @rooms[id] ||= begin
    req("/room/#{id.to_s}")[:room]
  end
end

#room_named(name) ⇒ Object



32
33
34
# File 'lib/sparks.rb', line 32

def room_named(name)
  req("/rooms")[:rooms].find{|r| r[:name] == name }
end

#speak(id, message, type = 'TextMessage') ⇒ Object Also known as: say



50
51
52
53
54
# File 'lib/sparks.rb', line 50

def speak(id, message, type = 'TextMessage')
  data = {'body' => message, 'type' => type}
  json = Yajl::Encoder.encode('message' => data)
  req("/room/#{id}/speak", json)
end

#tweet(id, message) ⇒ Object



65
66
67
# File 'lib/sparks.rb', line 65

def tweet(id, message)
  speak id, message, 'TweetMessage'
end

#user(id) ⇒ Object



28
29
30
# File 'lib/sparks.rb', line 28

def user(id)
  req("/users/#{id}")[:user]
end

#watch(id) ⇒ Object



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
112
113
# File 'lib/sparks.rb', line 69

def watch(id)
  # campfire won't let you stream until you've joined the room
  join(id)

  # don't allow retries if we've never connected before.
  retries ||= nil

  uri = URI("https://streaming.campfirenow.com") + "/room/#{id}/live.json"
  logger.debug "Ready to stream from #{uri}"

  request = Net::HTTP::Get.new(uri.path)
  request.basic_auth @token, "x"

  @http.request(uri, request) do |response|
    logger.debug "Connected and streaming from room #{id}"
    # connected! allow retries.
    retries = 0

    # Set up a Yajl stream parser
    parser = Yajl::Parser.new(:symbolize_keys => true)
    parser.on_parse_complete = -> hash { yield hash }

    # Feed chunks into the stream parser
    response.read_body do |chunk|
      # Campfire keepalive pings
      next if chunk == " "
      parser << chunk
    end
  end
rescue Yajl::ParseError,          # Bad JSON in the response
    SystemCallError,              # All Errno errors
    SocketError,                  # Errors from socket operations
    Net::HTTP::Persistent::Error, # Timeout, SSL, or connection error
    Net::HTTPBadResponse,         # response wasn't 2xx
    Net::HTTPHeaderSyntaxError,   # response header issue
    Net::ProtocolError => e       # not http
  # pass through errors if we haven't ever connected
  raise e unless retries
  # if we connected at least once, try, try, again
  retries += 1
  logger.error "#{e.class}: #{e.message}"
  logger.error "Trying to stream again in #{retries * 2}s"
  sleep retries * 2
  retry
end