#! C:\Perl\bin\perl.exe use File::Copy; use File::Path; use Net::FTP; sub generate_sorta_unique { $sessionId =""; $length=4; for($i=0 ; $i< $length ;) { $j = chr(int(rand(127))); if($j =~ /[a-zA-Z0-9]/){ $sessionId .=$j; $i++; } } return($sessionId); } sub trim_files { opendir(BG, "$CONFIG{'archive'}"); @files = grep(!/^\.\.?$/, readdir(BG)); closedir(BG); if(!@files) { return(0); } foreach $file (@files) { ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $osize, $atime, $mtime, $ctime, $blksize, $blocks) = stat("$CONFIG{'archive'}/$file"); $now = time(); if($now > ($mtime + ($CONFIG{'trim_days'} * 1440))) { print "Trimming: $file...\n"; unlink("$CONFIG{'archive'}/$file"); } } } sub watch_dir() { opendir(BG, "$CONFIG{'watch'}") || die("Problem opening $CONFIG{'watch'}: $!\n"); @files = grep(!/^\.\.?$/, readdir(BG)); closedir(BG); if(!@files) { return; } $new_file = ''; foreach $file (@files) { print("Found file: $file\n"); ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $osize, $atime, $mtime, $ctime, $blksize, $blocks) = stat("$CONFIG{'watch'}/$file"); $now = time(); if($now < ($mtime + $CONFIG{'wait'})) { print("Skipping $file\n"); next; } $rename = 0; $u = ''; if($CONFIG{'unique'}) { $u = generate_sorta_unique() . '_'; $rename = 1; } $p = ''; if($CONFIG{'prefix'}) { $p = $CONFIG{'prefix'} . '_'; $rename = 1; } $new_file = $p . $u . $file; $new_file =~ s/ /_/g; if($rename) { move("$CONFIG{'watch'}/$file", "$CONFIG{'watch'}/$new_file"); print "Renaming: $file -> $new_file\n"; } else { $new_file = $file; } my $start = time(); send_ftp($CONFIG{'user'}, $CONFIG{'pass'}, $CONFIG{'host'}, $CONFIG{'ftp_dir'}, "$CONFIG{'watch'}/$new_file"); my $end = time(); my $time_difference = $end - $start; print("Sent $new_file in $time_difference seconds.\n"); if($CONFIG{'archive'}) { print "$file, $CONFIG{'archive'}/$new_file\n"; move("$CONFIG{'watch'}/$new_file", "$CONFIG{'archive'}/$new_file") or die("Couldn't archive $new_file: $!"); } else { unlink("$CONFIG{'watch'}/$new_file"); } } if($CONFIG{'trim_days'}) { trim_files(); } } sub send_ftp { $i = 0; while($i < 5) { ($user, $pass, $host, $dir, $file) = @_; $ftp = Net::FTP->new($host, Debug => 0) or print "Cannot connect to $host: $@"; $ftp->login($user, $pass) or print "Cannot login ", $ftp->message; if($dir) { $ftp->cwd($dir) or print "Cannot change working directory ", $ftp->message; } if($ftp->put($file)) { $ftp->quit; last; } else { print "get failed ", $ftp->message; } $ftp->quit; $i++; } } open(CONFIG, "config.txt") or die("Coudln't open config.txt: $!"); @all = ; close(CONFIG); foreach $line (@all) { if($line =~ /\#/ || !$line) { next; } ($name, $value) = split(/ = /, $line); $line =~ s/\\/\\\\/g; chomp($value); $CONFIG{"$name"} = $value; } if($CONFIG{'loop'}) { while(1) { watch_dir(); sleep(10); } } else { watch_dir(); }