Class: Trubl::Client

Inherits:
Object
  • Object
show all
Includes:
API::Category, API::Channel, API::Conversation, API::Hashtags, API::Me, API::Search, API::Streams, API::Suggested_Users, API::Touts, API::Users, OAuth
Defined in:
lib/trubl/client.rb

Overview

Note:

All methods have been separated into modules and follow the grouping used in http://developer.tout.com/apis the Tout API Documentation.

Wrapper for the Tout REST API

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from OAuth

#client_auth, #password_auth

Methods included from API::Users

#follow_user, #retrieve_user, #retrieve_user_followers, #retrieve_user_likes, #retrieve_user_touts, #retrieve_user_widgets, #retrieve_users, #unfollow_user

Methods included from API::Touts

#create_tout, #delete_tout, #featured_touts, #latest_touts, #like_tout, #retout_tout, #retrieve_tout, #retrieve_tout_conversation, #retrieve_touts, #retrieve_updates, #tout_liked_by, #unlike_tout, #update_tout

Methods included from API::Suggested_Users

#suggested_users

Methods included from API::Streams

#retrieve_stream_touts

Methods included from API::Search

#search_hashtags, #search_touts, #search_users

Methods included from API::Me

#friends, #get_me, #get_my_authorizations, #get_my_fb_sharing_settings, #get_my_liked_touts, #get_my_touts, #update_me, #widgets

Methods included from API::Hashtags

#follow_hashtag, #retrieve_hashtag, #retrieve_hashtag_touts, #retrieve_suggested_hashtags, #retrieve_trending_hashtags, #unfollow_hashtag

Methods included from API::Conversation

#retrieve_conversation, #retrieve_conversation_participants, #retrieve_conversation_touts

Methods included from API::Channel

#retrieve_channel, #retrieve_channel_touts, #retrieve_channel_users

Methods included from API::Category

#retrieve_category, #retrieve_category_touts, #retrieve_category_users

Constructor Details

#initialize(client_id = nil, client_secret = nil, callback_url = nil, *args) ⇒ Client

Initialize a new Tout client with creds and callback url



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/trubl/client.rb', line 45

def initialize(client_id=nil, client_secret=nil, callback_url=nil, *args)
  opts = (args.last.is_a?(Hash) ? args.last : {}).with_indifferent_access

  opts.delete_if { |k, v| v.nil? }.reverse_merge!(default_tout_configuration)

  @client_id =     client_id
  @client_secret = client_secret
  @access_token =  opts[:access_token]
  @callback_url =  callback_url
  @uri_scheme =    opts[:uri_scheme]
  @uri_host =      opts[:uri_host]
  @uri_port =      opts[:uri_port]
  @uri_base_path = opts[:uri_base_path]
  @uri_version =   opts[:uri_version]
  @auth_site =     opts[:auth_site]
  @authorize_url = opts[:authorize_url]
  @token_url =     opts[:token_url]
  @email =         opts[:email]
  @password =      opts[:password]
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



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

def access_token
  @access_token
end

#callback_urlObject (readonly)

Returns the value of attribute callback_url.



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

def callback_url
  @callback_url
end

#client_idObject (readonly)

Returns the value of attribute client_id.



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

def client_id
  @client_id
end

#client_secretObject (readonly)

Returns the value of attribute client_secret.



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

def client_secret
  @client_secret
end

Instance Method Details

#api_uri_rootObject



88
89
90
91
92
93
94
95
96
97
98
# File 'lib/trubl/client.rb', line 88

def api_uri_root()
  # Changed this from URI.join because scheme became pointless. It could not
  # override the scheme set in the host and the scheme was required to be set
  # in @uri_host or else URI.join throws an error
  URI.parse('').tap do |uri|
    uri.scheme = @uri_scheme
    uri.host   = @uri_host.gsub(/https?:\/\//, '') # strip the scheme if it is part of the hostname
    uri.path   = [@uri_base_path, @uri_version, nil].join('/')
    uri.port   = @uri_port unless @uri_port.blank?
  end.to_s
end

#credentialsObject



80
81
82
83
84
85
86
# File 'lib/trubl/client.rb', line 80

def credentials()
  { 
    client_id:     @client_id,
    client_secret: @client_secret,
    access_token:  @access_token
  }
end

#default_tout_configurationObject



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/trubl/client.rb', line 66

def default_tout_configuration
  {
    uri_scheme:    'https',
    uri_host:      'api.tout.com',
    uri_base_path: '/api',
    uri_version:   'v1',
    auth_site:     'https://www.tout.com/',
    authorize_url: '/oauth/authorize',
    token_url:     '/oauth/token',
    email:         nil,
    password:      nil
  }.with_indifferent_access
end

#delete(path, params = {}) ⇒ Object

Perform an HTTP DELETE request



101
102
103
# File 'lib/trubl/client.rb', line 101

def delete(path, params={})
  request(:delete, path, params)
end

#get(path, params = {}) ⇒ Object

Perform an HTTP GET request



106
107
108
# File 'lib/trubl/client.rb', line 106

def get(path, params={})
  request(:get, path, params)
end

#multi_request(method, requests = [], opts = {}) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/trubl/client.rb', line 158

def multi_request(method, requests=[], opts={})
  return [] if requests.blank? or [:get].exclude?(method.to_sym)

  if requests.size == 1
    request = requests.first
    path = [request[:path], request[:query].try(:to_query)].compact.join('?')
    return [request(method, path, request[:params])]
  end

  opts.reverse_merge! max_concurrency: 10

  Trubl.logger.info("Trubl::Client   multi-#{method}-ing #{requests.join(', ')} with headers #{headers}")      

  action = RUBY_ENGINE == 'ruby' ? :multi_request_typhoeus : :multi_request_threaded

  self.send(action, method, requests, opts).collect do |response|
    response.body.force_encoding("utf-8") if response.body and response.body.respond_to?(:force_encoding)
    response
  end
end

#multi_request_threaded(method, requests = [], opts = {}) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/trubl/client.rb', line 179

def multi_request_threaded(method, requests=[], opts={})
  responses = []
  mutex = Mutex.new
  requests = requests.clone

  opts[:max_concurrency].times.map do
    Thread.new(requests, responses) do |requests, responses|
      while request = mutex.synchronize { requests.pop }
        response = HTTParty.send(method, full_url(request[:path]), {headers: headers}.merge(request[:params] || {} ))
        mutex.synchronize { responses << response }
      end
    end
  end.each(&:join) 

  responses     
end

#multi_request_typhoeus(method, requests = [], opts = {}) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/trubl/client.rb', line 196

def multi_request_typhoeus(method, requests=[], opts={})
  # https://github.com/lostisland/faraday/wiki/Parallel-requests
  # https://github.com/typhoeus/typhoeus/issues/226
  hydra = Typhoeus::Hydra.new(max_concurrency: opts[:max_concurrency])
 
  conn = Faraday.new(url: api_uri_root, parallel_manager: hydra) do |builder|
    builder.request  :url_encoded
    builder.adapter  :typhoeus
  end

  requests = requests.collect do |request|
    if request.is_a?(String)
      {path: request, params: {}}
    else
      request.reverse_merge params: {}
    end
  end

  [].tap do |responses|
    conn.in_parallel do
      requests.each do |request|
        path = [request[:path], request[:query].try(:to_query)].compact.join('?')
        responses << conn.send(method, path, request[:params], headers)
      end
    end
  end
end

#multipart_post(path, params = {}) ⇒ Object

Perform an HTTP Multipart Form Request

Raises:

  • (ArgumentError)


116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/trubl/client.rb', line 116

def multipart_post(path, params={})
  raise ArgumentError.new("Must specify a valid file to include\nYou specified #{params[:data]}") unless File.exists?(params[:data])
  uri = full_uri(path)
  payload = { 'tout[data]' => Faraday::UploadIO.new(params[:data], 'video/mp4')}.merge(params)

  Trubl.logger.info("Trubl::Client   multipart post-ing #{uri.to_s} (content omitted)")

  Faraday.new(url: uri.host) do |faraday|
    faraday.headers = options
    faraday.request :multipart
    faraday.response :logger
    faraday.adapter Faraday.default_adapter
  end.post(uri.to_s, payload).tap do |response|      
    if !response.status =~ /20[0-9]/
      Trubl.logger.fatal("Trubl::Client   multipart post-ing #{uri.to_s} #{response.code} #{response.parsed_response}")
    end
  end
end

#post(path, params = {}) ⇒ Object

Perform an HTTP POST request



111
112
113
# File 'lib/trubl/client.rb', line 111

def post(path, params={})
  request(:post, path, params)
end

#put(path, params = {}) ⇒ Object

Perform an HTTP PUT request



136
137
138
# File 'lib/trubl/client.rb', line 136

def put(path, params={})
  request(:put, path, params)
end

#request(method, path, params) ⇒ Object

ToDo: model response handling off of oauth2.client.request in fact, perhaps we swap this out for the oauth2 request method...



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/trubl/client.rb', line 142

def request(method, path, params)
  params ||= {}
  uri = full_url(path)

  Trubl.logger.info("Trubl::Client   #{method}-ing #{uri} with params #{params.merge(headers: headers)}")
  response = HTTParty.send(method, uri, params.merge(headers: headers))

  if !response.code =~ /20[0-9]/
    Trubl.logger.fatal("Trubl::Client   #{response.code} #{method}-ing #{uri.to_s} #{response.parsed_response}")
  else
    Trubl.logger.debug("Trubl::Client   #{uri} response: #{response.body}")
  end
  response.body.force_encoding("utf-8") if response.body and response.body.respond_to?(:force_encoding)
  response
end

#set_logger(level) ⇒ Object



224
225
226
# File 'lib/trubl/client.rb', line 224

def set_logger(level)
  Trubl.logger(level)
end