blib/lib/Finance/Bank/LaPoste.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Finance::Bank::LaPoste;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Graphics::Magick;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use HTTP::Cookies;
8 use LWP::UserAgent;
9 use HTML::Parser;
10 use HTML::Form;
11 use Digest::MD5();
12  
13 our $VERSION = '9.04';
14  
15 # $Id: $
16 # $Log: LaPoste.pm,v $
17  
18 =pod
19  
20 =head1 NAME
21  
22 Finance::Bank::LaPoste - Check your "La Poste" accounts from Perl
23  
24 =head1 SYNOPSIS
25  
26 use Finance::Bank::LaPoste;
27  
28 my @accounts = Finance::Bank::LaPoste->check_balance(
29 username => "0120123456L", # your main account is something like
30 # 0123456 L 012, stick it together with the region first
31 password => "123456", # a password is usually 6 numbers
32 all_accounts => 1, # if you want credit card and savings accounts
33 );
34  
35 foreach my $account (@accounts) {
36 print "Name: ", $account->name, " ", $account->owner, " Account_no: ", $account->account_no, "\n", "*" x 80, "\n";
37 print $_->as_string, "\n" foreach $account->statements;
38 }
39  
40 =head1 DESCRIPTION
41  
42 This module provides a read-only interface to the Videoposte online banking
43 system at L<https://www.videoposte.com/>. You will need either Crypt::SSLeay
44 installed.
45  
46 The interface of this module is similar to other Finance::Bank::* modules.
47  
48 =head1 WARNING
49  
50 This is code for B<online banking>, and that means B<your money>, and that
51 means B<BE CAREFUL>. You are encouraged, nay, expected, to audit the source
52 of this module yourself to reassure yourself that I am not doing anything
53 untoward with your banking data. This software is useful to me, but is
54 provided under B<NO GUARANTEE>, explicit or implied.
55  
56 =cut
57  
58 my $parse_table = sub {
59 my ($html) = @_;
60 my $h = HTML::Parser->new;
61  
62 my (@l, $row, $td, $href);
63 $h->report_tags('td', 'tr', 'a');
64 $h->handler(start => sub {
65 my ($tag, $attr) = @_;
66 if ($tag eq 'tr') {
67 $row = [];
68 } elsif ($tag eq 'td') {
69 push @$row, ('') x ($attr->{colspan} - 1) if $attr->{colspan};
70 $td = '';
71 } elsif ($tag eq 'a') {
72 $href = $attr->{href} if defined $td;
73 }
74 }, 'tag,attr');
75 $h->handler(end => sub {
76 my ($tag) = @_;
77 if ($tag eq '/tr') {
78 push @l, $row if $row;
79 undef $row;
80 } elsif ($tag eq '/td' && defined $td) {
81 $td =~ s/(
82 |&nbsp;|\s)+/ /g;
83 $td =~ s/^\s*//;
84 $td =~ s/\s*$//;
85 push @$row, $href ? [ $td, $href ] : $td;
86 $href = $td = undef;
87 }
88 }, 'tag');
89
90 $h->handler(text => sub {
91 my ($text) = @_;
92 $td .= " $text" if defined $td;
93 }, 'text');
94 $h->parse($html);
95  
96 \@l;
97 };
98  
99 my $normalize_number = sub {
100 my ($s) = @_;
101 defined($s) or return 0;
102 $s =~ s/\xC2?\xA0//; # non breakable space, both in UTF8 and latin1
103 $s =~ s/ //g;
104 $s =~ s/,/./;
105 $s + 0; # turn into a number
106 };
107  
108 =pod
109  
110 =head1 METHODS
111  
112 =head2 new(username => "0120123456L", password => "123456", cb_accounts => 1, all_accounts => 0, feedback => sub { warn "Finance::Bank::LaPoste: $_[0]\n" })
113  
114 Return an object . You can optionally provide to this method a LWP::UserAgent
115 object (argument named "ua"). You can also provide a function used for
116 feedback (useful for verbose mode or debugging) (argument named "feedback")
117  
118 =cut
119  
120 my $first_url = 'https://voscomptesenligne.labanquepostale.fr/voscomptes/canalXHTML/identif.ea?origin=particuliers';
121  
122 sub _login {
123 my ($self) = @_;
124 $self->{feedback}->("login") if $self->{feedback};
125  
126 my $cookie_jar = HTTP::Cookies->new;
127 my $response = $self->{ua}->request(HTTP::Request->new(GET => $first_url));
128 $cookie_jar->extract_cookies($response);
129 $self->{ua}->cookie_jar($cookie_jar);
130  
131 my %mangling_map = _get_number_mangling_map($self, _get_img_map_data($self, $response));
132 my $password = join('', map { $mangling_map{$_} } split('', $self->{password}));
133  
134 my $form = HTML::Form->parse($response->content, $first_url);
135 $form->value(username => $self->{username});
136 $form->value(password => $password);
137  
138 push @{$self->{ua}->requests_redirectable}, 'POST';
139 $response = $self->{ua}->request($form->click);
140 $response->is_success or die "login failed\n" . $response->error_as_HTML;
141  
142 $self->{feedback}->("list accounts") if $self->{feedback};
143  
144 $response = _handle_javascript_redirects($self, $response);
145  
146 $self->{accounts} = [ _list_accounts($self, $response) ];
147 }
148  
149 sub _handle_javascript_redirects {
150 my ($self, $response) =@_;
151  
152 while ($response->content =~ /top.location.replace\(["'](.*)["']\)/) {
153 $response = $self->{ua}->request(HTTP::Request->new(GET => _rel_url($response, $1)));
154 $response->is_success or die "login failed\n" . $response->error_as_HTML;
155 }
156 $response;
157 }
158  
159 sub _rel_url {
160 my ($response, $rel) = @_;
161 my $base = $response->base;
162 if ($rel =~ m!^/!) {
163 $base =~ m!([^/]*//[^/]*)! && "$1$rel";
164 } else {
165 $base =~ s/\?.*//;
166 _rel_fullurl("$base/../$rel");
167 }
168 }
169  
170 sub _rel_fullurl {
171 my ($s) = @_;
172 while ($s =~ s![^/]*/\.\./!!) {}
173 $s;
174 }
175  
176  
177 sub _output { my $f = shift; open(my $F, ">$f") or die "output in file $f failed: $!\n"; print $F $_ foreach @_; 1 }
178  
179 # to update %img_md5sum_to_number, set $debug_imgs to 1,
180 # then rename /tmp/img*.xpm into /tmp/[0-9].xpm according to the image
181 # then do "md5sum /tmp/[0-9].xpm"
182 my $debug_imgs = 0;
183 my %img_md5sum_to_number = (
184 '7b0866f479c82ef8cc6c2d599b283644' => 0,
185 'dbe97681a77bd75f811cd318e1b6def3' => 0,
186 '1f15c095fe13e73d341ff1f099925c59' => 1,
187 '264fc8643f2277ce7df738d8bf0d4533' => 1,
188 'af46867b6383a7f4ba563bd493c59163' => 2,
189 'bc09366762776a5bca2161105607302b' => 2,
190 '79215c3e70645d77bee10b57f41397bb' => 3,
191 '71a5e8344d0343928ff077cf292fc7e3' => 3,
192 '6cc8cc78c841a3baa24ea997f5e95372' => 4,
193 '50a363a8d16f6fbba5e8b14432e2d73e' => 4,
194 '424288417b5c56e211dd7e770b7f2a78' => 5,
195 'd8ce75d8bd5c64a2ed10deede9ad7bc9' => 5,
196 '6647804420c37a463b762a3a0d7e247e' => 6,
197 '03c32205bcc9fa135b2a3d105dbb2644' => 6,
198 'a26bac1f76ebffceaeb2eccf5e806ebe' => 7,
199 'ab159c63f95caa870429812c0cd09ea5' => 7,
200 '069cd50cee9e34dff1f17b387122ff5a' => 8,
201 '16454f3fb921be822f379682d0727f3f' => 8,
202 'e74f78fb6d04b5d9f0a814d120a685d8' => 9,
203 '336809b2bb178abdb8beec26e523af34' => 9,
204 '6110983d937627e8b2c131335c9c73e8' => 'blank',
205 );
206  
207 sub _get_number_mangling_map {
208 my ($self, $img_map_data) = @_;
209  
210 my $img_map=Graphics::Magick->new;
211 $img_map->BlobToImage($img_map_data);
212 $img_map->Threshold(threshold => '90%');
213  
214 my $size = 64;
215  
216 my $i = 0;
217 my %map;
218 for my $y (0 .. 3) {
219 for my $x (0 .. 3) {
220  
221 my $newimage = $img_map->Clone;
222 $newimage->Crop(geometry =>
223 sprintf("%dx%d+%d+%d",
224 12, 17,
225 25+ $x * ($size),
226 21 + $y * ($size)));
227 $newimage->Set(magick => 'xpm');
228 my ($img) = $newimage->ImageToBlob;
229 if ($debug_imgs) {
230 _output("/tmp/img$x$y.xpm", $img);
231 }
232 my $md5sum = Digest::MD5::md5_hex($img);
233 my $number = $img_md5sum_to_number{$md5sum};
234 defined($number) or die "missing md5sum, please update \%img_md5sum_to_number (setting \$debug_imgs will help)\n";
235 $map{$number} = sprintf("%02d", $i);
236 $i++;
237 }
238 }
239 %map;
240 }
241  
242 sub _get_img_map_data {
243 my ($self, $response) = @_;
244 my ($url) = $response->content =~ /background:url\((loginform.*?)\)/;
245 _GET_content($self, _rel_url($response, $url));
246 }
247  
248 sub _GET_content {
249 my ($self, $url) = @_;
250  
251 my $req = $self->{ua}->request(HTTP::Request->new(GET => $url));
252 $req->is_success or die "getting $url failed\n" . $req->error_as_HTML;
253 $req->content;
254 }
255  
256 sub _list_accounts {
257 my ($self, $response) = @_;
258 my $html = $response->content;
259 my @l = _list_accounts_one_page($self, $html);
260  
261 if ($self->{all_accounts}) {
262 my $html = _GET_content($self, _rel_url($response, '/voscomptes/canalXHTML/comptesCommun/synthese_ep/afficheSyntheseEP-synthese_ep.ea'));
263 push @l, _list_accounts_one_page($self, $html, 'savings');
264 }
265 @l;
266 }
267  
268 sub _list_accounts_one_page {
269 my ($self, $html, $type) = @_;
270 my @l;
271  
272 my $flag = '';
273 my ($url, $name, $owner, $account_no, $balance_cb);
274  
275 foreach (split("\n", $html)) {
276 if ($flag eq 'url' && m!<a href="(.*?)"! || m!redirigerVersPage\(event, '(.*?)'\)!) {
277 $url = $1;
278 } elsif (m!<h3>(.*?)\s*</h3>(?:<span>(.*)</span>)?!) {
279 $name = $1;
280 $owner = $2;
281 } elsif (m!num(?:&#233;|..?)ro de compte">.*</abbr>(.*?)</!) {
282 $account_no = $1;
283 } elsif (m!<div class="amount-euro">([\d\s,.+-]*)! && $url) {
284 my $balance = $normalize_number->($1);
285 push @l, { url => $url, balance => $balance, name => $name, owner => $owner, account_no => $account_no, type => $type } if $url;
286 $url = '';
287 } elsif ($flag eq 'balance_cb' && m!<span class="amount">([\d\s,.+-]*)!) {
288 $flag = '';
289 $balance_cb = $normalize_number->($1);
290 $url =~ s/&amp;/&/g;
291 push @l, { url => $url, balance => $balance_cb, name => "Carte bancaire", owner => $owner, account_no => $account_no, type => 'cb' } if $self->{cb_accounts} || $self->{all_accounts};
292 }
293  
294 if (/account-resume--ccp|account-resume--saving/) {
295 $flag = 'url';
296 } elsif (/D&eacute;bit diff&eacute;r&eacute; en cours/) {
297 $flag = 'balance_cb';
298 }
299 }
300  
301 @l;
302 }
303  
304 sub _list_cb_accounts {
305 my ($self, $url) = @_;
306  
307 my $response = $self->{ua}->request(HTTP::Request->new(GET => $url));
308 $response->is_success or die "getting $url failed\n" . $response->error_as_HTML;
309  
310 my $accounts = $parse_table->($response->content);
311 map {
312 my ($account, $account_no, $balance) = grep { $_ ne '' } @$_;
313 if (ref $account && $account_no) {
314 my $url = $account->[1];
315 {
316 name => $account->[0],
317 account_no => $account_no,
318 balance => $normalize_number->($balance),
319 $url =~ /(releve_ccp|releve_cne|releve_cb|mouvementsCarteDD)\.ea/ ? (url => _rel_url($response, $url)) : (),
320 };
321 } else { () }
322 } @$accounts;
323 }
324  
325 sub new {
326 my ($class, %opts) = @_;
327 my $self = bless \%opts, $class;
328  
329 exists $self->{password} or croak "Must provide a password";
330 exists $self->{username} or croak "Must provide a username";
331  
332 $self->{ua} ||= LWP::UserAgent->new(agent => 'Mozilla');
333  
334 $self->{ua}->add_handler(request_preprepare => sub {
335 my ($request, $ua, $h) = @_;
336 if ($request->uri =~ m!/\.\./!) {
337 $request->uri(_rel_fullurl($request->uri));
338 }
339 #print $request->uri . "\n";
340 });
341  
342 _login($self);
343 $self;
344 }
345  
346 sub default_account {
347 die "default_account can't be used anymore";
348 }
349  
350 =pod
351  
352 =head2 check_balance(username => "0120123456L", password => "123456")
353  
354 Return a list of account (F::B::LaPoste::Account) objects, one for each of
355 your bank accounts.
356  
357 =cut
358  
359 sub check_balance {
360 my $self = &new;
361  
362 map { Finance::Bank::LaPoste::Account->new($self, %$_) } @{$self->{accounts}};
363 }
364  
365 package Finance::Bank::LaPoste::Account;
366  
367 =pod
368  
369 =head1 Account methods
370  
371 =head2 sort_code()
372  
373 Return the sort code of the account. Currently, it returns an undefined
374 value.
375  
376 =head2 name()
377  
378 Returns the human-readable name of the account.
379  
380 =head2 owner()
381  
382 Return the account owner, if available.
383  
384 =head2 account_no()
385  
386 Return the account number, in the form C<0123456L012>.
387  
388 =head2 balance()
389  
390 Returns the balance of the account.
391  
392 =head2 type()
393  
394 Returns the account type, like C<cb> or C<savings>.
395  
396 =head2 statements()
397  
398 Return a list of Statement object (Finance::Bank::LaPoste::Statement).
399  
400 =head2 currency()
401  
402 Returns the currency of the account as a three letter ISO code (EUR, CHF,
403 etc.).
404  
405 =cut
406  
407 sub new {
408 my ($class, $bank, %account) = @_;
409 $account{$_} = $bank->{$_} foreach qw(ua feedback);
410 bless \%account, $class;
411 }
412  
413 sub sort_code { undef }
414 sub name { $_[0]{name} }
415 sub owner { $_[0]{owner} }
416 sub account_no { $_[0]{account_no} }
417 sub balance { $_[0]{balance} }
418 sub type { $_[0]{type} }
419 sub currency { 'EUR' }
420 sub statements {
421 my ($self) = @_;
422 my $url = $self->{url} or return;
423 $url =~ s/typeRecherche=1$/typeRecherche=10/; # 400 last operations
424  
425 $self->{statements} ||= do {
426 my $retry;
427 retry:
428 $self->{feedback}->("get statements") if $self->{feedback};
429 my $response = $self->{ua}->request(HTTP::Request->new(GET => $url));
430 $response->is_success or die "can't access account $self->{name} statements\n" . $response->error_as_HTML;
431  
432 my $html = $response->content;
433  
434 $self->{balance} ||= do {
435 my $balance = ($html =~ m!<span class='negatif'>(.*?)</span>&nbsp;euros! || $html =~ m!<span class="amount">(.*?)&nbsp;&euro;</span>!) && $1;
436 $normalize_number->($balance);
437 };
438 my $l = $parse_table->($html);
439  
440 @$l = map {
441 my ($date, $description, $amount1, $amount2) = @$_;
442 my $amount = $normalize_number->($amount2 || $amount1);
443 $date && $date =~ m!(\d+)/(\d+)! ? [ $date, $description, $amount ] : ();
444 } @$l;
445  
446 [ map {
447 my ($date, $description, $amount) = @$_;
448 my ($day, $month, $year) = $date =~ m|(\d+)/(\d+)/(\d+)|;
449 Finance::Bank::LaPoste::Statement->new(day => $day, month => $month, year => $year, description => $description, amount => $amount);
450 } @$l ];
451 };
452 @{$self->{statements}};
453 }
454  
455 sub _rel_url { &Finance::Bank::LaPoste::_rel_url }
456  
457  
458 package Finance::Bank::LaPoste::Statement;
459  
460 =pod
461  
462 =head1 Statement methods
463  
464 =head2 date()
465  
466 Returns the date when the statement occured, in DD/MM/YY format.
467  
468 =head2 description()
469  
470 Returns a brief description of the statement.
471  
472 =head2 amount()
473  
474 Returns the amount of the statement (expressed in Euros or the account's
475 currency). Although the Crédit Mutuel website displays number in continental
476 format (i.e. with a coma as decimal separator), amount() returns a real
477 number.
478  
479 =head2 as_string($separator)
480  
481 Returns a tab-delimited representation of the statement. By default, it uses
482 a tabulation to separate the fields, but the user can provide its own
483 separator.
484  
485 =cut
486  
487 sub new {
488 my ($class, %statement) = @_;
489 bless \%statement, $class;
490 }
491  
492 sub description { $_[0]{description} }
493 sub amount { $_[0]{amount} }
494 sub date {
495 my ($self) = @_;
496 my ($year) = $self->{year} =~ /..(..)/; # only 2 digits for year
497 "$year/$self->{month}/$self->{day}"
498 }
499  
500 sub as_string {
501 my ($self, $separator) = @_;
502 join($separator || "\t", $self->date, $self->{description}, $self->{amount});
503 }
504  
505 1;
506  
507 =pod
508  
509 =head1 COPYRIGHT
510  
511 Copyright 2002-2007, Pascal 'Pixel' Rigaux. All Rights Reserved. This module
512 can be redistributed under the same terms as Perl itself.
513  
514 =head1 AUTHOR
515  
516 Thanks to Cédric Bouvier for Finance::Bank::CreditMut
517 (and also to Simon Cozens and Briac Pilpré for various Finance::Bank::*)
518  
519 =head1 SEE ALSO
520  
521 Finance::Bank::BNPParibas, Finance::Bank::CreditMut
522  
523 =cut
↑ Summary