Skip to content

Instantly share code, notes, and snippets.

@robolson
Created October 18, 2009 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robolson/212563 to your computer and use it in GitHub Desktop.
Save robolson/212563 to your computer and use it in GitHub Desktop.
Catalog TV show downloads
#!/usr/bin/env ruby
#
# Cataloger watches the directory where completed torrents are placed.
# Upon scanning the directory for all .avi or .mkv files the script will
# attempt to extract the name of the TV show and the season number from the
# filename. Cataloger then checks for a directory of the format:
# "#{COMPLETED_DIR}/#{SHOW_NAME}/Season_#{SEASON_NUMBER}
# and copies over the file.
#
# Naturally this script is for educational purposes only.
#
require 'pathname'
require 'logger'
whoami = `whoami`.strip
COMPLETED_DIR = Pathname.new("/home/#{whoami}/torrents/completed/")
SHARED_DIR = Pathname.new("/media/sata3/shared/Videos/TV/")
Log = Logger.new("/home/#{whoami}/torrents/cataloger.log")
class String
# Capitalizes the first letter of every word
def titleize
split(' ').map{ |word| word.capitalize }.join(' ')
end
end
def normalize_show_name name
name.gsub(/\./, ' ').strip.titleize
end
def extract_show_info filename
episode = season = 0
# Strategy 1
if filename =~ /s([0-9]{1,2})/i
show_name = $~.pre_match
season = $1
if filename =~ /e([0-9\-]+)/i
episode = $1
end
end
# Strategy 2
if filename =~ /[ .]([0-9]{3})[ .]/
show_name = $~.pre_match
season = $1.to_i / 100
episode = $1.to_i % 100
end
# Strategy 3
if filename =~ /([0-9]{1,2})x([0-9]{1,2})/
show_name = $~.pre_match
season = $1
episode = $2
end
if season != 0 && episode != 0 && !show_name.empty?
return [normalize_show_name(show_name), season.to_s, episode.to_s]
end
end
def copy_episode season_dir, filename
destination = season_dir + filename
unless destination.exist?
Log.info "Copying #{filename.basename} to #{destination.dirname}"
FileUtils.copy_file(filename, destination)
end
end
Dir.chdir(COMPLETED_DIR)
Pathname.glob('*.{avi,mkv}') do |filename|
next if filename.directory?
show_name, season, episode = extract_show_info(filename.basename.to_s)
next if show_name.nil?
show_dir = SHARED_DIR + show_name
if show_dir.directory?
season_dir = show_dir + "Season_#{season.sub(/^0/, '')}"
season_dir.mkpath
copy_episode(season_dir, filename)
else
Log.warn "Could not find a folder for #{show_dir}"
end
end
Log.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment