Class: Kaltura::KalturaClientBase

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

Direct Known Subclasses

KalturaClient

Constant Summary collapse

FIELD_EXPIRY =

KS V2 constants

'_e'
FIELD_TYPE =
'_t'
FIELD_USER =
'_u'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ KalturaClientBase

Returns a new instance of KalturaClientBase.



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/kaltura_client_base.rb', line 54

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.



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

def config
  @config
end

#is_multirequestObject (readonly)

Returns the value of attribute is_multirequest.



52
53
54
# File 'lib/kaltura_client_base.rb', line 52

def is_multirequest
  @is_multirequest
end

#responseHeadersObject (readonly)

Returns the value of attribute responseHeaders.



53
54
55
# File 'lib/kaltura_client_base.rb', line 53

def responseHeaders
  @responseHeaders
end

Class Method Details

.camelcase_to_underscore(val) ⇒ Object



279
280
281
# File 'lib/kaltura_client_base.rb', line 279

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

.object_from_xml(xml_element, return_type = nil) ⇒ Object



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
271
272
273
274
275
276
277
# File 'lib/kaltura_client_base.rb', line 219

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



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
359
360
361
362
363
364
365
# File 'lib/kaltura_client_base.rb', line 334

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

#aes_encrypt(key, data) ⇒ Object



439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/kaltura_client_base.rb', line 439

def aes_encrypt(key, data)
    iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"	# no need for an IV since we add a random string to the message anyway
    key = Digest::SHA1.digest(key)[0..15]
    cipher = OpenSSL::Cipher::AES.new(128, :CBC)
    cipher.encrypt

    cipher.padding = 0 # we must disable native padding.
    cipher.key = key
    cipher.iv = iv
    block_size = cipher.block_size
    # this is needed to maintain compatibility with the legacy mcrypt extension, see https://github.com/kaltura/server/blob/Rigel-18.16.0/infra/general/KCryptoWrapper.class.php#L79
    data = data + "\0" * (block_size - data.bytesize % block_size)
    return cipher.update(data) + cipher.final
end

#do_http_request(url, params, files) ⇒ Object



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
211
212
213
214
215
216
217
# File 'lib/kaltura_client_base.rb', line 179

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



321
322
323
# File 'lib/kaltura_client_base.rb', line 321

def do_multirequest()
	return do_queue()
end

#do_queueObject



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
143
144
145
146
147
148
149
# File 'lib/kaltura_client_base.rb', line 77

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



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

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



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/kaltura_client_base.rb', line 380

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

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



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/kaltura_client_base.rb', line 398

def generate_session_v2(admin_secret, user_id, kaltura_session_type, partner_id, expiry=86400, privileges=nil)
  fields = {} 
  if privileges !=nil 
    privileges.split(',').each do |privilege|
      privilege.strip!
      if !privilege
        next 
      end
      if (privilege == '*')
          privilege = 'all:*'
      end
      splitted_privilege = privilege.split(':', 2)
      if (splitted_privilege.count > 1)
              fields[splitted_privilege[0]] = splitted_privilege[1]
      else
              fields[splitted_privilege[0]] = ''
      end
    end
  end
  fields[KalturaClientBase::FIELD_EXPIRY] = (Time.now.to_i + expiry.to_i)
  fields[KalturaClientBase::FIELD_TYPE] = kaltura_session_type
  fields[KalturaClientBase::FIELD_USER] = user_id

  # build fields string
  fields_str = URI.encode_www_form(fields)
  rand = ''
  for i in 0..15 do
    rand += rand(0..0xff).chr
  end
  fields_str = rand + fields_str
  fields_str = Digest::SHA1.digest(fields_str) + fields_str

  # encrypt and encode
  encrypted_fields = aes_encrypt(admin_secret, fields_str)
  decoded_ks = "v2|#{partner_id}|" + encrypted_fields
  # in other clients, we do not set the ks on the client object here, only return it; however, because
  # this was done in generate_session(), I added it for compatibility reasons.
		  self.ks = Base64.urlsafe_encode64(decoded_ks).gsub('+','-').gsub('/','_') 
  return self.ks 
end

#get_serve_urlObject



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

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



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

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

#log(msg) ⇒ Object



374
375
376
377
378
# File 'lib/kaltura_client_base.rb', line 374

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

#parse_to_objects(data) ⇒ Object



283
284
285
# File 'lib/kaltura_client_base.rb', line 283

def parse_to_objects(data)
	parse_xml_to_objects(data)
end

#parse_xml_to_objects(xml) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/kaltura_client_base.rb', line 287

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



66
67
68
69
70
71
72
73
74
75
# File 'lib/kaltura_client_base.rb', line 66

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



305
306
307
308
309
310
311
# File 'lib/kaltura_client_base.rb', line 305

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



151
152
153
154
# File 'lib/kaltura_client_base.rb', line 151

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

#signature(params) ⇒ Object



325
326
327
328
329
330
331
332
# File 'lib/kaltura_client_base.rb', line 325

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



317
318
319
# File 'lib/kaltura_client_base.rb', line 317

def start_multirequest()
	@is_multirequest = true
end