Class: Flareshow::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/service.rb

Overview

provides an interface to the shareflow api

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.debug_outputObject

Returns the value of attribute debug_output.



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

def debug_output
  @debug_output
end

.keyObject

Returns the value of attribute key.



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

def key
  @key
end

.serverObject

Returns the value of attribute server.



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

def server
  @server
end

Class Method Details

.api_endpointObject

return the api endpoint for a given host and domain



23
24
25
# File 'lib/service.rb', line 23

def api_endpoint
  @api_endpoint ||= URI.parse("http://#{server.host}/#{server.domain}/shareflow/api/v2.json")
end

.auth_endpointObject

return the authentication endpoint for a given host and domain



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

def auth_endpoint
  @auth_endpoint ||= URI.parse("http://#{server.host}/#{server.domain}/shareflow/api/v2/auth.json")
end

.authenticate(login, password) ⇒ Object

authenticate with the server using an http post



103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/service.rb', line 103

def authenticate(, password)
  params = {:login => , :password => password}
  response = post(auth_endpoint, params)
  # store the auth token returned from the authentication request
  if response["status_code"] == 200
    @key = response["resources"]["data"]["auth_token"]
    response
  else
    raise Flareshow::AuthenticationFailed
  end
rescue Exception => e
  Flareshow::Util.log_error e.message
  Flareshow::Util.log_error e.backtrace.join("\n")
end

.authenticated?Boolean

are we authenticated

Returns:

  • (Boolean)


189
190
191
# File 'lib/service.rb', line 189

def authenticated?
  !!@key
end

.commit(params = {}, files = []) ⇒ Object

commit changes to the server with an http post



126
127
128
129
130
131
# File 'lib/service.rb', line 126

def commit(params={}, files=[])
  raise Flareshow::AuthenticationRequired unless @key
  params, files = *files_from_params(params) if params["posts"]
  params = {"key" => @key, "data" => params}
  post(api_endpoint, params, files)
end

.configure(subdomain = nil, host = 'api.zenbe.com') ⇒ Object

setup the service to use a particular host and domain



11
12
13
14
15
# File 'lib/service.rb', line 11

def configure(subdomain=nil, host='api.zenbe.com')
  raise Flareshow::ConfigurationException unless subdomain
  self.server=Server.new(host, subdomain)
  @auth_endpoint = @api_endpoint = nil
end

.files_from_params(params) ⇒ Object

get the files out of the params



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/service.rb', line 134

def files_from_params(params)
  files = []
  # add any file parts passed in and assign a part id to the 
  params["posts"] = (params["posts"]).map do |f|
    if f["files"]
      f["files"] = (f["files"]).map do |ff|
        # we only want to send up new files from the client so we'll strip out any existing
        # files in the params that came down from the server
        val = nil
        if ff["part_id"]
          val = {"part_id" => ff["part_id"], "file_path" => ff["file_path"]} 
          files << val
        end
        val
      end.compact
    end
    f
  end
  [params, files]
end

.http_get(uri) ⇒ Object

do a get request



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/service.rb', line 77

def http_get(uri)
  uri = URI.parse(uri) unless uri.is_a? URI
  req = Net::HTTP::Get.new(uri.path + "?key=#{@key}")
  req.add_field "User-Agent", "ruby flareshow"
  http = Net::HTTP.new(uri.host, uri.port)
  http.set_debug_output DEFAULT_LOGGER if debug_output
  response = http.start{|h|http.request(req)}
  response = process_response(response)
  Flareshow::Util.log_error("resource not found") if response["status_code"] == 404
  response
end

.log_response(response) ⇒ Object

log the response



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/service.rb', line 90

def log_response(response)
  # log a service exception
  case response["status_code"]
    when 400
      log_service_error(response)
    when 500
      log_service_error(response)
    when 403
      log_service_error(response)
  end
end

.log_service_error(response) ⇒ Object

log a service error



174
175
176
177
178
179
180
181
# File 'lib/service.rb', line 174

def log_service_error(response)
  if response["resources"]
    Flareshow::Util.log_error(response["resources"]["message"])
    Flareshow::Util.log_error(response["resources"]["details"]) 
  else
    Flareshow::Util.log_error(response["body"])
  end
end

.logoutObject

clear the authenticated session



184
185
186
# File 'lib/service.rb', line 184

def logout
  @key = nil
end

.post(uri, params, files = []) ⇒ Object

make a post request to an endpoint returns a hash of

- status code
- headers
- body


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
# File 'lib/service.rb', line 37

def post(uri, params, files=[])
  raise Flareshow::ConfigurationException unless server_defined?
  # create the request object
  req = Net::HTTP::Post.new(uri.path)
  # set request headers
  req.add_field "Accept", "application/json"
  req.add_field "User-Agent", "ruby flareshow"
  req.add_field "Accept-Encoding", "compress, gzip"

  # just json
  if !files || files.empty?
    req.add_field "Content-type", "application/json; charset=UTF-8"
    # set the postbody
    req.body = params.to_json
  # handle file params
  else
    params = params.map{|p| 
      val = p[1].is_a?(String) ? p[1] : p[1].to_json
      Param.new(p[0], val, "application/json")
    }
    files.each do |f|
      params << FileParam.new(f["part_id"], f["file_path"], File.read(f["file_path"]))
    end
    body, header = *MultipartPost.prepare_query(params)
    req.add_field "Content-type", header["Content-type"]
    req.body = body
  end
  
  # make the request
  http = Net::HTTP.new(uri.host, uri.port)
  http.set_debug_output DEFAULT_LOGGER if debug_output
  response = http.start {|h| h.request(req)}
  
  # normalize the response
  response = process_response(response)
  log_response(response)
  response
end

.process_response(response) ⇒ Object

get the interesting bits out of the curl response



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/service.rb', line 156

def process_response(response)
  # read the response headers
  headers = {}; response.each_header{|k,v| headers[k] = v}
  # build a response object
  response_obj = {"status_code" => response.code.to_i, "headers" => headers, "body" => response.plain_body}
  
  # automatically handle json response
  if (/json/i).match(response.content_type)
    response_obj["resources"] = JSON.parse(response_obj["body"])
  end
  
  # log the response
  Flareshow::Util.log_info(response_obj["status_code"])
  Flareshow::Util.log_info(response_obj["body"])
  response_obj
end

.query(params = {}) ⇒ Object

query the server with an http post of the query params



119
120
121
122
123
# File 'lib/service.rb', line 119

def query(params={})
  raise Flareshow::AuthenticationRequired unless @key
  params = {"key" => @key, "query" => params}
  post(api_endpoint, params)
end

.server_defined?Boolean

has the server been configured?

Returns:

  • (Boolean)


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

def server_defined?
  !!server
end