Class: Halffare::Fetch

Inherits:
Object
  • Object
show all
Defined in:
lib/halffare/fetch.rb

Constant Summary collapse

USER_AGENT =
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'
URL_LOGIN =
'http://www.sbb.ch/meta/login.html'
URL_ORDERS =
'https://www.sbb.ch/ticketshop/b2c/dossierListe.do'
ORDER_NOTE_FILE_CREATED =
'halffare-orders-file-created'

Instance Method Summary collapse

Constructor Details

#initializeFetch

Returns a new instance of Fetch.



9
10
11
12
# File 'lib/halffare/fetch.rb', line 9

def initialize()
  @agent = ::Mechanize.new
  @agent.user_agent = USER_AGENT
end

Instance Method Details

#download(filename, pages, months) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/halffare/fetch.rb', line 30

def download(filename, pages, months)
  @response = @agent.get URL_ORDERS

  logged_in!

  begin
    left = pages.to_i
    page = 1
    stop_after = months ? (Date.today << months.to_i).strftime('%Y-%m-%d') : nil

    log_info "will stop scraping after reaching #{stop_after}" unless stop_after.nil?
    log_info "writing data to #{filename}"

    file = File.open(filename, "w")
    oldest_date_on_page = Date.today.strftime

    # fake entry so when evaluating this file the calculation goes up until today
    # and not to the last order.
    file.write "#{oldest_date_on_page}|#{oldest_date_on_page}|0|#{ORDER_NOTE_FILE_CREATED}|\n"

    loop do
      print ">>> page #{page}/#{pages} "
      orders do |idx, travel_date, order_date, price, note, name|
        print "."

        travel_date = Date.parse(travel_date).strftime
        order_date = Date.parse(order_date).strftime
        oldest_date_on_page = [order_date, oldest_date_on_page].min

        file.write "#{travel_date}|#{order_date}|#{price}|#{note}|#{name}\n" if stop_after.nil? || travel_date >= stop_after
      end
      puts
      next!

      log_debug "oldest order on page was on #{oldest_date_on_page}" if Halffare.debug

      page += 1
      left -= 1

      break if !stop_after.nil? && oldest_date_on_page < stop_after
      break if left <= 0
    end
  rescue IOError => e
    puts e
  ensure
    file.close unless file == nil
  end
end

#login(username, password) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/halffare/fetch.rb', line 14

def (username, password)
  username = ask("sbb.ch username?  ") unless username
  password = ask("sbb.ch password?  ") { |q| q.echo = "*" } unless password
  log_info "logging in..."

  #@agent.log = Logger.new('debug.log')

  @response = @agent.get URL_LOGIN

   = @response.forms.first
  ['logon.username'] = username
  ['logon.password'] = password

  @response = @agent.submit()
end