mirror of
https://github.com/nikdoof/tvorganise.git
synced 2025-12-13 06:42:16 +00:00
Wrap functions in a class.
This commit is contained in:
310
tvorganise.py
310
tvorganise.py
@@ -14,186 +14,174 @@ import shutil
|
|||||||
import ConfigParser
|
import ConfigParser
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
def getLogger():
|
class TvOrganiser():
|
||||||
lgr = logging.getLogger('tvorganise')
|
|
||||||
lgr.addHandler(logging.StreamHandler())
|
def _getLogger(self):
|
||||||
return lgr
|
lgr = logging.getLogger('tvorganise')
|
||||||
|
lgr.addHandler(logging.StreamHandler())
|
||||||
|
return lgr
|
||||||
|
|
||||||
def getConfig(file):
|
def _getConfig(self, file):
|
||||||
|
|
||||||
config = {}
|
config = {}
|
||||||
|
|
||||||
configpsr = ConfigParser.RawConfigParser()
|
configpsr = ConfigParser.RawConfigParser()
|
||||||
configpsr.read('tvorganise.cfg')
|
configpsr.read('tvorganise.cfg')
|
||||||
|
|
||||||
if configpsr.has_section('main'):
|
if configpsr.has_section('main'):
|
||||||
for k, v in configpsr.items('main'):
|
for k, v in configpsr.items('main'):
|
||||||
config[k] = v
|
config[k] = v
|
||||||
|
|
||||||
if configpsr.has_section('regex'):
|
if configpsr.has_section('regex'):
|
||||||
|
|
||||||
regex_config = {}
|
|
||||||
regex = []
|
|
||||||
|
|
||||||
# Load in subs before reading in the regex
|
regex_config = {}
|
||||||
for k, v in configpsr.items('regex'):
|
regex = []
|
||||||
if k[:5] != 'regex':
|
|
||||||
regex_config[k] = v
|
|
||||||
|
|
||||||
for k, v in configpsr.items('regex'):
|
# Load in subs before reading in the regex
|
||||||
if k[:5] == 'regex':
|
for k, v in configpsr.items('regex'):
|
||||||
regex.append(re.compile(v % regex_config))
|
if k[:5] != 'regex':
|
||||||
|
regex_config[k] = v
|
||||||
|
|
||||||
config['regex'] = regex
|
for k, v in configpsr.items('regex'):
|
||||||
|
if k[:5] == 'regex':
|
||||||
|
regex.append(re.compile(v % regex_config))
|
||||||
|
|
||||||
return config
|
config['regex'] = regex
|
||||||
|
|
||||||
|
self._config = config
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
def findFiles(args):
|
def _findFiles(self, args):
|
||||||
"""
|
"""
|
||||||
Takes a list of files/folders, grabs files inside them. Does not recurse
|
Takes a list of files/folders, grabs files inside them. Does not recurse
|
||||||
more than one level (if a folder is supplied, it will list files within)
|
more than one level (if a folder is supplied, it will list files within)
|
||||||
"""
|
"""
|
||||||
allfiles = []
|
allfiles = []
|
||||||
for cfile in args:
|
for cfile in args:
|
||||||
if os.path.isdir(cfile):
|
if os.path.isdir(cfile):
|
||||||
for sf in os.listdir(cfile):
|
for sf in os.listdir(cfile):
|
||||||
newpath = os.path.join(cfile, sf)
|
newpath = os.path.join(cfile, sf)
|
||||||
if os.path.isfile(newpath):
|
if os.path.isfile(newpath):
|
||||||
allfiles.append(newpath)
|
allfiles.append(newpath)
|
||||||
elif os.path.isfile(cfile):
|
elif os.path.isfile(cfile):
|
||||||
allfiles.append(cfile)
|
allfiles.append(cfile)
|
||||||
return allfiles
|
return allfiles
|
||||||
|
|
||||||
def processNames(names, verbose=False):
|
def processNames(self, names, verbose=False):
|
||||||
"""
|
"""
|
||||||
Takes list of names, runs them though the regexs
|
Takes list of names, runs them though the regexs
|
||||||
"""
|
"""
|
||||||
allEps = []
|
allEps = []
|
||||||
for f in names:
|
for f in names:
|
||||||
filepath, filename = os.path.split( f )
|
filepath, filename = os.path.split( f )
|
||||||
filename, ext = os.path.splitext( filename )
|
filename, ext = os.path.splitext( filename )
|
||||||
|
|
||||||
# Remove leading . from extension
|
# Remove leading . from extension
|
||||||
ext = ext.replace(".", "", 1)
|
ext = ext.replace(".", "", 1)
|
||||||
|
|
||||||
for r in config['regex']:
|
for r in config['regex']:
|
||||||
match = r.match(filename)
|
match = r.match(filename)
|
||||||
if match:
|
if match:
|
||||||
showname, seasno, epno, epname = match.groups()
|
showname, seasno, epno, epname = match.groups()
|
||||||
|
|
||||||
#remove ._- characters from name (- removed only if next to end of line)
|
#remove ._- characters from name (- removed only if next to end of line)
|
||||||
showname = re.sub("[\._]|\-(?=$)", " ", showname).strip()
|
showname = re.sub("[\._]|\-(?=$)", " ", showname).strip()
|
||||||
|
|
||||||
seasno, epno = int(seasno), int(epno)
|
seasno, epno = int(seasno), int(epno)
|
||||||
|
|
||||||
if verbose:
|
if verbose:
|
||||||
print "*"*20
|
print "*"*20
|
||||||
print "File:", filename
|
print "File:", filename
|
||||||
print "Pattern:", r.pattern
|
print "Pattern:", r.pattern
|
||||||
print "Showname:", showname
|
print "Showname:", showname
|
||||||
print "Seas:", seasno
|
print "Seas:", seasno
|
||||||
print "Ep:", epno
|
print "Ep:", epno
|
||||||
print "*"*20
|
print "*"*20
|
||||||
|
|
||||||
allEps.append({ 'file_showname':showname,
|
allEps.append({ 'file_showname':showname,
|
||||||
'seasno':seasno,
|
'seasno':seasno,
|
||||||
'epno':epno,
|
'epno':epno,
|
||||||
'filepath':filepath,
|
'filepath':filepath,
|
||||||
'filename':filename,
|
'filename':filename,
|
||||||
'ext':ext
|
'ext':ext
|
||||||
})
|
})
|
||||||
break # Matched - to the next file!
|
break # Matched - to the next file!
|
||||||
else:
|
else:
|
||||||
print "Invalid name: %s" % (f)
|
print "Invalid name: %s" % (f)
|
||||||
|
|
||||||
return allEps
|
return allEps
|
||||||
|
|
||||||
|
def _same_partition(f1, f2):
|
||||||
|
return os.stat(f1).st_dev == os.stat(f2).st_dev
|
||||||
|
|
||||||
def make_path(path):
|
###########################
|
||||||
try:
|
|
||||||
os.makedirs(path)
|
|
||||||
except OSError:
|
|
||||||
#print "Couldn't make path"
|
|
||||||
pass
|
|
||||||
|
|
||||||
def does_file_exist(path):
|
def main(self):
|
||||||
try:
|
parser = OptionParser(usage="%prog [options] <file or directories>")
|
||||||
os.stat(path)
|
parser.add_option("-a", "--always", dest = "always",
|
||||||
except OSError:
|
action="store_true", default = False,
|
||||||
file_exists = False
|
help="Do not ask for confirmation before copying")
|
||||||
else:
|
parser.add_option("-q", "--quiet", dest = "quiet",
|
||||||
file_exists = True
|
action="store_true", default = False,
|
||||||
return file_exists
|
help="Silence output")
|
||||||
|
parser.add_option("-c", "--config", dest = "config",
|
||||||
def same_partition(f1, f2):
|
action="store", default = "tvorganise.cfg",
|
||||||
return os.stat(f1).st_dev == os.stat(f2).st_dev
|
help="Use a custom configuration file")
|
||||||
|
parser.add_option("-v", "", dest = "verbose",
|
||||||
###########################
|
action="store_true", default = False,
|
||||||
|
help="Verbose output")
|
||||||
def main():
|
|
||||||
parser = OptionParser(usage="%prog [options] <file or directories>")
|
|
||||||
parser.add_option("-a", "--always", dest = "always",
|
|
||||||
action="store_true", default = False,
|
|
||||||
help="Do not ask for confirmation before copying")
|
|
||||||
parser.add_option("-q", "--quiet", dest = "quiet",
|
|
||||||
action="store_true", default = False,
|
|
||||||
help="Silence output")
|
|
||||||
parser.add_option("-c", "--config", dest = "config",
|
|
||||||
action="store", default = "tvorganise.cfg",
|
|
||||||
help="Use a custom configuration file")
|
|
||||||
parser.add_option("-v", "", dest = "verbose",
|
|
||||||
action="store_true", default = False,
|
|
||||||
help="Verbose output")
|
|
||||||
|
|
||||||
|
|
||||||
opts, args = parser.parse_args()
|
opts, args = parser.parse_args()
|
||||||
|
|
||||||
if os.path.exists(opts.config):
|
if os.path.exists(opts.config):
|
||||||
config = getConfig(opts.config)
|
config = getConfig(opts.config)
|
||||||
else:
|
else:
|
||||||
print 'Unable to find configuration file!'
|
print 'Unable to find configuration file!'
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
files = findFiles(args)
|
files = findFiles(args)
|
||||||
files = processNames(files, opts.verbose)
|
files = processNames(files, opts.verbose)
|
||||||
|
|
||||||
# Warn if no files are found, then exit
|
# Warn if no files are found, then exit
|
||||||
if len(files) == 0:
|
if len(files) == 0:
|
||||||
print 'No files found'
|
print 'No files found'
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
for name in files:
|
for name in files:
|
||||||
oldfile = os.path.join(name['filepath'], name['filename']) + "." + name['ext']
|
oldfile = os.path.join(name['filepath'], name['filename']) + "." + name['ext']
|
||||||
newpath = config['target_path'] % name
|
newpath = config['target_path'] % name
|
||||||
newfile = os.path.join(newpath, name['filename']) + "." + name['ext']
|
newfile = os.path.join(newpath, name['filename']) + "." + name['ext']
|
||||||
|
|
||||||
print "Old path:", oldfile
|
print "Old path:", oldfile
|
||||||
print "New path:", newfile
|
print "New path:", newfile
|
||||||
ans= "always"
|
ans= "always"
|
||||||
if ans == "always": opts.always = True
|
|
||||||
|
if opts.always:
|
||||||
if ans or opts.always:
|
if not os.path.exists(newpath):
|
||||||
make_path(newpath)
|
os.mkdirs(newpath)
|
||||||
file_exists = does_file_exist(newfile)
|
if os.path.exists(newfile):
|
||||||
if file_exists:
|
print "[!] File already exists, not copying"
|
||||||
print "[!] File already exists, not copying"
|
else:
|
||||||
else:
|
if self._same_partition(oldfile, newpath):
|
||||||
if same_partition(oldfile, newpath):
|
print "[*] Moving file"
|
||||||
print "[*] Moving file"
|
try:
|
||||||
try:
|
os.rename(oldfile, newfile)
|
||||||
os.rename(oldfile, newfile)
|
except Exception, errormsg:
|
||||||
except Exception, errormsg:
|
print "[!] Error moving file! %s" % (errormsg)
|
||||||
print "[!] Error moving file! %s" % (errormsg)
|
else:
|
||||||
else:
|
print "[*] Copying file"
|
||||||
print "[*] Copying file"
|
try:
|
||||||
try:
|
shutil.copy(oldfile, newfile)
|
||||||
shutil.copy(oldfile, newfile)
|
except Exception, errormsg:
|
||||||
except Exception, errormsg:
|
print "[!] Error copying file! %s" % (errormsg)
|
||||||
print "[!] Error copying file! %s" % (errormsg)
|
else:
|
||||||
else:
|
print "[*] ..done"
|
||||||
print "[*] ..done"
|
else:
|
||||||
else:
|
print "Skipping file"
|
||||||
print "Skipping file"
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
|
||||||
|
t = TvOrganiser()
|
||||||
|
t.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user