summaryrefslogtreecommitdiffstats
path: root/lib/Crawl/Bot.pm
blob: e6a5e15ffed85ca929046241e4aea0a46da2924a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package Crawl::Bot;
use Moose;
use MooseX::NonMoose;
extends 'Bot::BasicBot';

use autodie;
use XML::RAI;

has rss_feed => (
    is      => 'ro',
    isa     => 'Str',
    lazy    => 1,
    default => 'http://crawl.develz.org/mantis/issues_rss.php',
);

has cache_file => (
    is      => 'ro',
    isa     => 'Str',
    lazy    => 1,
    default => 'cache',
);

has items => (
    traits  => ['Hash'],
    isa     => 'HashRef',
    default => sub {
        my $self = shift;
        my $file = $self->cache_file;
        my $items = {};
        if (-r $file) {
            warn "Updating seen item list from the cache...";
            open my $fh, '<', $file;
            while (<$fh>) {
                chomp;
                $items->{$_} = 1;
                warn "  got item $_";
            }
        }
        else {
            warn "Updating seen item list from a fresh copy of the feed...";
            $self->each_item(sub {
                my $item = shift;
                my $link = $item->identifier;
                (my $id = $link) =~ s/.*=(\d+)$/$1/;
                $items->{$id} = 1;
                warn "  got item $id";
            });
        }
        return $items;
    },
    handles => {
        has_item  => 'exists',
        items     => 'keys',
        _add_item => 'set',
    },
);

sub add_item {
    my $self = shift;
    $self->_add_item($_[0], 1);
}

sub BUILD {
    my $self = shift;
    $self->save_cache;
}

sub each_item {
    my $self = shift;
    my ($code) = @_;
    my $rss = XML::RAI->parse_uri($self->rss_feed);
    for my $item (@{ $rss->items }) {
        $code->($item);
    }
}

sub save_cache {
    my $self = shift;
    warn "Saving cache state to " . $self->cache_file;
    open my $fh, '>', $self->cache_file;
    $fh->print("$_\n") for $self->items;
}

sub tick {
    my $self = shift;
    warn "Checking for new issues...";
    $self->each_item(sub {
        my $item = shift;
        my $link = $item->identifier;
        (my $id = $link) =~ s/.*=(\d+)$/$1/;
        return if $self->has_item($id);
        warn "New issue! ($id)";
        $self->say(
            channel => '##crawl-dev',
            body    => $item->title . ' (' . $item->link . ')'
        );
        $self->add_item($id);
    });
    $self->save_cache;

    return 60;
}

1;