#!/usr/bin/perl use strict; use warnings; # getopts module use Getopt::Std; # getstore module use LWP::Simple; use HTML::Entities; use File::Copy; use File::Basename; use File::Path qw(make_path remove_tree); #use File::Glob ':glob'; # forward declaration sub parse_file; sub parse_dirs; # get options our($opt_n, $opt_h); getopts('nh') or $opt_h = 1; # sets opt_n to true if -n is given #+or dies when options are unknown if ($opt_h) { print "Usage: renameseries [OPTION]... SOURCE DESTINATION\n"; print "Rename all files in SOURCE to the name downloaded from epguides.com then copy ". "the files to DESTINATION.\n"; print "\n"; print " -n will only print what would happen, doesn't change anything\n"; print " -h shows this help message\n"; exit 0; } @ARGV == 2 or die; my $url = 'http://epguides.com'; my $src = $ARGV[0]; my $dst = $ARGV[1]; parse_dirs($src); sub parse_dirs() { my $dir = $_[0]; opendir(my $dh, $dir) or die "Couldn't open dir '$dir': $!"; my @files = readdir $dh; closedir $dh; foreach my $file (@files) { next if $file =~ /^\./; my $path = "$dir/$file"; if (-d $path) { parse_dirs($path); } else { parse_file($dir,$file); } } } sub parse_file { my $path = $_[0]."/".$_[1]; my $file = $_[1]; if ($file =~ /(?.*?)\.S?0*(?\d+)(E|x)0*(?\d+).*\.(?.*)/i) { if ($opt_n) { print "Parsing '$file\n'"; } my $season = $+{season}; my $episode = length($+{episode}) == 1 ? '0' . $+{episode} : $+{episode}; my $pattern = '(0?'.$+{season}.')-([0 ]?'.$+{episode}.').*?>(.*?) *<\/a>'; my $extension = $+{extension} ? lc($+{extension}) : "avi"; (my $name = $+{name}) =~ s/\./ /g; (my $series_name = $name) =~ s/^The //i; $series_name =~ s/ //g; # fix for Doctor Who $series_name =~ s/(DoctorWho)(2005)/$1_$2/; $series_name =~ s/(Doctor.Who).(2005)/$1_$2/; $name =~ s/(Doctor Who) (2005)/$1 ($2)/; my $tmp = '/tmp/renameseries'; if ($opt_n) { print "Downloading '$url/$series_name'\n"; } getstore("$url/$series_name", $tmp); open FILE, $tmp or die "Could not download '$series_name' from '$url'"; my @lines = ; close FILE; unlink($tmp); foreach my $line (@lines) { if ($line =~ /$pattern/) { my $new_file_name = "$1x$episode $3.$extension"; if ($opt_n) { print "New Filename '$new_file_name'\n"; } decode_entities($new_file_name); my $new_path = "$dst/$name/Season $1"; make_path("$new_path"); $new_path = "$new_path/$new_file_name"; if (-e $new_path) { if ($opt_n) { print "File exists '$new_path'\n"; print "Unlink '$file'\n"; } else { unlink("$path") or die "Couldn't unlink '$_[0]': $!"; } } else { if (!$opt_n) { copy ("$path", "$new_path"); } print "Copied \'$file\' \n=> \'$new_path\'\n"; } last; } } } }