#!/usr/bin/perl -w
#
# artspicturehouserss:
# This is a ghastly train wreck of a screen scraper, because the Arts Cinema's
# pages are shite. It's all stateful.
#
# TODO: Get film descriptions from the pages linked from what's on, or perhaps
# from IMDB, if it has a public interface. Also generate more useful links.
#
# Copyright (c) 2004 Chris Lightfoot. All rights reserved.
# Email: chris@ex-parrot.com; WWW: http://www.ex-parrot.com/~chris/
#

my $rcsid = '$Id: artspicturehouserss,v 1.3 2004/03/08 14:52:48 chris Exp chris $';

use strict;

use POSIX;
use WWW::Mechanize;
use XML::RSS;

my %films;

my @months = qw(january february march april may june july august september october november december);
my %monthmap = map { $months[$_] => $_ } (0 .. 11);
my $monthre = join('|', @months);

# timestamp TIME
# Return the ISO timestamp representation of TIME.
sub timestamp ($) {
    my ($t) = @_;
    my @l = localtime($t);
    my @g = gmtime($t);

    return sprintf('%04d-%02d-%02dT%02d:%02d+%02d:00',
                $l[5] + 1900,
                $l[4] + 1,
                $l[3],
                $l[2],
                $l[1],
                $l[2] - $g[2]);
}

# timestring TIME
# Return a time string from TIME.
sub timestring ($) {
    my ($t) = @_;
    my @l = localtime($t);
    my @ln = localtime(time());
    return sprintf('%02d:%02d%s', $l[2], $l[1], ($l[7] == $ln[7] ? '' : ' tomorrow'));
}

# get_film_times CONTENT
# Extract available film times from the content.
sub get_film_times ($) {
    my ($content) = @_;
    # Get rid of all sorts of appalling cruft.
    $content =~ s#</?(?:font|b|i)[^>]*># #sgi;

    $content =~ s#<td[^>]+>#<td>#gsi;
    $content =~ s#<tr[^>]+>#<tr>#gsi;
   
    my ($film, $screen, $cert)
        = ($content =~
            m#
                <tr>
                    \s*<td>\s*Film\s*</td>.+?
                </tr>\s*
                <tr>
                    \s*<td>\s*([^<]+?)\s*</td>
                    \s*<td>\s*([^<]+?)\s*</td>
                    \s*<td>\s*([^<]+?)\s*</td>
                \s*</tr>
            #xsi) or return undef;

    $films{$film} = [$screen, $cert, []];

    while ($content =~ m#
                    \s*<tr>
                        \s*<td>.+?($monthre)\s+(\d+),\s+(\d+)\s*</td>
                        \s*(.+?)
                    \s*</(?:tr|table)>
                #xsig) {
        my ($year, $month, $day) = ($3 - 1900, $monthmap{lc($1)}, $2);
        my $date = sprintf('%04d-%02d-%02d', $3, $monthmap{lc($1)} + 1, $2);
        my $x = $4;

        my @times = ($x =~ m#
                    <a\s+href=[^>]+>(\d\d:\d\d)[^<]*</a>
                #xsig);

        # Save showing times as UNIX times.
        foreach (@times) {
            my ($H, $M) = m#(\d+):(\d+)#;
            push(@{$films{$film}->[2]}, mktime(0, $M, $H, $day, $month, $year, 0, 0, 0));
        }
    }

    delete($films{$film}) unless (@{$films{$film}->[2]} > 0);
}

my $mech = new WWW::Mechanize();

$mech->agent_alias('Windows IE 6');
$mech->get('http://www.picturehouses.co.uk/site/cinemas/Cambridge/whats-on.htm')
    or die "couldn't get `what's on' link";
$mech->follow_link(text_regex => qr#book\s+online#i)
    or die "couldn't reach `book online' link";
$mech->get('http://www.picturehouses.co.uk/booking/booking_v2/films.asp')
    or die "couldn't get films link";

for (my $n = 1; ; ++$n) {
    $mech->follow_link(
        url_regex => qr#shows\.asp\?fid=#,
        n => $n) or last;

#    print $mech->uri(), "\n";

    get_film_times($mech->content());

    $mech->get('http://www.picturehouses.co.uk/booking/booking_v2/films.asp')
        or die "couldn't get films link";
}

my $rss = new XML::RSS(version => '1.0', encoding => 'iso-8859-1');

$rss->channel(
        title   => 'Arts Picture House, Cambridge',
        link    => 'http://www.picturehouses.co.uk/site/cinemas/Cambridge/whats-on.htm',
        description => "What's on at the Arts today."
    );

# For each film, we find the earliest performance which is in the future.
my $now = time();
my $horizon = $now + 24 * 3600;
foreach my $film (sort { $films{$b}->[2]->[0] <=> $films{$a}->[2]->[0] } keys %films) {
    if (my @times = grep { $_ > $now && $_ <= $horizon } @{$films{$film}->[2]}) {
        my $blurb = "Showing at " . timestring($times[0]);
        if (@times > 1) {
            $blurb .= '; also ' . join(", ", map { timestring($_) } @times[1 .. $#times]);
        }
        $blurb .= '.';
        $rss->add_item(
            title => $film,
            link => "http://www.imdb.com/find?q=$film",
            description => $blurb,
            dc => {
                date => timestamp($times[0])
            }
        );
    }
}

print $rss->as_string();

exit 0;
