logbot-redirect 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/perl
  2. use local::lib;
  3. use v5.10;
  4. use strict;
  5. use warnings;
  6. use FindBin qw( $RealBin );
  7. use lib "$RealBin/lib";
  8. BEGIN { $ENV{TZ} = 'UTC' }
  9. use LogBot::Config qw( find_config load_config );
  10. use LogBot::Util qw( file_time );
  11. use LogBot::Web::Util qw( rewrite_old_urls );
  12. use Mojo::URL ();
  13. use Mojolicious::Lite qw( app );
  14. # build default url
  15. my $default_network = $ENV{LOGBOT_DEFAULT_NETWORK} // die 'LOGBOT_DEFAULT_NETWORK not set';
  16. my $default_config = load_config(find_config($default_network), web => 1);
  17. my $default_url = Mojo::URL->new($default_config->{url});
  18. sub redirect {
  19. my ($c) = @_;
  20. $c->stash(config => $default_config);
  21. my $redirect_url = rewrite_old_urls($c);
  22. # redirect old server-side url
  23. if (defined($c->req->query_params->param('cid'))) {
  24. say "redirecting old url to $redirect_url" if $ENV{DEBUG};
  25. return $c->redirect_to($redirect_url);
  26. }
  27. # redirect old urls
  28. if ($redirect_url) {
  29. say "redirecting old url to $redirect_url" if $ENV{DEBUG};
  30. $c->stash(redirect_to => $redirect_url);
  31. return $c->render('redirect');
  32. }
  33. # redirect to default network
  34. my $req_url = $c->req->url;
  35. my $url = $default_url->clone();
  36. $url->path($req_url->path);
  37. $url->query($req_url->query);
  38. say "redirecting to $url" if $ENV{DEBUG};
  39. $c->redirect_to($url);
  40. }
  41. # static file with timestamp
  42. my %cache;
  43. helper static => sub {
  44. my ($self, $file) = @_;
  45. return $cache{static}->{$file} //= '/static/' . $file . '?' . file_time($RealBin . '/web/public/static/' . $file);
  46. };
  47. # configure mojo
  48. app->secrets('!logbot!');
  49. app->renderer->paths([$RealBin . '/web/templates']);
  50. app->static->paths([$RealBin . '/web/public']);
  51. app->config(
  52. hypnotoad => {
  53. listen => ['http://127.0.0.1:' . ($ENV{LOGBOT_PORT} // 3001)],
  54. pid_file => ($ENV{LOGBOT_PID_FILE} // $RealBin . '/logbot-web.pid'),
  55. workers => 2,
  56. },
  57. );
  58. get '/' => \&redirect;
  59. get '/*' => \&redirect;
  60. app->start;