Commit 75e54f73 authored by Birte Kristina Friesel's avatar Birte Kristina Friesel
Browse files

Fetch map asynchronously

parent e540de17
Loading
Loading
Loading
Loading
+101 −71
Original line number Diff line number Diff line
package DBInfoscreen::Controller::Map;

use Mojo::Base 'Mojolicious::Controller';
use Mojo::JSON qw(decode_json);
use Mojo::Promise;

use Encode qw(decode);

my $dbf_version = qx{git describe --dirty} || 'experimental';

chomp $dbf_version;

sub get_hafas_polyline {
	my ( $ua, $cache, $trip_id, $line ) = @_;
sub get_hafas_polyline_p {
	my ( $self, $trip_id, $line ) = @_;

	my $url
	  = "https://2.db.transport.rest/trips/${trip_id}?lineName=${line}&polyline=true";
	my $cache   = $self->app->cache_iris_main;
	my $promise = Mojo::Promise->new;

	say $url;

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

	$ua->request_timeout(2);

	#say $url;
	my $res
	  = $ua->get(
	$self->ua->request_timeout(5)
	  ->get_p(
		$url => { 'User-Agent' => "dbf.finalrewind.org/${dbf_version}" } )
	  ->result;
	if ( $res->is_error ) {
		return;
	}

	my $json = decode_json( $res->body );
	  ->then(
		sub {
			my ($tx) = @_;
			my $body = decode( 'utf-8', $tx->res->body );
			my $json = decode_json($body);
			my @coordinate_list;

			for my $feature ( @{ $json->{polyline}{features} } ) {
@@ -47,7 +52,16 @@ sub get_hafas_polyline {
			};

			$cache->freeze( $url, $ret );
	return $ret;
			$promise->resolve($ret);
		}
	)->catch(
		sub {
			my ($err) = @_;
			$promise->reject($err);
		}
	)->wait;

	return $promise;
}

sub route {
@@ -55,8 +69,12 @@ sub route {
	my $trip_id = $self->stash('tripid');
	my $line_no = $self->stash('lineno');

	my $pl = get_hafas_polyline( $self->ua, $self->app->cache_iris_main,
		$trip_id, $line_no );
	$self->render_later;

	$self->get_hafas_polyline_p( $trip_id, $line_no )->then(
		sub {
			my ($pl) = @_;

			my @polyline = @{ $pl->{polyline} };
			my @line_pairs;
			my @station_coordinates;
@@ -100,5 +118,17 @@ sub route {
				station_coordinates => [@station_coordinates],
			);
		}
	)->catch(
		sub {
			my ($err) = @_;
			$self->render(
				'route_map',
				title     => "Fehler",
				hide_opts => 1,
			);

		}
	)->wait;
}

1;
+3 −3
Original line number Diff line number Diff line
% if (0) {
% if (my $err = stash('error')) {
  <div class="container">
    <div class="error">
      <strong>Fehler!</strong>
		Baz
      <strong>Fehler bei der Routenabfrage</strong>
%=    $err
    </div>
  </div>
% }