require 'pp' require 'rubygems' require 'json' require 'httpclient' username = ARGV[0] password = ARGV[1] api_key = ARGV[2] file = ARGV[3] list_id = ARGV[4] cue_lang = ARGV[5] response_lang = ARGV[6] if ! username || ! password || ! api_key || ! file || ! list_id || ! cue_lang || ! response_lang print " Usage: ruby upload.rb username password api_key file list_id 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 client = HTTPClient.new user = username password = password client.set_auth(nil, user, password) 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 begin 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, :api_key => api_key, 'response[text]' => response, }) item = JSON.parse(res) item_id = item['id'] print "new item: #{item_id}\n" res = client.post_content( "http://api.smart.fm/lists/#{list_id}/items.json", { 'id' => item_id, :api_key => api_key, }) # One possibility is: # {"error"=>{"code"=>400, "message"=>"Item already in Goal"}} # and we're OK with that. if ! item_id || ! item_id.is_a?(Numeric) if item['error']['message'] == 'Item already in Goal' print "Item's already in; that's OK.\n" pp res # Skip to save time; hopefully the audio file is there next else print "Something bad happened.\n" pp JSON.parse(res) raise Exception.new(true) end 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 rescue Exception => problem # Delete the item if we uploaded it if( item_id ) res = client.delete( "http://api.smart.fm/lists/#{list_id}/items/#{item_id}?api_key=#{api_key}" ) end print "Had an error with card #{cue}: #{problem} -- sleeping & retrying\n" sleep 60 retry end sleep 1 }