Class: Kaltura::KalturaClientBase

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

Direct Known Subclasses

KalturaClient

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ KalturaClientBase



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/kaltura_client_base.rb', line 47

def initialize(config)
  @should_log = false
  @config = config
  @calls_queue = []
  @client_configuration = {}
  @request_configuration = {}

  if @config.logger != nil
    @should_log = true
  end
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



44
45
46
# File 'lib/kaltura_client_base.rb', line 44

def config
  @config
end

#is_multirequestObject (readonly)

Returns the value of attribute is_multirequest.



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

def is_multirequest
  @is_multirequest
end

#responseHeadersObject (readonly)

Returns the value of attribute responseHeaders.



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

def responseHeaders
  @responseHeaders
end

Class Method Details

.camelcase_to_underscore(val) ⇒ Object



272
273
274
# File 'lib/kaltura_client_base.rb', line 272

def self.camelcase_to_underscore(val)
  val.gsub(/(.)([A-Z])/,'\1_\2').downcase
end

.object_from_xml(xml_element, return_type = nil) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/kaltura_client_base.rb', line 212

def self.object_from_xml(xml_element, return_type = nil)
  if xml_element == nil
    return nil
  end
  instance = nil
  if xml_element.elements.size > 0
    if xml_element.elements[1].name == 'item' # array or map
      if (xml_element.elements[1].elements['itemKey'].nil?) # array
        instance = []
        xml_element.elements.each('item') do | element |
          instance.push(KalturaClientBase.object_from_xml(element, return_type))
        end
      else # map
        instance = {}
        xml_element.elements.each('item') do | element |
          item_key = element.get_text('itemKey').to_s
          instance[item_key] = KalturaClientBase.object_from_xml(element, return_type)
        end
      end
    else # object
      object_type_element = xml_element.get_text('objectType')
      if (object_type_element != nil)
        object_class = xml_element.get_text('objectType').value.to_s
        kalturaModule = Module.const_get("Kaltura")
        
        begin
          instance = kalturaModule.const_get(object_class).new
        rescue NameError => e
          if(return_type != nil)
            instance = kalturaModule.const_get(return_type).new
          else
            raise e
          end
        end

        instance.from_xml(xml_element);
      else # error
        error_element = xml_element.elements['error']
        if (error_element != nil)
          code = xml_element.elements["error/code"].text
          message = xml_element.elements["error/message"].text

          instance = KalturaAPIError.new(code, message)
        end
      end
    end
  elsif return_type == nil
    return nil 
  else # simple type
    value = xml_element.text
    if return_type == "int"
      return value.to_i
    end
    
    return value
  end

  return instance;
end

Instance Method Details

#add_param(params, name, value) ⇒ Object



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/kaltura_client_base.rb', line 327

def add_param(params, name, value)
  if value == KalturaNotImplemented
    return
  elsif value == nil
    params[name + '__null'] = ''
  elsif value.is_a? Hash
    params[name] = {}
    if value.empty?
      add_param(params[name], "-", "");
    else
      value.each do |sub_name, sub_value|
        add_param(params[name], sub_name, sub_value);
      end
    end
  elsif value.is_a? Array
    if value.empty?
      params[name] = {}
      add_param(params[name], "-", "");
    else
      params[name] = Array.new(value.size)
      value.each_with_index do |ele, i|
        if ele.is_a? KalturaObjectBase
          add_param(params[name], i, ele.to_params)
        end
      end
    end
  elsif value.is_a? KalturaObjectBase
    add_param(params, name, value.to_params)
  else
    params[name] = value
  end
end

#do_http_request(url, params, files) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/kaltura_client_base.rb', line 172

def do_http_request(url, params, files)

  headers = @config.requestHeaders
  headers[ 'Accept'] = 'text/xml';
    
  payload = {}
    
  if(files.size > 0)
    payload = files
    payload[:json] = params.to_json
  else
    payload = params.to_json
    headers[ 'Content-Type'] = 'application/json';
  end
  
  options = {
    :method => :post, 
    :url => url, 
    :headers => headers,
    :timeout => @config.timeout,
    :open_timeout => @config.timeout,
    :payload => payload
  }

  log("request options: " + JSON.pretty_generate(options))
                      if @config.http_proxy and !@config.http_proxy.empty?
                        RestClient.proxy = @config.http_proxy
                        log('Proxy server: ' + @config.http_proxy + ' will be used (KalturaConfiguration::http_proxy was set).')
                      elsif ENV['https_proxy']
                        RestClient.proxy = ENV['https_proxy']
                        log('Proxy server: ' + ENV['https_proxy'] + ' will be used (https_proxy ENV var is set).')
                      elsif ENV['http_proxy']
                        RestClient.proxy = ENV['http_proxy']
                        log('Proxy server: ' + ENV['http_proxy'] + ' will be used (http_proxy ENV var is set).')
                      end
  res = RestClient::Request.execute(options)

  return res
end

#do_multirequestObject



314
315
316
# File 'lib/kaltura_client_base.rb', line 314

def do_multirequest()
  return do_queue()
end

#do_queueObject



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
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
139
140
141
142
# File 'lib/kaltura_client_base.rb', line 70

def do_queue()
  begin
    @responseHeaders = {}
    start_time = Time.now

    if @calls_queue.length == 0
      @is_multirequest = false
      return []
    end

    log('service url: [' + @config.service_url + ']')

    # append the basic params
    params = {}
    files = {}
      
    url = @config.service_url+"/api_v3/"
    if (@is_multirequest)
      url += "service/multirequest/"
      i = 0
      @calls_queue.each do |call|
        call_params = call.get_params_for_multirequest(i)
        params.merge!(call_params)
        call_files = call.get_files_for_multirequest(i)
        files.merge!(call_files)
        i = i.next
      end
    else
      call = @calls_queue[0]
      url += "service/#{call.service}/action/#{call.action}"
      params.merge!(call.params)
      files = call.files
    end
    
    add_param(params, "format", @config.format)
    @client_configuration.each do |key, value|
      add_param(params, key, value)
    end

    signature = signature(params)
    add_param(params, "kalsig", signature)

    log("url: " + url)
    log("params: " + params.to_yaml)

    result = do_http_request(url, params, files)

    @responseHeaders = result.headers
    log("server: [" + result.headers[:x_me].to_s + "], session: [" + result.headers[:x_kaltura_session].to_s + "]")

    log("result (xml): " + result.body)

    result_object = parse_to_objects(result.body)

    # reset
    reset_request()

    log("result (object yaml dump): " + result_object.to_yaml)

    end_time = Time.now

    log("execution time for [#{url}]: [#{end_time - start_time}]")

    return result_object

  rescue KalturaAPIError => e
    reset_request()
    raise e
  rescue Exception => e
    reset_request()
    raise KalturaAPIError.new("KALTURA_RUBY_CLIENT_ERROR", e.to_s)
  end
end

#escape(s) ⇒ Object

Escapes a query parameter. Taken from RFuzz



361
362
363
364
365
# File 'lib/kaltura_client_base.rb', line 361

def escape(s)
  s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
    '%' + $1.unpack('H2'*$1.size).join('%').upcase
  }.tr(' ', '+')
end

#generate_session(admin_secret, user_id, kaltura_session_type, partner_id, expiry = 86400, privileges = nil) ⇒ Object



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/kaltura_client_base.rb', line 373

def generate_session(admin_secret, user_id, kaltura_session_type, partner_id, expiry=86400, privileges=nil)

  session = "#{partner_id};#{partner_id};#{Time.now.to_i + expiry};#{kaltura_session_type};#{rand.to_s.gsub("0.", "")};#{user_id};#{privileges};"

  digest_generator = OpenSSL::Digest.new('sha1')

  digest_generator.update(admin_secret)
  digest_generator.update(session)

  digest = digest_generator.hexdigest

  signature = digest + "|" + session
  b64 = Base64.encode64(signature)
  cleaned = b64.gsub("\n","")

  self.ks = cleaned
end

#get_serve_urlObject



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/kaltura_client_base.rb', line 149

def get_serve_url()
  url = @config.service_url+"/api_v3/service/"

  call = @calls_queue[0]
  url += call.service + "/action/" + call.action
  params = call.params

  # reset
  @calls_queue = []
  @is_multirequest = false

  query_string = '?'
  params.each do |name, value|
    query_string << "#{name}=#{CGI::escape(value.to_s)}&"
  end

  serve_url = "#{url}#{query_string}"

  log("serve_url: " + serve_url)

  return serve_url
end

#is_error(doc) ⇒ Object



306
307
308
# File 'lib/kaltura_client_base.rb', line 306

def is_error(doc)
  return doc.elements["xml/result/error/message"] && doc.elements["xml/result/error/code"];
end

#log(msg) ⇒ Object



367
368
369
370
371
# File 'lib/kaltura_client_base.rb', line 367

def log(msg)
  if @should_log
    config.logger.log(Logger::INFO, msg)
  end
end

#parse_to_objects(data) ⇒ Object



276
277
278
# File 'lib/kaltura_client_base.rb', line 276

def parse_to_objects(data)
  parse_xml_to_objects(data)
end

#parse_xml_to_objects(xml) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/kaltura_client_base.rb', line 280

def parse_xml_to_objects(xml)
  doc = REXML::Document.new(xml)
  raise_exception_if_error(doc)
  if (@is_multirequest)
    results = {}
    request_index = 0
    doc.elements.each('xml/result/*') do | element |
      results[request_index] = KalturaClientBase.object_from_xml(element, @calls_queue[request_index].return_type)
      request_index += 1
    end
    return results
  else
    doc.elements.each('xml/result') do | element |
      return KalturaClientBase.object_from_xml(element, @calls_queue.first.return_type)
    end
  end
end

#queue_service_action_call(service, action, return_type, params = {}, files = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
# File 'lib/kaltura_client_base.rb', line 59

def queue_service_action_call(service, action, return_type, params = {}, files = {})
  # in start session partner id is optional (default nil). if partner id was not set, use the one in the config

  @request_configuration.each do |key, value|
    add_param(params, key, value)
  end

  call = KalturaServiceActionCall.new(service, action, return_type, params, files);
  @calls_queue.push(call);
end

#raise_exception_if_error(doc) ⇒ Object



298
299
300
301
302
303
304
# File 'lib/kaltura_client_base.rb', line 298

def raise_exception_if_error(doc)
  if is_error(doc)
    code = doc.elements["xml/result/error/code"].text
    message = doc.elements["xml/result/error/message"].text
    raise KalturaAPIError.new(code, message)
  end
end

#reset_requestObject



144
145
146
147
# File 'lib/kaltura_client_base.rb', line 144

def reset_request()
  @calls_queue = []
  @is_multirequest = false
end

#signature(params) ⇒ Object



318
319
320
321
322
323
324
325
# File 'lib/kaltura_client_base.rb', line 318

def signature(params)
  kParams = params.select { |key, value| !value.is_a?(File) }
  str = kParams.keys.map {|key| key.to_s }.sort.map {|key|
    "#{key}#{params[key]}"
  }.join("")

  Digest::MD5.hexdigest(str)
end

#start_multirequestObject



310
311
312
# File 'lib/kaltura_client_base.rb', line 310

def start_multirequest()
  @is_multirequest = true
end