Automatically Unrar Everything In A Folder

This script enters into all subfolders of the given folder, unrars all archives and then deletes the rar files. If the folder name matches HDTV or another filter of your choosing, the script will also move any video files to the root folder and delete the containing folder.

Designed to be run on a regular schedule, the script will skip any folders it has already processed. To run regularly, add to cron.

Here’s the script:

def episode(dir)
  dir.match "HDTV"
end

def unrar_delete(thefile,allfiles)
  if system "/opt/local/bin/unrar e -y %s > /dev/null" % thefile.gsub(' ',' ')
    for file in allfiles
      File.delete(file)
    end
    return true
  end
  return false
end

rootdir = "/Volumes/Filmer/Incoming"

Dir["%s/*" % rootdir].each do |dir|
  if File.directory? dir and not dir.match "UNPACKED"
    ok = false
    Dir.chdir(dir)
    Dir['%s/*.rar' % dir].each do |rarfile|
      puts rarfile
      ok = unrar_delete(rarfile, Dir[rarfile.gsub("part01","part??")]) if rarfile.match "part01.rar"
      ok = unrar_delete(rarfile, Dir[rarfile.gsub(".rar",".r??")]) if not rarfile.match /part[0-9]{2}/
    end

    if ok
      if episode(dir)
        system "mv *.avi %s" % rootdir
        system "mv *.mkv %s" % rootdir
        Dir.chdir(rootdir)
        system "rm -r %s" % dir
      else
        File.rename(dir,"%s UNPACKED" % dir)
      end
    end
  end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s