#!/usr/bin/env python
from optparse import OptionParser
import os
import re
import sys
VERSION = "0.1"
#compatible with Python v2.6.6+
def set_options():
"""
parses command line options, checks source and destination directory existence.
"""
global OPT, ARG, DEST
usage = "%prog [option] dir1 [dir2] [dir3] [...]"
version = "%prog " + VERSION
description = "Creates season-based symlinks based for absolutely numbered animes."
parser = OptionParser(usage=usage,version=version,description=description)
parser.set_defaults(recursion=False,run=True,verbose=0)
parser.add_option("-v", "--verbose",
dest="verbose", action="store_const", const=2,
help="increases output verbosity")
parser.add_option("-n", "--dry-run",
dest="run", action="store_false",
help="simulate actions without making any changes.")
(OPT, ARG) = parser.parse_args()
#checks arguments
if len(ARG) < 1:
print "Not enough arguments"
parser.print_help()
sys.exit(2)
for dir in ARG:
if not os.path.exists(dir):
print "ERROR:", dir, "does not exist."
sys.exit(2)
if OPT.verbose > 2:
print "OPT =", OPT
print "ARG =", ARG
print
def abs2sep(series, aep):
#if OPT.verbose > 1:
#print "series =",series
#print "abs ep =",aep
anime = {
'Bleach': [20, 21, 22, 28, 18, 22, 20, 16, 22, 16, 7, 17, 36, 51, 26, 999],
'Naruto Shippuuden': [32, 21, 18, 17, 24, 31, 8, 24, 21, 22, 24, 999]
}
if not(series in anime):
return (-1,-1)
a = aep
s = 0
e = 0
for num in anime[series]:
if a <= 0:
break
if (a-num) <= 0:
e = a
a -= num
s += 1
return (s,e)
def create_symlink(source, target_dir, target_ext, series, season, ep):
link_name = "%s %dx%d.%s" % (series, season, ep, target_ext)
target_file = os.path.join(target_dir,link_name)
# remove existing symlink conflicts in case paths change
if (OPT.run == True):
# only remove symlink if they point to different files
if os.path.islink(target_file):
if os.stat(source).st_ino != os.stat(target_file).st_ino:
os.remove(target_file)
else:
return
print source,
print " ==> ",target_file
os.symlink(source,target_file)
def main():
set_options()
for dir in ARG:
for dir_path, dir_names, file_names in os.walk(dir):
for file in file_names:
match = re.search(r'\[.+\](.+)-\s+(\d+).*\.([^\.]+)$',str(file))
if match == None:
if OPT.verbose > 1:
print "[SKIP]", file
continue
series = match.group(1).strip()
abs_ep = int(match.group(2))
file_ext = match.group(3).strip()
sep = abs2sep(series,abs_ep)
if sep[0] != -1:
create_symlink(os.path.join(dir_path,file), dir_path, file_ext, series, sep[0], sep[1])
main()