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