diff options
Diffstat (limited to 'lib/Travelynx/Controller')
-rw-r--r-- | lib/Travelynx/Controller/Account.pm | 1256 | ||||
-rwxr-xr-x | lib/Travelynx/Controller/Api.pm | 370 | ||||
-rw-r--r-- | lib/Travelynx/Controller/Passengerrights.pm | 17 | ||||
-rwxr-xr-x | lib/Travelynx/Controller/Profile.pm | 641 | ||||
-rw-r--r-- | lib/Travelynx/Controller/Static.pm | 25 | ||||
-rw-r--r-- | lib/Travelynx/Controller/Traewelling.pm | 117 | ||||
-rwxr-xr-x | lib/Travelynx/Controller/Traveling.pm | 2580 |
7 files changed, 4001 insertions, 1005 deletions
diff --git a/lib/Travelynx/Controller/Account.pm b/lib/Travelynx/Controller/Account.pm index 12a059a..bf1eac2 100644 --- a/lib/Travelynx/Controller/Account.pm +++ b/lib/Travelynx/Controller/Account.pm @@ -1,25 +1,232 @@ package Travelynx::Controller::Account; -# Copyright (C) 2020 Daniel Friesel +# Copyright (C) 2020-2023 Birte Kristina Friesel +# Copyright (C) 2025 networkException <git@nwex.de> # # SPDX-License-Identifier: AGPL-3.0-or-later use Mojo::Base 'Mojolicious::Controller'; -use Crypt::Eksblowfish::Bcrypt qw(bcrypt en_base64); +use JSON; +use Math::Polygon; +use Mojo::Util qw(xml_escape); +use Text::Markdown; use UUID::Tiny qw(:std); -sub hash_password { - my ($password) = @_; - my @salt_bytes = map { int( rand(255) ) + 1 } ( 1 .. 16 ); - my $salt = en_base64( pack( 'C[16]', @salt_bytes ) ); +my %visibility_itoa = ( + 100 => 'public', + 80 => 'travelynx', + 60 => 'followers', + 30 => 'unlisted', + 10 => 'private', +); - return bcrypt( $password, '$2a$12$' . $salt ); -} +my %visibility_atoi = ( + public => 100, + travelynx => 80, + followers => 60, + unlisted => 30, + private => 10, +); + +# Internal Helpers sub make_token { return create_uuid_as_string(UUID_V4); } +sub send_registration_mail { + my ( $self, %opt ) = @_; + + my $email = $opt{email}; + my $token = $opt{token}; + my $user = $opt{user}; + my $user_id = $opt{user_id}; + my $ip = $opt{ip}; + my $date = DateTime->now( time_zone => 'Europe/Berlin' ) + ->strftime('%d.%m.%Y %H:%M:%S %z'); + + my $ua = $self->req->headers->user_agent; + my $reg_url = $self->url_for('reg')->to_abs->scheme('https'); + my $tos_url = $self->url_for('tos')->to_abs->scheme('https'); + my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); + + my $body = "Hallo, ${user}!\n\n"; + $body .= "Mit deiner E-Mail-Adresse (${email}) wurde ein Account bei\n"; + $body .= "travelynx angelegt.\n\n"; + $body + .= "Falls die Registrierung von dir ausging, kannst du den Account unter\n"; + $body .= "${reg_url}/${user_id}/${token}\n"; + $body .= "freischalten.\n"; + $body .= "Beachte dabei die Nutzungsbedingungen: ${tos_url}\n\n"; + $body + .= "Falls nicht, ignoriere diese Mail bitte. Nach etwa 48 Stunden wird deine\n"; + $body + .= "Mail-Adresse erneut zur Registrierung freigeschaltet. Falls auch diese fehlschlägt,\n"; + $body + .= "werden wir sie dauerhaft sperren und keine Mails mehr dorthin schicken.\n\n"; + $body .= "Daten zur Registrierung:\n"; + $body .= " * Datum: ${date}\n"; + $body .= " * Client: ${ip}\n"; + $body .= " * UserAgent: ${ua}\n\n\n"; + $body .= "Impressum: ${imprint_url}\n"; + + return $self->sendmail->custom( $email, 'Registrierung bei travelynx', + $body ); +} + +sub send_address_confirmation_mail { + my ( $self, $email, $token ) = @_; + + my $name = $self->current_user->{name}; + my $ip = $self->req->headers->header('X-Forwarded-For'); + my $ua = $self->req->headers->user_agent; + my $date = DateTime->now( time_zone => 'Europe/Berlin' ) + ->strftime('%d.%m.%Y %H:%M:%S %z'); + + # In case Mojolicious is not running behind a reverse proxy + $ip + //= sprintf( '%s:%s', $self->tx->remote_address, $self->tx->remote_port ); + my $confirm_url = $self->url_for('confirm_mail')->to_abs->scheme('https'); + my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); + + my $body = "Hallo ${name},\n\n"; + $body .= "Bitte bestätige unter <${confirm_url}/${token}>,\n"; + $body .= "dass du mit dieser Adresse E-Mail empfangen kannst.\n\n"; + $body + .= "Du erhältst diese Mail, da eine Änderung der deinem travelynx-Account\n"; + $body .= "zugeordneten Mail-Adresse beantragt wurde.\n\n"; + $body .= "Daten zur Anfrage:\n"; + $body .= " * Datum: ${date}\n"; + $body .= " * Client: ${ip}\n"; + $body .= " * UserAgent: ${ua}\n\n\n"; + $body .= "Impressum: ${imprint_url}\n"; + + return $self->sendmail->custom( $email, + 'travelynx: Mail-Adresse bestätigen', $body ); +} + +sub send_name_notification_mail { + my ( $self, $old_name, $new_name ) = @_; + + my $ip = $self->req->headers->header('X-Forwarded-For'); + my $ua = $self->req->headers->user_agent; + my $date = DateTime->now( time_zone => 'Europe/Berlin' ) + ->strftime('%d.%m.%Y %H:%M:%S %z'); + + # In case Mojolicious is not running behind a reverse proxy + $ip + //= sprintf( '%s:%s', $self->tx->remote_address, $self->tx->remote_port ); + my $confirm_url = $self->url_for('confirm_mail')->to_abs->scheme('https'); + my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); + + my $body = "Hallo ${new_name},\n\n"; + $body .= "Der Name deines Travelynx-Accounts wurde erfolgreich geändert.\n"; + $body + .= "Bitte beachte, dass du dich ab sofort nur mit dem neuen Namen anmelden kannst.\n\n"; + $body .= "Alter Name: ${old_name}\n\n"; + $body .= "Neue Name: ${new_name}\n\n"; + $body .= "Daten zur Anfrage:\n"; + $body .= " * Datum: ${date}\n"; + $body .= " * Client: ${ip}\n"; + $body .= " * UserAgent: ${ua}\n\n\n"; + $body .= "Impressum: ${imprint_url}\n"; + + return $self->sendmail->custom( $self->current_user->{email}, + 'travelynx: Name geändert', $body ); +} + +sub send_password_notification_mail { + my ($self) = @_; + my $user = $self->current_user->{name}; + my $email = $self->current_user->{email}; + my $ip = $self->req->headers->header('X-Forwarded-For'); + my $ua = $self->req->headers->user_agent; + my $date = DateTime->now( time_zone => 'Europe/Berlin' ) + ->strftime('%d.%m.%Y %H:%M:%S %z'); + + # In case Mojolicious is not running behind a reverse proxy + $ip + //= sprintf( '%s:%s', $self->tx->remote_address, $self->tx->remote_port ); + my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); + + my $body = "Hallo ${user},\n\n"; + $body + .= "Das Passwort deines travelynx-Accounts wurde soeben geändert.\n\n"; + $body .= "Daten zur Änderung:\n"; + $body .= " * Datum: ${date}\n"; + $body .= " * Client: ${ip}\n"; + $body .= " * UserAgent: ${ua}\n\n\n"; + $body .= "Impressum: ${imprint_url}\n"; + + $self->sendmail->custom( $email, 'travelynx: Passwort geändert', $body ); +} + +sub send_lostpassword_confirmation_mail { + my ( $self, %opt ) = @_; + my $email = $opt{email}; + my $name = $opt{name}; + my $uid = $opt{uid}; + my $token = $opt{token}; + + my $ip = $self->req->headers->header('X-Forwarded-For'); + my $ua = $self->req->headers->user_agent; + my $date = DateTime->now( time_zone => 'Europe/Berlin' ) + ->strftime('%d.%m.%Y %H:%M:%S %z'); + + # In case Mojolicious is not running behind a reverse proxy + $ip + //= sprintf( '%s:%s', $self->tx->remote_address, $self->tx->remote_port ); + my $recover_url = $self->url_for('recover')->to_abs->scheme('https'); + my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); + + my $body = "Hallo ${name},\n\n"; + $body .= "Unter ${recover_url}/${uid}/${token}\n"; + $body + .= "kannst du ein neues Passwort für deinen travelynx-Account vergeben.\n\n"; + $body + .= "Du erhältst diese Mail, da mit deinem Accountnamen und deiner Mail-Adresse\n"; + $body + .= "ein Passwort-Reset angefordert wurde. Falls diese Anfrage nicht von dir\n"; + $body .= "ausging, kannst du sie ignorieren.\n\n"; + $body .= "Daten zur Anfrage:\n"; + $body .= " * Datum: ${date}\n"; + $body .= " * Client: ${ip}\n"; + $body .= " * UserAgent: ${ua}\n\n\n"; + $body .= "Impressum: ${imprint_url}\n"; + + my $success + = $self->sendmail->custom( $email, 'travelynx: Neues Passwort', $body ); +} + +sub send_lostpassword_notification_mail { + my ( $self, $account ) = @_; + my $user = $account->{name}; + my $email = $account->{email}; + my $ip = $self->req->headers->header('X-Forwarded-For'); + my $ua = $self->req->headers->user_agent; + my $date = DateTime->now( time_zone => 'Europe/Berlin' ) + ->strftime('%d.%m.%Y %H:%M:%S %z'); + + # In case Mojolicious is not running behind a reverse proxy + $ip + //= sprintf( '%s:%s', $self->tx->remote_address, $self->tx->remote_port ); + my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); + + my $body = "Hallo ${user},\n\n"; + $body .= "Das Passwort deines travelynx-Accounts wurde soeben über die"; + $body .= " 'Passwort vergessen'-Funktion geändert.\n\n"; + $body .= "Daten zur Änderung:\n"; + $body .= " * Datum: ${date}\n"; + $body .= " * Client: ${ip}\n"; + $body .= " * UserAgent: ${ua}\n\n\n"; + $body .= "Impressum: ${imprint_url}\n"; + + return $self->sendmail->custom( $email, 'travelynx: Passwort geändert', + $body ); +} + +# Controllers + sub login_form { my ($self) = @_; $self->render('login'); @@ -35,8 +242,9 @@ sub do_login { if ( $self->validation->csrf_protect->has_error('csrf_token') ) { $self->render( - 'login', - invalid => 'csrf', + 'bad_request', + csrf => 1, + status => 400 ); } else { @@ -47,10 +255,18 @@ sub do_login { else { my $data = $self->users->get_login_data( name => $user ); if ( $data and $data->{status} == 0 ) { - $self->render( 'login', invalid => 'confirmation' ); + $self->render( + 'login', + status => 400, + invalid => 'confirmation' + ); } else { - $self->render( 'login', invalid => 'credentials' ); + $self->render( + 'login', + status => 400, + invalid => 'credentials' + ); } } } @@ -69,9 +285,6 @@ sub register { my $password = $self->req->param('password'); my $password2 = $self->req->param('password2'); my $ip = $self->req->headers->header('X-Forwarded-For'); - my $ua = $self->req->headers->user_agent; - my $date = DateTime->now( time_zone => 'Europe/Berlin' ) - ->strftime('%d.%m.%Y %H:%M:%S %z'); # In case Mojolicious is not running behind a reverse proxy $ip @@ -79,8 +292,9 @@ sub register { if ( $self->validation->csrf_protect->has_error('csrf_token') ) { $self->render( - 'register', - invalid => 'csrf', + 'bad_request', + csrf => 1, + status => 400 ); return; } @@ -88,17 +302,21 @@ sub register { if ( my $registration_denylist = $self->app->config->{registration}->{denylist} ) { - open( my $fh, "<", $registration_denylist ) - or die("cannot open($registration_denylist)"); - while ( my $line = <$fh> ) { - chomp $line; - if ( $ip eq $line ) { - close($fh); - $self->render( 'register', invalid => "denylist" ); - return; + if ( open( my $fh, "<", $registration_denylist ) ) { + while ( my $line = <$fh> ) { + chomp $line; + if ( $ip eq $line ) { + close($fh); + $self->render( 'register', invalid => "denylist" ); + return; + } } + close($fh); + } + else { + $self->log->error("Cannot open($registration_denylist): $!"); + die("Cannot verify registration: $!"); } - close($fh); } if ( my $error = $self->users->is_name_invalid( name => $user ) ) { @@ -132,47 +350,31 @@ sub register { # a human user should take at least five seconds to fill out the form. # Throw a CSRF error at presumed spammers. $self->render( - 'register', - invalid => 'csrf', + 'bad_request', + csrf => 1, + status => 400 ); return; } my $token = make_token(); - my $pw_hash = hash_password($password); my $db = $self->pg->db; my $tx = $db->begin; - my $user_id = $self->users->add_user( - db => $db, - name => $user, - email => $email, - token => $token, - password_hash => $pw_hash + my $user_id = $self->users->add( + db => $db, + name => $user, + email => $email, + token => $token, + password => $password, ); - my $reg_url = $self->url_for('reg')->to_abs->scheme('https'); - my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); - my $body = "Hallo, ${user}!\n\n"; - $body .= "Mit deiner E-Mail-Adresse (${email}) wurde ein Account bei\n"; - $body .= "travelynx angelegt.\n\n"; - $body - .= "Falls die Registrierung von dir ausging, kannst du den Account unter\n"; - $body .= "${reg_url}/${user_id}/${token}\n"; - $body .= "freischalten.\n\n"; - $body - .= "Falls nicht, ignoriere diese Mail bitte. Nach etwa 48 Stunden wird deine\n"; - $body - .= "Mail-Adresse erneut zur Registrierung freigeschaltet. Falls auch diese fehlschlägt,\n"; - $body - .= "werden wir sie dauerhaft sperren und keine Mails mehr dorthin schicken.\n\n"; - $body .= "Daten zur Registrierung:\n"; - $body .= " * Datum: ${date}\n"; - $body .= " * Client: ${ip}\n"; - $body .= " * UserAgent: ${ua}\n\n\n"; - $body .= "Impressum: ${imprint_url}\n"; - - my $success - = $self->sendmail->custom( $email, 'Registrierung bei travelynx', $body ); + my $success = $self->send_registration_mail( + email => $email, + token => $token, + ip => $ip, + user => $user, + user_id => $user_id + ); if ($success) { $tx->commit; $self->render( 'login', from => 'register' ); @@ -209,8 +411,13 @@ sub verify { sub delete { my ($self) = @_; + my $uid = $self->current_user->{id}; if ( $self->validation->csrf_protect->has_error('csrf_token') ) { - $self->render( 'account', invalid => 'csrf' ); + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); return; } @@ -222,13 +429,14 @@ sub delete { ) ) { - $self->render( 'account', invalid => 'deletion password' ); + $self->flash( invalid => 'deletion password' ); + $self->redirect_to('account'); return; } - $self->users->flag_deletion( uid => $self->current_user->{id} ); + $self->users->flag_deletion( uid => $uid ); } else { - $self->users->unflag_deletion( uid => $self->current_user->{id} ); + $self->users->unflag_deletion( uid => $uid ); } $self->redirect_to('account'); } @@ -236,7 +444,11 @@ sub delete { sub do_logout { my ($self) = @_; if ( $self->validation->csrf_protect->has_error('csrf_token') ) { - $self->render( 'login', invalid => 'csrf' ); + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); return; } $self->logout; @@ -246,75 +458,346 @@ sub do_logout { sub privacy { my ($self) = @_; - my $user = $self->current_user; - my $public_level = $user->{is_public}; + my $user = $self->current_user; if ( $self->param('action') and $self->param('action') eq 'save' ) { - if ( $self->param('status_level') eq 'intern' ) { - $public_level |= 0x01; - $public_level &= ~0x02; + my %opt; + my $default_visibility + = $visibility_atoi{ $self->param('status_level') }; + if ( defined $default_visibility ) { + $opt{default_visibility} = $default_visibility; } - elsif ( $self->param('status_level') eq 'extern' ) { - $public_level |= 0x02; - $public_level &= ~0x01; + + my $past_visibility = $visibility_atoi{ $self->param('history_level') }; + if ( defined $past_visibility ) { + $opt{past_visibility} = $past_visibility; } - else { - $public_level &= ~0x03; + + $opt{comments_visible} = $self->param('public_comment') ? 1 : 0; + + $opt{past_all} = $self->param('history_age') eq 'infinite' ? 1 : 0; + $opt{past_status} = $self->param('past_status') ? 1 : 0; + + $self->users->set_privacy( + uid => $user->{id}, + %opt + ); + + $self->flash( success => 'privacy' ); + $self->redirect_to('account'); + } + else { + $self->param( + status_level => $visibility_itoa{ $user->{default_visibility} } ); + $self->param( public_comment => $user->{comments_visible} ); + $self->param( + history_level => $visibility_itoa{ $user->{past_visibility} } ); + $self->param( history_age => $user->{past_all} ? 'infinite' : 'month' ); + $self->param( past_status => $user->{past_status} ); + $self->render( 'privacy', name => $user->{name} ); + } +} + +sub social { + my ($self) = @_; + + my $user = $self->current_user; + + if ( $self->param('action') and $self->param('action') eq 'save' ) { + if ( $self->validation->csrf_protect->has_error('csrf_token') ) { + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); + return; } - # public comment with non-public status does not make sense - if ( $self->param('public_comment') - and $self->param('status_level') ne 'private' ) - { - $public_level |= 0x04; + my %opt; + my $accept_follow = $self->param('accept_follow'); + + if ( $accept_follow eq 'yes' ) { + $opt{accept_follows} = 1; } - else { - $public_level &= ~0x04; + elsif ( $accept_follow eq 'request' ) { + $opt{accept_follow_requests} = 1; } - if ( $self->param('history_level') eq 'intern' ) { - $public_level |= 0x10; - $public_level &= ~0x20; + $self->users->set_social( + uid => $user->{id}, + %opt + ); + + $self->flash( success => 'social' ); + $self->redirect_to('account'); + } + else { + if ( $user->{accept_follows} ) { + $self->param( accept_follow => 'yes' ); } - elsif ( $self->param('history_level') eq 'extern' ) { - $public_level |= 0x20; - $public_level &= ~0x10; + elsif ( $user->{accept_follow_requests} ) { + $self->param( accept_follow => 'request' ); } else { - $public_level &= ~0x30; + $self->param( accept_follow => 'no' ); } + $self->render( 'social', name => $user->{name} ); + } +} - if ( $self->param('history_age') eq 'infinite' ) { - $public_level |= 0x40; - } - else { - $public_level &= ~0x40; - } +sub social_list { + my ($self) = @_; - $self->users->set_privacy( - uid => $user->{id}, - level => $public_level - ); + my $kind = $self->stash('kind'); + my $user = $self->current_user; - $self->flash( success => 'privacy' ); - $self->redirect_to('account'); + if ( $kind eq 'follow-requests-received' ) { + my @follow_reqs + = $self->users->get_follow_requests( uid => $user->{id} ); + $self->render( + 'social_list', + type => 'follow-requests-received', + entries => [@follow_reqs], + notifications => $user->{notifications}, + ); + } + elsif ( $kind eq 'follow-requests-sent' ) { + my @follow_reqs = $self->users->get_follow_requests( + uid => $user->{id}, + sent => 1 + ); + $self->render( + 'social_list', + type => 'follow-requests-sent', + entries => [@follow_reqs], + notifications => $user->{notifications}, + ); + } + elsif ( $kind eq 'followers' ) { + my @followers = $self->users->get_followers( uid => $user->{id} ); + $self->render( + 'social_list', + type => 'followers', + entries => [@followers], + notifications => $user->{notifications}, + ); + } + elsif ( $kind eq 'follows' ) { + my @following = $self->users->get_followees( uid => $user->{id} ); + $self->render( + 'social_list', + type => 'follows', + entries => [@following], + notifications => $user->{notifications}, + ); + } + elsif ( $kind eq 'blocks' ) { + my @blocked = $self->users->get_blocked_users( uid => $user->{id} ); + $self->render( + 'social_list', + type => 'blocks', + entries => [@blocked], + notifications => $user->{notifications}, + ); } else { - $self->param( - status_level => $public_level & 0x01 ? 'intern' - : $public_level & 0x02 ? 'extern' - : 'private' + $self->render( 'not_found', status => 404 ); + } +} + +sub social_action { + my ($self) = @_; + + my $user = $self->current_user; + my $action = $self->param('action'); + my $target_ids = $self->param('target'); + my $redirect_to = $self->param('redirect_to'); + + for my $key ( + qw(follow request_follow follow_or_request unfollow remove_follower cancel_follow_request accept_follow_request reject_follow_request block unblock) + ) + { + if ( $self->param($key) ) { + $action = $key; + $target_ids = $self->param($key); + } + } + + if ( $self->validation->csrf_protect->has_error('csrf_token') ) { + $self->redirect_to('/'); + return; + } + + if ( $action and $action eq 'clear_notifications' ) { + $self->users->update_notifications( + db => $self->pg->db, + uid => $user->{id}, + has_follow_requests => 0 ); - $self->param( public_comment => $public_level & 0x04 ? 1 : 0 ); - $self->param( - history_level => $public_level & 0x10 ? 'intern' - : $public_level & 0x20 ? 'extern' - : 'private' + $self->flash( success => 'clear_notifications' ); + $self->redirect_to('account'); + return; + } + + if ( not( $action and $target_ids and $redirect_to ) ) { + $self->redirect_to('/'); + return; + } + + for my $target_id ( split( qr{,}, $target_ids ) ) { + my $target = $self->users->get_privacy_by( uid => $target_id ); + + if ( not $target ) { + next; + } + + if ( $action eq 'follow' and $target->{accept_follows} ) { + $self->users->follow( + uid => $user->{id}, + target => $target->{id} + ); + } + elsif ( $action eq 'request_follow' + and $target->{accept_follow_requests} ) + { + $self->users->request_follow( + uid => $user->{id}, + target => $target->{id} + ); + } + elsif ( $action eq 'follow_or_request' ) { + if ( $target->{accept_follows} ) { + $self->users->follow( + uid => $user->{id}, + target => $target->{id} + ); + } + elsif ( $target->{accept_follow_requests} ) { + $self->users->request_follow( + uid => $user->{id}, + target => $target->{id} + ); + } + } + elsif ( $action eq 'unfollow' ) { + $self->users->unfollow( + uid => $user->{id}, + target => $target->{id} + ); + } + elsif ( $action eq 'remove_follower' ) { + $self->users->remove_follower( + uid => $user->{id}, + follower => $target->{id} + ); + } + elsif ( $action eq 'cancel_follow_request' ) { + $self->users->cancel_follow_request( + uid => $user->{id}, + target => $target->{id} + ); + } + elsif ( $action eq 'accept_follow_request' ) { + $self->users->accept_follow_request( + uid => $user->{id}, + applicant => $target->{id} + ); + } + elsif ( $action eq 'reject_follow_request' ) { + $self->users->reject_follow_request( + uid => $user->{id}, + applicant => $target->{id} + ); + } + elsif ( $action eq 'block' ) { + $self->users->block( + uid => $user->{id}, + target => $target->{id} + ); + } + elsif ( $action eq 'unblock' ) { + $self->users->unblock( + uid => $user->{id}, + target => $target->{id} + ); + } + + if ( $redirect_to eq 'profile' ) { + + # profile links do not perform bulk actions + $self->redirect_to( '/p/' . $target->{name} ); + return; + } + } + + $self->redirect_to($redirect_to); +} + +sub profile { + my ($self) = @_; + my $user = $self->current_user; + + if ( $self->param('action') and $self->param('action') eq 'save' ) { + if ( $self->validation->csrf_protect->has_error('csrf_token') ) { + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); + return; + } + my $md = Text::Markdown->new; + my $bio = $self->param('bio'); + + if ( length($bio) > 2000 ) { + $bio = substr( $bio, 0, 2000 ) . '…'; + } + + my $profile = { + bio => { + markdown => $bio, + html => $md->markdown( xml_escape($bio) ), + }, + metadata => [], + }; + for my $i ( 0 .. 20 ) { + my $key = $self->param("key_$i"); + my $value = $self->param("value_$i"); + if ($key) { + if ( length($value) > 500 ) { + $value = substr( $value, 0, 500 ) . '…'; + } + my $html_value + = ( $value + =~ s{ \[ ([^]]+) \]\( ([^)]+) \) }{'<a href="' . xml_escape($2) . '" rel="me">' . xml_escape($1) .'</a>' }egrx + ); + $profile->{metadata}[$i] = { + key => $key, + value => { + markdown => $value, + html => $html_value, + }, + }; + } + else { + last; + } + } + $self->users->set_profile( + uid => $user->{id}, + profile => $profile ); - $self->param( - history_age => $public_level & 0x40 ? 'infinite' : 'month' ); - $self->render( 'privacy', name => $user->{name} ); + $self->redirect_to( '/p/' . $user->{name} ); + } + + my $profile = $self->users->get_profile( uid => $user->{id} ); + $self->param( bio => $profile->{bio}{markdown} ); + for my $i ( 0 .. $#{ $profile->{metadata} } ) { + $self->param( "key_$i" => $profile->{metadata}[$i]{key} ); + $self->param( "value_$i" => $profile->{metadata}[$i]{value}{markdown} ); } + + $self->render( 'edit_profile', name => $user->{name} ); } sub insight { @@ -355,13 +838,16 @@ sub insight { sub webhook { my ($self) = @_; - my $hook = $self->get_webhook; + my $uid = $self->current_user->{id}; + + my $hook = $self->users->get_webhook( uid => $uid ); if ( $self->param('action') and $self->param('action') eq 'save' ) { $hook->{url} = $self->param('url'); $hook->{token} = $self->param('token'); $hook->{enabled} = $self->param('enabled') // 0; - $self->set_webhook( + $self->users->set_webhook( + uid => $uid, url => $hook->{url}, token => $hook->{token}, enabled => $hook->{enabled} @@ -372,7 +858,7 @@ sub webhook { sub { $self->render( 'webhooks', - hook => $self->get_webhook, + hook => $self->users->get_webhook( uid => $uid ), new_hook => 1 ); } @@ -398,8 +884,9 @@ sub change_mail { if ( $action and $action eq 'update_mail' ) { if ( $self->validation->csrf_protect->has_error('csrf_token') ) { $self->render( - 'change_mail', - invalid => 'csrf', + 'bad_request', + csrf => 1, + status => 400 ); return; } @@ -421,7 +908,6 @@ sub change_mail { } my $token = make_token(); - my $name = $self->current_user->{name}; my $db = $self->pg->db; my $tx = $db->begin; @@ -432,34 +918,7 @@ sub change_mail { token => $token ); - my $ip = $self->req->headers->header('X-Forwarded-For'); - my $ua = $self->req->headers->user_agent; - my $date = DateTime->now( time_zone => 'Europe/Berlin' ) - ->strftime('%d.%m.%Y %H:%M:%S %z'); - - # In case Mojolicious is not running behind a reverse proxy - $ip - //= sprintf( '%s:%s', $self->tx->remote_address, - $self->tx->remote_port ); - my $confirm_url - = $self->url_for('confirm_mail')->to_abs->scheme('https'); - my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); - - my $body = "Hallo ${name},\n\n"; - $body .= "Bitte bestätige unter <${confirm_url}/${token}>,\n"; - $body .= "dass du mit dieser Adresse E-Mail empfangen kannst.\n\n"; - $body - .= "Du erhältst diese Mail, da eine Änderung der deinem travelynx-Account\n"; - $body .= "zugeordneten Mail-Adresse beantragt wurde.\n\n"; - $body .= "Daten zur Anfrage:\n"; - $body .= " * Datum: ${date}\n"; - $body .= " * Client: ${ip}\n"; - $body .= " * UserAgent: ${ua}\n\n\n"; - $body .= "Impressum: ${imprint_url}\n"; - - my $success - = $self->sendmail->custom( $email, - 'travelynx: Mail-Adresse bestätigen', $body ); + my $success = $self->send_address_confirmation_mail( $email, $token ); if ($success) { $tx->commit; @@ -485,9 +944,9 @@ sub change_name { if ( $action and $action eq 'update_name' ) { if ( $self->validation->csrf_protect->has_error('csrf_token') ) { $self->render( - 'change_name', - name => $old_name, - invalid => 'csrf', + 'bad_request', + csrf => 1, + status => 400 ); return; } @@ -510,10 +969,10 @@ sub change_name { return; } - # The users table has a unique constraint on the "name" column, so having - # two users with the same name is not possible. The race condition - # between the user_name_exists check in is_name_invalid and this - # change_name call is harmless. + # The users table has a unique constraint on the "name" column, so having + # two users with the same name is not possible. The race condition + # between the user_name_exists check in is_name_invalid and this + # change_name call is harmless. my $success = $self->users->change_name( uid => $self->current_user->{id}, name => $new_name @@ -531,32 +990,7 @@ sub change_name { $self->flash( success => 'name' ); $self->redirect_to('account'); - my $ip = $self->req->headers->header('X-Forwarded-For'); - my $ua = $self->req->headers->user_agent; - my $date = DateTime->now( time_zone => 'Europe/Berlin' ) - ->strftime('%d.%m.%Y %H:%M:%S %z'); - - # In case Mojolicious is not running behind a reverse proxy - $ip - //= sprintf( '%s:%s', $self->tx->remote_address, - $self->tx->remote_port ); - my $confirm_url - = $self->url_for('confirm_mail')->to_abs->scheme('https'); - my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); - - my $body = "Hallo ${new_name},\n\n"; - $body - .= "Der Name deines Travelynx-Accounts wurde erfolgreich geändert.\n"; - $body .= "Alter Name: ${old_name}\n"; - $body .= "Neue Name: ${new_name}\n\n"; - $body .= "Daten zur Anfrage:\n"; - $body .= " * Datum: ${date}\n"; - $body .= " * Client: ${ip}\n"; - $body .= " * UserAgent: ${ua}\n\n\n"; - $body .= "Impressum: ${imprint_url}\n"; - - $self->sendmail->custom( $self->current_user->{email}, - 'travelynx: Name geändert', $body ); + $self->send_name_notification_mail( $old_name, $new_name ); } else { $self->render( 'change_name', name => $old_name ); @@ -569,6 +1003,273 @@ sub password_form { $self->render('change_password'); } +sub lonlat_in_polygon { + my ( $self, $polygon, $lonlat ) = @_; + + my $circle = shift( @{$polygon} ); + my @holes = @{$polygon}; + + my $circle_poly = Math::Polygon->new( @{$circle} ); + if ( $circle_poly->contains($lonlat) ) { + for my $hole (@holes) { + my $hole_poly = Math::Polygon->new( @{$hole} ); + if ( $hole_poly->contains($lonlat) ) { + return; + } + } + return 1; + } + return; +} + +sub backend_form { + my ($self) = @_; + my $user = $self->current_user; + + my @backends = $self->stations->get_backends; + my @suggested_backends; + + my %place_map = ( + AT => 'Österreich', + CH => 'Schweiz', + 'CH-BE' => 'Kanton Bern', + 'CH-GE' => 'Kanton Genf', + 'CH-LU' => 'Kanton Luzern', + 'CH-ZH' => 'Kanton Zürich', + DE => 'Deutschland', + 'DE-BB' => 'Brandenburg', + 'DE-BW' => 'Baden-Württemberg', + 'DE-BE' => 'Berlin', + 'DE-BY' => 'Bayern', + 'DE-HB' => 'Bremen', + 'DE-HE' => 'Hessen', + 'DE-MV' => 'Mecklenburg-Vorpommern', + 'DE-NI' => 'Niedersachsen', + 'DE-NW' => 'Nordrhein-Westfalen', + 'DE-RP' => 'Rheinland-Pfalz', + 'DE-SH' => 'Schleswig-Holstein', + 'DE-ST' => 'Sachsen-Anhalt', + 'DE-TH' => 'Thüringen', + DK => 'Dänemark', + 'GB-NIR' => 'Nordirland', + LI => 'Liechtenstein', + LU => 'Luxembourg', + IE => 'Irland', + 'US-CA' => 'California', + 'US-TX' => 'Texas', + ); + + my ( $user_lat, $user_lon ) + = $self->journeys->get_latest_checkout_latlon( uid => $user->{id} ); + + for my $backend (@backends) { + my $type = 'UNKNOWN'; + if ( $backend->{iris} ) { + $type = 'IRIS-TTS'; + $backend->{name} = 'IRIS'; + $backend->{longname} = 'Deutsche Bahn: IRIS-TTS'; + $backend->{homepage} = 'https://www.bahn.de'; + $backend->{legacy} = 1; + } + elsif ( $backend->{dbris} ) { + $type = 'DBRIS'; + $backend->{longname} = 'Deutsche Bahn: bahn.de'; + $backend->{homepage} = 'https://www.bahn.de'; + $backend->{recommended} = 1; + } + elsif ( $backend->{efa} ) { + if ( my $s = $self->efa->get_service( $backend->{name} ) ) { + $type = 'EFA'; + $backend->{longname} = $s->{name}; + $backend->{homepage} = $s->{homepage}; + $backend->{regions} = [ map { $place_map{$_} // $_ } + @{ $s->{coverage}{regions} // [] } ]; + $backend->{has_area} = $s->{coverage}{area} ? 1 : 0; + $backend->{association} = 1; + + if ( + $s->{coverage}{area} + and $s->{coverage}{area}{type} eq 'Polygon' + and $self->lonlat_in_polygon( + $s->{coverage}{area}{coordinates}, + [ $user_lon, $user_lat ] + ) + ) + { + push( @suggested_backends, $backend ); + } + elsif ( $s->{coverage}{area} + and $s->{coverage}{area}{type} eq 'MultiPolygon' ) + { + for my $s_poly ( + @{ $s->{coverage}{area}{coordinates} // [] } ) + { + if ( + $self->lonlat_in_polygon( + $s_poly, [ $user_lon, $user_lat ] + ) + ) + { + push( @suggested_backends, $backend ); + last; + } + } + } + } + else { + $type = undef; + } + } + elsif ( $backend->{hafas} ) { + + # These backends lack a journey endpoint or are no longer + # operational and are thus useless for travelynx + if ( $backend->{name} eq 'Resrobot' + or $backend->{name} eq 'TPG' + or $backend->{name} eq 'VRN' + or $backend->{name} eq 'DB' ) + { + $type = undef; + } + + # PKP is behind a GeoIP filter. Only list it if travelynx.conf + # indicates that our IP is allowed or provides a proxy. + elsif ( + $backend->{name} eq 'PKP' + and not( $self->app->config->{hafas}{PKP}{geoip_ok} + or $self->app->config->{hafas}{PKP}{proxy} ) + ) + { + $type = undef; + } + elsif ( my $s = $self->hafas->get_service( $backend->{name} ) ) { + $type = 'HAFAS'; + $backend->{longname} = $s->{name}; + $backend->{homepage} = $s->{homepage}; + $backend->{regions} = [ map { $place_map{$_} // $_ } + @{ $s->{coverage}{regions} // [] } ]; + $backend->{has_area} = $s->{coverage}{area} ? 1 : 0; + + if ( $backend->{name} eq 'ÖBB' ) { + $backend->{recommended} = 1; + } + else { + $backend->{association} = 1; + } + + if ( + $s->{coverage}{area} + and $s->{coverage}{area}{type} eq 'Polygon' + and $self->lonlat_in_polygon( + $s->{coverage}{area}{coordinates}, + [ $user_lon, $user_lat ] + ) + ) + { + push( @suggested_backends, $backend ); + } + elsif ( $s->{coverage}{area} + and $s->{coverage}{area}{type} eq 'MultiPolygon' ) + { + for my $s_poly ( + @{ $s->{coverage}{area}{coordinates} // [] } ) + { + if ( + $self->lonlat_in_polygon( + $s_poly, [ $user_lon, $user_lat ] + ) + ) + { + push( @suggested_backends, $backend ); + last; + } + } + } + } + else { + $type = undef; + } + } + elsif ( $backend->{motis} ) { + my $s = $self->motis->get_service( $backend->{name} ); + + $type = 'MOTIS'; + $backend->{longname} = $s->{name}; + $backend->{homepage} = $s->{homepage}; + $backend->{regions} = [ map { $place_map{$_} // $_ } + @{ $s->{coverage}{regions} // [] } ]; + $backend->{has_area} = $s->{coverage}{area} ? 1 : 0; + $backend->{experimental} = 1; + + if ( $backend->{name} eq 'transitous' ) { + $backend->{regions} = ['Weltweit']; + } + if ( $backend->{name} eq 'RNV' ) { + $backend->{homepage} = 'https://rnv-online.de/'; + } + + if ( + $s->{coverage}{area} + and $s->{coverage}{area}{type} eq 'Polygon' + and $self->lonlat_in_polygon( + $s->{coverage}{area}{coordinates}, + [ $user_lon, $user_lat ] + ) + ) + { + push( @suggested_backends, $backend ); + } + elsif ( $s->{coverage}{area} + and $s->{coverage}{area}{type} eq 'MultiPolygon' ) + { + for my $s_poly ( @{ $s->{coverage}{area}{coordinates} // [] } ) + { + if ( + $self->lonlat_in_polygon( + $s_poly, [ $user_lon, $user_lat ] + ) + ) + { + push( @suggested_backends, $backend ); + last; + } + } + } + } + $backend->{type} = $type; + } + + @backends = map { $_->[1] } + sort { $a->[0] cmp $b->[0] } + map { [ lc( $_->{name} ), $_ ] } grep { $_->{type} } @backends; + + $self->render( + 'select_backend', + suggestions => \@suggested_backends, + backends => \@backends, + user => $user, + redirect_to => $self->req->param('redirect_to') // '/', + ); +} + +sub change_backend { + my ($self) = @_; + + my $backend_id = $self->req->param('backend'); + my $redir = $self->req->param('redirect_to') // '/'; + + if ( $backend_id !~ m{ ^ \d+ $ }x ) { + $self->redirect_to($redir); + } + + $self->users->set_backend( + uid => $self->current_user->{id}, + backend_id => $backend_id, + ); + + $self->redirect_to($redir); +} + sub change_password { my ($self) = @_; my $old_password = $self->req->param('oldpw'); @@ -576,7 +1277,11 @@ sub change_password { my $password2 = $self->req->param('newpw2'); if ( $self->validation->csrf_protect->has_error('csrf_token') ) { - $self->render( 'change_password', invalid => 'csrf' ); + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); return; } @@ -601,37 +1306,14 @@ sub change_password { return; } - my $pw_hash = hash_password($password); - $self->users->set_password_hash( - uid => $self->current_user->{id}, - password_hash => $pw_hash + $self->users->set_password( + uid => $self->current_user->{id}, + password => $password ); $self->flash( success => 'password' ); $self->redirect_to('account'); - - my $user = $self->current_user->{name}; - my $email = $self->current_user->{email}; - my $ip = $self->req->headers->header('X-Forwarded-For'); - my $ua = $self->req->headers->user_agent; - my $date = DateTime->now( time_zone => 'Europe/Berlin' ) - ->strftime('%d.%m.%Y %H:%M:%S %z'); - - # In case Mojolicious is not running behind a reverse proxy - $ip - //= sprintf( '%s:%s', $self->tx->remote_address, $self->tx->remote_port ); - my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); - - my $body = "Hallo ${user},\n\n"; - $body - .= "Das Passwort deines travelynx-Accounts wurde soeben geändert.\n\n"; - $body .= "Daten zur Änderung:\n"; - $body .= " * Datum: ${date}\n"; - $body .= " * Client: ${ip}\n"; - $body .= " * UserAgent: ${ua}\n\n\n"; - $body .= "Impressum: ${imprint_url}\n"; - - $self->sendmail->custom( $email, 'travelynx: Passwort geändert', $body ); + $self->send_password_notification_mail(); } sub request_password_reset { @@ -639,7 +1321,11 @@ sub request_password_reset { if ( $self->param('action') and $self->param('action') eq 'initiate' ) { if ( $self->validation->csrf_protect->has_error('csrf_token') ) { - $self->render( 'recover_password', invalid => 'csrf' ); + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); return; } @@ -672,36 +1358,12 @@ sub request_password_reset { return; } - my $ip = $self->req->headers->header('X-Forwarded-For'); - my $ua = $self->req->headers->user_agent; - my $date = DateTime->now( time_zone => 'Europe/Berlin' ) - ->strftime('%d.%m.%Y %H:%M:%S %z'); - - # In case Mojolicious is not running behind a reverse proxy - $ip - //= sprintf( '%s:%s', $self->tx->remote_address, - $self->tx->remote_port ); - my $recover_url = $self->url_for('recover')->to_abs->scheme('https'); - my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); - - my $body = "Hallo ${name},\n\n"; - $body .= "Unter ${recover_url}/${uid}/${token}\n"; - $body - .= "kannst du ein neues Passwort für deinen travelynx-Account vergeben.\n\n"; - $body - .= "Du erhältst diese Mail, da mit deinem Accountnamen und deiner Mail-Adresse\n"; - $body - .= "ein Passwort-Reset angefordert wurde. Falls diese Anfrage nicht von dir\n"; - $body .= "ausging, kannst du sie ignorieren.\n\n"; - $body .= "Daten zur Anfrage:\n"; - $body .= " * Datum: ${date}\n"; - $body .= " * Client: ${ip}\n"; - $body .= " * UserAgent: ${ua}\n\n\n"; - $body .= "Impressum: ${imprint_url}\n"; - - my $success - = $self->sendmail->custom( $email, 'travelynx: Neues Passwort', - $body ); + my $success = $self->send_lostpassword_confirmation_mail( + email => $email, + name => $name, + uid => $uid, + token => $token + ); if ($success) { $tx->commit; @@ -720,7 +1382,11 @@ sub request_password_reset { my $password2 = $self->param('newpw2'); if ( $self->validation->csrf_protect->has_error('csrf_token') ) { - $self->render( 'set_password', invalid => 'csrf' ); + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); return; } if ( @@ -743,10 +1409,9 @@ sub request_password_reset { return; } - my $pw_hash = hash_password($password); - $self->users->set_password_hash( - uid => $id, - password_hash => $pw_hash + $self->users->set_password( + uid => $id, + password => $password ); my $account = $self->get_user_data($id); @@ -764,31 +1429,7 @@ sub request_password_reset { token => $token ); - my $user = $account->{name}; - my $email = $account->{email}; - my $ip = $self->req->headers->header('X-Forwarded-For'); - my $ua = $self->req->headers->user_agent; - my $date = DateTime->now( time_zone => 'Europe/Berlin' ) - ->strftime('%d.%m.%Y %H:%M:%S %z'); - - # In case Mojolicious is not running behind a reverse proxy - $ip - //= sprintf( '%s:%s', $self->tx->remote_address, - $self->tx->remote_port ); - my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https'); - - my $body = "Hallo ${user},\n\n"; - $body - .= "Das Passwort deines travelynx-Accounts wurde soeben über die"; - $body .= " 'Passwort vergessen'-Funktion geändert.\n\n"; - $body .= "Daten zur Änderung:\n"; - $body .= " * Datum: ${date}\n"; - $body .= " * Client: ${ip}\n"; - $body .= " * UserAgent: ${ua}\n\n\n"; - $body .= "Impressum: ${imprint_url}\n"; - - $self->sendmail->custom( $email, 'travelynx: Passwort geändert', - $body ); + $self->send_lostpassword_notification_mail($account); } else { $self->render('recover_password'); @@ -825,6 +1466,15 @@ sub confirm_mail { my $id = $self->current_user->{id}; my $token = $self->stash('token'); + # Some mail clients include the trailing ">" from the confirmation mail + # when opening/copying the confirmation link. A token will never contain + # this symbol, so remove it just in case. + $token =~ s{>}{}; + + # I did not yet find a mail client that also includes the trailing ",", + # but you never now... + $token =~ s{,}{}; + if ( $self->users->change_mail_with_token( uid => $id, @@ -841,10 +1491,27 @@ sub confirm_mail { } sub account { - my ($self) = @_; + my ($self) = @_; + my $uid = $self->current_user->{id}; + my $rx_follow_requests = $self->users->has_follow_requests( uid => $uid ); + my $tx_follow_requests = $self->users->has_follow_requests( + uid => $uid, + sent => 1 + ); + my $followers = $self->users->has_followers( uid => $uid ); + my $following = $self->users->has_followees( uid => $uid ); + my $blocked = $self->users->has_blocked_users( uid => $uid ); - $self->render('account'); - $self->users->mark_seen( uid => $self->current_user->{id} ); + $self->render( + 'account', + api_token => $self->users->get_api_token( uid => $uid ), + num_rx_follow_requests => $rx_follow_requests, + num_tx_follow_requests => $tx_follow_requests, + num_followers => $followers, + num_following => $following, + num_blocked => $blocked, + ); + $self->users->mark_seen( uid => $uid ); } sub json_export { @@ -868,4 +1535,53 @@ sub json_export { ); } +sub webfinger { + my ($self) = @_; + + my $resource = $self->param('resource'); + + if ( not $resource ) { + $self->render( 'not_found', status => 404 ); + return; + } + + my $root_url = $self->base_url_for('/')->to_abs->host; + + if ( not $root_url + or not $resource + =~ m{ ^ acct: [@]? (?<name> [^@]+ ) [@] $root_url $ }x ) + { + $self->render( 'not_found', status => 404 ); + return; + } + + my $name = $+{name}; + my $user = $self->users->get_privacy_by( name => $name ); + + if ( not $user ) { + $self->render( 'not_found', status => 404 ); + return; + } + + my $profile_url + = $self->base_url_for("/p/${name}")->to_abs->scheme('https')->to_string; + + $self->render( + text => JSON->new->encode( + { + subject => $resource, + aliases => [ $profile_url, ], + links => [ + { + rel => 'http://webfinger.net/rel/profile-page', + type => 'text/html', + href => $profile_url, + }, + ], + } + ), + format => 'json', + ); +} + 1; diff --git a/lib/Travelynx/Controller/Api.pm b/lib/Travelynx/Controller/Api.pm index 974b9ca..572d3fa 100755 --- a/lib/Travelynx/Controller/Api.pm +++ b/lib/Travelynx/Controller/Api.pm @@ -1,15 +1,17 @@ package Travelynx::Controller::Api; -# Copyright (C) 2020 Daniel Friesel +# Copyright (C) 2020-2023 Birte Kristina Friesel # # SPDX-License-Identifier: AGPL-3.0-or-later use Mojo::Base 'Mojolicious::Controller'; use DateTime; use List::Util; -use Travel::Status::DE::IRIS::Stations; +use Mojo::JSON qw(encode_json); use UUID::Tiny qw(:std); +# Internal Helpers + sub make_token { return create_uuid_as_string(UUID_V4); } @@ -19,6 +21,9 @@ sub sanitize { if ( not defined $value ) { return undef; } + if ( not defined $type ) { + return $value ? ( '' . $value ) : undef; + } if ( $type eq '' ) { return '' . $value; } @@ -28,15 +33,29 @@ sub sanitize { return 0; } +# Contollers + sub documentation { my ($self) = @_; - $self->render('api_documentation'); + if ( $self->is_user_authenticated ) { + my $uid = $self->current_user->{id}; + $self->render( + 'api_documentation', + uid => $uid, + api_token => $self->users->get_api_token( uid => $uid ), + ); + } + else { + $self->render('api_documentation'); + } } sub get_v1 { my ($self) = @_; + $self->res->headers->access_control_allow_origin(q{*}); + my $api_action = $self->stash('user_action'); my $api_token = $self->stash('token'); if ( $api_action !~ qr{ ^ (?: status | history | action ) $ }x ) { @@ -67,8 +86,11 @@ sub get_v1 { return; } - my $token = $self->get_api_token($uid); - if ( $api_token ne $token->{$api_action} ) { + my $token = $self->users->get_api_token( uid => $uid ); + if ( not $api_token + or not $token->{$api_action} + or $api_token ne $token->{$api_action} ) + { $self->render( json => { error => 'Invalid token', @@ -77,7 +99,7 @@ sub get_v1 { return; } if ( $api_action eq 'status' ) { - $self->render( json => $self->get_user_status_json_v1($uid) ); + $self->render( json => $self->get_user_status_json_v1( uid => $uid ) ); } else { $self->render( @@ -100,6 +122,7 @@ sub travel_v1 { deprecated => \0, error => 'Malformed JSON', }, + status => 400, ); return; } @@ -113,6 +136,7 @@ sub travel_v1 { deprecated => \0, error => 'Malformed token', }, + status => 400, ); return; } @@ -126,11 +150,12 @@ sub travel_v1 { deprecated => \0, error => 'Malformed token', }, + status => 400, ); return; } - my $token = $self->get_api_token($uid); + my $token = $self->users->get_api_token( uid => $uid ); if ( not $token->{'travel'} or $api_token ne $token->{'travel'} ) { $self->render( json => { @@ -138,6 +163,7 @@ sub travel_v1 { deprecated => \0, error => 'Invalid token', }, + status => 400, ); return; } @@ -150,8 +176,9 @@ sub travel_v1 { success => \0, deprecated => \0, error => 'Missing or invalid action', - status => $self->get_user_status_json_v1($uid) + status => $self->get_user_status_json_v1( uid => $uid ) }, + status => 400, ); return; } @@ -160,12 +187,20 @@ sub travel_v1 { my $from_station = sanitize( q{}, $payload->{fromStation} ); my $to_station = sanitize( q{}, $payload->{toStation} ); my $train_id; + my $dbris = sanitize( undef, $payload->{dbris} ); + my $hafas = sanitize( undef, $payload->{hafas} ); + my $motis = sanitize( undef, $payload->{motis} ); + + if ( not $hafas and exists $payload->{train}{journeyID} ) { + $dbris //= 'bahn.de'; + } if ( not( $from_station - and ( ( $payload->{train}{type} and $payload->{train}{no} ) - or $payload->{train}{id} ) + and ( ( $payload->{train}{type} and $payload->{train}{no} ) + or $payload->{train}{id} + or $payload->{train}{journeyID} ) ) ) { @@ -174,131 +209,149 @@ sub travel_v1 { success => \0, deprecated => \0, error => 'Missing fromStation or train data', - status => $self->get_user_status_json_v1($uid) + status => $self->get_user_status_json_v1( uid => $uid ) }, + status => 400, ); return; } - if ( - @{ - [ - Travel::Status::DE::IRIS::Stations::get_station( - $from_station) - ] - } != 1 - ) + if ( not $hafas + and not $dbris + and not $self->stations->search( $from_station, backend_id => 1 ) ) { $self->render( json => { success => \0, deprecated => \0, - error => 'fromStation is ambiguous', - status => $self->get_user_status_json_v1($uid) + error => 'Unknown fromStation', + status => $self->get_user_status_json_v1( uid => $uid ) }, + status => 400, ); return; } - if ( - $to_station - and @{ - [ - Travel::Status::DE::IRIS::Stations::get_station( - $to_station) - ] - } != 1 - ) + if ( $to_station + and not $hafas + and not $dbris + and not $self->stations->search( $to_station, backend_id => 1 ) ) { $self->render( json => { success => \0, deprecated => \0, - error => 'toStation is ambiguous', - status => $self->get_user_status_json_v1($uid) + error => 'Unknown toStation', + status => $self->get_user_status_json_v1( uid => $uid ) }, + status => 400, ); return; } - if ( exists $payload->{train}{id} ) { - $train_id = sanitize( 0, $payload->{train}{id} ); + my $train_p; + + if ( exists $payload->{train}{journeyID} ) { + $train_p = Mojo::Promise->resolve( + sanitize( q{}, $payload->{train}{journeyID} ) ); + } + elsif ( exists $payload->{train}{id} ) { + $train_p + = Mojo::Promise->resolve( sanitize( 0, $payload->{train}{id} ) ); } else { my $train_type = sanitize( q{}, $payload->{train}{type} ); my $train_no = sanitize( q{}, $payload->{train}{no} ); - my $status = $self->iris->get_departures( + + $train_p = $self->iris->get_departures_p( station => $from_station, lookbehind => 140, lookahead => 40 + )->then( + sub { + my ($status) = @_; + if ( $status->{errstr} ) { + return Mojo::Promise->reject( + 'Error requesting departures from fromStation: ' + . $status->{errstr} ); + } + my ($train) = List::Util::first { + $_->type eq $train_type and $_->train_no eq $train_no + } + @{ $status->{results} }; + if ( not defined $train ) { + return Mojo::Promise->reject( + 'Train not found at fromStation'); + } + return Mojo::Promise->resolve( $train->train_id ); + } ); - if ( $status->{errstr} ) { + } + + $self->render_later; + + $train_p->then( + sub { + my ($train_id) = @_; + return $self->checkin_p( + station => $from_station, + train_id => $train_id, + uid => $uid, + hafas => $hafas, + dbris => $dbris, + motis => $motis, + ); + } + )->then( + sub { + my ($train) = @_; + if ( $payload->{comment} ) { + $self->in_transit->update_user_data( + uid => $uid, + user_data => + { comment => sanitize( q{}, $payload->{comment} ) } + ); + } + if ($to_station) { + + # the user may not have provided the correct to_station, so + # request related stations for checkout. + return $self->checkout_p( + station => $to_station, + force => 0, + uid => $uid, + with_related => 1, + ); + } + return Mojo::Promise->resolve; + } + )->then( + sub { + my ( undef, $error ) = @_; + if ($error) { + return Mojo::Promise->reject($error); + } $self->render( json => { - success => \0, - error => - 'Error requesting departures from fromStation: ' - . $status->{errstr}, - status => $self->get_user_status_json_v1($uid) + success => \1, + deprecated => \0, + status => $self->get_user_status_json_v1( uid => $uid ) } ); - return; } - my ($train) = List::Util::first { - $_->type eq $train_type and $_->train_no eq $train_no - } - @{ $status->{results} }; - if ( not defined $train ) { + )->catch( + sub { + my ($error) = @_; $self->render( json => { success => \0, deprecated => \0, - error => 'Train not found at fromStation', - status => $self->get_user_status_json_v1($uid) + error => 'Checkin/Checkout error: ' . $error, + status => $self->get_user_status_json_v1( uid => $uid ) } ); - return; } - $train_id = $train->train_id; - } - - my ( $train, $error ) = $self->checkin( - station => $from_station, - train_id => $train_id, - uid => $uid - ); - if ( $payload->{comment} and not $error ) { - $self->in_transit->update_user_data( - uid => $uid, - user_data => { comment => sanitize( q{}, $payload->{comment} ) } - ); - } - if ( $to_station and not $error ) { - ( $train, $error ) = $self->checkout( - station => $to_station, - force => 0, - uid => $uid - ); - } - if ($error) { - $self->render( - json => { - success => \0, - deprecated => \0, - error => 'Checkin/Checkout error: ' . $error, - status => $self->get_user_status_json_v1($uid) - } - ); - } - else { - $self->render( - json => { - success => \1, - deprecated => \0, - status => $self->get_user_status_json_v1($uid) - } - ); - } + )->wait; } elsif ( $payload->{action} eq 'checkout' ) { my $to_station = sanitize( q{}, $payload->{toStation} ); @@ -309,7 +362,7 @@ sub travel_v1 { success => \0, deprecated => \0, error => 'Missing toStation', - status => $self->get_user_status_json_v1($uid) + status => $self->get_user_status_json_v1( uid => $uid ) }, ); return; @@ -322,30 +375,43 @@ sub travel_v1 { ); } - my ( $train, $error ) = $self->checkout( - station => $to_station, - force => $payload->{force} ? 1 : 0, - uid => $uid - ); - if ($error) { - $self->render( - json => { - success => \0, - deprecated => \0, - error => 'Checkout error: ' . $error, - status => $self->get_user_status_json_v1($uid) + $self->render_later; + + # the user may not have provided the correct to_station, so + # request related stations for checkout. + $self->checkout_p( + station => $to_station, + force => $payload->{force} ? 1 : 0, + uid => $uid, + with_related => 1, + )->then( + sub { + my ( $train, $error ) = @_; + if ($error) { + return Mojo::Promise->reject($error); } - ); - } - else { - $self->render( - json => { - success => \1, - deprecated => \0, - status => $self->get_user_status_json_v1($uid) - } - ); - } + $self->render( + json => { + success => \1, + deprecated => \0, + status => $self->get_user_status_json_v1( uid => $uid ) + } + ); + return; + } + )->catch( + sub { + my ($err) = @_; + $self->render( + json => { + success => \0, + deprecated => \0, + error => 'Checkout error: ' . $err, + status => $self->get_user_status_json_v1( uid => $uid ) + } + ); + } + )->wait; } elsif ( $payload->{action} eq 'undo' ) { my $error = $self->undo( 'in_transit', $uid ); @@ -355,7 +421,7 @@ sub travel_v1 { success => \0, deprecated => \0, error => $error, - status => $self->get_user_status_json_v1($uid) + status => $self->get_user_status_json_v1( uid => $uid ) } ); } @@ -364,7 +430,7 @@ sub travel_v1 { json => { success => \1, deprecated => \0, - status => $self->get_user_status_json_v1($uid) + status => $self->get_user_status_json_v1( uid => $uid ) } ); } @@ -413,7 +479,7 @@ sub import_v1 { return; } - my $token = $self->get_api_token($uid); + my $token = $self->users->get_api_token( uid => $uid ); if ( not $token->{'import'} or $api_token ne $token->{'import'} ) { $self->render( json => { @@ -457,13 +523,13 @@ sub import_v1 { } %opt = ( - uid => $uid, - train_type => sanitize( q{}, $payload->{train}{type} ), - train_no => sanitize( q{}, $payload->{train}{no} ), - train_line => sanitize( q{}, $payload->{train}{line} ), - cancelled => $payload->{cancelled} ? 1 : 0, - dep_station => sanitize( q{}, $payload->{fromStation}{name} ), - arr_station => sanitize( q{}, $payload->{toStation}{name} ), + uid => $uid, + train_type => sanitize( q{}, $payload->{train}{type} ), + train_no => sanitize( q{}, $payload->{train}{no} ), + train_line => sanitize( q{}, $payload->{train}{line} ), + cancelled => $payload->{cancelled} ? 1 : 0, + dep_station => sanitize( q{}, $payload->{fromStation}{name} ), + arr_station => sanitize( q{}, $payload->{toStation}{name} ), sched_departure => sanitize( 0, $payload->{fromStation}{scheduledTime} ), rt_departure => sanitize( @@ -478,8 +544,9 @@ sub import_v1 { $payload->{toStation}{realTime} // $payload->{toStation}{scheduledTime} ), - comment => sanitize( q{}, $payload->{comment} ), - lax => $payload->{lax} ? 1 : 0, + comment => sanitize( q{}, $payload->{comment} ), + lax => $payload->{lax} ? 1 : 0, + backend_id => 1, ); if ( $payload->{intermediateStops} @@ -518,14 +585,20 @@ sub import_v1 { my $journey; if ( not $error ) { - $journey = $self->journeys->get_single( - uid => $uid, - db => $db, - journey_id => $journey_id, - verbose => 1 - ); - $error - = $self->journeys->sanity_check( $journey, $payload->{lax} ? 1 : 0 ); + eval { + $journey = $self->journeys->get_single( + uid => $uid, + db => $db, + journey_id => $journey_id, + verbose => 1 + ); + $error + = $self->journeys->sanity_check( $journey, + $payload->{lax} ? 1 : 0 ); + }; + if ($@) { + $error = $@; + } } if ($error) { @@ -568,11 +641,15 @@ sub import_v1 { sub set_token { my ($self) = @_; if ( $self->validation->csrf_protect->has_error('csrf_token') ) { - $self->render( 'account', invalid => 'csrf' ); + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); return; } my $token = make_token(); - my $token_id = $self->app->token_type->{ $self->param('token') }; + my $token_id = $self->users->get_token_id( $self->param('token') ); if ( not $token_id ) { $self->redirect_to('account'); @@ -605,4 +682,25 @@ sub set_token { $self->redirect_to('account'); } +sub autocomplete { + my ($self) = @_; + + $self->res->headers->cache_control('max-age=86400, immutable'); + + my $backend_id = $self->param('backend_id') // 1; + + my $output + = "document.addEventListener('DOMContentLoaded',function(){M.Autocomplete.init(document.querySelectorAll('.autocomplete'),{\n"; + $output .= 'minLength:3,limit:50,data:'; + $output + .= encode_json( + $self->stations->get_for_autocomplete( backend_id => $backend_id ) ); + $output .= "\n});});\n"; + + $self->render( + format => 'js', + data => $output + ); +} + 1; diff --git a/lib/Travelynx/Controller/Passengerrights.pm b/lib/Travelynx/Controller/Passengerrights.pm index 1503483..5759d2e 100644 --- a/lib/Travelynx/Controller/Passengerrights.pm +++ b/lib/Travelynx/Controller/Passengerrights.pm @@ -1,5 +1,6 @@ package Travelynx::Controller::Passengerrights; -# Copyright (C) 2020 Daniel Friesel + +# Copyright (C) 2020-2023 Birte Kristina Friesel # # SPDX-License-Identifier: AGPL-3.0-or-later use Mojo::Base 'Mojolicious::Controller'; @@ -7,12 +8,15 @@ use Mojo::Base 'Mojolicious::Controller'; use DateTime; use CAM::PDF; +# Internal Helpers + sub mark_if_missed_connection { my ( $self, $journey, $next_journey ) = @_; my $possible_delay = ( $next_journey->{rt_departure}->epoch - - $journey->{sched_arrival}->epoch ) / 60; + - $journey->{sched_arrival}->epoch ) + / 60; my $wait_time = ( $next_journey->{rt_departure}->epoch - $journey->{rt_arrival}->epoch ) / 60; @@ -85,6 +89,8 @@ sub mark_substitute_connection { } } +# Controllers + sub list_candidates { my ($self) = @_; @@ -115,6 +121,8 @@ sub list_candidates { } } + my @abo_journeys + = grep { $_->{delay} >= 20 and $_->{delay} < 60 } @journeys; @journeys = grep { $_->{delay} >= 60 or $_->{connection_missed} } @journeys; my @cancelled = $self->journeys->get( @@ -148,8 +156,9 @@ sub list_candidates { $self->respond_to( json => { json => [@journeys] }, any => { - template => 'passengerrights', - journeys => [@journeys] + template => 'passengerrights', + journeys => [@journeys], + abo_journeys => [@abo_journeys] } ); } diff --git a/lib/Travelynx/Controller/Profile.pm b/lib/Travelynx/Controller/Profile.pm new file mode 100755 index 0000000..db30d36 --- /dev/null +++ b/lib/Travelynx/Controller/Profile.pm @@ -0,0 +1,641 @@ +package Travelynx::Controller::Profile; + +# Copyright (C) 2020-2023 Birte Kristina Friesel +# +# SPDX-License-Identifier: AGPL-3.0-or-later +use Mojo::Base 'Mojolicious::Controller'; + +use DateTime; + +# Internal Helpers + +sub status_token_ok { + my ( $self, $status, $ts2_ext ) = @_; + my $token = $self->param('token') // q{}; + + my ( $eva, $ts, $ts2 ) = split( qr{-}, $token ); + if ( not $ts ) { + return; + } + + $ts2 //= $ts2_ext; + + if ( $eva == $status->{dep_eva} + and $ts == $status->{timestamp}->epoch % 337 + and $ts2 == $status->{sched_departure}->epoch ) + { + return 1; + } + return; +} + +sub journey_token_ok { + my ( $self, $journey, $ts2_ext ) = @_; + my $token = $self->param('token') // q{}; + + my ( $eva, $ts, $ts2 ) = split( qr{-}, $token ); + if ( not $ts ) { + return; + } + + $ts2 //= $ts2_ext; + + if ( $eva == $journey->{from_eva} + and $ts == $journey->{checkin_ts} % 337 + and $ts2 == $journey->{sched_dep_ts} ) + { + return 1; + } + return; +} + +# Controllers + +sub profile { + my ($self) = @_; + + my $name = $self->stash('name'); + my $user = $self->users->get_privacy_by( name => $name ); + + if ( not $user ) { + $self->render( 'not_found', status => 404 ); + return; + } + + my $profile = $self->users->get_profile( uid => $user->{id} ); + + my $my_user; + my $relation; + my $inverse_relation; + my $is_self; + if ( $self->is_user_authenticated ) { + $my_user = $self->current_user; + if ( $my_user->{id} == $user->{id} ) { + $is_self = 1; + $my_user = undef; + } + else { + $relation = $self->users->get_relation( + subject => $my_user->{id}, + object => $user->{id} + ); + $inverse_relation = $self->users->get_relation( + subject => $user->{id}, + object => $my_user->{id} + ); + } + } + + my $status = $self->get_user_status( $user->{id} ); + if ( $status->{checked_in} or $status->{arr_name} ) { + my $visibility = $status->{effective_visibility}; + if ( + not( + $visibility == 100 + or ( $visibility >= 80 and $my_user ) + or + ( $visibility >= 60 and $relation and $relation eq 'follows' ) + or ( $visibility >= 60 and $is_self ) + or ( $visibility >= 30 and $self->status_token_ok($status) ) + ) + ) + { + $status->{checked_in} = 0; + $status->{arr_name} = undef; + } + } + if ( not $status->{checked_in} + and $status->{arr_name} + and not $user->{past_status} ) + { + $status->{arr_name} = undef; + } + + my $map_data = {}; + if ( $status->{checked_in} ) { + $map_data = $self->journeys_to_map_data( + journeys => [$status], + ); + } + + my @journeys; + + if ( + $user->{past_visibility_str} eq 'public' + or ( $user->{past_visibility_str} eq 'travelynx' + and ( $my_user or $is_self ) ) + or ( $user->{past_visibility_str} eq 'followers' + and ( ( $relation and $relation eq 'follows' ) or $is_self ) ) + ) + { + + my %opt = ( + uid => $user->{id}, + limit => 10, + with_datetime => 1 + ); + + if ( not $user->{past_all} ) { + my $now = DateTime->now( time_zone => 'Europe/Berlin' ); + $opt{before} = DateTime->now( time_zone => 'Europe/Berlin' ); + $opt{after} = $now->clone->subtract( weeks => 4 ); + } + + if ($is_self) { + $opt{min_visibility} = 'followers'; + } + elsif ($my_user) { + if ( $relation and $relation eq 'follows' ) { + $opt{min_visibility} = 'followers'; + } + else { + $opt{min_visibility} = 'travelynx'; + } + } + else { + $opt{min_visibility} = 'public'; + } + + @journeys = $self->journeys->get(%opt); + } + + $self->respond_to( + json => { + json => { + name => $name, + uid => $user->{id}, + bio => $profile->{bio}{html}, + metadata => $profile->{metadata}, + } + }, + any => { + template => 'profile', + title => "travelynx: $name", + name => $name, + uid => $user->{id}, + privacy => $user, + bio => $profile->{bio}{html}, + metadata => $profile->{metadata}, + is_self => $is_self, + following => ( $relation and $relation eq 'follows' ) ? 1 : 0, + follow_requested => ( $relation and $relation eq 'requests_follow' ) + ? 1 + : 0, + can_follow => + ( $my_user and $user->{accept_follows} and not $relation ) ? 1 + : 0, + can_request_follow => ( + $my_user and $user->{accept_follow_requests} and not $relation + ) ? 1 + : 0, + follows_me => + ( $inverse_relation and $inverse_relation eq 'follows' ) ? 1 + : 0, + follow_reqs_me => ( + $inverse_relation and $inverse_relation eq 'requests_follow' + ) ? 1 + : 0, + journey => $status, + journeys => [@journeys], + with_map => 1, + %{$map_data}, + } + ); +} + +sub journey_details { + my ($self) = @_; + my $name = $self->stash('name'); + my $journey_id = $self->stash('id'); + my $user = $self->users->get_privacy_by( name => $name ); + + $self->param( journey_id => $journey_id ); + + my $my_user; + my $relation; + my $inverse_relation; + my $is_self; + if ( $self->is_user_authenticated ) { + $my_user = $self->current_user; + if ( $my_user->{id} == $user->{id} ) { + $is_self = 1; + $my_user = undef; + } + else { + $relation = $self->users->get_relation( + subject => $my_user->{id}, + object => $user->{id} + ); + } + } + + if ( not( $user and $journey_id and $journey_id =~ m{ ^ \d+ $ }x ) ) { + $self->render( + 'journey', + status => 404, + error => 'notfound', + journey => {} + ); + return; + } + + my $journey = $self->journeys->get_single( + uid => $user->{id}, + journey_id => $journey_id, + verbose => 1, + with_datetime => 1, + with_route_datetime => 1, + with_polyline => 1, + with_visibility => 1, + ); + + if ( not $journey ) { + $self->render( + 'journey', + status => 404, + error => 'notfound', + journey => {} + ); + return; + } + + my $is_past; + if ( not $user->{past_all} ) { + my $now = DateTime->now( time_zone => 'Europe/Berlin' ); + if ( $journey->{sched_dep_ts} < $now->subtract( weeks => 4 )->epoch ) { + $is_past = 1; + } + } + + my $visibility = $journey->{effective_visibility}; + + if ( + not( ( $visibility == 100 and not $is_past ) + or ( $visibility >= 80 and $my_user and not $is_past ) + or ( $visibility >= 60 and $relation and $relation eq 'follows' ) + or ( $visibility >= 60 and $is_self ) + or ( $visibility >= 30 and $self->journey_token_ok($journey) ) ) + ) + { + $self->render( + 'journey', + status => 404, + error => 'notfound', + journey => {} + ); + return; + } + + my $title = sprintf( 'Fahrt von %s nach %s am %s', + $journey->{from_name}, $journey->{to_name}, + $journey->{rt_arrival}->strftime('%d.%m.%Y') ); + my $delay = 'pünktlich '; + if ( $journey->{rt_arrival} != $journey->{sched_arrival} ) { + $delay = sprintf( + 'mit %+d ', + ( + $journey->{rt_arrival}->epoch + - $journey->{sched_arrival}->epoch + ) / 60 + ); + } + my $description = sprintf( 'Ankunft mit %s %s %s', + $journey->{type}, $journey->{no}, + $journey->{rt_arrival}->strftime('um %H:%M') ); + if ( $journey->{km_route} > 0.1 ) { + $description = sprintf( '%.0f km mit %s %s – Ankunft %sum %s', + $journey->{km_route}, $journey->{type}, $journey->{no}, + $delay, $journey->{rt_arrival}->strftime('%H:%M') ); + } + my %tw_data = ( + card => 'summary', + site => '@derfnull', + image => $self->url_for('/static/icons/icon-512x512.png') + ->to_abs->scheme('https'), + title => $title, + description => $description, + ); + my %og_data = ( + type => 'article', + image => $tw_data{image}, + url => $self->url_for->to_abs, + site_name => 'travelynx', + title => $title, + description => $description, + ); + + my $map_data = $self->journeys_to_map_data( + journeys => [$journey], + include_manual => 1, + ); + if ( $journey->{user_data}{comment} + and not $user->{comments_visible} ) + { + delete $journey->{user_data}{comment}; + } + $self->render( + 'journey', + title => "travelynx: $title", + error => undef, + journey => $journey, + with_map => 1, + username => $name, + readonly => 1, + twitter => \%tw_data, + opengraph => \%og_data, + %{$map_data}, + ); +} + +sub user_status { + my ($self) = @_; + + my $name = $self->stash('name'); + my $ts = $self->stash('ts') // 0; + my $user = $self->users->get_privacy_by( name => $name ); + + if ( not $user ) { + $self->respond_to( + json => { + json => { error => 'not found' }, + status => 404, + }, + any => { + template => 'not_found', + status => 404 + } + ); + return; + } + + my $my_user; + my $relation; + my $inverse_relation; + my $is_self; + if ( $self->is_user_authenticated ) { + $my_user = $self->current_user; + if ( $my_user->{id} == $user->{id} ) { + $is_self = 1; + $my_user = undef; + } + else { + $relation = $self->users->get_relation( + subject => $my_user->{id}, + object => $user->{id} + ); + } + } + + my $status = $self->get_user_status( $user->{id} ); + + if ( + $ts + and ( not $status->{checked_in} + or $status->{sched_departure}->epoch != $ts ) + ) + { + for my $journey ( + $self->journeys->get( + uid => $user->{id}, + sched_dep_ts => $ts, + limit => 1, + with_visibility => 1, + ) + ) + { + my $visibility = $journey->{effective_visibility}; + if ( + $visibility == 100 + or ( $visibility >= 80 and $my_user ) + or + ( $visibility >= 60 and $relation and $relation eq 'follows' ) + or ( $visibility >= 60 and $is_self ) + or ( $visibility >= 30 + and $self->journey_token_ok( $journey, $ts ) ) + ) + { + my $token = $self->param('token') // q{}; + $self->redirect_to( + "/p/${name}/j/$journey->{id}?token=${token}-${ts}"); + } + else { + $self->respond_to( + json => { + json => { error => 'not found' }, + status => 404, + }, + any => { + template => 'not_found', + status => 404 + } + ); + } + return; + } + $self->respond_to( + json => { + json => { error => 'not found' }, + status => 404, + }, + any => { + template => 'not_found', + status => 404 + } + ); + return; + } + + my %tw_data = ( + card => 'summary', + site => '@derfnull', + image => $self->url_for('/static/icons/icon-512x512.png') + ->to_abs->scheme('https'), + ); + my %og_data = ( + type => 'article', + image => $tw_data{image}, + url => $self->url_for("/status/${name}")->to_abs->scheme('https'), + site_name => 'travelynx', + ); + + if ( $status->{checked_in} or $status->{arr_name} ) { + my $visibility = $status->{effective_visibility}; + if ( + not( + $visibility == 100 + or ( $visibility >= 80 and $my_user ) + or + ( $visibility >= 60 and $relation and $relation eq 'follows' ) + or ( $visibility >= 60 and $is_self ) + or + ( $visibility >= 30 and $self->status_token_ok( $status, $ts ) ) + ) + ) + { + $status = {}; + } + } + if ( not $status->{checked_in} + and $status->{arr_name} + and not $user->{past_status} ) + { + $status = {}; + } + + if ( $status->{checked_in} ) { + $og_data{url} .= '/' . $status->{sched_departure}->epoch; + $og_data{title} = $tw_data{title} = "${name} ist unterwegs"; + $og_data{description} = $tw_data{description} = sprintf( + '%s %s von %s nach %s', + $status->{train_type}, $status->{train_line} // $status->{train_no}, + $status->{dep_name}, $status->{arr_name} // 'irgendwo' + ); + if ( $status->{real_arrival}->epoch ) { + $tw_data{description} .= $status->{real_arrival} + ->strftime(' – Ankunft gegen %H:%M Uhr'); + $og_data{description} .= $status->{real_arrival} + ->strftime(' – Ankunft gegen %H:%M Uhr'); + } + } + else { + $og_data{title} = $tw_data{title} + = "${name} ist gerade nicht eingecheckt"; + $og_data{description} = $tw_data{description} = q{}; + } + + my $map_data = {}; + if ( $status->{checked_in} ) { + $map_data = $self->journeys_to_map_data( + journeys => [$status], + ); + } + + $self->respond_to( + json => { + json => { + account => { + name => $name, + }, + status => $self->get_user_status_json_v1( + status => $status, + privacy => $user, + public => 1 + ), + version => $self->app->config->{version} // 'UNKNOWN', + }, + }, + any => { + template => 'user_status', + name => $name, + title => "travelynx: $tw_data{title}", + privacy => $user, + journey => $status, + twitter => \%tw_data, + opengraph => \%og_data, + with_map => 1, + %{$map_data}, + version => $self->app->config->{version} // 'UNKNOWN', + }, + ); +} + +sub status_card { + my ($self) = @_; + + my $name = $self->stash('name'); + $name =~ s{[.]html$}{}; + my $user = $self->users->get_privacy_by( name => $name ); + + delete $self->stash->{layout}; + + if ( not $user ) { + $self->render( 'not_found', status => 404 ); + return; + } + + my $my_user; + my $relation; + my $inverse_relation; + my $is_self; + if ( $self->is_user_authenticated ) { + $my_user = $self->current_user; + if ( $my_user->{id} == $user->{id} ) { + $is_self = 1; + $my_user = undef; + } + else { + $relation = $self->users->get_relation( + subject => $my_user->{id}, + object => $user->{id} + ); + } + } + + my $status = $self->get_user_status( $user->{id} ); + my $visibility; + my $map_data = {}; + if ( $status->{checked_in} or $status->{arr_name} ) { + my $visibility = $status->{effective_visibility}; + if ( + not( + $visibility == 100 + or ( $visibility >= 80 and $my_user ) + or + ( $visibility >= 60 and $relation and $relation eq 'follows' ) + or ( $visibility >= 60 and $is_self ) + or ( $visibility >= 30 and $self->status_token_ok($status) ) + ) + ) + { + $status->{checked_in} = 0; + $status->{arr_name} = undef; + } + } + if ( not $status->{checked_in} + and $status->{arr_name} + and not $user->{past_status} ) + { + $status->{arr_name} = undef; + } + + if ( $status->{checked_in} ) { + $map_data = $self->journeys_to_map_data( + journeys => [$status], + ); + } + + $self->render( + '_public_status_card', + name => $name, + privacy => $user, + journey => $status, + from_profile => $self->param('profile') ? 1 : 0, + %{$map_data}, + ); +} + +sub checked_in { + my ($self) = @_; + + my $uid = $self->current_user->{id}; + my @journeys = $self->in_transit->get_timeline( + uid => $uid, + with_data => 1 + ); + + if ( $self->param('ajax') ) { + delete $self->stash->{layout}; + $self->render( + '_timeline-checked-in', + journeys => [@journeys], + ); + } + else { + $self->render( + 'timeline-checked-in', + journeys => [@journeys], + ); + } +} + +1; diff --git a/lib/Travelynx/Controller/Static.pm b/lib/Travelynx/Controller/Static.pm index addcd61..bcd6fda 100644 --- a/lib/Travelynx/Controller/Static.pm +++ b/lib/Travelynx/Controller/Static.pm @@ -1,29 +1,32 @@ package Travelynx::Controller::Static; -# Copyright (C) 2020 Daniel Friesel + +# Copyright (C) 2020-2023 Birte Kristina Friesel # # SPDX-License-Identifier: AGPL-3.0-or-later use Mojo::Base 'Mojolicious::Controller'; -my $travelynx_version = qx{git describe --dirty} || 'experimental'; - sub about { my ($self) = @_; - $self->render( 'about', - version => $self->app->config->{version} // 'UNKNOWN' ); + $self->render( 'about', title => 'Über travelynx' ); } sub changelog { my ($self) = @_; - $self->render( 'changelog', - version => $self->app->config->{version} // 'UNKNOWN' ); + $self->render( 'changelog', title => 'travelynx: Changelog' ); } sub imprint { my ($self) = @_; - $self->render('imprint'); + $self->render( 'imprint', title => 'travelynx: Impressum' ); +} + +sub legend { + my ($self) = @_; + + $self->render( 'legend', title => 'travelynx: Legende' ); } sub offline { @@ -32,4 +35,10 @@ sub offline { $self->render('offline'); } +sub tos { + my ($self) = @_; + + $self->render('terms-of-service'); +} + 1; diff --git a/lib/Travelynx/Controller/Traewelling.pm b/lib/Travelynx/Controller/Traewelling.pm index e906b1f..6aa789c 100644 --- a/lib/Travelynx/Controller/Traewelling.pm +++ b/lib/Travelynx/Controller/Traewelling.pm @@ -1,59 +1,97 @@ package Travelynx::Controller::Traewelling; -# Copyright (C) 2020 Daniel Friesel + +# Copyright (C) 2020-2023 Birte Kristina Friesel # # SPDX-License-Identifier: AGPL-3.0-or-later use Mojo::Base 'Mojolicious::Controller'; use Mojo::Promise; -sub settings { +sub oauth { my ($self) = @_; - my $uid = $self->current_user->{id}; - if ( $self->param('action') and $self->validation->csrf_protect->has_error('csrf_token') ) { $self->render( - 'traewelling', - invalid => 'csrf', + 'bad_request', + csrf => 1, + status => 400 ); return; } - if ( $self->param('action') and $self->param('action') eq 'login' ) { - my $email = $self->param('email'); - my $password = $self->param('password'); - $self->render_later; - $self->traewelling_api->login_p( - uid => $uid, - email => $email, - password => $password - )->then( - sub { - my $traewelling = $self->traewelling->get($uid); - $self->param( sync_source => 'none' ); - $self->render( - 'traewelling', - traewelling => $traewelling, - new_traewelling => 1, - ); + $self->render_later; + + my $oa = $self->config->{traewelling}{oauth}; + + return $self->oauth2->get_token_p( + traewelling => { + redirect_uri => + $self->base_url_for('/oauth/traewelling')->to_abs->scheme( + $self->app->mode eq 'development' ? 'http' : 'https' + )->to_string, + scope => 'read-statuses write-statuses' + } + )->then( + sub { + my ($provider) = @_; + if ( not defined $provider ) { + + # OAuth2 plugin performed a redirect, no need to render + return; } - )->catch( - sub { - my ($err) = @_; - $self->render( - 'traewelling', - traewelling => {}, - new_traewelling => 1, - login_error => $err, - ); + if ( not $provider or not $provider->{access_token} ) { + $self->flash( new_traewelling => 1 ); + $self->flash( login_error => 'no token received' ); + $self->redirect_to('/account/traewelling'); + return; } - )->wait; + my $uid = $self->current_user->{id}; + my $token = $provider->{access_token}; + $self->traewelling->link( + uid => $self->current_user->{id}, + token => $provider->{access_token}, + refresh_token => $provider->{refresh_token}, + expires_in => $provider->{expires_in}, + ); + return $self->traewelling_api->get_user_p( $uid, $token )->then( + sub { + $self->flash( new_traewelling => 1 ); + $self->redirect_to('/account/traewelling'); + } + ); + } + )->catch( + sub { + my ($err) = @_; + say "error $err"; + $self->flash( new_traewelling => 1 ); + $self->flash( login_error => $err ); + $self->redirect_to('/account/traewelling'); + return; + } + ); +} + +sub settings { + my ($self) = @_; + + my $uid = $self->current_user->{id}; + + if ( $self->param('action') + and $self->validation->csrf_protect->has_error('csrf_token') ) + { + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); return; } - elsif ( $self->param('action') and $self->param('action') eq 'logout' ) { + + if ( $self->param('action') and $self->param('action') eq 'logout' ) { $self->render_later; - my $traewelling = $self->traewelling->get($uid); + my $traewelling = $self->traewelling->get( uid => $uid ); $self->traewelling_api->logout_p( uid => $uid, token => $traewelling->{token} @@ -78,17 +116,17 @@ sub settings { elsif ( $self->param('action') and $self->param('action') eq 'config' ) { $self->traewelling->set_sync( uid => $uid, - push_sync => $self->param('sync_source') eq 'travelynx' ? 1 : 0, + push_sync => $self->param('sync_source') eq 'travelynx' ? 1 : 0, pull_sync => $self->param('sync_source') eq 'traewelling' ? 1 : 0, - toot => $self->param('toot') ? 1 : 0, - tweet => $self->param('tweet') ? 1 : 0, + toot => $self->param('toot') ? 1 : 0, + tweet => $self->param('tweet') ? 1 : 0, ); $self->flash( success => 'traewelling' ); $self->redirect_to('account'); return; } - my $traewelling = $self->traewelling->get($uid); + my $traewelling = $self->traewelling->get( uid => $uid ); if ( $traewelling->{push_sync} ) { $self->param( sync_source => 'travelynx' ); @@ -106,6 +144,7 @@ sub settings { $self->param( tweet => 1 ); } + $self->stash( title => 'travelynx × träwelling' ); $self->render( 'traewelling', traewelling => $traewelling, diff --git a/lib/Travelynx/Controller/Traveling.pm b/lib/Travelynx/Controller/Traveling.pm index ffc4211..fd2abb1 100755 --- a/lib/Travelynx/Controller/Traveling.pm +++ b/lib/Travelynx/Controller/Traveling.pm @@ -1,338 +1,446 @@ package Travelynx::Controller::Traveling; -# Copyright (C) 2020 Daniel Friesel +# Copyright (C) 2020-2023 Birte Kristina Friesel +# Copyright (C) 2025 networkException <git@nwex.de> # # SPDX-License-Identifier: AGPL-3.0-or-later use Mojo::Base 'Mojolicious::Controller'; use DateTime; use DateTime::Format::Strptime; -use JSON; -use List::Util qw(uniq min max); -use List::UtilsBy qw(max_by uniq_by); +use List::Util qw(uniq min max); +use List::UtilsBy qw(max_by uniq_by); use List::MoreUtils qw(first_index); +use Mojo::UserAgent; +use Mojo::Promise; use Text::CSV; use Travel::Status::DE::IRIS::Stations; -sub homepage { - my ($self) = @_; - if ( $self->is_user_authenticated ) { - $self->render( - 'landingpage', - version => $self->app->config->{version} // 'UNKNOWN', - with_autocomplete => 1, - with_geolocation => 1 - ); - $self->users->mark_seen( uid => $self->current_user->{id} ); - } - else { - $self->render( - 'landingpage', - version => $self->app->config->{version} // 'UNKNOWN', - intro => 1 - ); +# Internal Helpers + +sub has_str_in_list { + my ( $str, @strs ) = @_; + if ( List::Util::any { $str eq $_ } @strs ) { + return 1; } + return; } -sub user_status { - my ($self) = @_; +# when called with "eva" provided: look up connections from eva, either +# for provided backend_id / hafas or (if not provided) for user backend id. +# When calld without "eva": look up connections from current/latest arrival +# eva, using the checkin's backend id. +sub get_connecting_trains_p { + my ( $self, %opt ) = @_; - my $name = $self->stash('name'); - my $ts = $self->stash('ts') // 0; - my $user = $self->users->get_privacy_by_name( name => $name ); + my $user = $self->current_user; + my $uid = $opt{uid} //= $user->{id}; + my $use_history = $self->users->use_history( uid => $uid ); - if ( not $user or not $user->{public_level} & 0x03 ) { - $self->render('not_found'); - return; - } + my ( $eva, $exclude_via, $exclude_train_id, $exclude_before ); + my $now = $self->now->epoch; + my ( $stationinfo, $arr_epoch, $arr_platform, $arr_countdown ); - if ( $user->{public_level} & 0x01 and not $self->is_user_authenticated ) { - $self->render( 'login', redirect_to => $self->req->url ); - return; - } + my $promise = Mojo::Promise->new; - my $status = $self->get_user_status( $user->{id} ); - my $journey; + if ( $user->{backend_dbris} ) { - if ( - $ts - and ( not $status->{checked_in} - or $status->{sched_departure}->epoch != $ts ) - and ( $user->{public_level} & 0x20 - or - ( $user->{public_level} & 0x10 and $self->is_user_authenticated ) ) - ) - { - for my $candidate ( - $self->journeys->get( - uid => $user->{id}, - limit => 10, - ) - ) - { - if ( $candidate->{sched_dep_ts} eq $ts ) { - $journey = $self->journeys->get_single( - uid => $user->{id}, - journey_id => $candidate->{id}, - verbose => 1, - with_datetime => 1, - with_polyline => 1, - ); - } - } + # We do get a little bit of via information, so this might work in some + # cases. But not reliably. Probably best to leave it out entirely then. + return $promise->reject; } + if ( $user->{backend_efa} ) { - my %tw_data = ( - card => 'summary', - site => '@derfnull', - image => $self->url_for('/static/icons/icon-512x512.png') - ->to_abs->scheme('https'), - ); - my %og_data = ( - type => 'article', - image => $tw_data{image}, - url => $self->url_for("/status/${name}")->to_abs->scheme('https'), - site_name => 'travelynx', - ); + # TODO + return $promise->reject; + } + if ( $user->{backend_motis} ) { - if ($journey) { - $og_data{title} = $tw_data{title} = sprintf( 'Fahrt von %s nach %s', - $journey->{from_name}, $journey->{to_name} ); - $og_data{description} = $tw_data{description} - = $journey->{rt_arrival}->strftime('Ankunft am %d.%m.%Y um %H:%M'); - $og_data{url} .= "/${ts}"; - } - elsif ( - $ts - and ( not $status->{checked_in} - or $status->{sched_departure}->epoch != $ts ) - ) - { - $og_data{title} = $tw_data{title} = "Bahnfahrt beendet"; - $og_data{description} = $tw_data{description} - = "${name} hat das Ziel erreicht"; + # FIXME: The following code can't handle external_ids currently + return $promise->reject; } - elsif ( $status->{checked_in} ) { - $og_data{url} .= '/' . $status->{sched_departure}->epoch; - $og_data{title} = $tw_data{title} = "${name} ist unterwegs"; - $og_data{description} = $tw_data{description} = sprintf( - '%s %s von %s nach %s', - $status->{train_type}, $status->{train_line} // $status->{train_no}, - $status->{dep_name}, $status->{arr_name} // 'irgendwo' - ); - if ( $status->{real_arrival}->epoch ) { - $tw_data{description} .= $status->{real_arrival} - ->strftime(' – Ankunft gegen %H:%M Uhr'); - $og_data{description} .= $status->{real_arrival} - ->strftime(' – Ankunft gegen %H:%M Uhr'); + + if ( $opt{eva} ) { + if ( $use_history & 0x01 ) { + $eva = $opt{eva}; + } + elsif ( $opt{destination_name} ) { + $eva = $opt{eva}; + } + if ( not defined $opt{backend_id} ) { + if ( $opt{hafas} ) { + $opt{backend_id} + = $self->stations->get_backend_id( hafas => $opt{hafas} ); + } + else { + $opt{backend_id} = $user->{backend_id}; + } } } else { - $og_data{title} = $tw_data{title} - = "${name} ist gerade nicht eingecheckt"; - $og_data{description} = $tw_data{description} - = "Letztes Fahrtziel: $status->{arr_name}"; - } - - if ($journey) { - if ( not $user->{public_level} & 0x04 ) { - delete $journey->{user_data}{comment}; + if ( $use_history & 0x02 ) { + my $status = $self->get_user_status; + $opt{backend_id} = $status->{backend_id}; + $eva = $status->{arr_eva}; + $exclude_via = $status->{dep_name}; + $exclude_train_id = $status->{train_id}; + $arr_platform = $status->{arr_platform}; + $stationinfo = $status->{extra_data}{stationinfo_arr}; + if ( $status->{real_arrival} ) { + $exclude_before = $arr_epoch = $status->{real_arrival}->epoch; + $arr_countdown = $status->{arrival_countdown}; + } } - my $map_data = $self->journeys_to_map_data( - journeys => [$journey], - include_manual => 1, - ); - $self->render( - 'journey', - error => undef, - with_map => 1, - readonly => 1, - journey => $journey, - twitter => \%tw_data, - opengraph => \%og_data, - %{$map_data}, - ); } - else { - $self->render( - 'user_status', - name => $name, - public_level => $user->{public_level}, - journey => $status, - twitter => \%tw_data, - opengraph => \%og_data, - ); + + $exclude_before //= $now - 300; + + if ( not $eva ) { + return $promise->reject; } -} -sub public_profile { - my ($self) = @_; + $self->log->debug( + "get_connecting_trains_p(backend_id => $opt{backend_id}, eva => $eva)"); - my $name = $self->stash('name'); - my $user = $self->users->get_privacy_by_name( name => $name ); + my @destinations = $self->journeys->get_connection_targets(%opt); - if ( - $user - and ( $user->{public_level} & 0x22 - or - ( $user->{public_level} & 0x11 and $self->is_user_authenticated ) ) - ) - { - my $status = $self->get_user_status( $user->{id} ); - my @journeys; - if ( $user->{public_level} & 0x40 ) { - @journeys = $self->journeys->get( - uid => $user->{id}, - limit => 10, - with_datetime => 1 - ); - } - else { - my $now = DateTime->now( time_zone => 'Europe/Berlin' ); - my $month_ago = $now->clone->subtract( weeks => 4 ); - @journeys = $self->journeys->get( - uid => $user->{id}, - limit => 10, - with_datetime => 1, - after => $month_ago, - before => $now - ); - } - $self->render( - 'profile', - name => $name, - uid => $user->{id}, - public_level => $user->{public_level}, - journey => $status, - journeys => [@journeys], - version => $self->app->config->{version} // 'UNKNOWN', - ); + @destinations = uniq_by { $_->{name} } @destinations; + + if ($exclude_via) { + @destinations = grep { $_->{name} ne $exclude_via } @destinations; } - else { - $self->render('not_found'); + + if ( not @destinations ) { + return $promise->reject; } -} -sub public_journey_details { - my ($self) = @_; - my $name = $self->stash('name'); - my $journey_id = $self->stash('id'); - my $user = $self->users->get_privacy_by_name( name => $name ); + $self->log->debug( 'get_connection_targets returned ' + . join( q{, }, map { $_->{name} } @destinations ) ); + + my $can_check_in = not $arr_epoch || ( $arr_countdown // 1 ) < 0; + my $lookahead + = $can_check_in ? 40 : ( ( ${arr_countdown} // 0 ) / 60 + 40 ); + + my $iris_promise = Mojo::Promise->new; + my %via_count = map { $_->{name} => 0 } @destinations; + + my $backend + = $self->stations->get_backend( backend_id => $opt{backend_id} ); + if ( $opt{backend_id} == 0 ) { + $self->iris->get_departures_p( + station => $eva, + lookbehind => 10, + lookahead => $lookahead, + with_related => 1 + )->then( + sub { + my ($stationboard) = @_; + if ( $stationboard->{errstr} ) { + $promise->resolve( [], [] ); + return; + } - $self->param( journey_id => $journey_id ); + @{ $stationboard->{results} } = map { $_->[0] } + sort { $a->[1] <=> $b->[1] } + map { [ $_, $_->departure ? $_->departure->epoch : 0 ] } + @{ $stationboard->{results} }; + my @results; + my @cancellations; + my $excluded_train; + for my $train ( @{ $stationboard->{results} } ) { + if ( not $train->departure ) { + next; + } + if ( $exclude_before + and $train->departure + and $train->departure->epoch < $exclude_before ) + { + next; + } + if ( $exclude_train_id + and $train->train_id eq $exclude_train_id ) + { + $excluded_train = $train; + next; + } + + # In general, this function is meant to return feasible + # connections. However, cancelled connections may also be of + # interest and are also useful for logging cancellations. + # To satisfy both demands with (hopefully) little confusion and + # UI clutter, this function returns two concatenated arrays: + # actual connections (ordered by actual departure time) followed + # by cancelled connections (ordered by scheduled departure time). + # This is easiest to achieve in two separate loops. + # + # Note that a cancelled train may still have a matching destination + # in its route_post, e.g. if it leaves out $eva due to + # unscheduled route changes but continues on schedule afterwards + # -- so it is only cancelled at $eva, not on the remainder of + # the route. Also note that this specific case is not yet handled + # properly by the cancellation logic etc. + + if ( $train->departure_is_cancelled ) { + my @via = ( + $train->sched_route_post, $train->sched_route_end + ); + for my $dest (@destinations) { + if ( has_str_in_list( $dest->{name}, @via ) ) { + push( @cancellations, [ $train, $dest ] ); + next; + } + } + } + else { + my @via = ( $train->route_post, $train->route_end ); + for my $dest (@destinations) { + if ( $via_count{ $dest->{name} } < 2 + and has_str_in_list( $dest->{name}, @via ) ) + { + push( @results, [ $train, $dest ] ); + + # Show all past and up to two future departures per destination + if ( not $train->departure + or $train->departure->epoch >= $now ) + { + $via_count{ $dest->{name} }++; + } + next; + } + } + } + } - if ( not( $journey_id and $journey_id =~ m{ ^ \d+ $ }x ) ) { - $self->render( - 'journey', - status => 404, - error => 'notfound', - journey => {} - ); - return; - } + @results = map { $_->[0] } + sort { $a->[1] <=> $b->[1] } + map { + [ + $_, + $_->[0]->departure->epoch + // $_->[0]->sched_departure->epoch + ] + } @results; + @cancellations = map { $_->[0] } + sort { $a->[1] <=> $b->[1] } + map { [ $_, $_->[0]->sched_departure->epoch ] } + @cancellations; + + # remove trains whose route matches the excluded one's + if ($excluded_train) { + my $route_pre + = join( '|', reverse $excluded_train->route_pre ); + @results + = grep { join( '|', $_->[0]->route_post ) ne $route_pre } + @results; + my $route_post = join( '|', $excluded_train->route_post ); + @results + = grep { join( '|', $_->[0]->route_post ) ne $route_post } + @results; + } - if ( - $user - and ( $user->{public_level} & 0x20 - or - ( $user->{public_level} & 0x10 and $self->is_user_authenticated ) ) - ) - { - my $journey = $self->journeys->get_single( - uid => $user->{id}, - journey_id => $journey_id, - verbose => 1, - with_datetime => 1, - with_polyline => 1, - ); + # add message IDs and 'transfer short' hints + for my $result (@results) { + my $train = $result->[0]; + my @message_ids + = List::Util::uniq map { $_->[1] } $train->raw_messages; + $train->{message_id} = { map { $_ => 1 } @message_ids }; + my $interchange_duration; + if ( exists $stationinfo->{i} ) { + if ( defined $arr_platform + and defined $train->platform ) + { + $interchange_duration + = $stationinfo->{i}{$arr_platform} + { $train->platform }; + } + $interchange_duration //= $stationinfo->{i}{"*"}; + } + if ( defined $interchange_duration ) { + my $interchange_time + = ( $train->departure->epoch - $arr_epoch ) / 60; + if ( $interchange_time < $interchange_duration ) { + $train->{interchange_text} = 'Anschluss knapp'; + $train->{interchange_icon} = 'directions_run'; + } + elsif ( $interchange_time == $interchange_duration ) { + $train->{interchange_text} + = 'Anschluss könnte knapp werden'; + $train->{interchange_icon} = 'directions_run'; + } + } + } - if ( not( $user->{public_level} & 0x40 ) ) { - my $month_ago = DateTime->now( time_zone => 'Europe/Berlin' ) - ->subtract( weeks => 4 )->epoch; - if ( $journey and $journey->{rt_dep_ts} < $month_ago ) { - $journey = undef; + $promise->resolve( [ @results, @cancellations ], [] ); + return; } - } - - if ($journey) { - my $title = sprintf( 'Fahrt von %s nach %s am %s', - $journey->{from_name}, $journey->{to_name}, - $journey->{rt_arrival}->strftime('%d.%m.%Y') ); - my $description = sprintf( 'Ankunft mit %s %s %s', - $journey->{type}, $journey->{no}, - $journey->{rt_arrival}->strftime('um %H:%M') ); - my %tw_data = ( - card => 'summary', - site => '@derfnull', - image => $self->url_for('/static/icons/icon-512x512.png') - ->to_abs->scheme('https'), - title => $title, - description => $description, - ); - my %og_data = ( - type => 'article', - image => $tw_data{image}, - url => $self->url_for->to_abs, - site_name => 'travelynx', - title => $title, - description => $description, - ); - - my $map_data = $self->journeys_to_map_data( - journeys => [$journey], - include_manual => 1, - ); - if ( $journey->{user_data}{comment} - and not $user->{public_level} & 0x04 ) - { - delete $journey->{user_data}{comment}; + )->catch( + sub { + $promise->resolve( [], [] ); + return; } - $self->render( - 'journey', - error => undef, - journey => $journey, - with_map => 1, - username => $name, - readonly => 1, - twitter => \%tw_data, - opengraph => \%og_data, - %{$map_data}, - ); - } - else { - $self->render('not_found'); - } + )->wait; } - else { - $self->render('not_found'); + elsif ( $backend->{dbris} ) { + return $promise->reject; + } + elsif ( $backend->{efa} ) { + return $promise->reject; + } + elsif ( $backend->{hafas} ) { + my $hafas_service = $backend->{name}; + $self->hafas->get_departures_p( + service => $hafas_service, + eva => $eva, + lookbehind => 10, + lookahead => $lookahead + )->then( + sub { + my ($status) = @_; + my @hafas_trains; + my @all_hafas_trains = $status->results; + for my $hafas_train (@all_hafas_trains) { + for my $stop ( $hafas_train->route ) { + for my $dest (@destinations) { + if ( $stop->loc->name + and $stop->loc->name eq $dest->{name} + and $via_count{ $dest->{name} } < 2 + and $hafas_train->datetime ) + { + my $departure = $hafas_train->datetime; + my $arrival = $stop->arr; + my $delay = $hafas_train->delay; + if ( $delay + and $stop->arr == $stop->sched_arr ) + { + $arrival->add( minutes => $delay ); + } + if ( $departure->epoch >= $exclude_before ) { + $via_count{ $dest->{name} }++; + push( + @hafas_trains, + [ + $hafas_train, $dest, + $arrival, $hafas_service + ] + ); + } + } + } + } + } + $promise->resolve( [], \@hafas_trains ); + return; + } + )->catch( + sub { + my ($err) = @_; + $self->log->debug("get_connection_trains: hafas: $err"); + $promise->resolve( [], [] ); + return; + } + )->wait; } -} -sub public_status_card { - my ($self) = @_; + return $promise; +} - my $name = $self->stash('name'); - my $user = $self->users->get_privacy_by_name( name => $name ); +sub compute_effective_visibility { + my ( $self, $default_visibility, $journey_visibility ) = @_; + if ( $journey_visibility eq 'default' ) { + return $default_visibility; + } + return $journey_visibility; +} - delete $self->stash->{layout}; +# Controllers - if ( - $user - and ( $user->{public_level} & 0x02 - or - ( $user->{public_level} & 0x01 and $self->is_user_authenticated ) ) - ) - { - my $status = $self->get_user_status( $user->{id} ); +sub homepage { + my ($self) = @_; + if ( $self->is_user_authenticated ) { + my $user = $self->current_user; + my $uid = $user->{id}; + my $status = $self->get_user_status; + my @timeline = $self->in_transit->get_timeline( + uid => $uid, + short => 1 + ); + $self->stash( timeline => [@timeline] ); + my @recent_targets; + if ( $status->{checked_in} ) { + my $map_data = {}; + if ( $status->{arr_name} ) { + $map_data = $self->journeys_to_map_data( + journeys => [$status], + ); + } + my $journey_visibility + = $self->compute_effective_visibility( + $user->{default_visibility_str}, + $status->{visibility_str} ); + if ( defined $status->{arrival_countdown} + and $status->{arrival_countdown} < ( 40 * 60 ) ) + { + $self->render_later; + $self->get_connecting_trains_p->then( + sub { + my ( $connections_iris, $connections_hafas ) = @_; + $self->render( + 'landingpage', + user => $user, + user_status => $status, + journey_visibility => $journey_visibility, + connections_iris => $connections_iris, + connections_hafas => $connections_hafas, + with_map => 1, + %{$map_data}, + ); + $self->users->mark_seen( uid => $uid ); + } + )->catch( + sub { + $self->render( + 'landingpage', + user => $user, + user_status => $status, + journey_visibility => $journey_visibility, + with_map => 1, + %{$map_data}, + ); + $self->users->mark_seen( uid => $uid ); + } + )->wait; + return; + } + else { + $self->render( + 'landingpage', + user => $user, + user_status => $status, + journey_visibility => $journey_visibility, + with_map => 1, + %{$map_data}, + ); + $self->users->mark_seen( uid => $uid ); + return; + } + } + else { + @recent_targets = uniq_by { $_->{external_id_or_eva} } + $self->journeys->get_latest_checkout_stations( uid => $uid ); + } $self->render( - '_public_status_card', - name => $name, - public_level => $user->{public_level}, - journey => $status + 'landingpage', + user => $user, + user_status => $status, + recent_targets => \@recent_targets, + with_autocomplete => 1, + with_geolocation => 1, + backend_id => $user->{backend_id}, ); + $self->users->mark_seen( uid => $uid ); } else { - $self->render('not_found'); + $self->render( 'landingpage', intro => 1 ); } } @@ -342,14 +450,103 @@ sub status_card { delete $self->stash->{layout}; + my @timeline = $self->in_transit->get_timeline( + uid => $self->current_user->{id}, + short => 1 + ); + $self->stash( timeline => [@timeline] ); + if ( $status->{checked_in} ) { - $self->render( '_checked_in', journey => $status ); + my $map_data = {}; + if ( $status->{arr_name} ) { + $map_data = $self->journeys_to_map_data( + journeys => [$status], + ); + } + my $journey_visibility + = $self->compute_effective_visibility( + $self->current_user->{default_visibility_str}, + $status->{visibility_str} ); + if ( defined $status->{arrival_countdown} + and $status->{arrival_countdown} < ( 40 * 60 ) ) + { + $self->render_later; + $self->get_connecting_trains_p->then( + sub { + my ( $connections_iris, $connections_hafas ) = @_; + $self->render( + '_checked_in', + journey => $status, + journey_visibility => $journey_visibility, + connections_iris => $connections_iris, + connections_hafas => $connections_hafas, + %{$map_data}, + ); + } + )->catch( + sub { + $self->render( + '_checked_in', + journey => $status, + journey_visibility => $journey_visibility, + %{$map_data}, + ); + } + )->wait; + return; + } + $self->render( + '_checked_in', + journey => $status, + journey_visibility => $journey_visibility, + %{$map_data}, + ); } elsif ( $status->{cancellation} ) { - $self->render( '_cancelled_departure', - journey => $status->{cancellation} ); + $self->render_later; + $self->get_connecting_trains_p( + backend_id => $status->{backend_id}, + eva => $status->{cancellation}{dep_eva}, + destination_name => $status->{cancellation}{arr_name} + )->then( + sub { + my ($connecting_trains) = @_; + $self->render( + '_cancelled_departure', + journey => $status->{cancellation}, + connections_iris => $connecting_trains + ); + } + )->catch( + sub { + $self->render( '_cancelled_departure', + journey => $status->{cancellation} ); + } + )->wait; + return; } else { + my @connecting_trains; + my $now = DateTime->now( time_zone => 'Europe/Berlin' ); + if ( $now->epoch - $status->{timestamp}->epoch < ( 30 * 60 ) ) { + $self->render_later; + $self->get_connecting_trains_p->then( + sub { + my ( $connections_iris, $connections_hafas ) = @_; + $self->render( + '_checked_out', + journey => $status, + connections_iris => $connections_iris, + connections_hafas => $connections_hafas, + ); + } + )->catch( + sub { + $self->render( '_checked_out', journey => $status ); + } + )->wait; + return; + } $self->render( '_checked_out', journey => $status ); } } @@ -357,43 +554,251 @@ sub status_card { sub geolocation { my ($self) = @_; - my $lon = $self->param('lon'); - my $lat = $self->param('lat'); + my $lon = $self->param('lon'); + my $lat = $self->param('lat'); + my $backend_id = $self->param('backend') // 0; if ( not $lon or not $lat ) { - $self->render( json => { error => 'Invalid lon/lat received' } ); + $self->render( + json => { error => "Invalid lon/lat (${lon}/${lat}) received" } ); + return; } - else { - my @candidates = map { - { - ds100 => $_->[0][0], - name => $_->[0][1], - eva => $_->[0][2], - lon => $_->[0][3], - lat => $_->[0][4], - distance => $_->[1], - } - } Travel::Status::DE::IRIS::Stations::get_station_by_location( $lon, - $lat, 10 ); - @candidates = uniq_by { $_->{name} } @candidates; - if ( @candidates > 5 ) { - $self->render( - json => { - candidates => [ @candidates[ 0 .. 4 ] ], + + if ( $backend_id !~ m{ ^ \d+ $ }x ) { + $self->render( + json => { error => "Invalid backend (${backend_id}) received" } ); + return; + } + + my ( $dbris_service, $efa_service, $hafas_service, $motis_service ); + my $backend = $self->stations->get_backend( backend_id => $backend_id ); + if ( $backend->{dbris} ) { + $dbris_service = $backend->{name}; + } + if ( $backend->{efa} ) { + $efa_service = $backend->{name}; + } + elsif ( $backend->{hafas} ) { + $hafas_service = $backend->{name}; + } + elsif ( $backend->{motis} ) { + $motis_service = $backend->{name}; + } + + if ($dbris_service) { + $self->render_later; + + Travel::Status::DE::DBRIS->new_p( + promise => 'Mojo::Promise', + user_agent => Mojo::UserAgent->new, + geoSearch => { + latitude => $lat, + longitude => $lon + } + )->then( + sub { + my ($dbris) = @_; + my @results = map { + { + name => $_->name, + eva => $_->eva, + distance => 0, + dbris => $dbris_service, + } + } $dbris->results; + if ( @results > 10 ) { + @results = @results[ 0 .. 9 ]; } - ); + $self->render( + json => { + candidates => [@results], + } + ); + } + )->catch( + sub { + my ($err) = @_; + $self->render( + json => { + candidates => [], + warning => $err, + } + ); + } + )->wait; + return; + } + elsif ($efa_service) { + $self->render_later; + + Travel::Status::DE::EFA->new_p( + promise => 'Mojo::Promise', + user_agent => Mojo::UserAgent->new, + service => $efa_service, + coord => { + lat => $lat, + lon => $lon + } + )->then( + sub { + my ($efa) = @_; + my @results = map { + { + name => $_->full_name, + eva => $_->id_code, + distance => 0, + efa => $efa_service, + } + } $efa->results; + if ( @results > 10 ) { + @results = @results[ 0 .. 9 ]; + } + $self->render( + json => { + candidates => [@results], + } + ); + } + )->catch( + sub { + my ($err) = @_; + $self->render( + json => { + candidates => [], + warning => $err, + } + ); + } + )->wait; + return; + } + elsif ($hafas_service) { + $self->render_later; + + my $agent = $self->ua; + if ( my $proxy = $self->app->config->{hafas}{$hafas_service}{proxy} ) { + $agent = Mojo::UserAgent->new; + $agent->proxy->http($proxy); + $agent->proxy->https($proxy); } - else { - $self->render( - json => { - candidates => [@candidates], + + Travel::Status::DE::HAFAS->new_p( + promise => 'Mojo::Promise', + user_agent => $agent, + service => $hafas_service, + geoSearch => { + lat => $lat, + lon => $lon + } + )->then( + sub { + my ($hafas) = @_; + my @hafas = map { + { + name => $_->name, + eva => $_->eva, + distance => $_->distance_m / 1000, + hafas => $hafas_service + } + } $hafas->results; + if ( @hafas > 10 ) { + @hafas = @hafas[ 0 .. 9 ]; } - ); + $self->render( + json => { + candidates => [@hafas], + } + ); + } + )->catch( + sub { + my ($err) = @_; + $self->render( + json => { + candidates => [], + warning => $err, + } + ); + } + )->wait; + + return; + } + elsif ($motis_service) { + $self->render_later; + + Travel::Status::MOTIS->new_p( + promise => 'Mojo::Promise', + user_agent => $self->ua, + time_zone => 'Europe/Berlin', + + service => $motis_service, + stops_by_coordinate => { + lat => $lat, + lon => $lon + } + )->then( + sub { + my ($motis) = @_; + my @motis = map { + { + id => $_->id, + name => $_->name, + distance => 0, + motis => $motis_service, + } + } $motis->results; + + if ( @motis > 10 ) { + @motis = @motis[ 0 .. 9 ]; + } + + $self->render( + json => { + candidates => [@motis], + } + ); + } + )->catch( + sub { + my ($err) = @_; + $self->render( + json => { + candidates => [], + warning => $err, + } + ); + } + )->wait; + + return; + } + + my @iris = map { + { + ds100 => $_->[0][0], + name => $_->[0][1], + eva => $_->[0][2], + lon => $_->[0][3], + lat => $_->[0][4], + distance => $_->[1], + hafas => 0, } + } Travel::Status::DE::IRIS::Stations::get_station_by_location( $lon, + $lat, 10 ); + @iris = uniq_by { $_->{name} } @iris; + if ( @iris > 5 ) { + @iris = @iris[ 0 .. 4 ]; } + $self->render( + json => { + candidates => [@iris], + } + ); + } -sub log_action { +sub travel_action { my ($self) = @_; my $params = $self->req->json; @@ -428,67 +833,142 @@ sub log_action { if ( $params->{action} eq 'checkin' ) { - my ( $train, $error ) = $self->checkin( - station => $params->{station}, - train_id => $params->{train} - ); - my $destination = $params->{dest}; + my $status = $self->get_user_status; + my $promise; - if ($error) { - $self->render( - json => { - success => 0, - error => $error, - }, - ); - } - elsif ( not $destination ) { - $self->render( - json => { - success => 1, - redirect_to => '/', - }, - ); + if ( $status->{checked_in} + and $status->{arr_eva} + and $status->{arrival_countdown} <= 0 ) + { + $promise = $self->checkout_p( station => $status->{arr_eva} ); } else { - # Silently ignore errors -- if they are permanent, the user will see - # them when selecting the destination manually. - my ( $still_checked_in, undef ) = $self->checkout( - station => $destination, - force => 0 - ); - my $station_link = '/s/' . $destination; - $self->render( - json => { - success => 1, - redirect_to => $still_checked_in ? '/' : $station_link, - }, - ); + $promise = Mojo::Promise->resolve; } + + $self->render_later; + $promise->then( + sub { + return $self->checkin_p( + dbris => $params->{dbris}, + efa => $params->{efa}, + hafas => $params->{hafas}, + motis => $params->{motis}, + station => $params->{station}, + train_id => $params->{train}, + train_suffix => $params->{suffix}, + ts => $params->{ts}, + ); + } + )->then( + sub { + my $destination = $params->{dest}; + if ( not $destination ) { + $self->render( + json => { + success => 1, + redirect_to => '/', + }, + ); + return; + } + + # Silently ignore errors -- if they are permanent, the user will see + # them when selecting the destination manually. + return $self->checkout_p( + station => $destination, + force => 0 + ); + } + )->then( + sub { + my ( $still_checked_in, undef ) = @_; + if ( my $destination = $params->{dest} ) { + my $station_link = '/s/' . $destination; + if ( $status->{is_dbris} ) { + $station_link .= '?dbris=' . $status->{backend_name}; + } + elsif ( $status->{is_efa} ) { + $station_link .= '?efa=' . $status->{backend_name}; + } + elsif ( $status->{is_hafas} ) { + $station_link .= '?hafas=' . $status->{backend_name}; + } + $self->render( + json => { + success => 1, + redirect_to => $still_checked_in + ? '/' + : $station_link, + }, + ); + } + return; + } + )->catch( + sub { + my ($error) = @_; + $self->render( + json => { + success => 0, + error => $error, + }, + ); + } + )->wait; } elsif ( $params->{action} eq 'checkout' ) { - my ( $still_checked_in, $error ) = $self->checkout( + $self->render_later; + my $status = $self->get_user_status; + $self->checkout_p( station => $params->{station}, force => $params->{force} - ); - my $station_link = '/s/' . $params->{station}; + )->then( + sub { + my ( $still_checked_in, $error ) = @_; + my $station_link = '/s/' . $params->{station}; + if ( $status->{is_dbris} ) { + $station_link .= '?dbris=' . $status->{backend_name}; + } + elsif ( $status->{is_efa} ) { + $station_link .= '?efa=' . $status->{backend_name}; + } + elsif ( $status->{is_hafas} ) { + $station_link .= '?hafas=' . $status->{backend_name}; + } - if ($error) { - $self->render( - json => { - success => 0, - error => $error, - }, - ); - } - else { - $self->render( - json => { - success => 1, - redirect_to => $still_checked_in ? '/' : $station_link, - }, - ); - } + if ($error) { + $self->render( + json => { + success => 0, + error => $error, + }, + ); + } + else { + $self->render( + json => { + success => 1, + redirect_to => $still_checked_in + ? '/' + : $station_link, + }, + ); + } + return; + } + )->catch( + sub { + my ($error) = @_; + $self->render( + json => { + success => 0, + error => $error, + }, + ); + return; + } + )->wait; } elsif ( $params->{action} eq 'undo' ) { my $status = $self->get_user_status; @@ -504,7 +984,36 @@ sub log_action { else { my $redir = '/'; if ( $status->{checked_in} or $status->{cancelled} ) { - $redir = '/s/' . $status->{dep_ds100}; + if ( $status->{is_dbris} ) { + $redir + = '/s/' + . $status->{dep_eva} + . '?dbris=' + . $status->{backend_name}; + } + elsif ( $status->{is_efa} ) { + $redir + = '/s/' + . $status->{dep_eva} . '?efa=' + . $status->{backend_name}; + } + elsif ( $status->{is_hafas} ) { + $redir + = '/s/' + . $status->{dep_eva} + . '?hafas=' + . $status->{backend_name}; + } + elsif ( $status->{is_motis} ) { + $redir + = '/s/' + . $status->{dep_external_id} + . '?motis=' + . $status->{backend_name}; + } + else { + $redir = '/s/' . $status->{dep_ds100}; + } } $self->render( json => { @@ -515,50 +1024,74 @@ sub log_action { } } elsif ( $params->{action} eq 'cancelled_from' ) { - my ( undef, $error ) = $self->checkin( + $self->render_later; + $self->checkin_p( + dbris => $params->{dbris}, + efa => $params->{efa}, + hafas => $params->{hafas}, + motis => $params->{motis}, station => $params->{station}, - train_id => $params->{train} - ); - - if ($error) { - $self->render( - json => { - success => 0, - error => $error, - }, - ); - } - else { - $self->render( - json => { - success => 1, - redirect_to => '/', - }, - ); - } + train_id => $params->{train}, + ts => $params->{ts}, + )->then( + sub { + $self->render( + json => { + success => 1, + redirect_to => '/', + }, + ); + } + )->catch( + sub { + my ($error) = @_; + $self->render( + json => { + success => 0, + error => $error, + }, + ); + } + )->wait; } elsif ( $params->{action} eq 'cancelled_to' ) { - my ( undef, $error ) = $self->checkout( + $self->render_later; + $self->checkout_p( station => $params->{station}, force => 1 - ); - - if ($error) { - $self->render( - json => { - success => 0, - error => $error, - }, - ); - } - else { - $self->render( - json => { - success => 1, - redirect_to => '/', - }, - ); - } + )->then( + sub { + my ( undef, $error ) = @_; + if ($error) { + $self->render( + json => { + success => 0, + error => $error, + }, + ); + } + else { + $self->render( + json => { + success => 1, + redirect_to => '/', + }, + ); + } + return; + } + )->catch( + sub { + my ($error) = @_; + $self->render( + json => { + success => 0, + error => $error, + }, + ); + return; + } + )->wait; } elsif ( $params->{action} eq 'delete' ) { my $error = $self->journeys->delete( @@ -595,65 +1128,477 @@ sub log_action { } sub station { - my ($self) = @_; - my $station = $self->stash('station'); - my $train = $self->param('train'); - - my $status = $self->iris->get_departures( - station => $station, - lookbehind => 120, - lookahead => 30, - with_related => 1 + my ($self) = @_; + my $station = $self->stash('station'); + my $train = $self->param('train'); + my $trip_id = $self->param('trip_id'); + my $timestamp = $self->param('timestamp'); + my $user = $self->current_user; + my $uid = $user->{id}; + + my @timeline = $self->in_transit->get_timeline( + uid => $uid, + short => 1 ); + my %checkin_by_train; + for my $checkin (@timeline) { + push( @{ $checkin_by_train{ $checkin->{train_id} } }, $checkin ); + } + $self->stash( checkin_by_train => \%checkin_by_train ); - if ( $status->{errstr} ) { - $self->render( - 'landingpage', - version => $self->app->config->{version} // 'UNKNOWN', - with_autocomplete => 1, - with_geolocation => 1, - error => $status->{errstr} + $self->render_later; + + if ( $timestamp and $timestamp =~ m{ ^ \d+ $ }x ) { + $timestamp = DateTime->from_epoch( + epoch => $timestamp, + time_zone => 'Europe/Berlin' ); } else { - # You can't check into a train which terminates here - my @results = grep { $_->departure } @{ $status->{results} }; + $timestamp = DateTime->now( time_zone => 'Europe/Berlin' ); + } + + my ( $dbris_service, $efa_service, $hafas_service, $motis_service ); - @results = map { $_->[0] } - sort { $b->[1] <=> $a->[1] } - map { [ $_, $_->departure->epoch // $_->sched_departure->epoch ] } - @results; + if ( $self->param('dbris') ) { + $dbris_service = $self->param('dbris'); + } + elsif ( $self->param('efa') ) { + $efa_service = $self->param('efa'); + } + elsif ( $self->param('hafas') ) { + $hafas_service = $self->param('hafas'); + } + elsif ( $self->param('motis') ) { + $motis_service = $self->param('motis'); + } + else { + if ( $user->{backend_dbris} ) { + $dbris_service = $user->{backend_name}; + } + elsif ( $user->{backend_efa} ) { + $efa_service = $user->{backend_name}; + } + elsif ( $user->{backend_hafas} ) { + $hafas_service = $user->{backend_name}; + } + elsif ( $user->{backend_motis} ) { + $motis_service = $user->{backend_name}; + } + } - if ($train) { - @results - = grep { $_->type . ' ' . $_->train_no eq $train } @results; + my $promise; + if ($dbris_service) { + if ( $station !~ m{ [@] L = \d+ }x ) { + $self->render_later; + $self->dbris->get_station_id_p($station)->then( + sub { + my ($dbris_station) = @_; + $self->redirect_to( '/s/' . $dbris_station->{id} ); + } + )->catch( + sub { + my ($err) = @_; + $self->redirect_to('/'); + } + )->wait; + return; } + $promise = $self->dbris->get_departures_p( + station => $station, + timestamp => $timestamp, + lookbehind => 30, + ); + } + elsif ($efa_service) { + $promise = $self->efa->get_departures_p( + service => $efa_service, + name => $station, + timestamp => $timestamp, + lookbehind => 10, + lookahead => 50, + ); + } + elsif ($hafas_service) { + $promise = $self->hafas->get_departures_p( + service => $hafas_service, + eva => $station, + timestamp => $timestamp, + lookbehind => 30, + lookahead => 30, + ); + } + elsif ($motis_service) { + if ( $station !~ m/.*_.*/ ) { + $self->render_later; + $self->motis->get_station_by_query_p( + service => $motis_service, + query => $station, + )->then( + sub { + my ($motis_station) = @_; + $self->redirect_to( '/s/' . $motis_station->{id} ); + } + )->catch( + sub { + my ($err) = @_; + say "$err"; - $self->render( - 'departures', - eva => $status->{station_eva}, - results => \@results, - station => $status->{station_name}, - related_stations => $status->{related_stations}, - title => "travelynx: $status->{station_name}", + $self->redirect_to('/'); + } + )->wait; + return; + } + $promise = $self->motis->get_departures_p( + service => $motis_service, + station_id => $station, + timestamp => $timestamp, + lookbehind => 30, + lookahead => 30, + ); + } + else { + $promise = $self->iris->get_departures_p( + station => $station, + lookbehind => 120, + lookahead => 30, + with_related => 1, ); } - $self->users->mark_seen( uid => $self->current_user->{id} ); + $promise->then( + sub { + my ($status) = @_; + my @results; + + my $now = $self->now->epoch; + my $now_within_range + = abs( $timestamp->epoch - $now ) < 1800 ? 1 : 0; + + if ($dbris_service) { + + @results = map { $_->[0] } + sort { $b->[1] <=> $a->[1] } + map { [ $_, $_->dep->epoch ] } $status->results; + + $status = { + station_eva => $station, + related_stations => [], + }; + + if ( $station =~ m{ [@] O = (?<name> [^@]+ ) [@] }x ) { + $status->{station_name} = $+{name}; + } + } + elsif ($hafas_service) { + + @results = map { $_->[0] } + sort { $b->[1] <=> $a->[1] } + map { [ $_, $_->datetime->epoch ] } $status->results; + if ( $status->station->{eva} ) { + $self->stations->add_meta( + eva => $status->station->{eva}, + meta => $status->station->{evas} // [], + hafas => $hafas_service, + ); + } + $status = { + station_eva => $status->station->{eva}, + station_name => ( + List::Util::reduce { length($a) < length($b) ? $a : $b } + @{ $status->station->{names} } + ), + related_stations => [], + }; + } + elsif ($efa_service) { + @results = map { $_->[0] } + sort { $b->[1] <=> $a->[1] } + map { [ $_, $_->datetime->epoch ] } $status->results; + $status = { + station_eva => $status->stop->id_num, + station_name => $status->stop->full_name, + related_stations => [], + }; + } + elsif ($motis_service) { + @results = map { $_->[0] } + sort { $b->[1] <=> $a->[1] } + map { [ $_, $_->stopover->departure->epoch ] } + $status->results; + + $status = { + station_eva => $station, + station_name => + $status->{results}->[0]->stopover->stop->name, + related_stations => [], + }; + } + else { + + # You can't check into a train which terminates here + @results = grep { $_->departure } @{ $status->{results} }; + + @results = map { $_->[0] } + sort { $b->[1] <=> $a->[1] } + map { + [ $_, $_->departure->epoch // $_->sched_departure->epoch ] + } @results; + } + + my $user_status = $self->get_user_status; + + my $can_check_out = 0; + if ( $user_status->{checked_in} ) { + for my $stop ( @{ $user_status->{route_after} } ) { + if ( + $stop->[1] eq $status->{station_eva} + or List::Util::any { $stop->[1] eq $_->{uic} } + @{ $status->{related_stations} } + ) + { + $can_check_out = 1; + last; + } + } + } + + my $connections_p; + if ( $trip_id and ( $dbris_service or $hafas_service ) ) { + @results = grep { $_->id eq $trip_id } @results; + } + elsif ( $train and not $hafas_service ) { + @results + = grep { $_->type . ' ' . $_->train_no eq $train } @results; + } + else { + if ( $user_status->{cancellation} + and $status->{station_eva} eq + $user_status->{cancellation}{dep_eva} ) + { + $connections_p = $self->get_connecting_trains_p( + eva => $user_status->{cancellation}{dep_eva}, + destination_name => + $user_status->{cancellation}{arr_name}, + efa => $efa_service, + hafas => $hafas_service, + ); + } + else { + $connections_p = $self->get_connecting_trains_p( + eva => $status->{station_eva}, + efa => $efa_service, + hafas => $hafas_service + ); + } + } + + if ($connections_p) { + $connections_p->then( + sub { + my ( $connections_iris, $connections_hafas ) = @_; + $self->render( + 'departures', + user => $user, + dbris => $dbris_service, + efa => $efa_service, + hafas => $hafas_service, + motis => $motis_service, + eva => $status->{station_eva}, + datetime => $timestamp, + now_in_range => $now_within_range, + results => \@results, + station => $status->{station_name}, + related_stations => $status->{related_stations}, + user_status => $user_status, + can_check_out => $can_check_out, + connections_iris => $connections_iris, + connections_hafas => $connections_hafas, + title => "travelynx: $status->{station_name}", + ); + } + )->catch( + sub { + $self->render( + 'departures', + user => $user, + dbris => $dbris_service, + efa => $efa_service, + hafas => $hafas_service, + motis => $motis_service, + eva => $status->{station_eva}, + datetime => $timestamp, + now_in_range => $now_within_range, + results => \@results, + station => $status->{station_name}, + related_stations => $status->{related_stations}, + user_status => $user_status, + can_check_out => $can_check_out, + title => "travelynx: $status->{station_name}", + ); + } + )->wait; + } + else { + $self->render( + 'departures', + user => $user, + dbris => $dbris_service, + efa => $efa_service, + hafas => $hafas_service, + motis => $motis_service, + eva => $status->{station_eva}, + datetime => $timestamp, + now_in_range => $now_within_range, + results => \@results, + station => $status->{station_name}, + related_stations => $status->{related_stations}, + user_status => $user_status, + can_check_out => $can_check_out, + title => "travelynx: $status->{station_name}", + ); + } + } + )->catch( + sub { + my ( $err, $status ) = @_; + if ( $status and $status->{suggestions} ) { + $self->render( + 'disambiguation', + suggestions => $status->{suggestions}, + status => 300, + ); + } + elsif ( $efa_service + and $status + and scalar $status->name_candidates ) + { + $self->render( + 'disambiguation', + suggestions => [ + map { { name => $_->name, eva => $_->id_num } } + $status->name_candidates + ], + status => 300, + ); + } + elsif ( $hafas_service + and $status + and $status->errcode eq 'LOCATION' ) + { + $self->hafas->search_location_p( + service => $hafas_service, + query => $station + )->then( + sub { + my ($hafas2) = @_; + my @suggestions = $hafas2->results; + if ( @suggestions == 1 ) { + $self->redirect_to( '/s/' + . $suggestions[0]->eva + . '?hafas=' + . $hafas_service ); + } + else { + $self->render( + 'disambiguation', + suggestions => [ + map { { name => $_->name, eva => $_->eva } } + @suggestions + ], + status => 300, + ); + } + } + )->catch( + sub { + my ($err2) = @_; + $self->render( + 'exception', + exception => +"locationSearch threw '$err2' when handling '$err'", + status => 502 + ); + } + )->wait; + } + elsif ( $err + =~ m{svcRes|connection close|Service Temporarily Unavailable|Forbidden|HTTP 500 Internal Server Error} + ) + { + $self->render( + 'bad_gateway', + message => $err, + status => 502, + select_new_backend => 1, + ); + } + elsif ( $err =~ m{timeout}i ) { + $self->render( + 'gateway_timeout', + message => $err, + status => 504, + select_new_backend => 1, + ); + } + else { + $self->render( + 'exception', + exception => $err, + status => 500 + ); + } + } + )->wait; + $self->users->mark_seen( uid => $uid ); } sub redirect_to_station { my ($self) = @_; my $station = $self->param('station'); - $self->redirect_to("/s/${station}"); + if ( $self->param('backend_dbris') ) { + $self->render_later; + $self->dbris->get_station_id_p($station)->then( + sub { + my ($dbris_station) = @_; + $self->redirect_to( '/s/' . $dbris_station->{id} ); + } + )->catch( + sub { + my ($err) = @_; + $self->redirect_to('/'); + } + )->wait; + } + elsif ( $self->param('backend_motis') ) { + $self->render_later; + $self->motis->get_station_by_query( + service => $self->param('backend_motis'), + query => $station, + )->then( + sub { + my ($motis_station) = @_; + $self->redirect_to( '/s/' . $motis_station->{id} ); + } + )->catch( + sub { + my ($err) = @_; + $self->redirect_to('/'); + } + )->wait; + } + else { + $self->redirect_to("/s/${station}"); + } } sub cancelled { my ($self) = @_; my @journeys = $self->journeys->get( - uid => $self->current_user->{id}, - cancelled => 1, - with_datetime => 1 + uid => $self->current_user->{id}, + cancelled => 1, + with_datetime => 1, + with_route_datetime => 1 ); $self->respond_to( @@ -668,7 +1613,10 @@ sub cancelled { sub history { my ($self) = @_; - $self->render( template => 'history' ); + $self->render( + template => 'history', + title => 'travelynx: History' + ); } sub commute { @@ -719,10 +1667,10 @@ sub commute { $candidate_count{ $journey->{from_name} }++; } else { - # Avoid selecting an intermediate station for multi-leg commutes. - # Assumption: The intermediate station is also used for private - # travels -> penalize stations which are used on weekends or at - # unexpected times. + # Avoid selecting an intermediate station for multi-leg commutes. + # Assumption: The intermediate station is also used for private + # travels -> penalize stations which are used on weekends or at + # unexpected times. $candidate_count{ $journey->{from_name} }--; $candidate_count{ $journey->{to_name} }--; } @@ -776,6 +1724,7 @@ sub commute { journeys_by_month => \%journeys_by_month, count_by_month => \%count_by_month, total_journeys => $total, + title => 'travelynx: Reisen nach Station', months => [ qw(Januar Februar März April Mai Juni Juli August September Oktober November Dezember) ], @@ -785,20 +1734,69 @@ sub commute { sub map_history { my ($self) = @_; - my $location = $self->app->coordinates_by_station; - if ( not $self->param('route_type') ) { $self->param( route_type => 'polybee' ); } my $route_type = $self->param('route_type'); + my $filter_from = $self->param('filter_from'); + my $filter_until = $self->param('filter_to'); + my $filter_type = $self->param('filter_type'); my $with_polyline = $route_type eq 'beeline' ? 0 : 1; + my $parser = DateTime::Format::Strptime->new( + pattern => '%d.%m.%Y', + locale => 'de_DE', + time_zone => 'Europe/Berlin' + ); + + if ( $filter_from + and $filter_from =~ m{ ^ (\d+) [.] (\d+) [.] (\d+) $ }x ) + { + $filter_from = $parser->parse_datetime($filter_from); + } + else { + $filter_from = undef; + } + + if ( $filter_until + and $filter_until =~ m{ ^ (\d+) [.] (\d+) [.] (\d+) $ }x ) + { + $filter_until = $parser->parse_datetime($filter_until)->set( + hour => 23, + minute => 59, + second => 58 + ); + } + else { + $filter_until = undef; + } + + my $year; + if ( $filter_from + and $filter_from->day == 1 + and $filter_from->month == 1 + and $filter_until + and $filter_until->day == 31 + and $filter_until->month == 12 + and $filter_from->year == $filter_until->year ) + { + $year = $filter_from->year; + } + my @journeys = $self->journeys->get( uid => $self->current_user->{id}, - with_polyline => $with_polyline + with_polyline => $with_polyline, + after => $filter_from, + before => $filter_until, ); + if ($filter_type) { + my @filter = split( qr{, *}, $filter_type ); + @journeys + = grep { has_str_in_list( $_->{type}, @filter ) } @journeys; + } + if ( not @journeys ) { $self->render( template => 'history_map', @@ -820,7 +1818,9 @@ sub map_history { $self->render( template => 'history_map', + year => $year, with_map => 1, + title => 'travelynx: Karte', %{$res} ); } @@ -839,15 +1839,19 @@ sub csv_history { my $buf = q{}; $csv->combine( - qw(Zugtyp Linie Nummer Start Ziel), - 'Start (DS100)', - 'Ziel (DS100)', - 'Abfahrt (soll)', - 'Abfahrt (ist)', - 'Ankunft (soll)', - 'Ankunft (ist)', - 'Kommentar', - 'ID' + qw(type line number), + 'departure stop name', + 'departure stop id', + 'arrival stop name', + 'arrival stop id', + 'scheduled departure', + 'real-time departure', + 'scheduled arrival', + 'real-time arrival', + 'operator', + 'carriage type', + 'comment', + 'id' ); $buf .= $csv->string; @@ -864,13 +1868,17 @@ sub csv_history { $journey->{line}, $journey->{no}, $journey->{from_name}, + $journey->{from_eva}, $journey->{to_name}, - $journey->{from_ds100}, - $journey->{to_ds100}, - $journey->{sched_departure}->strftime('%Y-%m-%d %H:%M'), - $journey->{rt_departure}->strftime('%Y-%m-%d %H:%M'), - $journey->{sched_arrival}->strftime('%Y-%m-%d %H:%M'), - $journey->{rt_arrival}->strftime('%Y-%m-%d %H:%M'), + $journey->{to_eva}, + $journey->{sched_departure}->strftime('%Y-%m-%d %H:%M:%S'), + $journey->{rt_departure}->strftime('%Y-%m-%d %H:%M:%S'), + $journey->{sched_arrival}->strftime('%Y-%m-%d %H:%M:%S'), + $journey->{rt_arrival}->strftime('%Y-%m-%d %H:%M:%S'), + $journey->{user_data}{operator} // q{}, + join( q{ + }, + map { $_->{desc} // $_->{name} } + @{ $journey->{user_data}{wagongroups} // [] } ), $journey->{user_data}{comment} // q{}, $journey->{id} ) @@ -886,42 +1894,126 @@ sub csv_history { ); } -sub yearly_history { +sub year_in_review { my ($self) = @_; my $year = $self->stash('year'); my @journeys; - my $stats; # DateTime is very slow when looking far into the future due to DST changes # -> Limit time range to avoid accidental DoS. if ( not( $year =~ m{ ^ [0-9]{4} $ }x and $year > 1990 and $year < 2100 ) ) { - @journeys = $self->journeys->get( - uid => $self->current_user->{id}, - with_datetime => 1 - ); + $self->render( 'not_found', status => 404 ); + return; } - else { - my $interval_start = DateTime->new( - time_zone => 'Europe/Berlin', - year => $year, - month => 1, - day => 1, - hour => 0, - minute => 0, - second => 0, + + my $interval_start = DateTime->new( + time_zone => 'Europe/Berlin', + year => $year, + month => 1, + day => 1, + hour => 0, + minute => 0, + second => 0, + ); + my $interval_end = $interval_start->clone->add( years => 1 ); + @journeys = $self->journeys->get( + uid => $self->current_user->{id}, + after => $interval_start, + before => $interval_end, + with_datetime => 1 + ); + + if ( not @journeys ) { + $self->render( + 'not_found', + message => 'Keine Fahrten im angefragten Jahr gefunden.', + status => 404 ); - my $interval_end = $interval_start->clone->add( years => 1 ); - @journeys = $self->journeys->get( - uid => $self->current_user->{id}, - after => $interval_start, - before => $interval_end, - with_datetime => 1 + return; + } + + my $now = $self->now; + if ( + not( $year < $now->year or ( $now->month == 12 and $now->day == 31 ) ) ) + { + $self->render( + 'not_found', + message => +'Der aktuelle Jahresrückblick wird erst zum Jahresende (am 31.12.) freigeschaltet', + status => 404 ); - $stats = $self->journeys->get_stats( - uid => $self->current_user->{id}, - year => $year + return; + } + + my ( $stats, $review ) = $self->journeys->get_stats( + uid => $self->current_user->{id}, + year => $year, + review => 1 + ); + + $self->render( + 'year_in_review', + title => "travelynx: Jahresrückblick $year", + year => $year, + stats => $stats, + review => $review, + ); + +} + +sub yearly_history { + my ($self) = @_; + my $year = $self->stash('year'); + my $filter = $self->param('filter'); + my @journeys; + + # DateTime is very slow when looking far into the future due to DST changes + # -> Limit time range to avoid accidental DoS. + if ( not( $year =~ m{ ^ [0-9]{4} $ }x and $year > 1990 and $year < 2100 ) ) + { + $self->render( 'not_found', status => 404 ); + return; + } + my $interval_start = DateTime->new( + time_zone => 'Europe/Berlin', + year => $year, + month => 1, + day => 1, + hour => 0, + minute => 0, + second => 0, + ); + my $interval_end = $interval_start->clone->add( years => 1 ); + @journeys = $self->journeys->get( + uid => $self->current_user->{id}, + after => $interval_start, + before => $interval_end, + with_datetime => 1 + ); + + if ( $filter and $filter eq 'single' ) { + @journeys = $self->journeys->grep_single(@journeys); + } + + if ( not @journeys ) { + $self->render( + 'not_found', + status => 404, + message => 'Keine Fahrten im angefragten Jahr gefunden.' ); + return; + } + + my $stats = $self->journeys->get_stats( + uid => $self->current_user->{id}, + year => $year + ); + + my $with_review; + my $now = $self->now; + if ( $year < $now->year or ( $now->month == 12 and $now->day == 31 ) ) { + $with_review = 1; } $self->respond_to( @@ -932,10 +2024,12 @@ sub yearly_history { } }, any => { - template => 'history_by_year', - journeys => [@journeys], - year => $year, - statistics => $stats + template => 'history_by_year', + title => "travelynx: $year", + journeys => [@journeys], + year => $year, + have_review => $with_review, + statistics => $stats } ); @@ -946,7 +2040,6 @@ sub monthly_history { my $year = $self->stash('year'); my $month = $self->stash('month'); my @journeys; - my $stats; my @months = ( qw(Januar Februar März April Mai Juni Juli August September Oktober November Dezember) @@ -961,35 +2054,43 @@ sub monthly_history { and $month < 13 ) ) { - @journeys = $self->journeys->get( - uid => $self->current_user->{id}, - with_datetime => 1 - ); + $self->render( 'not_found', status => 404 ); + return; } - else { - my $interval_start = DateTime->new( - time_zone => 'Europe/Berlin', - year => $year, - month => $month, - day => 1, - hour => 0, - minute => 0, - second => 0, - ); - my $interval_end = $interval_start->clone->add( months => 1 ); - @journeys = $self->journeys->get( - uid => $self->current_user->{id}, - after => $interval_start, - before => $interval_end, - with_datetime => 1 - ); - $stats = $self->journeys->get_stats( - uid => $self->current_user->{id}, - year => $year, - month => $month + my $interval_start = DateTime->new( + time_zone => 'Europe/Berlin', + year => $year, + month => $month, + day => 1, + hour => 0, + minute => 0, + second => 0, + ); + my $interval_end = $interval_start->clone->add( months => 1 ); + @journeys = $self->journeys->get( + uid => $self->current_user->{id}, + after => $interval_start, + before => $interval_end, + with_datetime => 1 + ); + + if ( not @journeys ) { + $self->render( + 'not_found', + message => 'Keine Fahrten im angefragten Monat gefunden.', + status => 404 ); + return; } + my $stats = $self->journeys->get_stats( + uid => $self->current_user->{id}, + year => $year, + month => $month + ); + + my $month_name = $months[ $month - 1 ]; + $self->respond_to( json => { json => { @@ -998,12 +2099,15 @@ sub monthly_history { } }, any => { - template => 'history_by_month', - journeys => [@journeys], - year => $year, - month => $month, - month_name => $months[ $month - 1 ], - statistics => $stats + template => 'history_by_month', + title => "travelynx: $month_name $year", + journeys => [@journeys], + year => $year, + month => $month, + month_name => $month_name, + filter_from => $interval_start, + filter_to => $interval_end->clone->subtract( days => 1 ), + statistics => $stats } ); @@ -1013,7 +2117,8 @@ sub journey_details { my ($self) = @_; my $journey_id = $self->stash('id'); - my $uid = $self->current_user->{id}; + my $user = $self->current_user; + my $uid = $user->{id}; $self->param( journey_id => $journey_id ); @@ -1028,11 +2133,13 @@ sub journey_details { } my $journey = $self->journeys->get_single( - uid => $uid, - journey_id => $journey_id, - verbose => 1, - with_datetime => 1, - with_polyline => 1, + uid => $uid, + journey_id => $journey_id, + verbose => 1, + with_datetime => 1, + with_route_datetime => 1, + with_polyline => 1, + with_visibility => 1, ); if ($journey) { @@ -1040,11 +2147,53 @@ sub journey_details { journeys => [$journey], include_manual => 1, ); + my $with_share; + my $share_text; + + my $visibility + = $self->compute_effective_visibility( + $user->{default_visibility_str}, + $journey->{visibility_str} ); + + if ( $visibility eq 'public' + or $visibility eq 'travelynx' + or $visibility eq 'followers' + or $visibility eq 'unlisted' ) + { + my $delay = 'pünktlich '; + if ( $journey->{rt_arrival} != $journey->{sched_arrival} ) { + $delay = sprintf( + 'mit %+d ', + ( + $journey->{rt_arrival}->epoch + - $journey->{sched_arrival}->epoch + ) / 60 + ); + } + $with_share = 1; + $share_text + = $journey->{km_route} + ? sprintf( '%.0f km', $journey->{km_route} ) + : 'Fahrt'; + $share_text .= sprintf( ' mit %s %s – Ankunft %sum %s', + $journey->{type}, $journey->{no}, + $delay, $journey->{rt_arrival}->strftime('%H:%M') ); + } + $self->render( 'journey', - error => undef, - journey => $journey, - with_map => 1, + title => sprintf( + 'travelynx: Fahrt %s %s %s am %s', + $journey->{type}, $journey->{line} // '', + $journey->{no}, + $journey->{sched_departure}->strftime('%d.%m.%Y um %H:%M') + ), + error => undef, + journey => $journey, + journey_visibility => $visibility, + with_map => 1, + with_share => $with_share, + share_text => $share_text, %{$map_data}, ); } @@ -1059,6 +2208,94 @@ sub journey_details { } +sub visibility_form { + my ($self) = @_; + my $dep_ts = $self->param('dep_ts'); + my $journey_id = $self->param('id'); + my $action = $self->param('action') // 'none'; + my $user = $self->current_user; + my $user_level = $user->{default_visibility_str}; + my $uid = $user->{id}; + my $status = $self->get_user_status; + my $visibility = $status->{visibility_str}; + my $journey; + + if ($journey_id) { + $journey = $self->journeys->get_single( + uid => $uid, + journey_id => $journey_id, + with_datetime => 1, + with_visibility => 1, + ); + $visibility = $journey->{visibility_str}; + } + + if ( $action eq 'save' ) { + if ( $self->validation->csrf_protect->has_error('csrf_token') ) { + $self->render( + 'bad_request', + csrf => 1, + status => 400 + ); + } + elsif ( $dep_ts and $dep_ts != $status->{sched_departure}->epoch ) { + $self->render( + 'edit_visibility', + error => 'old', + user_level => $user_level, + journey => {} + ); + } + else { + if ($dep_ts) { + $self->in_transit->update_visibility( + uid => $uid, + visibility => $self->param('status_level'), + ); + $self->redirect_to('/'); + $self->run_hook( $uid, 'update' ); + } + elsif ($journey_id) { + $self->journeys->update_visibility( + uid => $uid, + id => $journey_id, + visibility => $self->param('status_level'), + ); + $self->redirect_to( '/journey/' . $journey_id ); + } + } + return; + } + + $self->param( status_level => $visibility ); + + if ($journey_id) { + $self->render( + 'edit_visibility', + error => undef, + user_level => $user_level, + journey => $journey + ); + } + elsif ( $status->{checked_in} ) { + $self->param( dep_ts => $status->{sched_departure}->epoch ); + $self->render( + 'edit_visibility', + error => undef, + user_level => $user_level, + journey => $status + ); + } + else { + $self->render( + 'edit_visibility', + error => 'notfound', + user_level => $user_level, + journey => {} + ); + } +} + sub comment_form { my ($self) = @_; my $dep_ts = $self->param('dep_ts'); @@ -1099,11 +2336,13 @@ sub comment_form { } else { $self->app->log->debug("set comment"); + my $uid = $self->current_user->{id}; $self->in_transit->update_user_data( - uid => $self->current_user->{id}, + uid => $uid, user_data => { comment => $self->param('comment') } ); $self->redirect_to('/'); + $self->run_hook( $uid, 'update' ); } } @@ -1123,10 +2362,11 @@ sub edit_journey { } my $journey = $self->journeys->get_single( - uid => $uid, - journey_id => $journey_id, - verbose => 1, - with_datetime => 1, + uid => $uid, + journey_id => $journey_id, + verbose => 1, + with_datetime => 1, + with_route_datetime => 1, ); if ( not $journey ) { @@ -1227,11 +2467,12 @@ sub edit_journey { if ( not $error ) { $journey = $self->journeys->get_single( - uid => $uid, - db => $db, - journey_id => $journey_id, - verbose => 1, - with_datetime => 1, + uid => $uid, + db => $db, + journey_id => $journey_id, + verbose => 1, + with_datetime => 1, + with_route_datetime => 1, ); $error = $self->journeys->sanity_check($journey); } @@ -1273,6 +2514,8 @@ sub edit_journey { sub add_journey_form { my ($self) = @_; + $self->stash( backend_id => $self->current_user->{backend_id} ); + if ( $self->param('action') and $self->param('action') eq 'save' ) { my $parser = DateTime::Format::Strptime->new( pattern => '%d.%m.%Y %H:%M', @@ -1293,8 +2536,9 @@ sub add_journey_form { $self->render( 'add_journey', with_autocomplete => 1, - error => -'Zug muss als „Typ Nummer“ oder „Typ Linie Nummer“ eingegeben werden.' + status => 400, + error => +'Fahrt muss als „Typ Nummer“ oder „Typ Linie Nummer“ eingegeben werden.' ); return; } @@ -1307,6 +2551,7 @@ sub add_journey_form { $self->render( 'add_journey', with_autocomplete => 1, + status => 400, error => "${key}: Ungültiges Datums-/Zeitformat" ); return; @@ -1329,8 +2574,9 @@ sub add_journey_form { my $db = $self->pg->db; my $tx = $db->begin; - $opt{db} = $db; - $opt{uid} = $self->current_user->{id}; + $opt{db} = $db; + $opt{uid} = $self->current_user->{id}; + $opt{backend_id} = $self->current_user->{backend_id}; my ( $journey_id, $error ) = $self->journeys->add(%opt); @@ -1348,6 +2594,7 @@ sub add_journey_form { $self->render( 'add_journey', with_autocomplete => 1, + status => 400, error => $error, ); } @@ -1365,4 +2612,241 @@ sub add_journey_form { } } +sub add_intransit_form { + my ($self) = @_; + + $self->stash( backend_id => $self->current_user->{backend_id} ); + + if ( $self->param('action') and $self->param('action') eq 'save' ) { + my $parser = DateTime::Format::Strptime->new( + pattern => '%d.%m.%Y %H:%M', + locale => 'de_DE', + time_zone => 'Europe/Berlin' + ); + my %opt; + my %trip; + + my @parts = split( qr{\s+}, $self->param('train') ); + + if ( @parts == 2 ) { + @trip{ 'train_type', 'train_no' } = @parts; + } + elsif ( @parts == 3 ) { + @trip{ 'train_type', 'train_line', 'train_no' } = @parts; + } + else { + $self->render( + 'add_intransit', + with_autocomplete => 1, + status => 400, + error => +'Fahrt muss als „Typ Nummer“ oder „Typ Linie Nummer“ eingegeben werden.' + ); + return; + } + + for my $key (qw(sched_departure sched_arrival)) { + if ( $self->param($key) ) { + my $datetime = $parser->parse_datetime( $self->param($key) ); + if ( not $datetime ) { + $self->render( + 'add_intransit', + with_autocomplete => 1, + status => 400, + error => "${key}: Ungültiges Datums-/Zeitformat" + ); + return; + } + $trip{$key} = $datetime; + } + } + + for my $key (qw(dep_station arr_station route comment)) { + $trip{$key} = $self->param($key); + } + + $opt{backend_id} = $self->current_user->{backend_id}; + + my $dep_stop = $self->stations->search( $trip{dep_station}, + backend_id => $opt{backend_id} ); + my $arr_stop = $self->stations->search( $trip{arr_station}, + backend_id => $opt{backend_id} ); + + if ( defined $trip{route} ) { + $trip{route} = [ split( qr{\r?\n\r?}, $trip{route} ) ]; + } + + my $route_has_start = 0; + my $route_has_stop = 0; + + for my $station ( @{ $trip{route} || [] } ) { + if ( $station eq $dep_stop->{name} + or $station eq $dep_stop->{eva} ) + { + $route_has_start = 1; + } + if ( $station eq $arr_stop->{name} + or $station eq $arr_stop->{eva} ) + { + $route_has_stop = 1; + } + } + + my @route; + + if ( not $route_has_start ) { + push( + @route, + [ + $dep_stop->{name}, + $dep_stop->{eva}, + { + lat => $dep_stop->{lat}, + lon => $dep_stop->{lon}, + } + ] + ); + } + + if ( $trip{route} ) { + my @unknown_stations; + my $prev_epoch; + for my $station ( @{ $trip{route} } ) { + my $ts; + my %station_data; + if ( $station + =~ m{ ^ (?<stop> [^@]+? ) \s* [@] \s* (?<timestamp> .+ ) $ }x + ) + { + $station = $+{stop}; + $ts = $parser->parse_datetime( $+{timestamp} ); + if ( $ts and $ts->epoch > $prev_epoch ) { + $station_data{sched_arr} = $ts->epoch; + $station_data{sched_dep} = $ts->epoch; + $prev_epoch = $ts->epoch; + } + else { + $self->render( + 'add_intransit', + with_autocomplete => 1, + status => 400, + error => "Ungültige Zeitangabe: $+{timestamp}" + ); + return; + } + } + my $station_info = $self->stations->search( $station, + backend_id => $opt{backend_id} ); + if ($station_info) { + $station_data{lat} = $station_info->{lat}; + $station_data{lon} = $station_info->{lon}; + push( + @route, + [ + $station_info->{name}, $station_info->{eva}, + \%station_data, + ] + ); + } + else { + push( @route, [ $station, undef, {} ] ); + push( @unknown_stations, $station ); + } + } + + if ( @unknown_stations == 1 ) { + $self->render( + 'add_intransit', + with_autocomplete => 1, + status => 400, + error => "Unbekannter Unterwegshalt: $unknown_stations[0]" + ); + return; + } + elsif (@unknown_stations) { + $self->render( + 'add_intransit', + with_autocomplete => 1, + status => 400, + error => 'Unbekannte Unterwegshalte: ' + . join( ', ', @unknown_stations ) + ); + return; + } + } + + if ( not $route_has_stop ) { + push( + @route, + [ + $arr_stop->{name}, + $arr_stop->{eva}, + { + lat => $arr_stop->{lat}, + lon => $arr_stop->{lon}, + } + ] + ); + } + + for my $station (@route) { + if ( $station->[0] eq $dep_stop->{name} + or $station->[1] eq $dep_stop->{eva} ) + { + $station->[2]{sched_dep} = $trip{sched_departure}->epoch; + } + if ( $station->[0] eq $arr_stop->{name} + or $station->[1] eq $arr_stop->{eva} ) + { + $station->[2]{sched_arr} = $trip{sched_arrival}->epoch; + } + } + + my $error; + my $db = $self->pg->db; + my $tx = $db->begin; + + $trip{dep_id} = $dep_stop->{eva}; + $trip{arr_id} = $arr_stop->{eva}; + $trip{route} = \@route; + + $opt{db} = $db; + $opt{manual} = \%trip; + $opt{uid} = $self->current_user->{id}; + + if ( not defined $trip{dep_id} ) { + $error = "Unknown departure stop '$trip{dep_station}'"; + } + elsif ( not defined $trip{arr_id} ) { + $error = "Unknown arrival stop '$trip{arr_station}'"; + } + elsif ( $trip{sched_arrival} <= $trip{sched_departure} ) { + $error = 'Ankunftszeit muss nach Abfahrtszeit liegen'; + } + else { + $error = $self->in_transit->add(%opt); + } + + if ($error) { + $self->render( + 'add_intransit', + with_autocomplete => 1, + status => 400, + error => $error, + ); + } + else { + $tx->commit; + $self->redirect_to('/'); + } + } + else { + $self->render( + 'add_intransit', + with_autocomplete => 1, + error => undef + ); + } +} + 1; |