| 1 | package Finance::Currency::Convert::Esunbank; | ||
| 2 | 3 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 3 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | |||
| 5 | our $VERSION = v0.1.0; | ||
| 6 | |||
| 7 | 3 | ▶ | use Exporter 'import'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | our @EXPORT_OK = qw(get_currencies convert_currency); | ||
| 9 | |||
| 10 | 3 | ▶ | use POSIX qw(strftime); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 11 | 3 | ▶ | use Mojo::Collection; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 12 | use Mojo::UserAgent; | ||
| 13 | use Mojo::JSON qw(encode_json); | ||
| 14 | |||
| 15 | sub get_currencies { | ||
| 16 | my ($error, $result); | ||
| 17 | |||
| 18 | my $dom; | ||
| 19 | eval { | ||
| 20 | $dom = _fetch_currency_exchange_web_page(); | ||
| 21 | } or do { | ||
| 22 | $error = @$; | ||
| 23 | }; | ||
| 24 | return ($error, undef) if defined $error; | ||
| 25 | |||
| 26 | my @rows = $dom->find("table.tableStyle2 tr")->map( | ||
| 27 | sub { | ||
| 28 | my ($el) = @_; | ||
| 29 | my @cells = $el->find("td")->each; | ||
| 30 | return unless @cells; | ||
| 31 | |||
| 32 | my @names = $cells[0]->all_text =~ m/ (\p{Han}+) \( (\p{Latin}{3}) \) /x; | ||
| 33 | return { | ||
| 34 | currency => $names[1], | ||
| 35 | zh_currency_name => $names[0], | ||
| 36 | en_currency_name => $names[1], | ||
| 37 | buy_at => $cells[2]->all_text, | ||
| 38 | sell_at => $cells[2]->all_text, | ||
| 39 | }; | ||
| 40 | })->each; | ||
| 41 | |||
| 42 | return (undef, \@rows); | ||
| 43 | } | ||
| 44 | |||
| 45 | sub convert_currency { | ||
| 46 | my ($amount, $from_currency, $to_currency) = @_; | ||
| 47 | return ("The convertion target must be 'TWD'. Cannot proceed with '$to_currency'", undef) unless $to_currency eq 'TWD'; | ||
| 48 | |||
| 49 | my ($error, $result) = get_currencies(); | ||
| 50 | return ($error, undef) if defined $error; | ||
| 51 | |||
| 52 | my $rate; | ||
| 53 | for (@$result) { | ||
| 54 | if ($_->{currency} eq $from_currency) { | ||
| 55 | $rate = $_; | ||
| 56 | last; | ||
| 57 | } | ||
| 58 | } | ||
| 59 | return ("Unknown currency: $from_currency", undef) unless $rate; | ||
| 60 | |||
| 61 | return (undef, $amount * $rate->{buy_at}); | ||
| 62 | } | ||
| 63 | |||
| 64 | sub _fetch_currency_exchange_web_page { | ||
| 65 | my @t = localtime(); | ||
| 66 | my $ua = Mojo::UserAgent->new; | ||
| 67 | $ua->transactor->name('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:76.0) Gecko/20100101 Firefox/76.0'); | ||
| 68 | my $result = $ua->get('https://www.esunbank.com.tw/bank/iframe/widget/rate/foreign-exchange-rate')->result; | ||
| 69 | die $result->message if $result->is_error; | ||
| 70 | return $result->dom; | ||
| 71 | } | ||
| 72 | |||
| 73 | 1; | ||
| 74 | |||
| 75 | __END__ | ||