#! /usr/bin/perl use warnings; use strict; # getopts module use Getopt::Std; # getstore madule use LWP::Simple; # Curent Working Directory module use Cwd; use HTML::Entities; #use utf8; # eguides URL my $url = 'http://epguides.com'; # get options our($opt_n, $opt_s, $opt_h); getopts('ns:h') 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]... [DIRECTORY]\n"; print " or: renameseries [OPTION]... -s SERIE [DIRECTORY]\n"; print "Rename all files in DIRECTORY to the name downloaded from epguides.com\n"; exit 0; } my $path = getcwd(); #print $path; my $series_name; if ($opt_s) { $series_name = $opt_s; } else { $path .= @ARGV==1?"/$ARGV[0]":""; # $path =~ /.*\/(.*?)(?: *\[.*?\])*(?:\/Season \d+)/; my @paths = split("\\/",$path); foreach my $p (reverse(@paths)) { if ($p =~ /Season|Series/ || !$p ) { next; } $series_name = $p; # print "$p\n"; last; } # $series_name = $1 or die("Could not find Series name in path"); # print $series_name . "\n"; # substitute 'The' at the beginning #or substitute any of the folowing characters '-' ',' '.' ' ' #or substitute [.*] $series_name =~ s/(^The|[- ,\.]|\[.*\])//g; } #print $series_name; $path = @ARGV==1?"./$ARGV[0]":"./"; my $tmp = '/tmp/renameseries'; getstore( "$url/$series_name", $tmp); open FILE, $tmp or die "Could not download '$series_name' from '$url'"; my @lines = ; close FILE; unlink($tmp); #use diagnostics; #my @old_file_names = <"$path". *>; opendir(my $dh , $path) or die "Couldn't open dir '$path': $!"; my @old_file_names;# = readdir $dh; @old_file_names = grep { /^/ && -f "$path/$_" } readdir($dh); #foreach my $old_file_name (@old_file_names) { # print $old_file_name . "\n"; #} if ($opt_n) { print "Path : " . $path . "\n"; } foreach my $old_file_name (@old_file_names) { # print $old_file_name . "\n"; if ($old_file_name =~ /0?(?\d+).*?0?(?\d+)(.*\.(?.*)|.*)/) { # print $+{episode} . "\n"; my $episode = length($+{episode}) == 1 ? '0' . $+{episode} : $+{episode}; my $pattern = '(0?'.$+{season}.')-([0 ]?'.$+{episode}.').*?>(.*?) *<\/a>'; my $extension = $+{extension} ? $+{extension} : "avi"; foreach my $line (@lines) { if ($line =~ /$pattern/) { my $new_file_name = $1 . "x" . $episode . " " .$3 . ".$extension"; decode_entities($new_file_name); # print "pattern -> " . $pattern . "\n"; if ($new_file_name eq $old_file_name) { last; } if ($opt_n) { print $old_file_name . " -> " . $new_file_name . "\n"; } else { rename("$path/$old_file_name", "$path/$new_file_name"); } last; } } } }