summaryrefslogtreecommitdiff
path: root/lib/DBInfoscreen/Helper/Wagonorder.pm
blob: 98c22ca669c0612204550c85d252f81490ca7284 (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
package DBInfoscreen::Helper::Wagonorder;

use strict;
use warnings;
use 5.020;

use DateTime;
use Encode qw(decode encode);
use Mojo::JSON qw(decode_json);
use XML::LibXML;

sub new {
	my ( $class, %opt ) = @_;

	my $version = $opt{version};

	$opt{header}
	  = { 'User-Agent' =>
		  "dbf/${version} +https://finalrewind.org/projects/db-fakedisplay" };

	return bless( \%opt, $class );

}

sub is_available {
	my ( $self, $train, $wr_link ) = @_;

	if ( $self->check_wagonorder( $train->train_no, $wr_link ) ) {
		return 1;
	}
	elsif ( $train->is_wing ) {
		my $wing = $train->wing_of;
		if ( $self->check_wagonorder( $wing->train_no, $wr_link ) ) {
			return 1;
		}
	}
	return;
}

sub check_wagonorder {
	my ( $self, $train_no, $wr_link ) = @_;

	my $url
	  = "https://lib.finalrewind.org/dbdb/has_wagonorder/${train_no}/${wr_link}";
	my $cache = $self->{cache};

	if ( my $content = $self->{cache}->get($url) ) {
		return $content eq 'y' ? 1 : undef;
	}

	my $ua = $self->{user_agent}->request_timeout(2);

	my $res = eval { $ua->head( $url => $self->{header} )->result };

	if ($@) {
		$self->{log}->debug("check_wagonorder($url): $@");
		return;
	}
	if ( $res->is_error ) {
		$cache->set( $url, 'n' );
		return;
	}
	else {
		$cache->set( $url, 'y' );
		return 1;
	}
}

1;