aboutsummaryrefslogtreecommitdiff
path: root/oyster
blob: 6522c91eba2a49a970ec7498543a4050106bf320 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env perl 
use strict;
use warnings;
use WWW::Mechanize;
use WWW::Mechanize::TreeBuilder;
use URI;
use DBI;
use Text::CSV_XS;
use Path::Class;
use Getopt::Long::Descriptive;
use Try::Tiny;
use DateTime;
use DateTime::Format::Strptime;
use open ':std',':locale';
 
my $default_db_path = file(__FILE__)->parent->file('oyster.db')->stringify;;
 
my ($opt,$usage) = describe_options(
    '%c %o',
    'database|d=s''path to the database to use',
      default => $default_db_path } ],
    'username|u=s''username to log in as (updates value in db)' ],
    'password|p=s''password to log in with (updates value in db)' ],
    [],
    'verbose|v''print progess' ],
    'help|h''print help and exit' ],
);
if ($opt->help) {
    print $usage->text;
    exit;
}
 
sub progress {
    return unless $opt->verbose;
    my $str=shift;
    printf "$str\n",@_;
}
 
my $dbh = DBI->connect(
    'dbi:SQLite:dbname='.$opt->database,
    '','',
    RaiseError => 1, PrintError => 0, AutoCommit => 1 },
);
 
my ($username,$password);
try {
    progress('getting credentials');
    ($username,$password) = $dbh->selectrow_array(
        'select username,password from credentials'
    );
}
catch {
    progress('new db, creating');
    # no table, create schema 
    $dbh->do(q{create table credentials (
      username text unique not null,
      password text not null
    )});
    $dbh->do(q{create table journeys (
      start_ts integer not null,
      stop_ts  integer not null,
      description text not null,
      charge real,
      credit real,
      balance real,
      note text,
      unique (start_ts,stop_ts) on conflict replace
    )});
    $dbh->do(
        q{insert into credentials (username,password) values (?,?)},
        {},
        $opt->username,
        $opt->password,
    );
};
if ($opt->username or $opt->password) {
    progress('updating credentials from command line');
    $username = $opt->username if $opt->username;
    $password = $opt->password if $opt->password;
    $dbh->do(q{update credentials set username=?, password=?},
             {},
             $username,$password);
}
 
my $mech = WWW::Mechanize->new(ssl_opts=>{verify_hostname=>0});
WWW::Mechanize::TreeBuilder->meta->apply(
    $mech,
    tree_class => 'HTML::TreeBuilder::XPath',
);
$mech->agent_alias('Linux Mozilla');
 
progress('logging in');
$mech->get('https://account.tfl.gov.uk/oyster/login');
$mech->submit_form(
    form_name => 'sign-in',
    fields => {
        j_username => $username,
        UserName => $username,
        j_password => $password,
        Password => $password,
    },
);
 
$mech->uri =~ m{^https://oyster.tfl.gov.uk/oyster/oyster/selectCard}
    or die "login failed\n".$mech->content;
progress('getting journeys history');
$mech->follow_link(text_regex => qr{journey history}i);
 
my ($input_button) = $mech->findnodes(
    q{//form[@name='jhDownloadForm']//a[@class=~/button_dwld/]}
);
 
my $js=$input_button->findvalue('@onclick');
my (undef,$url) = ($js=~m{action=(["'])(\S+?)\1});
$url=URI->new_abs($url,$mech->uri);
 
progress('downloading CSV');
my $res = $mech->post($url, {});
die "CSV download failed\n".$res->decoded_content
    if !$res->is_success;
 
my $date_parser = DateTime::Format::Strptime->new(
    pattern => '%d-%b-%Y %H:%M',
    locale => 'en_GB',
    time_zone => 'Europe/London',
    on_error => 'croak',
);
my $csv=Text::CSV_XS->new({binary=>1});
my $csv_text=$res->decoded_content;
open my $fh,'<',\$csv_text;
 
my $headers=[];
while (defined($headersand @$headers<2 ) {
    $headers = $csv->getline($fh);
}
die "Could not find any data in the CSV"
    unless defined $headers;
$csv->column_names($headers);
 
progress('parsing CSV');
while (my $row = $csv->getline_hr($fh)) {
    progress('got a row (for %s, %s - %s)',
             $row->{Date},
             $row->{'Start Time'},
             $row->{'End Time'},
         );
    # bus journeys don't have a end time 
    $row->{'End Time'} ||= $row->{'Start Time'};
    $row->{'Start Time'} ||= $row->{'End Time'};
    my $start_dt = $date_parser->parse_datetime(
        $row->{Date}.' '.$row->{'Start Time'});
    my $stop_dt = $date_parser->parse_datetime(
        $row->{Date}.' '.$row->{'End Time'});
    if ($stop_dt < $start_dt) {
        # if it ends after midnight, it looks like we went back in time 
        $stop_dt->add(days=>1);
    }
    # a duplicate row will get overwritten 
    $dbh->do(q{insert into journeys(start_ts,stop_ts,description,charge,credit,balance,note) values (?,?,?,?,?,?,?)},
             {},
             $start_dt->epoch,
             $stop_dt->epoch,
             $row->{'Journey/Action'},
             $row->{Charge},
             $row->{Credit},
             $row->{Balance},
             $row->{Note},
         );
}
progress('done');
 
exit 0;
 
__END__
 
=head1 NAME
 
oyster - save journey data from TfL
 
=head1 SYNOPSIS
 
  ./oyster -u $username -p $password
  ./oyster
 
=head1 DESCRIPTION
 
See http://www.thenautilus.net/SW/oyster/
 
=head1 AUTHOR
 
Gianni Ceccarelli <dakkar@thenautilus.net>
 
=head1 COPYRIGHT AND LICENSE
 
This software is copyright (c) 2012 by Gianni Ceccarelli.
 
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, version 3.
 
=cut