Created
July 30, 2009 17:42
-
-
Save konklone/158801 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/https' | |
require 'rexml/document' | |
require 'yaml' | |
CERT_FILENAME = File.dirname(__FILE__) + "/cacert.pem" | |
class Wesabe | |
attr_accessor :email, :password, :accounts, :account_xml, :http | |
def initialize(file) | |
creds_from_file file | |
initialize_http | |
end | |
def fetch_accounts | |
self.account_xml = get_accounts_xml | |
self.accounts = parse_accounts_list account_xml | |
end | |
def creds_from_file(file) | |
creds = YAML.load_file file | |
self.email = creds[:email] | |
self.password = creds[:password] | |
end | |
def initialize_http | |
unless File.exist?(CERT_FILENAME) | |
puts "Downloading certificate..." | |
cert = Net::HTTP.get('curl.haxx.se', '/ca/cacert.pem') | |
File.open(CERT_FILENAME, "w") { |f| f << cert } | |
puts "Certificate downloaded." | |
end | |
self.http = Net::HTTP.new("www.wesabe.com", 443) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_PEER | |
http.ca_file = CERT_FILENAME | |
end | |
def trigger_updates | |
http.start do |wesabe| | |
request = Net::HTTP::Post.new('/user/login') | |
request.set_form_data({'email' => email, 'password' => password}) | |
response = http.request(request) | |
case response | |
when Net::HTTPOK | |
STDERR.puts "Bad email and password" | |
when Net::HTTPRedirection | |
puts "Logged in successfully" | |
response.body | |
else | |
STDERR.puts "Unexpected response: #{response.inspect}" | |
exit(-1) | |
end | |
end | |
end | |
def get_accounts_xml | |
http.start do |wesabe| | |
request = Net::HTTP::Get.new('/accounts.xml') | |
request.basic_auth(email, password) | |
response = http.request(request) | |
case response | |
when Net::HTTPFound | |
STDERR.puts "Incorrect email or password." | |
response.each_header do |key, value| | |
STDERR.puts "#{key}: #{value}" | |
end | |
exit(-1) | |
when Net::HTTPOK | |
response.body | |
else | |
STDERR.puts "Unexpected response: #{response.inspect}" | |
exit(-1) | |
end | |
end | |
end | |
def parse_accounts_list(xml) | |
accounts = {} | |
doc = REXML::Document.new(xml) | |
doc.root.each_element('//account') do |account| | |
id = account.elements["id"].text | |
name = account.elements["name"].text | |
balance = account.elements["current-balance"].text.to_f | |
balance_in_cents = (balance * 100).to_i | |
accounts[id] = { | |
:name => name, | |
:balance => balance, | |
:balance_in_cents => balance_in_cents | |
} | |
end | |
accounts | |
end | |
def [](id) | |
accounts[id.to_s] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment