robolson (owner)

Revisions

gist: 212563 Download_button fork
public
Description:
Catalog TV show downloads
Public Clone URL: git://gist.github.com/212563.git
Embed All Files: show embed
Text #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/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