#!/usr/bin/perl
#
# rss-torrentflux.pl 0.9c is a Perl-Frontend to TorrentFlux
# <http://www.torrentflux.com/>
#
# It should work with TorrentFlux up to Version 1.5
# For problems with specific versions, please contact the author.
#
# It listens to RSS-Feeds, tries to match to Regular Expressions,
# adds the torrents to TorrentFlux and starts the download.
#
# This script was developed by Sebastian Sproesser
# <sebastian@sproesser.org>
#
# This script is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
#
# The following Perl-Modules need to be installed:
# * Getopt::Long
# * LWP::Simple
# * WWW::Mechanize
# * XML::RSS

use warnings;
use strict;

use vars qw/$torrentflux_url $torrentflux_user
    $torrentflux_password @rssfeeds @regexp @seentorrents/;

##########################################################################
#################### Options you really should set :) ####################
##########################################################################

# Provide a URL, where your TorrentFlux is located:
#$torrentflux_url = 'http://user:password@torrentflux.example/torrentflux/';
$torrentflux_url = '';

# Provide a username/password for TorrentFlux
#$torrentflux_user = 'user';
#$torrentflux_password = 'password';
$torrentflux_user = '';
$torrentflux_password = '';

# Provide RSS-Feeds to grab Torrents from:
#@rssfeeds = ('http://rssfeed1.example/',
#             'http://nextfeed.example');
@rssfeeds = ();

# Provide Perl-Regular-Expressions to match the wanted Titles. Case is ignored:
#@regexp = ('simpsons.*(pdtv|hdtv)', # Matches every Simpsons-Episode in PDTV or HDTV
#           '^24');                  # Matches every Title beginning with 24
@regexp = ();

##########################################################################
############# You shouldn't need to edit anything below here #############
##########################################################################

use Getopt::Long;

my ($verbose, $help, $nostart);

die "Usage: $0 [-n] [-v] [-h]
\t-n\tDon't start download, just add URL to TorrentFlux
\t-v\tBe verbose
\t-h\tDisplay this help screen"
    unless GetOptions('v|verbose' => \$verbose,
		      'h|help' => \$help,
		      'n|nostart' => \$nostart,
		      ) and !$help;

use LWP::Simple;
use XML::RSS;
use WWW::Mechanize;

my $mech = WWW::Mechanize->new();
my $rss = new XML::RSS;

my $response = $mech->get($torrentflux_url);
die ($response->status_line) unless ($response->is_success());

for ($mech->forms()) {
    if ($_->attr('name') eq 'theForm') {
	$mech->form_name('theForm');
	$mech->set_fields(username => $torrentflux_user,
			  iamhim   => $torrentflux_password);
	my $response = $mech->click();
	die ($response->status_line) unless ($response->is_success());
    }
}
die ('Could possibly not login to TorrentFlux!') unless ($mech->form_name('form_url'));

# Get list of downloaded torrents
if (open(TORRENTS, '<', $ENV{HOME}.'/.seentorrents')) {
    push(@seentorrents,$_) while(<TORRENTS>);
    chomp(@seentorrents);
    close(TORRENTS);
}

 FEED: for my $feed (@rssfeeds) {
     my $feedcontent = get($feed);
     if (!$feedcontent) {
	 warn "Could not get RSS-Feed $feed";
	 next FEED;
     }
     $rss->parse($feedcontent);
     
   ITEM: foreach my $item (@{$rss->{'items'}}) {
       my $title = $item->{'title'};
       my $url = $item->{'link'};
       my $filename = $url;
       $filename =~ s!^.*/!!;
       for (@regexp) {
	   if ($title =~ /$_/i) {
	       # Check if download has already started
	       for (@seentorrents) {
		   next ITEM if ($filename eq $_);
	       }
	       print "Found new Match: $title\n" if ($verbose);
	       # Add URL to Torrentflux
	       $mech->submit_form(form_name=>'form_url',
				  fields => {url_upload => $url,});
	       if ($mech->content() !~ /ERROR/) {
		   # Start Download
		   if (!$nostart) {
		       my $response = $mech->get($torrentflux_url.'index.php?torrent='.$filename);
		       die ($response->status_line) unless ($response->is_success());
		   }
		   push(@seentorrents, $filename);
		   print " Successfully added torrent to TorrentFlux\n" if ($verbose);
	       } else {
		   print " Failed to add torrent to TorrentFlux. Will try again next time.\n" if ($verbose);
	       }
	   }
       }
   }
 }

# Update ~/.seentorrents
open(TORRENTS, '>',$ENV{HOME}.'/.seentorrents') or die 'Could not write to ~/.seentorrents';
print TORRENTS join("\n",@seentorrents);
close(TORRENTS);