Class: Truveo

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

Overview

The Truveo class implements a Ruby version of the Truveo API (see the Truveo Developer Site for details).

A Truveo object is initialized with an developer id, which is free and can be obtained from the Truveo Developer Site. A developer id will allow you to call the Truveo API up to 10,000 times per day.

Currently user functions, like ratings, are not implemented in the Ruby API.

Constant Summary collapse

@@sorter =
%w(sort:mostPopular sort:mostPopularNow sort:mostPopularThisWeek sort:mostPopularThisMonth sort:vrank sort:mostRecent sort:mostRelevant sort:topFavorites sort:highestRated)
@@filter =

XXXX add these, should there be two types? One that takes a comparison and one that doesn’t?

%w(days_old: bitrate: type:free type:reg type:sub type:rent type:buy runtime: quality:poor quality:fair quality:good quality:excellent format:win format:real format:qt format:flash format:hi-q site: file_size:)
@@modifier =
%w(category: channel: tag: user: id: sim: title: description: artist: album: show: actor: director: writer: producer: distributor:)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(appid, site = 'xml.searchvideo.com', path = "/apiv3?", port = 80) ⇒ Truveo

Create a new Truveo object for querying the Truveo video search engine. The appid is required. For your free appid go to My API Account where you easily sign up for your own appid, allowing you up to 10,000 Truveo queries per day. :call-seq: new(appid)

Example:

t = Truveo.new('my_appid')  # create a new Truveo object with your app_id


254
255
256
257
258
259
# File 'lib/truveo.rb', line 254

def initialize(appid, site = 'xml.searchvideo.com', path = "/apiv3?", port=80)
  @appid = appid 
  @site = site
  @path = path
  @port = port
end

Class Method Details

.filterObject

array of Truveo supported filters such as type:free

Example:

Truveo.filter.each{|f| puts f } # print all the filters


233
234
235
# File 'lib/truveo.rb', line 233

def Truveo.filter
  @@filter
end

.modifierObject

array of Truveo supported modifiers such as tag:

Example:

Truveo.modifier.each{|m| puts m } # print all the modifiers


242
243
244
# File 'lib/truveo.rb', line 242

def Truveo.modifier
  @@modifier
end

.sorterObject

array of Truveo supported sorters such as sort:vrank

Example:

Truveo.sorter.each{|s| puts s } # print all the sorters


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

def Truveo.sorter
  @@sorter
end

Instance Method Details

#api_error(xml) ⇒ Object

return the error as hash or nil if no error



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/truveo.rb', line 283

def api_error(xml) #:nodoc:
  if xml.nil?
    res = TruveoResponse.new
    res.error_code = '69'
    res.error_text = 'bad xml'
    return res
  end
  #<?xml version='1.0' encoding='UTF-8'?><Response><Error Code='14'>Access Denied: invalid appid.</Error></Response>
  if elt = xml.elements['//Error']
    res = TruveoResponse.new
    res.error_code = elt.attributes["Code"]
    res.error_text = elt.text
    return res
  end
  nil
end

#elt_text(xml, s) ⇒ Object

convert an xml element to a string



301
302
303
304
305
306
# File 'lib/truveo.rb', line 301

def elt_text(xml,s) #:nodoc:
  if elt = xml.elements[s]
    return elt.text
  end
  return nil
end

generic get_related for each of the get_related type calls



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/truveo.rb', line 423

def get_related(type='Tags', query='', results=10, start=0) #:nodoc:

  params = Hash.new
  params[:method] = "truveo.videos.getRelated#{type}"
  params[:query] = query    
  params[:appid]  = @appid              
  params[:results] = results
  params[:start] = start    

  xml = rest(params)
  
  res = TruveoResponse.new
  
  # check for error codes
  err = api_error(xml)
  return err if !err.nil?

  res.method = elt_text(xml,'//Response/method')
  res.query = elt_text(xml,'//Response/query')
  res.sortby = elt_text(xml,'//Response/sortby')
  res.query_suggestion = elt_text(xml,'//Response/querySuggestion')   
  
  res.sphinxquery = elt_text(xml,'//Response/sphinxquery')
  res.sphinxfilters = elt_text(xml,'//Response/sphinxfilters')
  
  res.total_results_returned = elt_text(xml, '//totalResultsReturned')    
  res.first_result_position = elt_text(xml, '//firstResultPosition')       
   
  res.send("#{singularize(type).downcase}_set=", set_hash(xml,"//#{singularize(type)}"))
  
  res
  
end

Return a hash of the categories and counts related to the query.

The results and start parameters are used for paging through the result set.



486
487
488
# File 'lib/truveo.rb', line 486

def get_related_categories(query='', results=10, start=0)
  get_related('Categories',query, results, start)
end

Return a hash of the channels and counts related to the query.

The results and start parameters are used for paging through the result set.



472
473
474
# File 'lib/truveo.rb', line 472

def get_related_channels(query='', results=10, start=0)
  get_related('Channels',query, results, start)
end

Return a hash of the tags and counts related to the query.

The results and start parameters are used for paging through the result set.

Example:

t = Truveo.new('appid_goes_here')
res = t.get_related_tags('funny')
res.tag_set.each_pair{|k,v| puts "tag: #{k} count: #{v}" }


465
466
467
# File 'lib/truveo.rb', line 465

def get_related_tags(query='', results=10, start=0)
  get_related('Tags', query, results, start)
end

Return a hash of the users and counts related to the query.

The results and start parameters are used for paging through the result set.



479
480
481
# File 'lib/truveo.rb', line 479

def get_related_users(query='', results=10, start=0)
  get_related('Users',query, results, start)
end

#get_videos(query = '', results = 10, start = 0, showRelatedItems = 0, tagResults = 10, channelResults = 10, categoryResults = 10, userResults = 10, showAdult = 0) ⇒ Object

performs the specified query and returns the results in the form of a TruveoResponse object.

query

this is the search query to run. See Building Search Queries for details.

results

number of results to return, the default is 10, the maximum is 50.

start

where to start the result set being returned, defaults to 0. Can be used to page through results.

showRelatedItems

indicates if the tag set, category set, and user set should be returned. Values should be 0 or 1, the default is 0.

tagResults

number of tags requested in the tag_set response.

channelResults

number of channels requested in the channel_set response.

categoryResults

number of categories requested in the category_set response.

userResults

number of users requested in the user_set response.

showAdult

flag indicating whether or not adult content should be included in the result set.

All of the result sizes above are maximums. A query may return fewer than the requested number of results if the requested

number of results don’t match.

If the query string is empty, then the top results are returned in vrank order.

If showRelatedItems is zero, the response will only includea a video_set. The tag_set, channel_set, category_set, and user_set parameters will be left out.



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/truveo.rb', line 333

def get_videos(query='', results=10, start=0, showRelatedItems=0, tagResults=10, channelResults=10, categoryResults=10, userResults=10, showAdult=0)
  params = Hash.new
  params[:method] = 'truveo.videos.getVideos'
  params[:query] = query    
  params[:showRelatedItems] = showRelatedItems
  params[:tagResults] = tagResults
  params[:channelResults] = channelResults
  params[:categoryResults] = categoryResults
  params[:userResults] = userResults
  params[:showAdult] = showAdult
  params[:appid]  = @appid              
  params[:results] = results
  params[:start] = start

  get_videos_hash(params)

end

#get_videos_hash(params) ⇒ Object

:nodoc:



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/truveo.rb', line 351

def get_videos_hash(params) #:nodoc:


  xml = rest(params)
  
  res = TruveoResponse.new
  
  # save params for next_video call
  res.params = params
  res.truveo = self
  
  # check for error codes
  err = api_error(xml)
  puts "get_videos(#{params[:query]}) returned error: #{err.error_code} #{err.error_text}" if $VERBOSE && !err.nil?
  return err if !err.nil?

  res.method = elt_text(xml,'//Response/method')
  res.query = elt_text(xml,'//Response/query')
  res.sortby = elt_text(xml,'//Response/sortby')
  res.query_suggestion = elt_text(xml,'//Response/querySuggestion')   
  
  res.total_results_available = elt_text(xml, '//VideoSet/totalResultsAvailable')
  res.total_results_returned = elt_text(xml, '//VideoSet/totalResultsReturned')    
  res.first_result_position = elt_text(xml, '//VideoSet/firstResultPosition')        

  res.rss_url = elt_text(xml, '//rssUrl')        
  res.video_set_title = elt_text(xml, '//VideoSet/title')        
  
  res.sphinxquery = elt_text(xml,'//Response/sphinxquery')
  res.sphinxfilters = elt_text(xml,'//Response/sphinxfilters')    
       
  # store the video set
  res.video_set = Array.new
  @video_set = Array.new
  xml.elements.each('//Video') {|v| 
    res.video_set << (tvid = xml_to_hash(v))
    @video_set << tvid      
  }
  
  @next_start = res.total_results_returned.to_i + res.first_result_position.to_i
  
  if res.total_results_returned.to_i != res.video_set.length
    puts "Warning: results mismatch: res.total_results_returned (#{res.total_results_returned}) != res.video_set.length (#{res.video_set.length})"
    # puts xml.to_s
  end
  
  # the channel_set is a hash, one entry per channel.  the key is the channel name, the value is the count.
  res.channel_results_returned = elt_text(xml, '//ChannelSet/totalResultsReturned')        
  res.channel_set = set_hash(xml,'//Channel')
  
  res.tag_results_returned = elt_text(xml, '//TagSet/totalResultsReturned')            
  res.tag_set = set_hash(xml,'//Tag')
  
  res.category_results_returned = elt_text(xml, '//CategorySet/totalResultsReturned')            
  res.category_set = set_hash(xml, '//Category')
  
  res.user_results_returned = elt_text(xml, '//UserSet/totalResultsReturned')            
  res.user_set = set_hash(xml, '//User')
  
  res
  
end

#rest(parms) ⇒ Object

generic rest call



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/truveo.rb', line 262

def rest(parms) # :nodoc:
  call = String.new(@path)
  parms.each{|k,v| call << "#{k}=#{v}&"}
  call.chop! 
  call = URI.escape(call)
  api_site = Net::HTTP.new(@site,@port)
  # puts call
  xml = REXML::Document.new(body = api_site.request_get(call).body)
  return xml
rescue REXML::ParseException => e
  puts "rest parse rescue: " # + e.to_s
  puts "zzz>>> #{body}<<<zzz"
  return nil
rescue Exception => e
  puts "rest rescue: " + e.to_s.split("\n")[0]
  pp e
  puts "site, path, parms: #{@site}, #{@path}, :#{call}:"
  return nil
end

#set_hash(xml, s) ⇒ Object

return the hash for the given set (category, channel, tag, or user)



415
416
417
418
419
# File 'lib/truveo.rb', line 415

def set_hash(xml,s) #:nodoc:
  h = Hash.new
  xml.elements.each(s){|v| h[v.elements['name'].text] = v.elements['count'].text.to_i}   
  h
end

#xml_to_hash(xml) ⇒ Object

convert xml to hash



309
310
311
312
313
# File 'lib/truveo.rb', line 309

def xml_to_hash(xml) #:nodoc:
  h = Hash.new
  xml.elements.each{|e| h[e.name] = e.text }
  h 
end