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

# Copyright (C) 2025 Birte Kristina Friesel
#
# SPDX-License-Identifier: AGPL-3.0-or-later

use strict;
use warnings;
use 5.020;

use DateTime;
use Encode qw(decode encode);
use Travel::Status::DE::DBRIS;
use Mojo::JSON qw(decode_json);
use Mojo::Promise;
use Mojo::UserAgent;

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_journey_p {
	my ( $self, %opt ) = @_;

	my $agent = $self->{user_agent};

	if ( my $proxy = $ENV{DBFAKEDISPLAY_DBRIS_PROXY} ) {
		$agent = Mojo::UserAgent->new;
		$agent->proxy->http($proxy);
		$agent->proxy->https($proxy);
	}

	return Travel::Status::DE::DBRIS->new_p(
		journey    => $opt{id},
		cache      => $self->{realtime_cache},
		promise    => 'Mojo::Promise',
		user_agent => $agent->request_timeout(10)
	);
}

# Input: TripID
# Output: Promise returning a Travel::Status::DE::DBRIS::Journey instance on success
sub get_polyline_p {
	my ( $self, %opt ) = @_;

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

	my $agent = $self->{user_agent};

	if ( my $proxy = $ENV{DBFAKEDISPLAY_DBRIS_PROXY} ) {
		$agent = Mojo::UserAgent->new;
		$agent->proxy->http($proxy);
		$agent->proxy->https($proxy);
	}

	Travel::Status::DE::DBRIS->new_p(
		journey       => $trip_id,
		with_polyline => 1,
		cache         => $self->{realtime_cache},
		promise       => 'Mojo::Promise',
		user_agent    => $agent->request_timeout(10)
	)->then(
		sub {
			my ($dbris) = @_;
			my $journey = $dbris->result;

			$promise->resolve($journey);
			return;
		}
	)->catch(
		sub {
			my ($err) = @_;
			$self->{log}->debug("DBRIS->new_p($trip_id) error: $err");
			$promise->reject($err);
			return;
		}
	)->wait;

	return $promise;
}

1;