]> git.sesse.net Git - remoteglot/blob - www/analysis.pl
Slight cleanup in analysis.pl.
[remoteglot] / www / analysis.pl
1 #! /usr/bin/perl
2 use CGI;
3 use POSIX;
4 use Date::Manip;
5 use Linux::Inotify2;
6 use AnyEvent;
7 use strict;
8 use warnings;
9
10 my $json_filename = "/srv/analysis.sesse.net/www/analysis.json";
11
12 my $cv = AnyEvent->condvar;
13 my $updated = 0;
14 my $cgi = CGI->new;
15 my $inotify = Linux::Inotify2->new;
16 $inotify->watch($json_filename, IN_MODIFY, sub {
17         $updated = 1;
18         $cv->send;
19 });
20         
21 my $inotify_w = AnyEvent->io (
22         fh => $inotify->fileno, poll => 'r', cb => sub { $inotify->poll }
23 );
24 my $wait = AnyEvent->timer (
25         after => 30,
26         cb    => sub { $cv->send; },
27 );
28
29 my $ims = 0;
30 if (exists($ENV{'HTTP_IF_MODIFIED_SINCE'})) {
31         my $date = Date::Manip::Date->new;
32         $date->parse($ENV{'HTTP_IF_MODIFIED_SINCE'});
33         $ims = $date->printf("%s");
34 }
35 my $time = (stat($json_filename))[9];
36
37 # If we have something that's modified since IMS, send it out at once
38 if ($time > $ims) {
39         output();
40         exit;
41 }
42
43 # If not, wait, then send. Apache will deal with the 304-ing.
44 if (defined($cgi->param('first')) && $cgi->param('first') != 1) {
45         $cv->recv;
46 }
47 output();
48
49 sub output {
50         my $time = (stat($json_filename))[9];
51         my $lm_str = POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
52
53         print CGI->header(-type=>'text/json',
54                           -last_modified=>$lm_str,
55                           -access_control_allow_origin=>'http://analysis.sesse.net',
56                           -expires=>'now');
57         open my $fh, "<", $json_filename
58                 or die "$json_filename: $!";
59         my $data;
60         {
61                 local $/ = undef;
62                 $data = <$fh>;
63         }
64         print $data;
65 }