server.psgi 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. use strict;
  2. use warnings;
  3. no warnings 'experimental';
  4. use feature qw{signatures};
  5. use Date::Format qw{strftime};
  6. use URL::Encode ();
  7. use Text::Xslate ();
  8. use Plack::MIME ();
  9. use Mojo::File ();
  10. use DateTime::Format::HTTP();
  11. use Encode qw{encode_utf8};
  12. #Grab our custom routes
  13. use lib 'lib';
  14. use Trog::Routes::HTML;
  15. use Trog::Routes::JSON;
  16. # Troglodyne philosophy - simple as possible
  17. # Import the routes
  18. my %routes = %Trog::Routes::HTML::routes;
  19. @routes{keys(%Trog::Routes::JSON::routes)} = values(%Trog::Routes::JSON::routes);
  20. # Things we will actually produce from routes rather than just serving up files
  21. my $ct = 'Content-type';
  22. my %content_types = (
  23. plain => "$ct:text/plain;",
  24. html => "$ct:text/html; charset=UTF-8",
  25. json => "$ct:application/json;",
  26. blob => "$ct:application/octet-stream;",
  27. );
  28. my $cd = 'Content-disposition';
  29. my %content_dispositions = (
  30. attachment => 'attachment; filename=',
  31. inline => 'inline; filename=',
  32. );
  33. my $cc = 'Cache-control';
  34. my %cache_control = (
  35. revalidate => "$cc: no-cache, max-age=0;",
  36. nocache => "$cc: no-store;",
  37. static => "$cc: public, max-age=604800, immutable",
  38. );
  39. my $app = sub {
  40. my $env = shift;
  41. my $last_fetch = 0;
  42. if ($env->{HTTP_IF_MODIFIED_SINCE}) {
  43. $last_fetch = DateTime::Format::HTTP->parse_datetime($env->{HTTP_IF_MODIFIED_SINCE})->epoch();
  44. }
  45. my $query = {};
  46. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  47. my $path = $env->{PATH_INFO};
  48. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  49. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  50. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  51. }
  52. # If it's just a file, serve it up
  53. return _serve("www/$path", $last_fetch) if -f "www/$path";
  54. #TODO reject inappropriate content-lengths
  55. return [ 404, [$content_types{plain}], ["RETURN TO SENDER"]] unless exists $routes{$path};
  56. return [ 400, [$content_types{plain}], ["BAD REQUEST"]] unless $routes{$path}{method} eq $env->{REQUEST_METHOD};
  57. #TODO fish out what user is in cookie
  58. $query->{user} = 'Nobody';
  59. my $output = $routes{$path}{callback}->($query,$env->{input}, \&_render);
  60. return $output;
  61. };
  62. sub _serve ($path, $last_fetch=0) {
  63. my $mf = Mojo::File->new($path);
  64. my $ext = '.'.$mf->extname();
  65. my $ft;
  66. $ft = Plack::MIME->mime_type($ext) if $ext;
  67. $ft = "$ct:$ft;" if $ft;
  68. $ft ||= $content_types{plain};
  69. my @headers = ($ft);
  70. #TODO figure out content-disposition
  71. #TODO use static Cache-Control for everything but JS/CSS?
  72. push(@headers,$cache_control{revalidate});
  73. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  74. my $mt = (stat($path))[9];
  75. my @gm = gmtime($mt);
  76. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  77. my $code = $mt > $last_fetch ? 200 : 304;
  78. push(@headers, "Last-Modified: $now_string\n");
  79. my $h = join("\n",@headers);
  80. if (open(my $fh, '<', $path)) {
  81. return [ $code, [$h], $fh];
  82. }
  83. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  84. }
  85. sub _render ($template, $vars) {
  86. my $processor = Text::Xslate->new(
  87. path => 'www/templates',
  88. header => ['header.tx'],
  89. footer => ['footer.tx'],
  90. );
  91. #XXX default vars that need to be pulled from config
  92. $vars->{dir} //= 'ltr';
  93. $vars->{lang} //= 'en-US';
  94. $vars->{title} //= 'tCMS';
  95. #XXX Need to have minification detection and so forth, use LESS
  96. $vars->{stylesheets} //= [];
  97. #XXX Need to have minification detection, use Typescript
  98. $vars->{scripts} //= [];
  99. $vars->{contenttype} //= $content_types{html};
  100. $vars->{cachecontrol} //= $cache_control{revalidate};
  101. my @headers = ($vars->{contenttype});
  102. push(@headers,$vars->{contentdisposition}) if $vars->{contentdisposition};
  103. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  104. my $h = join("\n",@headers);
  105. my $body = $processor->render($template,$vars);
  106. return [200, [$h], [encode_utf8($body)]];
  107. }