The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl -w

use XML::Simple qw/XMLout XMLin/;
use Getopt::Long;
use Digest::MD5 qw/md5_hex/;
use POSIX qw/strftime/;
use LWP::UserAgent;
use Date::Manip;
use strict;

my %opt = (
  prefix => $ENV{RSSDROP_PREFIX} || "$ENV{HOME}/.rssdrop",
  fetch => 1,
);

my @getopt =
  qw/prefix=s
     mailfolder=s
     add
     delete
     fetch!
     umask=s
     verbose
     help/;

GetOptions(\%opt, @getopt) or do { print STDERR usage(); exit 1; };
do { print usage(); exit 0; } if $opt{help};

if (!-e "$opt{prefix}/config") {
  print STDERR "entering one-time setup...\n";
  setup();
}

my $config = read_config("$opt{prefix}/config");
my $mdu = mdu_init();
my $ua = LWP::UserAgent->new;
my $tempdir_xxx = sprintf '%s/tmp.%s.XXXXXX'
  => $opt{prefix}, strftime('%F', localtime);
my $tempdir = tempdir($tempdir_xxx);

$config->{mailfolder} = $opt{mailfolder} if $opt{mailfolder};

umask($opt{umask} ? oct($opt{umask}) : 0077);

if ($opt{add}) {
  while (my ($feedname, $feedurl) = splice @ARGV, 0, 2) {
    my $format = eval { taste_feed($feedurl) };

    if ($@) {
      warn "error fetching or parsing feed, not adding: $@\n";
      next;
    }
    elsif (!$format) {
      warn "unknown feed format, not adding\n";
      next;
    }

    $config->{feeds}->{$feedname}->{url} = $feedurl;
  }
  safe_write_config($config);
}
elsif ($opt{delete}) {
  while (my $feedname = shift @ARGV) {
    die "error deleting $feedname, not found"
      unless delete $config->{feeds}->{$feedname};
  }
  safe_write_config($config);
}
else {
  my @feednames = @ARGV ? @ARGV : sort keys %{$config->{feeds}};

  for my $feedname (@feednames) {
    my $feed = eval { load_feed($feedname, fetch => $opt{fetch}) };
    
    if ($@) {
      print "feed error ($feedname): $@";
      next;
    }

    # process items in the feed: fetch fulltext and deliver

    for my $item (@{ $feed->items }) {
      eval { drop_item($feed, $item); };
      warn "$@" if $@;
    }
  }
}

$tempdir and -d $tempdir and rmdir $tempdir or
  die "error removing temporary directory $tempdir: $!";

exit 0;


sub usage {
  my $usage = qq{
  rssdrop feed1 feed2 ...    # fetch new feed entries
  rssdrop -a feedname url    # subscribe to a new feed
  rssdrop -d feedname        # unsubscribe

    --add                      feed1 url1 feed2 url2 ...
    --delete                   feed1 feed2 ...
    --nofetch                  don't fetch feeds or fulltext
    --umask NUM                specify octal umask for new files [077]
    --prefix DIR               path/to/rssdrop/dir
    --mailfolder DIR           path/to/maildir/folder/area
    --verbose
    --help
  };

  $usage =~ s/\n  /\n/g;
  $usage =~ s/^\n//;
  return $usage;
}

sub setup {
  die "no mailfolder specified (--mailfolder=xyz)" unless $opt{mailfolder};
  ensure_dir($opt{prefix});
  ensure_dir("$opt{prefix}/tmp");
  safe_write_config({ mailfolder => $opt{mailfolder} });
}

sub taste_feed {
  my $url = shift;

  verbose("tasting feed at $url");

  my $response = $ua->get($url);

  die "error fetching feed" unless $response;
  die "error fetching feed: ".$response->message unless
    $response->is_success;

  my $index = eval { XMLin($response->content) };

  die "error, invalid feed xml at $url: $@" if $@;
  die "empty feed xml at $url" unless $index;

  return Feed->new({ index => $index })->format;
}

sub load_feed {
  my $feedname = shift;
  my %arg = @_;
  my $feed = $config->{feeds}->{$feedname} or
    die "error: no such feed $feedname";

  $feed->{name} = $feedname;
  $feed->{folder} ||= $feedname;
  $feed->{dir} = "$opt{prefix}/feeds/$feed->{folder}";
  $feed->{maildir} = "$config->{mailfolder}/$feed->{folder}";

  init_feeddir($feed->{dir});
  init_maildir($feed->{maildir});

  $feed->{feedfile} = "$feed->{dir}/rss/index.xml";
  fetch_feed($feed) if $arg{fetch};

  my $xml = slurp_file($feed->{feedfile});
  $xml =~ s/[^[:print:]]//;

  my %xmlin_opts = (
    ForceArray => [ qw/item entry/ ],
    KeyAttr => []
  );

  $feed->{index} = XMLin($xml, %xmlin_opts) or
    die "error reading rss file $feed->{feedfile}";

  $feed = Feed->new($feed);

  return $feed;
}

sub fetch_feed {  
  my $feed = shift;

  verbose("fetching feed $feed->{url}");
  fetch_atomic($ua, $feed->{url}, $feed->{feedfile}, "$tempdir/index.xml");
}


# TODO deliver fulltext and rss as separate multipart mime attachments
# TODO add options for text/plain renderers

sub drop_item {
  my $feed = shift;
  my $item = shift;

  my $link = $item->link;
  my $md5 = md5_hex($link);
  my $fetchfile = "$feed->{dir}/fetched/$md5";
  my $deliverfile = "$feed->{dir}/delivered/$md5";

  if (-e $deliverfile) {
    verbose("already delivered item $link");
    return;
  }

  my $content;

  if (!-e $fetchfile) {
    if ($feed->{fulltext} && $opt{fetch}) {
      verbose("fetching item $link");

      # optionally turn on cookies for the duration of this page fetch

      if ($feed->{cookies}) {
        $ua->cookie_jar({ file => "$tempdir/cookies.txt" });
      }

      fetch_atomic($ua, $link, $fetchfile, "$tempdir/$md5");

      if ($feed->{cookies}) {
        $ua->cookie_jar(undef);
        !-e "$tempdir/cookies.txt" or unlink "$tempdir/cookies.txt" or 
          die "error removing cookie file: $!";
      }
    }
    else {
      $content = $item->content;
      safe_cat($content, $fetchfile, "$tempdir/$md5");
    }
  }

  $content ||= slurp_file($fetchfile);

  my $mime;

  $mime ||= 'text/html' if looks_like_html($content);
  $mime ||= mime($fetchfile) if $feed->{fulltext};
  $mime ||= 'text/plain';

  my $time;

  $time ||= parse_time($item->pub_time);
  $time ||= parse_time($feed->pub_time);
  $time ||= time;

  my $from;

  $from ||= $item->author;
  $from ||= $feed->author;
  $from ||= scrape_email($content);  # this is getting pretty desperate
  $from ||= 'rssdrop@localhost';

  # deliver the item as mail

  my $unique = mdu_generate($mdu);
  my ($tmp, $new) = map "$feed->{maildir}/$_/$unique" => qw/tmp new/;

  open my $fh, '>', $tmp or
    die "error opening $tmp for write: $!";

  binmode $fh, ':utf8';

  print  $fh "Content-Type: $mime\n";
  print  $fh "Content-Disposition: inline\n";
  printf $fh 'Date: %s'."\n",
    strftime('%a, %e %b %Y %H:%M:%S %z', localtime $time);
  printf $fh 'From: %s'."\n", $from;
  printf $fh 'Subject: %s'."\n", $item->title;
  print  $fh "\n";
  print  $fh $content;

  close $fh or
    die "error closing $tmp after write: $!";

  link $tmp => $new or
    die "error hardlinking $tmp to $new: $!";
  unlink $tmp or
    die "error removing temporary file $tmp: $!";

  rename $fetchfile => $deliverfile or
    die "error renaming $fetchfile => $deliverfile";
}

sub scrape_email {
  for (grep $_ => @_) {
    return $1 if /(\S+\@\S+\.\S+)/;
  }
}

sub parse_time {
  my $time = shift or return undef;
  my $date = ParseDate($time) or return undef;
  return UnixDate($date, '%s');
}

sub fetch_atomic {
  my ($ua, $url, $file, $tempfile) = @_;
  my $response = $ua->get($url, ':content_file' => $tempfile);
 
  die "error fetching $url" unless $response;
  die "error fetching $url: ".$response->message if $response->is_error;

  rename $tempfile => $file or
    die "error moving $tempfile to $file: $!";
}

sub init_maildir {
  my $dir = shift;
  ensure_dir("$dir/$_") for qw/cur new tmp/;
}

sub init_feeddir {
  my $dir = shift;
  ensure_dir("$dir/$_") for qw/rss fetched delivered tmp/;
}

sub mdu_init {
  my $host = `hostname`;
  die "error executing hostname: ".($? >> 1) if $?;
  chomp $host;
  return { host => $host, delivered => 0 };
}

sub mdu_generate {
  my $mdu = shift;
  return sprintf '%d.%d_%d.%s', +time, $$, $mdu->{delivered}++, $mdu->{host};
}

sub read_config {
  my $file = shift;
  my $section;
  my %config = ( feeds => {} );

  open my $fh, '<', $file or
    die "error opening $file for read: $!";

  while (<$fh>) {
    chomp;
    s/^\s+//;
    s/\s+$//;
    next unless $_;
    next if /^#/;

    if (/^\[(.+)\]/) {
      # enter a new section
      $section = $1;
      $config{feeds}->{$section} = {};
    }
    elsif (/^(\S+)\s*=\s*(\S+)$/) {
      # augment a section, or global config
      $section ?
        $config{feeds}->{$section}->{$1} = $2 :
        $config{$1} = $2;
    }
    else {
      die "config syntax error ($.): $_";
    }
  }

  close $fh or
    die "error closing $file after read: $!";

  return \%config;
}

sub serialise_config {
  my $config = shift;
  my $str = '';

  # global config

  for (grep $_ ne 'feeds' => keys %$config) {
    $str .= "$_ = $config->{$_}\n";
  }

  $str .= "\n";

  # per-feed config

  for my $feedname (sort keys %{$config->{feeds}}) {
    my $feed = $config->{feeds}->{$feedname};
    $str .= "[$feedname]\n";
    $str .= "$_ = $feed->{$_}\n" for keys %$feed;
    $str .= "\n";
  }

  return $str;
}

sub safe_write_config {
  my $config = shift;
  my $str = serialise_config($config);

  safe_cat($str, "$opt{prefix}/config", "$tempdir/config");
}

sub ensure_dir {
  my $dir = shift;
  my @parts = split m{/} => $dir;
  my $p;

  do {
    if ($p = defined $p ? $p.'/'.shift @parts : shift @parts) {
      -d $p or mkdir $p or die "mkdir failed: $!";
    }
  } while (@parts);
}

sub slurp_file {
  my $file = shift;
  
  open my $fh, '<', $file or
    die "error opening $file for read: $!";
  my $content = do { local $/; <$fh> };
  close $fh or
    die "error closing $file after read: $!";

  return $content;
}

sub safe_cat {
  my $data = shift;
  my $file = shift;
  my $tempfile = shift;

  open my $fh, '>', "$tempfile" or
    die "error opening $tempfile for write: $!";

  binmode $fh, ':utf8';
  print $fh $data;
 
  close $fh or
    die "error closing $tempfile after write: $!";
  rename $tempfile => $file or
    die "error rename $tempfile to $file: $!";
}

sub tempdir {
  my $template = shift;
  $template =~ s/(X+)// or
    die "bad tempdir template: $template";
  my $fill = length $1;
  my @set = ('A' .. 'Z', 'a' .. 'z', 0 .. 9 );
  my $attempts = 1000;

  unless ($template =~ m{/}) {
    $template = ($ENV{TMPDIR}||'/tmp').'/'.$template;
  }

  for (my $i=0; $i<$attempts; $i++) {
    my $noise = join('' => map $set[rand @set] => 1 .. $fill);
    my $path = $template.$noise;
    next unless mkdir $path, 0700;
    return $path;
  }

  die "max tempdir attempts ($attempts) reached.";
}

sub mime {
  my $file = shift;
  my $mime = `file -b -i "$file"`;
  die "error guessing mime type for $file: ".($? >> 1) if $?;
  chomp $mime;
  return $mime;
}

sub looks_like_html {
  return substr(shift, 0, 4096) =~
    m{(</a>|</b>|</i>|</u>|<p>|<br\s*/?>|&\w{2,6};)}i;
}

sub verbose {
  return unless $opt{verbose};

  for (@_) {
    print STDERR $_;
    print "\n" unless /\n$/;
  }
}



package Feed;

use XML::Simple qw/XMLin/;
use strict;

sub new {
  my $this = shift;
  my $self = ref $_[0] ? shift : { index => {} };
  bless $self => ref($this) || $this;
  return $self->init(@_);
}

sub init {
  my $self = shift;
  my $index = $self->{index};
  my $source = shift;

  if (ref $source eq 'HASH') {
    $index->{$_} = $source->{$_} for keys %$source;
  }
  elsif ($source && !ref $source) {
    my %xmlin_opts = (
      ForceArray => [ qw/item entry/ ],
      KeyAttr => []
    );
    my $data = XMLin($source, %xmlin_opts) or
      die "error reading xml";
    $index->{$_} = $data->{$_} for keys %$data;
  }

  # detect feed format & upgrade feed object

  my %feed_classes = (
    'Feed::RSS' => qr{^rss/},
    'Feed::Atom' => qr{^atom/},
  );

  my $format = $self->format;

  while (my ($package, $re_format) = each %feed_classes) {
    if ($format =~ $re_format) {
      bless $self => $package;
      last;
    }
  }

  return $self;
}

sub format {
  my $index = shift->{index};

  return 'atom/1.0' if $index->{'xmlns:atom'};
  return 'atom/1.0' if $index->{entry};
  return 'rss/1.0' if $index->{item};
  return 'rss/2.0' if $index->{channel};

  return undef;
}

sub items {
  die "can't fetch items for unknown feed format ".(shift->format);
}

1;


package Feed::RSS;
use base qw/Feed/;

sub items {
  my $self = shift;
  my $index = $self->{index};
  my $format = $self->format;
  my $items = 
    $format eq 'rss/2.0' ? $index->{channel}->{item} :
    $format eq 'rss/1.0' ? $index->{item} :
      die "unknown rss format $format";

  $items = [ $items ] unless ref $items eq 'ARRAY';

  return [ map Feed::Item::RSS->new($_) => @{$items} ];
}

sub pub_time {
  my $channel = shift->{index}->{channel} or return undef;
  return $channel->{'dc:date'} || $channel->{pubDate};
}

sub author {
  my $channel = shift->{index}->{channel} or return undef;
  return $channel->{'dc:creator'} || $channel->{'dc:publisher'};
}

1;


package Feed::Atom;
use base qw/Feed/;

sub items {
  my $index = shift->{index};
  return [ map Feed::Item::Atom->new($_) => @{$index->{entry}} ];
}

sub author {
  my $w = shift->{index}->{author} or return undef;
  return "$w->{email} <$w->{name}>";
}

sub pub_time {
  return undef;
}

1;


package Feed::Item::RSS;
use XML::Simple qw/XMLout XMLin/;

sub new { bless $_[1] => ref($_[0]) || $_[0]; }
sub link { return $_[0]->{link} }
sub title { return $_[0]->{title} }
sub pub_time { return $_[0]->{'dc:date'} || $_[0]->{pubDate} }
sub author { return $_[0]->{'dc:creator'} || $_[0]->{'dc:publisher'} }
sub content { return XMLout($_[0], NoAttr => 1, NoEscape => 1) }

1;


package Feed::Item::Atom;

sub new { bless $_[1] => ref($_[0]) || $_[0]; }
sub title { return _atom_content(shift->{title}) }
sub content { return _atom_content(shift->{content}) }
sub pub_time { return _atom_content(shift->{published}) }
sub author { my $w = shift->{author}; return "$w->{email} <$w->{name}>" }

sub link {
  my $link = shift->{link};
  return $link->[-1]->{href} if ref $link eq 'ARRAY';
  return $link->{href};
}

sub _atom_content {
  return $_[0]->{content} if ref $_[0] eq 'HASH' && exists $_[0]->{content};
  return $_[0];
}

1;


__END__

=head1 NAME

rssdrop - deliver rss feeds to Maildirs

=head1 SYNOPSIS

rssdrop [ feedname1 feedname2 ... ] | [ -a feedname url ] | [ -d feedname ]

=head1 EXAMPLES 

Initialize rssdrop:

  $ rssdrop --mailfolder path/to/mailfolder

Subscribe to a new feed:

  $ rssdrop -a acme-widgets http://acme.com/widgets.rss

Fetch items in your new feed:

  $ rssdrop acme-widgets

Unsubscribe:

  $ rssdrop -d acme-widgets

Fetch all new items in all feeds:

  $ rssdrop

=head1 DESCRIPTION

rssdrop is a simple RSS -> mail gateway. It delivers new RSS feed
items directly to a local Maildir folder of your choice. You can use
your favorite mail client to read them.

rssdrop knows the basic structure of RSS 1.0, 2.0 and ATOM feeds, enough
to deliver the raw item xml as the body of the message, or fetch
the fulltext from the item link. Use fulltext = 1 in your feed config
for that.

=head1 OPTIONS

=over 4

=item --add feedname1 url1 feedname2 url2 ...

Add named feeds to your config. Checks that the url has valid rss.

=item --delete feedname1 feedname2 ...

Remove named feeds from your config.

=item --prefix path/to/rssdrop/dir

Controls where rssdrop will save its config. Fetched feeds and items
are also stored here.

By default, rssdrop uses the $RSSDROP_PREFIX variable. If not set, it
falls back to $HOME/.rssdrop. This directory will be created and
populated with an initial config file if they don't exist.

=item --mailfolder path/to/mailfolder

Sets the mailfolder rssdrop should deliver new items to. Each feed
has its own Maildir beneath $mailfolder. rssdrop will create a Maildir
for a feed if one doesn't exist.

This option is required and initially has no default. After one-time
setup, however, rssdrop saves your $mailfolder setting in the global
section of the config file. If you're happy with this setting, there's
no need to specify --mailfolder after that.

=item --verbose 

Turn on extra logging messages. By default, rssdrop is quiet.

=item --help

Display usage information.

=back

=head1 CONFIGURATION

The rssdrop config file (by default, ~/.rssdrop/config) uses a simple
ini-style format with a global config section followed by feed-specific
config. Here's a sample:

  mailfolder = /home/jdoe/var/mail

  [freebsd-sa]
  url = http://www.freebsd.org/security/advisories.rdf

  [craigslist-nyc-cheap-apts]
  fulltext = 1
  url = http://newyork.craigslist.org/search/aap?query=&minAsk=1000&maxAsk=2000&bedrooms=&format=rss

=head1 TODO

=over 4

=item * use mime multiparts to separate feed from fulltext

=item * support per-feed mimetype conversion filters

=item * add a --cleanup option to remove old / unused feed state

=back

=head1 BUGS

Please report bugs on CPAN.

=head1 AUTHOR

Alan Grow <agrow+nospam@iobound.net>

=head1 COPYRIGHT

Copyright (C) 2008 by Alan Grow

This application is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.3 or, at
your option, any later version of Perl 5 you may have available.

=cut