Skip to content

Instantly share code, notes, and snippets.

@jkongie
Created September 9, 2011 02:06
Show Gist options
  • Save jkongie/1205323 to your computer and use it in GitHub Desktop.
Save jkongie/1205323 to your computer and use it in GitHub Desktop.
TV Show Renaming Script
#!/usr/bin/env ruby
require 'highline/import'
require 'sofa'
class NoMatchFoundError < StandardError; end;
class EpisodeFile
attr_accessor :file, :season, :episode, :extension, :high_def, :valid
def initialize(file)
@file = file
@extension = File.extname(file)
@valid = true
extract_episode_info(file)
end
def rename(new_name)
File.rename(@file, new_name)
end
def valid?
@valid
end
private
def extract_episode_info(file)
unless file =~ /[sS]([0-9]{2})[eE]([0-9]{2})/
@valid = false
return
end
@season, @episode = $1.to_i, $2.to_i
file =~ /(720p|1080p)/
@high_def = $1
end
end
class ShowRenamer
attr_accessor :directory, :folder_name, :episode_files, :tvrage_show, :seasons
def initialize(directory)
@season = {}
@directory = directory
@folder_name = directory.split('/').last
Dir.chdir(directory)
@episode_files = load_episode_files
@show = find_show_on_tvrage
end
def load_episode_files
files = Dir.glob(File.join("**", "*.mkv"))
files = files.map{ |f| EpisodeFile.new(f) }
files.reject{ |f| !f.valid? }
end
# Find the correct show on TV Rage
def find_show_on_tvrage
show = nil
query = @folder_name
until show
puts "Searching for #{query}..."
show = Sofa::TVRage::Show.by_name(query)
if show.nil?
query = ask("Sorry but we couldn't find the show. Please enter the show name:")
else
display_show_summary(show)
unless agree("Is this the correct show? y/n")
show = nil
query = ask("Please enter the show name:")
end
end
end
show
end
def get_season_data_from_tvrage(season_number)
puts "Retrieving data from TVRage...Please wait"
@season[season_number] = @show.season_list[season_number - 1]
end
def new_name(season, ep_file)
episode = season.episodes[ep_file.episode - 1]
name = %Q(#{@folder_name} #{season.no}#{episode.num_in_season} - #{episode.title})
name << " #{ep_file.high_def}" if ep_file.high_def
name << ep_file.extension
end
def rename_all
@episode_files.each do |ep_file|
get_season_data_from_tvrage(ep_file.season) unless @season[ep_file.season]
current_season = @season[ep_file.season]
formatted_name = new_name(current_season, ep_file)
# if agree "[RENAME] #{ep_file.file} => #{formatted_name} (y/n)"
# ep_file.rename(formatted_name)
# end
puts "[RENAMING] #{ep_file.file} => #{formatted_name}"
ep_file.rename(formatted_name)
end
end
private
# Display the summary of a TVRage show
def display_show_summary(show)
puts "#{show.name} (#{show.started} - #{show.ended})"
end
end
# Get the given path otherwise use the current path
directory = ARGV[0] || Dir.pwd
renamer = ShowRenamer.new(directory)
renamer.rename_all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment