Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created January 24, 2010 18:12
Show Gist options
  • Select an option

  • Save lukeredpath/285347 to your computer and use it in GitHub Desktop.

Select an option

Save lukeredpath/285347 to your computer and use it in GitHub Desktop.
require 'fileutils'
REPORT_FOLDER = Pathname.new('/Users/luke/Documents/Business/Accounts/iTunes Finance Reports')
@agent = ITunesConnect::Agent.new
@agent.sign_in!('[email protected]', 'yourpassword')
begin
if @agent.signed_in?
@downloaded = 0
@agent.finance_reports.available_reports.each do |link|
output_dir = directory_for_report(link)
FileUtils.mkdir_p(output_dir)
@agent.download(link, output_dir)
@downloaded += 1
end
puts "Downloaded #{@downloaded} financial reports."
else
STDERR.puts "Couldn't sign in to iTunes Connect! Check your credentials."
exit 1
end
ensure
@agent.sign_out!
end
def directory_for_report(report)
result, month, year = *report.text.strip.match(/\d{8}_(\d{2})(\d{2}).*/)
date = Date.civil(year.to_i + 2000, month.to_i, 1)
output_dir = REPORT_FOLDER + date.strftime("%Y-%m-%b")
output_dir += 'Payment Advice' if report.text =~ /PYMT/
output_dir
end
require 'mechanize'
require 'open-uri'
require 'pathname'
module ITunesConnect
ROOT_URL = "https://itunesconnect.apple.com/"
LOGIN_PAGE = "#{ROOT_URL}/WebObjects/iTunesConnect.woa"
class Agent
attr_reader :current_page
def initialize
@current_page = nil
@agent = WWW::Mechanize.new
end
def sign_in!(username, password)
get(LOGIN_PAGE)
login_form = current_page.form('appleConnectForm')
login_form.theAccountName = username
login_form.theAccountPW = password
submit(login_form, 2)
end
def sign_out!
if logout_form = signed_in?
submit(logout_form)
end
end
def signed_in?
return nil unless current_page.respond_to?(:form)
current_page.form('signOutForm')
end
def click_link(link_text)
if links = current_page.links_with(:text => link_text)
click(links.first)
end
end
def finance_reports
link_text = 'Finance Reports'
if finance_link = (current_page.links_with(:text => link_text).first rescue nil)
click(finance_link)
else
return_home
click_link(link_text)
end
FinanceReports.new(@agent, current_page)
end
def return_home
click_link('Home')
end
def download(link, output_dir)
click(link)
if current_page.respond_to?(:filename)
File.open(output_dir + current_page.filename, 'w+') do |io|
io.write(current_page.body)
end
end
end
private
def click(link)
@current_page = @agent.click(link)
end
def get(url)
@current_page = @agent.get(url)
end
def submit(form, button_index = 0)
@current_page = @agent.submit(form, form.buttons[button_index])
end
end
class FinanceReports
def initialize(agent, page)
@agent, @page = agent, page
end
def available_reports
@page.links.map { |link| link if link.text.strip =~ /\.txt/}.compact
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment