summaryrefslogtreecommitdiff
path: root/lib/DBInfoscreen/Helper/Marudor.pm
blob: 41ba81efa98231a99db5368364cf820204f5d557 (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
package DBInfoscreen::Helper::Marudor;

# Copyright (C) 2020 Daniel Friesel
#
# SPDX-License-Identifier: BSD-2-Clause

use strict;
use warnings;
use 5.020;

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

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

	my $version = $opt{version};

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

	return bless( \%opt, $class );

}

sub get_json_p {
	my ( $self, $cache, $url ) = @_;

	my $promise = Mojo::Promise->new;

	if ( my $content = $cache->thaw($url) ) {
		return $promise->resolve($content);
	}

	$self->{log}->debug("get_json_p($url)");

	$self->{user_agent}->request_timeout(5)->get_p( $url => $self->{header} )
	  ->then(
		sub {
			my ($tx) = @_;

			if ( my $err = $tx->error ) {
				$self->{log}->debug(
"marudor->get_json_p($url): HTTP $err->{code} $err->{message}"
				);
				$promise->reject(
					"GET $url returned HTTP $err->{code} $err->{message}");
				return;
			}

			my $res = $tx->res->json;

			$cache->freeze( $url, $res );

			$promise->resolve($res);

			return;
		}
	)->catch(
		sub {
			my ($err) = @_;
			$self->{log}->debug("marudor->get_json_p($url): $err");
			$promise->reject($err);
			return;
		}
	)->wait;

	return $promise;
}

sub get_train_utilization {
	my ( $self, %opt ) = @_;

	my $promise = Mojo::Promise->new;
	my $train   = $opt{train};

	if ( not $train->sched_departure ) {
		$promise->reject("train has no departure");
		return $promise;
	}

	my $train_no     = $train->train_no;
	my $this_station = $train->station;
	my @route        = $train->route_post;
	my $next_station;
	my $dep = $train->sched_departure->epoch . '000';

	if ( @route > 1 ) {
		$next_station = $route[1];
	}
	else {
		$next_station = $route[0];
	}

	$self->get_json_p( $self->{realtime_cache},
"https://marudor.de/api/hafas/v1/auslastung/${this_station}/${next_station}/${train_no}/${dep}"
	)->then(
		sub {
			my ($utilization_json) = @_;

			$promise->resolve( $utilization_json->{first},
				$utilization_json->{second} );
			return;
		}
	)->catch(
		sub {
			$promise->reject;
			return;
		}
	)->wait;

	return $promise;
}

1;