Skip to content

Instantly share code, notes, and snippets.

@andy318
Created October 17, 2013 21:23
Show Gist options
  • Save andy318/7032415 to your computer and use it in GitHub Desktop.
Save andy318/7032415 to your computer and use it in GitHub Desktop.
Find a set of records in the db and update their contents based on JSON data retrieved from a web service
require 'rubygems'
require 'json'
require 'open-uri'
require 'active_support'
require 'net/http'
def save_video_metadata
# x = ZencoderJob.find_by_sql("select Z.* from zencoder_jobs as Z inner join items as I on I.id = Z.item_id where I.file_content_type like 'video%' and Z.status = 'finished'")
# x.each do |job|
ZencoderJob.where(status:"finished").joins(:item).where("items.file_content_type LIKE 'video%'").find_each do |job|
item = Item.unscoped.find(job.item_id)
video_detail = VideoDetail.find_or_create_by_item_id(job.item_id) if item
unless video_detail.format
json_hash = ActiveSupport::JSON.decode(open("https://app.zencoder.com/api/v2/jobs/#{job.job_id}.json?api_key=xyz").read)
if json_hash
begin
video_detail.format = json_hash['job']['input_media_file']['format']
video_detail.height = json_hash['job']['input_media_file']['height']
video_detail.width = json_hash['job']['input_media_file']['width']
video_detail.duration_seconds = json_hash['job']['input_media_file']['duration_in_ms'] / 1000
video_detail.frame_rate = json_hash['job']['input_media_file']['frame_rate'].to_s
video_detail.total_bitrate_kbps = json_hash['job']['input_media_file']['total_bitrate_in_kbps']
puts "About to save video_detail obect - #{video_detail.inspect}"
video_detail.save
rescue StandardError => e
puts "Error encountered #{e.inspect} while processing item -\n #{item.inspect}\nHere is the info returned from Zencoder - #{json_hash['job']['input_media_file'].inspect}"
end
else
puts "Skipping item #{job.item_id}, job #{job.job_id} since no information was returned by Zencode for it"
end
else
puts "Skipping item #{job.item_id} since video_details are already populated for it. Video details - #{video_detail.inspect}"
end
end
end
save_video_metadata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment