Class: Transcriptic::Client

Inherits:
Object
  • Object
show all
Extended by:
Helpers
Includes:
Helpers, UI
Defined in:
lib/transcriptic/client.rb

Overview

A Ruby class to call the Transcriptic REST API. You might use this if you want to manage your Transcriptic apps from within a Ruby program, such as Capistrano.

Example:

require 'transcriptic'
transcriptic = Transcriptic::Client.new('[email protected]', 'mypass')
transcriptic.list_resources
transcriptic.run_info("run-625f827a")

Defined Under Namespace

Modules: JSON

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers

json_decode, json_encode, running_on_a_mac?, running_on_windows?

Methods included from UI

#arrow, #confirm, #confirm_billing, #confirm_command, #confirm_quote, #deprecate, disable_error_capture, #display, #display_row, #display_table, enable_error_capture, #error, #error_with_failure, extended, extended_into, #fail, #format_bytes, #format_date, #format_with_bang, #get_terminal_environment, included, included_into, #indent, #info, #json_decode, #json_encode, #longest, #mute!, #output, #output_with_arrow, #output_with_bang, #output_with_indent, #quantify, #quiet?, #redisplay, #say, #say_status, #set_buffer, #status, #string_distance, #suggestion, #time_ago, #truncate, #unmute!, #wait_spinner, #warn

Constructor Details

#initialize(user, api_key, host = Transcriptic::Auth.default_host) ⇒ Client

Returns a new instance of Client.



37
38
39
40
41
# File 'lib/transcriptic/client.rb', line 37

def initialize(user, api_key, host = Transcriptic::Auth.default_host)
  @user = user
  @api_key = api_key
  @host = host
end

Instance Attribute Details

#api_keyObject

Returns the value of attribute api_key.



27
28
29
# File 'lib/transcriptic/client.rb', line 27

def api_key
  @api_key
end

#hostObject

Returns the value of attribute host.



27
28
29
# File 'lib/transcriptic/client.rb', line 27

def host
  @host
end

#userObject

Returns the value of attribute user.



27
28
29
# File 'lib/transcriptic/client.rb', line 27

def user
  @user
end

Class Method Details

.auth(user, password, host = Transcriptic::Auth.default_host) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/transcriptic/client.rb', line 29

def self.auth(user, password, host = Transcriptic::Auth.default_host)
  client = new(user, nil, host)
  json_decode client.post('/users/sign_in', {
    'user[email]' => user,
    'user[password]' => password
  }, :accept => 'json').to_s
end

.gem_version_stringObject



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

def self.gem_version_string
  "transcriptic/#{version}"
end

.versionObject



19
20
21
# File 'lib/transcriptic/client.rb', line 19

def self.version
  Transcriptic::VERSION
end

Instance Method Details

#create_or_get_protocol(labfile, signature) ⇒ Object



122
123
124
125
126
127
# File 'lib/transcriptic/client.rb', line 122

def create_or_get_protocol(labfile, signature)
  if not get_protocol(labfile)
    create_protocol(labfile)
  end
  update_protocol(labfile, signature)
end

#create_protocol(labfile) ⇒ Object



96
97
98
99
100
101
102
103
# File 'lib/transcriptic/client.rb', line 96

def create_protocol(labfile)
  json_decode post("/api/protocols", {
    "protocol[name]" => labfile.options[:name],
    "protocol[author_email]" => labfile.options[:email],
    "protocol[author_name]" => labfile.options[:author],
    "protocol[description]" => labfile.options[:description]
  }).to_s
end

#create_run(fd, project_id) ⇒ Object



129
130
131
132
133
134
135
# File 'lib/transcriptic/client.rb', line 129

def create_run(fd, project_id)
  payload = {
    'zipdata' => Base64.encode64(File.open(fd).read),
    'project_id' => project_id
  }
  json_decode post("/api/runs", payload, { 'Content-Type' => 'application/zip; charset=UTF-8' }).to_s
end

#delete(uri, extra_headers = {}) ⇒ Object

:nodoc:



193
194
195
# File 'lib/transcriptic/client.rb', line 193

def delete(uri, extra_headers={})    # :nodoc:
  process(:delete, uri, extra_headers)
end

#escape(value) ⇒ Object

:nodoc:



244
245
246
247
# File 'lib/transcriptic/client.rb', line 244

def escape(value)  # :nodoc:
  escaped = URI.escape(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
  escaped.gsub('.', '%2E') # not covered by the previous URI.escape
end

#extract_warning(response) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
# File 'lib/transcriptic/client.rb', line 217

def extract_warning(response)
  return unless response
  if response.headers[:x_transcriptic_warning] && @warning_callback
    warning = response.headers[:x_transcriptic_warning]
    @displayed_warnings ||= {}
    unless @displayed_warnings[warning]
      @warning_callback.call(warning)
      @displayed_warnings[warning] = true
    end
  end
end

#get(uri, extra_headers = {}) ⇒ Object

:nodoc:



181
182
183
# File 'lib/transcriptic/client.rb', line 181

def get(uri, extra_headers={})    # :nodoc:
  process(:get, uri, extra_headers)
end

#get_protocol(labfile) ⇒ Object



88
89
90
91
92
93
94
# File 'lib/transcriptic/client.rb', line 88

def get_protocol(labfile)
  begin
    json_decode get("/api/protocols/#{labfile.options[:name]}").to_s
  rescue RestClient::ResourceNotFound
    false
  end
end

#list_resourcesObject



47
48
49
# File 'lib/transcriptic/client.rb', line 47

def list_resources
  json_decode get("/api/resources.json").to_s
end

#list_runsObject



55
56
57
# File 'lib/transcriptic/client.rb', line 55

def list_runs
  json_decode get("/api/runs.json").to_s
end

#on_warning(&blk) ⇒ Object



169
170
171
# File 'lib/transcriptic/client.rb', line 169

def on_warning(&blk)
  @warning_callback = blk
end

#post(uri, payload = "", extra_headers = {}, host = host) ⇒ Object

:nodoc:



185
186
187
# File 'lib/transcriptic/client.rb', line 185

def post(uri, payload="", extra_headers={}, host=host)    # :nodoc:
  process(:post, uri, extra_headers, payload, host)
end

#process(method, uri, extra_headers = {}, payload = nil, host = host) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/transcriptic/client.rb', line 197

def process(method, uri, extra_headers={}, payload=nil, host=host)
  headers  = transcriptic_headers.merge(extra_headers)
  args     = [method, payload, headers].compact

  resource_options = default_resource_options_for_uri(uri)

  begin
    response = resource(uri, resource_options, host).send(*args)
  rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT, SocketError
    host = URI.parse(realize_full_uri(uri, host)).host
    Transcriptic.ui.error " !   Unable to connect to #{host}"
  rescue RestClient::SSLCertificateNotVerified => ex
    host = URI.parse(realize_full_uri(uri, host)).host
    Transcriptic.ui.error "WARNING: Unable to verify SSL certificate for #{host}\nTo disable SSL verification, run with TRANSCRIPTIC_SSL_VERIFY=disable"
  end

  extract_warning(response)
  response
end

#put(uri, payload, extra_headers = {}) ⇒ Object

:nodoc:



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

def put(uri, payload, extra_headers={})    # :nodoc:
  process(:put, uri, extra_headers, payload)
end

#read_logs(run_id, options = []) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/transcriptic/client.rb', line 137

def read_logs(run_id, options=[])
  query = "&" + options.join("&") unless options.empty?
  url = get("/api/runs/#{run_id}/logs.json?#{query}").to_s
  if 'not_found' == url
    error "Run #{run_id} not found!"
  end

  uri  = URI.parse(url);
  http = Net::HTTP.new(uri.host, uri.port)

  if uri.scheme == 'https'
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end

  http.read_timeout = 60 * 60 * 24

  begin
    http.start do
      http.request_get(uri.path + (uri.query ? "?" + uri.query : "")) do |request|
        request.read_body do |chunk|
          yield chunk
        end
      end
    end
  rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT, SocketError
    abort(" !    Could not connect to logging service")
  rescue Timeout::Error, EOFError
    abort("\n !    Request timed out")
  end
end

#resource(uri, options = {}, host = host) ⇒ Object



175
176
177
178
179
# File 'lib/transcriptic/client.rb', line 175

def resource(uri, options={}, host=host)
  RestClient.proxy = ENV['HTTP_PROXY'] || ENV['http_proxy']
  resource = RestClient::Resource.new(realize_full_uri(uri, host), options)
  resource
end

#resource_info(id) ⇒ Object



51
52
53
# File 'lib/transcriptic/client.rb', line 51

def resource_info(id)
  json_decode get("/api/resources/#{id}.json").to_s
end

#run_info(id) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/transcriptic/client.rb', line 59

def run_info(id)
  begin
    json_decode get("/api/runs/#{id}.json").to_s
  rescue RestClient::ResourceNotFound
    false
  end
end

#search_resources(term, limit = 10) ⇒ Object



43
44
45
# File 'lib/transcriptic/client.rb', line 43

def search_resources(term, limit = 10)
  json_decode get("/api/resources/search.json?query=#{escape(term)}&limit=#{limit}").to_s
end

#sign_upload(labfile, filename) ⇒ Object



67
68
69
# File 'lib/transcriptic/client.rb', line 67

def sign_upload(labfile, filename)
  json_decode get("/api/upload/sign?type=protocol-pkg&group=#{labfile.options[:group]}&name=#{labfile.options[:name]}&filename=#{filename}&version=#{labfile.options[:version]}").to_s
end

#transcriptic_headersObject

:nodoc:



229
230
231
232
233
234
235
236
237
238
# File 'lib/transcriptic/client.rb', line 229

def transcriptic_headers   # :nodoc:
  headers = {
    'X-API-Version'       => '1',
    'User-Agent'          => self.class.gem_version_string,
    'X-Ruby-Version'      => RUBY_VERSION,
    'X-Ruby-Platform'     => RUBY_PLATFORM
  }
  headers = headers.merge({'Authorization' => "Token token=\"#{@api_key}\""}) if @api_key
  headers
end

#update_protocol(labfile, signature) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/transcriptic/client.rb', line 105

def update_protocol(labfile, signature)
  payload = {
    "protocol[name]" => labfile.options[:name],
    "protocol[author_email]" => labfile.options[:email],
    "protocol[author_name]" => labfile.options[:author],
    "protocol[description]" => labfile.options[:description],
    "protocol[package][key]" => signature["key"],
    "protocol[package][version]" => labfile.options[:version],
    "protocol[package][dependencies]" => labfile.dependencies.to_json
  }
  begin
    json_decode put("/api/protocols/#{labfile.options[:name]}", payload).to_s
  rescue RestClient::UnprocessableEntity => ex
    json_decode ex.response.to_s
  end
end

#upload_to_s3(path, signature) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/transcriptic/client.rb', line 71

def upload_to_s3(path, signature)
  conn = Faraday.new(:url => "https://#{signature["bucket"]}.s3.amazonaws.com") do |faraday|
    faraday.request  :multipart
    faraday.request  :url_encoded
    faraday.adapter  :net_http
  end
  res = conn.post "/", {
    "key" => signature["key"],
    "AWSAccessKeyId" => signature["access_key"],
    "acl" => "private",
    "success_action_status" => signature["success_action_status"],
    "policy" => signature["policy"],
    "signature" => signature["signature"],
    "file" => Faraday::UploadIO.new(path, 'application/jar')
  }
end

#xml(raw) ⇒ Object

:nodoc:



240
241
242
# File 'lib/transcriptic/client.rb', line 240

def xml(raw)   # :nodoc:
  REXML::Document.new(raw)
end