require "rubygems"
require "nokogiri"
require "mechanize"
require "plist"
require "app_store"
# Client regroups all the calling and xml parsing mechanism to call the AppStore.
class AppStore::Client
# Urls
FeaturedCategoriesURL = "http://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewFeaturedSoftwareCategories"
ApplicationURL = "http://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware"
CategoryURL = "http://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewGenre"
SearchURL = "http://ax.search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search"
# Store Front
StoreFronts = {
:us => "143441",
:fr => "143442"
}
DefaultStoreFront = StoreFronts[:us]
def initialize(args = {})
# About the X-Apple-Store-Front header: this is used to select which store and which language.
# Format is XXXXXX-Y,Z where XXXXXX is the store number (us, french, ...), Y the language and Z the return format.
# If you omit the language, the default one for the store is used.
# Return format can be either "1" or "2" : "1" returns data to be directly displayed and "2" is a more structured format.
@store_front = "#{args[:store_front] || DefaultStoreFront},2"
end
# Call the Apple AppStore using given url and passing params with an HTTP Get method.
# Call is seen as a fake iPhone iTunes client.
def iphone_get(url, params = {})
Plist::parse_xml make_call_and_handle_answer(iphone_agent, url, params).body
end
alias :get :iphone_get
# Call the Apple AppStore using given url and passing params with HTTP Get method.
# Call is seen as a fake Mac OS X iTunes client.
def itunes_get(url, params = {})
Nokogiri.parse make_call_and_handle_answer(itunes_agent, url, params).body
end
protected
def iphone_agent
@iphone_agent ||= WWW::Mechanize.new { |a| a.user_agent = 'iTunes-iPhone/3.0 (2)' }
end
def itunes_agent
@itunes_agent ||= WWW::Mechanize.new { |a| a.user_agent = 'iTunes/9.0.1 (Macintosh; Intel Mac OS X 10.6.1) AppleWebKit/531.9' }
end
def headers
{
"X-Apple-Store-Front" => @store_front
}
end
# Make call using given agent, url and params.
# Handle answer code and returns answer if answer code was correct.
def make_call_and_handle_answer(agent, url, params)
answer = agent.get(:url => url, :headers => headers, :params => params)
raise AppStore::RequestError if answer.code.to_s != '200'
answer
end
end