summaryrefslogtreecommitdiff
path: root/lib/Travelynx/Helper/DBDB.pm
blob: 0db69509e5772500ce4b16ce0634bfb352df0a06 (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
package Travelynx::Helper::DBDB;

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

use strict;
use warnings;
use 5.020;

use Encode qw(decode);
use Mojo::Promise;
use Mojo::UserAgent;
use JSON;

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

	my $version = $opt{version};

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

	return bless( \%opt, $class );

}

sub get_stationinfo_p {
	my ( $self, $eva ) = @_;

	my $url = "https://lib.finalrewind.org/dbdb/s/${eva}.json";

	my $cache   = $self->{main_cache};
	my $promise = Mojo::Promise->new;

	if ( my $content = $cache->thaw($url) ) {
		$self->{log}->debug("get_stationinfo_p(${eva}): (cached)");
		return $promise->resolve($content);
	}

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

			if ( my $err = $tx->error ) {
				$self->{log}->debug(
"get_stationinfo_p(${eva}): HTTP $err->{code} $err->{message}"
				);
				$cache->freeze( $url, {} );
				$promise->reject("HTTP $err->{code} $err->{message}");
				return;
			}

			my $json = $tx->result->json;
			$self->{log}->debug("get_stationinfo_p(${eva}): success");
			$cache->freeze( $url, $json );
			$promise->resolve($json);
			return;
		}
	  )->catch(
		sub {
			my ($err) = @_;
			$self->{log}->debug("get_stationinfo_p(${eva}): Error ${err}");
			$cache->freeze( $url, {} );
			$promise->reject($err);
			return;
		}
	  )->wait;
	return $promise;
}

1;