require 'net/http' require 'pp' require 'rubygems' require 'json' require 'httpclient' class Hash def to_http_params results = [] return results if self.empty? self.each do |key, val| results << "#{key}=#{URI.encode(val.to_s)}" end results.join('&') end end username = ARGV[0] password = ARGV[1] api_key = ARGV[2] file = ARGV[3] list_name = ARGV[4] cue_lang = ARGV[5] response_lang = ARGV[6] if ! username || ! password || ! api_key || ! file || ! list_name || ! cue_lang || ! response_lang print " Usage: ruby upload.rb username password api_key file list_name cue_lang response_lang The file argument must be the name of a file that contains 4 columns, seperated by tabs: 1. cue text 2. response text 3. part of speech letter ( see http://developer.smart.fm/docs/Appendix/B_Parts_of_speech ) 4. local file name containing sound to upload " exit 1 end list_id = 0 client = HTTPClient.new user = username password = password client.set_auth(nil, user, password) # Look for the user's lists res = client.get_content("http://api.smart.fm/users/#{username}/lists/creator.json?per_page=100&include_private=true") JSON.parse(res).each { |item| print "id: #{item['id']}\n" # Use the id if it matches if item['title'] == list_name list_id = item['id'] end } if list_id == 0 # Create the list sleep 1 res = client.post_content( 'http://api.smart.fm/lists.json', { :api_key => api_key, 'list[name]' => list_name, 'list[language]' => cue_lang, 'list[translation_language]' => response_lang, }) # puts "list: " # pp JSON.parse(res)["id"] # puts "\n" if ! res || ! JSON.parse(res)["id"].to_i.is_a?(Numeric) exit 1 end list_id = JSON.parse(res)["id"].to_i puts "list id: #{list_id}\n" end f = File.open(file, "r") lines = f.readlines lines.each { |line| line = line.chomp bits = line.split("\t") cue = bits[0] response = bits[1] pos = bits[2] cue_file = bits[3] pp bits # Create the item sleep 1 res = client.post_content( "http://api.smart.fm/items.json", { 'response[language]' => response_lang, 'cue[text]' => cue, 'cue[part_of_speech]' => pos, 'cue[language]' => cue_lang, 'list_id' => list_id, :api_key => api_key, 'response[text]' => response, }) item_id = JSON.parse(res)['id'] print "new item: #{item_id}\n" if ! item_id || ! item_id.is_a?(Numeric) pp JSON.parse(res) exit 1 end sleep 1 # Upload the sound if cue_file =~ /^http:/ res = client.post_content( "http://api.smart.fm/items/#{item_id}/sounds.json", { :api_key => api_key, 'sound[url]' => cue_file, 'sound[text]' => cue, 'sound[language]' => cue_lang, } ) print "sound url add result: \n" pp JSON.parse(res) else res = client.post_content( "http://api.smart.fm/items/#{item_id}/sounds.json", { :api_key => api_key, 'sound[file]' => File.new('/home/rlpowell/programming/smart_fm_upload/test1.mp3'), 'sound[text]' => cue, 'sound[language]' => cue_lang, } ) print "sound upload result: \n" pp JSON.parse(res) end sleep 1 }