Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!

awescript.py with srr path support

By: Gfy on Aug 6th, 2011  |  syntax: Python  |  size: 46.06 KB  |  views: 291  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # newest that works with pyReScene: https://bitbucket.org/Gfy/pyrescene/
  2. # original: http://rescene.wikidot.com/downloads#awescript
  3.  
  4.  
  5.  
  6. #!/usr/bin/env python
  7. # -*- coding: utf-8 -*-
  8.  
  9. # MADE BY GUBER - REMOVE THIS TO MAKE YOUR FIRST BORN MY LUNCH
  10. # Copyright (c) 2009 guber
  11. #
  12. # Permission is hereby granted, free of charge, to any person
  13. # obtaining a copy of this software and associated documentation
  14. # files (the "Software"), to deal in the Software without
  15. # restriction, including without limitation the rights to use,
  16. # copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. # copies of the Software, and to permit persons to whom the
  18. # Software is furnished to do so, subject to the following
  19. # conditions:
  20. #
  21. # The above copyright notice and this permission notice shall be
  22. # included in all copies or substantial portions of the Software.
  23. #
  24. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  26. # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  28. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  29. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  30. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  31. # OTHER DEALINGS IN THE SOFTWARE.
  32.  
  33. import os
  34. import sys
  35. import glob
  36. import re
  37. import fileinput
  38. import subprocess
  39. from optparse import OptionParser
  40.  
  41. """
  42. Installation guide for Linux
  43. ----------------------------
  44.  
  45. Install the following software:
  46. - Mono (mono-runtime)
  47. - Python3
  48.  
  49. Create a folder /home/user/bin
  50. to create your own bin dir for executable files: (this step is not needed for all distros)
  51. * Create the dir:
  52.    mkdir ~/bin
  53. * To add a directory to your PATH, add
  54.    #my own executable files
  55.    PATH=$PATH:$HOME/bin
  56.  to your .bashrc file
  57.  
  58. Put the files awescript.py, srr.exe and srs.exe in ~/bin
  59. http://pastebin.com/JMWKZqTt (version that always stores paths in the srr)
  60.  
  61. Create a file "awescript" with the following content:
  62.  
  63. #!/bin/sh
  64. /usr/bin/python3.2 ~/bin/awescript.py "$1"
  65.  
  66. Do "whereis python" in the terminal to find out the path of you python installation if needed.
  67. Do "chmod u+x awescript" to change the permissions.
  68.  
  69. In awescript.py change this:
  70.    path_to_srs = "mono /usr/local/bin/srs.exe"
  71.    path_to_srr = "mono /usr/local/bin/srr.exe"
  72. to this:
  73.    path_to_srs = "mono /home/user/bin/srs.exe"
  74.    path_to_srr = "mono /home/user/bin/srr.exe"
  75.        
  76. Type "awescript --help" in any path in your terminal.
  77.  
  78. awescript -R . --srr-dir=~/srrs
  79. """
  80.  
  81. #TODO: ask for updated version/what features are requested
  82.  
  83. # This version always creates a .srr file with the -p option: paths will be stored.
  84.  
  85. #better handling of srs-dir and srr-dir - i.e. remove meta=DIREECTORY and just os.path.normalize it
  86.  
  87. #allow rarfix to be srr'd, skip unrar
  88.  
  89. #allow multiple main_files and loop each (for sfv's with multiple rar sets)
  90. #   will have to delete sfv files after unrar is done for all
  91. # ------ currently works for subs sfv's with multiple rar sets... will screw up if non-scene sfv has 2+ sets that aren't subs
  92.  
  93. #add option to never unrar compressed subtyp files
  94.  
  95. #add option to unrar/delete subs
  96.  
  97. #add error logging to a file
  98.  
  99. #add sfv check option
  100.  
  101. #parse existing srs/srr files and see if need to make new ones or use/rename existing!
  102. # srs -l
  103. # - look for .avi .mkv .divx
  104. # srr -l
  105. # - look for .srs .nfo .sfv and main rar sets
  106. # only delete srs in the filelist, bypassing DeleteFiles hardcoded
  107.  
  108. #need to make sure there's enough space to extract?
  109.  
  110. #replace unrar lb code with rar header detection code - avoid external programs at all times :)
  111.  
  112. #if sfv found and no rar - do a recursive check from that dir.
  113.  
  114. #if unrar runs and is okay, move subs/sample/etc to unrar_dir
  115.  
  116. #add support to ignore *.1.par2/sfv/rar files that par2 or alt.binz doesn't delete
  117. # - could cause alt.binz to execute before subs/sample downloaded though
  118.  
  119. #CJ| is gay
  120.  
  121.  
  122.  
  123. if(os.name == "nt"):
  124.     path_to_srs = "srs"
  125.     path_to_srr = "srr"
  126. else:
  127.     path_to_srs = "mono /usr/local/bin/srs.exe"
  128.     path_to_srr = "mono /usr/local/bin/srr.exe"
  129. path_to_unrar = "unrar"
  130.  
  131. overwrite_existing_subs = 1
  132.  
  133. overwrite_existing_samples = 1
  134.  
  135.  
  136.  
  137. def get_files(path, cwdsolo):
  138.    
  139.     sfvList = []
  140.     fileList = []
  141.     fileMainList = []
  142.     blackList = []
  143.     sets_in_main = 0
  144.    
  145.     fileList = glob.glob("*.*")
  146.    
  147.     #for file in fileList:
  148.     #    print(file)
  149.     #exit()
  150.     for root,dirs,files in os.walk(path):
  151.         base = os.path.relpath(root) + slash
  152.         if base == "."+slash: base = ""
  153.         for d in dirs:
  154.             fileList += glob.glob(base + d + slash + "*.*")
  155.     fileList.sort()
  156.    
  157.     #move sfv files to top of list
  158.     for file in fileList:
  159.         if re.search("\.sfv$", file, re.IGNORECASE):
  160.             sfvList.append(file)
  161.             fileList.remove(file)
  162.    
  163.     fileList = sfvList + fileList
  164.    
  165.     for file in fileList:
  166.         add = True
  167.         folder = ""
  168.         main_file = ""
  169.         main_files = []
  170.         sfv = ""
  171.         fset = []
  172.         typ = ""
  173.         subtyp = ""
  174.         dest = ""
  175.         sr_dir = "" #dir to store path for srs or srr that was created for fileset
  176.         part_fix = False
  177.        
  178.         (folder,filename) = os.path.split(file)
  179.         if folder: folder += slash
  180.        
  181.         if not re.search("\.(avi|mkv|divx|ogm|mpg|part0?0?1\.rar|00[0-1]|vob|m2ts|sfv|srs|srr)$", filename, re.IGNORECASE):
  182.             if not (re.search("\.rar$", filename, re.IGNORECASE) and not re.search("\.part\d{2,3}\.rar$", filename, re.IGNORECASE)):
  183.                 continue
  184.             if re.search("\.part[2-9]\.rar$", filename, re.IGNORECASE):
  185.                 basename = filename.split(".rar",1)[0]
  186.                 if not os.path.exists(folder + basename + ".r00"):
  187.                     continue
  188.                 part_fix = True
  189.        
  190.         #SFV Detection
  191.         if re.search("\.sfv$", filename, re.IGNORECASE):
  192.             sfv = filename
  193.             missingList = []
  194.             for line in fileinput.input([folder+filename]):
  195.                 line = line.strip()
  196.                 if not len(line) < 10 and not line[0:1] == ";":
  197.                     f = line[:-9]
  198.                    
  199.                     if not os.path.exists(folder + f):
  200.                         if re.search("\.(rar|[rs0-9][0-9][0-9])$", f, re.IGNORECASE):
  201.                             missingList.append(f)
  202.                         continue
  203.                    
  204.                     if re.search("\.part0?0?1\.rar$", f, re.IGNORECASE) or (re.search("\.(rar|00[0-1])$", f, re.IGNORECASE) and not re.search("\.part\d{1,3}\.rar$", f, re.IGNORECASE)):
  205.                         if main_file:
  206.                             blackList.append(f)
  207.                         else:
  208.                             main_file = f
  209.                         main_files.append(f)
  210.                     elif re.search("\.part[2-9]\.rar$", f, re.IGNORECASE):
  211.                         if os.path.exists(folder + f.split(".rar",1)[0] + ".r00"):
  212.                             if main_file:
  213.                                 blackList.append(f)
  214.                             else:
  215.                                 main_file = f
  216.                             main_files.append(f)
  217.                     if re.search("\.(rar|[rs0-9][0-9][0-9])$", f, re.IGNORECASE):
  218.                         fset.append(f)
  219.             #
  220.             #multi-rar sets subs fix
  221.             #
  222.             #if len(main_files) > 1:
  223.             #    for i in range(len(main_files)-1):
  224.             #        blackList.append(main_files[i])
  225.             #fset.append(sfv)
  226.             if len(missingList) > 0:
  227.                 cont = False
  228.                 print("Files missing from " + filename + ":\n " + str(missingList)) #str(missingList) +
  229.                 for miss in missingList:
  230.                     if re.search("\.(avi|divx|mkv|ogm|mpg)$", miss, re.IGNORECASE):
  231.                         print("SFV contains missing video file.  Skipping instead of quitting.")
  232.                         cont = True
  233.                         break
  234.                     elif re.search("\.(nfo|par2)$", miss, re.IGNORECASE):
  235.                         print("SFV contains MISC files.  Non-Scene SFV.")
  236.                         cont = True
  237.                         break
  238.                     elif re.search("(sub.*|-s)\.rar", miss, re.IGNORECASE) and len(missingList) <= 2:
  239.                         print("Subs files from SFV missing.")
  240.                         cont = True
  241.                         break
  242.                 if cont: continue
  243.                 if main_file: blackList.append(f)
  244.                 return []
  245.            
  246.             if not main_file: continue #sfv was probably corrupt
  247.        
  248.        
  249.         if not main_file:
  250.             main_file = filename
  251.        
  252.         #Look inside RAR and get types (i.e. AVI,MKV,SUBS)
  253.         if re.search("\.(rar|00[0-1])$", main_file, re.IGNORECASE):
  254.            
  255.             if blackList.count(main_file): continue
  256.             if os.path.exists(folder + main_file.split(".001",1)[0] + ".000"):
  257.                 continue #split files - not RARs
  258.            
  259.             for i in range(len(fileMainList)):
  260.                 if fileMainList[i][1].lower() == main_file.lower():
  261.                     add = False
  262.                     break #RAR file added by SFV, skip
  263.             if not add: continue
  264.            
  265.             if len(fset) == 0: #NO SFV!
  266.                 print("no sfv for %s" % main_file)
  267.                 fset = glob.glob(wildc(folder, main_file))
  268.                 for i in range(len(fset)):
  269.                     fset[i] = fset[i].rsplit(slash)[-1:][0] #remove path, keeping only filename
  270.                 #print(fset)
  271.            
  272.             if len(fset) >= 2:
  273.                 #print(fset)
  274.                 fset.sort() #Fixes when SFV set is out of order (i.e. RAR file at top in .r## set
  275.                 if os.path.getsize(folder+fset[len(fset)-1]) == os.path.getsize(folder+fset[len(fset)-2]):
  276.                     print("%s is the same size as %s.  Incomplete set." % (folder+fset[len(fset)-1],folder+fset[len(fset)-2]))
  277.                     #continue
  278.                     return []
  279.                 else: #since last 2 aren't same size, we must have last rar to check for missing!
  280.                     numRARs = 0
  281.                     if re.search("\.part(\d{1,3})\.rar$", fset[len(fset)-1], re.IGNORECASE):
  282.                         numRARs = int(re.search("\.part(\d{1,3})\.rar$", fset[len(fset)-1], re.IGNORECASE).groups()[0])
  283.                     elif re.search("\.s(\d{2})$", fset[len(fset)-2], re.IGNORECASE):
  284.                         numRARs = int(re.search("\.s(\d{2})$", fset[len(fset)-2], re.IGNORECASE).groups()[0])
  285.                         numRARs += 101
  286.                     elif re.search("\.r(\d{2})$", fset[len(fset)-2], re.IGNORECASE):
  287.                         numRARs = int(re.search("\.r(\d{2})$", fset[len(fset)-2], re.IGNORECASE).groups()[0])
  288.                         numRARs += 2
  289.                     elif re.search("\.(\d{3})$", fset[len(fset)-1], re.IGNORECASE):
  290.                         numRARs = int(re.search("\.(\d{3})$", fset[len(fset)-1], re.IGNORECASE).groups()[0])
  291.                         if re.search("\.(rar|000)$", main_file, re.IGNORECASE):
  292.                             numRARs += 1
  293.                     #else: return []
  294.  
  295.                     if numRARs != 0:
  296.                         if len(fset) != numRARs:
  297.                             print("Files missing from RAR set.  Quitting.")
  298.                             return []
  299.                         #else: #check for RARs with wrong size - exit if 2+ have different size.
  300.                         #    fileSize = os.path.getsize(folder+fset[0])
  301.                         #    diffFiles = 0
  302.                         #    for f in fset:
  303.                         #        if os.path.getsize(folder+f) != fileSize:
  304.                         #            diffFiles += 1
  305.                         #        if diffFiles == 2:
  306.                         #            print("2 or more files in the RAR set are a different size.  Set is bad.  Quitting.")
  307.                         #            return []
  308.        
  309.             output = ""
  310.             proc = subprocess.Popen("%s lb \"%s%s\"" % (path_to_unrar,folder,main_file), shell=True, stdout=subprocess.PIPE)
  311.             std = str(proc.communicate()[0]).lstrip("b'").rstrip("'")
  312.             if std:
  313.                 if os.name == "nt":
  314.                     output = std.split(r"\r\n")
  315.                 else:
  316.                     output = std.split(r"\n")
  317.             elif len(output) == 0 and re.search("\.(avi|divx|mkv|ogm|mpg)\.00[0-1]$", main_file, re.IGNORECASE):
  318.                 #if os.path.exists(folder + main_file.split(".001",1)[0] + ".000"):
  319.                 #    main_file = main_file.split(".001",1)[0] + ".000"
  320.                 print("%s is a joined file." % main_file)
  321.                 typ = "Video"
  322.                 subtyp = "Joined"
  323.                 #wild = glob.glob(wildc(folder,main_file)).sort()
  324.                 #continue
  325.             else:
  326.                 print("%s could be corrupt?" % main_file)
  327.                 continue
  328.            
  329.             if re.search("extra", main_file, re.IGNORECASE):
  330.                 subtyp = "Extras"
  331.                 if not re.search("extra", cwdsolo, re.IGNORECASE):
  332.                     dest = "Extras" + slash
  333.            
  334.             #
  335.             #need to check if already in a folder and use that
  336.             #
  337.             for s in output: #could be multiple files in the rar
  338.                 if not s: continue #for blanks at the end from splitting \r\n or \n
  339.                 if re.search("\.(avi|divx|mkv|ogm|mka|dts|ac3|mpg|mp3|ogg)$", s, re.IGNORECASE):
  340.                     typ = "Video"
  341.                     if not folder: sets_in_main += 1 #i.e. not in CD[1-9], so may need to move
  342.                 elif re.search("\.(iso|img|nrg|bin|gcm|cdi|dvd|gi)$", s, re.IGNORECASE):
  343.                     typ = "ISO"
  344.                     subtyp = "Compressed"
  345.                 else:
  346.                     #print("Unkown files in RAR %s or corrupt." % main_file)
  347.                     continue
  348.                 break
  349.             if not typ:
  350.                 for s in output: #could be multiple files in the rar
  351.                     if not s: continue #for blanks at the end from splitting \r\n or \n
  352.                     if re.search("\.(srt|sub|idx|rar)$", s, re.IGNORECASE):
  353.                         if re.search("vob.?sub", main_file, re.IGNORECASE):
  354.                             typ = "VobSubs"
  355.                             if not folder:
  356.                                 dest = "VobSubs"+slash
  357.                         else:
  358.                             typ = "Subs"
  359.                             if not folder:
  360.                                 dest = "Subs"+slash
  361.                         if subtyp == "Extras" and not re.search("extra", cwdsolo, re.IGNORECASE):
  362.                             if not folder: dest = "Extras" + slash + dest
  363.                         break
  364.             if not typ: typ = "Other"
  365.        
  366.         #Check for Video files NOT in RAR files - i.e. samples or previously extracted video        
  367.         elif re.search("\.(avi|mkv|vob|m2ts)$", main_file, re.IGNORECASE):
  368.            
  369.             if re.search("extra", main_file, re.IGNORECASE):
  370.                 subtyp = "Extras"
  371.             #check if sample
  372.             if re.search("sample", folder, re.IGNORECASE) or is_sample(folder + main_file):
  373.                 if re.search("\.vob$", main_file, re.IGNORECASE):
  374.                     typ = "VobSample"
  375.                     if not folder:
  376.                         dest = "VobSample"+slash
  377.                 elif re.search("\.m2ts$", main_file, re.IGNORECASE):
  378.                     typ = "m2tsSample"
  379.                     if not folder:
  380.                         dest = "Sample"+slash
  381.                 else:
  382.                     typ = "Sample"
  383.                     if not folder:
  384.                         dest = "Sample"+slash
  385.                 if subtyp == "Extras" and not re.search("extra", cwdsolo, re.IGNORECASE):
  386.                     if not folder:
  387.                         dest = "Extras" + slash + dest
  388.             else:
  389.                 #not a sample, add as extracted video
  390.                 typ = "Video"
  391.                 subtyp = "Extracted"
  392.                 if not folder: sets_in_main += 1 #i.e. not in CD[1-9], so may need to move
  393.                 #continue
  394.        
  395.         elif re.search("\.nfo$", main_file, re.IGNORECASE):
  396.             typ = "Other"
  397.             subtyp = "NFO"
  398.        
  399.         elif re.search("\.srs$", main_file, re.IGNORECASE):
  400.             if re.search("extra", main_file, re.IGNORECASE):
  401.                 subtyp = "Extras_SRS"
  402.                 if not folder:
  403.                     dest = "Extras"+slash + "Sample"+slash
  404.             else:
  405.                 subtyp = "SRS"
  406.                 if not folder:
  407.                     dest = "Sample"+slash
  408.             typ = "Sample"
  409.        
  410.         elif re.search("\.srr$", main_file, re.IGNORECASE):
  411.             typ = "Other"
  412.             subtyp = "SRR"
  413.        
  414.         if len(fset) == 0: fset.append(main_file)
  415.         #if dest and options.unrar_dir: dest = options.unrar_dir.rstrip(slash) + slash + dest
  416.        
  417.         fileMainList.append([folder,main_file,sfv,fset,typ,subtyp,dest,sr_dir])
  418.    
  419.    
  420.     #Detect CD folders - skip if folder has TV tags
  421.     if sets_in_main >= 2 and not re.search("([\._\s]s?\d{1,3}[\._\s]?[ex]\d{1,3}|s\d{1,3})", cwdsolo, re.IGNORECASE): #2 or more CDs possible
  422.         fileMainList = get_cds(fileMainList)
  423.    
  424.    
  425.     return fileMainList
  426.  
  427.  
  428.  
  429. def is_sample(video):
  430.     max_size     =  50000000
  431.     if re.search("\.mkv$", video, re.IGNORECASE):
  432.         max_size = 250000000
  433.    
  434.     if re.search("^.*?([\.\-_\w]?sa?mp).*?\.(?:avi|mkv|m2ts|vob)$", video, re.IGNORECASE):
  435.         if os.path.getsize(video) < max_size: return True
  436.     else: #no s?mp in filename - reduce filesize limits manually
  437.         if re.search("\.(avi|mkv|vob|m2ts)$", video, re.IGNORECASE) and os.path.getsize(video) < max_size / 2:
  438.             return True
  439.    
  440.     return False
  441.  
  442.  
  443.  
  444. def only_samples(files):
  445.     sample = False
  446.     for file in files:
  447.         if file[4] == "Video":
  448.             return False
  449.         elif file[4] == "Sample":
  450.             sample = True
  451.     return sample
  452.  
  453.  
  454.  
  455. def get_cds(fileMainList):
  456.     global slash
  457.     #folder,main_file,sfv,fset,typ,dest
  458.     fileList = fileMainList
  459.  
  460.     fileListNew = []
  461.     position = False
  462.     for i in range(len(fileList)):
  463.         if fileList[i][4] != "Video": continue
  464.         fileListTemp = []
  465.         file = fileList[i][1]
  466.         posTemp = 0
  467.        
  468.         if re.search("(s\d{1,3}[\._]?e\d{1,3})", file, re.IGNORECASE): continue #TV Test (file) - MAKE THIS FOR DIR
  469.         for j in range(len(fileList)):
  470.             if i == j: continue # i <= j ?  since they've already been compared once?
  471.             if fileList[j][4] != "Video": continue
  472.             file2 = fileList[j][1]
  473.             if re.search("(s\d{1,3}[\._]?e\d{1,3})", file2, re.IGNORECASE): continue #TV Test (file2)
  474.             if len(file) == len(file2):
  475.                 diff = 0
  476.                 for k in range(len(file)):
  477.                     if file[k] != file2[k]:
  478.                         diff += 1
  479.                         if diff > 1: break
  480.                         if posTemp:
  481.                             if k != posTemp:
  482.                                 #Can't compute differences for CDs.  Skipping.
  483.                                 continue
  484.                         posTemp = k
  485.                         #print(file)
  486.                 if diff == 1: fileListTemp.append(j)
  487.         if len(fileListTemp) > len(fileListNew):
  488.             fileListNew = fileListTemp
  489.             fileListNew.append(i)
  490.             position = posTemp
  491.     fileListNew.sort()
  492.    
  493.     if len(fileListNew) <= 1: return fileMainList
  494.     print("CDs: Detected!")
  495.  
  496.     diff = 99
  497.    
  498.     for i in fileListNew:
  499.         file = fileMainList[i][1]
  500.         char = file[position]
  501.         if re.match("^([1-9])$", char):
  502.             cd = char
  503.         elif re.match("^([A-Fa-f])$", char):
  504.             if char == "a": cd = "1"
  505.             elif char == "b": cd = "2"
  506.             elif char == "c": cd = "3"
  507.             elif char == "d": cd = "4"
  508.             elif char == "e": cd = "5"
  509.             elif char == "f": cd = "6"
  510.         else:
  511.             print(file + " is NOT a cd, subs?")
  512.             continue
  513.        
  514.         #fix for releases with only parts 3/4 but pre as CD1/CD2 (separate release with 1/2)
  515.         if diff == 99:
  516.             if int(cd) == 1:
  517.                 diff = 0
  518.             else: #assume it's sorted and just didn't start at 1
  519.                 diff = int(cd) - 1
  520.         cd = str(int(cd) - diff)
  521.         print(file + " is CD" + cd)
  522.        
  523.         #get/make directory
  524.         fileMainList[i][6] = "CD" + cd + slash
  525.         if re.search("\.(rar|00[0-1])$", file, re.IGNORECASE):
  526.             fileMainList[i][5] = "CD"
  527.         else:
  528.             fileMainList[i][5] = "Extracted_CD"
  529.  
  530.    
  531.     return fileMainList
  532.  
  533.  
  534.  
  535. def wildc(folder,file):
  536.     global slash
  537.     if not os.path.exists(folder+file): return False
  538.    
  539.     basename = False
  540.     wildcard = False
  541.     if re.search("\.(part01\.rar)$", file, re.IGNORECASE):
  542.         ext = re.search("\.(part01\.rar)$", file, re.IGNORECASE).groups()[0]
  543.         wildcard = ".[Pp][Aa][Rr][Tt][0-9][0-9].[Rr][Aa][Rr]"
  544.     elif re.search("\.(part001\.rar)$", file, re.IGNORECASE):
  545.         ext = re.search("\.(part001\.rar)$", file, re.IGNORECASE).groups()[0]
  546.         wildcard = ".[Pp][Aa][Rr][Tt][0-9][0-9][0-9].[Rr][Aa][Rr]"
  547.     elif re.search("\.(rar)$", file, re.IGNORECASE):
  548.         if re.search("\.(part1\.rar)$", file, re.IGNORECASE):
  549.             filename = folder + file.split(".rar",1)[0]+".r00".replace("[", "[[]")
  550.             if os.path.exists(filename):
  551.                 ext = re.search("\.(part1\.rar)$", file, re.IGNORECASE).groups()[0]
  552.                 wildcard = ".[Pp][Aa][Rr][Tt]1.[Rr]??"
  553.             else:
  554.                 ext = re.search("\.(part1\.rar)$", file, re.IGNORECASE).groups()[0]
  555.                 wildcard = ".[Pp][Aa][Rr][Tt][0-9].[Rr][Aa][Rr]"
  556.         else:
  557.             ext = re.search("\.(rar)$", file, re.IGNORECASE).groups()[0]
  558.             wildcard = ".[Rr]??"
  559.     elif re.search(".(00[0-1])$", file, re.IGNORECASE):
  560.         ext = re.search("\.(00[0-1])$", file, re.IGNORECASE).groups()[0]
  561.         wildcard = ".[0-9][0-9][0-9]"
  562.     else: return False
  563.    
  564.     basename = file.split("."+ext,1)[0].replace("[", "[[]")
  565.    
  566.        
  567.     return folder + basename + wildcard
  568.  
  569.  
  570.  
  571. def move_files(files, options, cwdsolo):
  572.     global slash
  573.    
  574.     if options.move_subs:
  575.         files = move(files, "Subs", "", True, options.debug)
  576.         files = move(files, "VobSubs", "", True, options.debug)
  577.         if options.move_extras:
  578.             files = move(files, "Subs", "Extras", True, options.debug)
  579.             files = move(files, "VobSubs", "Extras", True, options.debug)
  580.    
  581.     if options.move_samples and not (options.delete_samples and options.delete_srs_after_srr):
  582.         if not only_samples(files):
  583.             files = move(files, "Sample", "", True, options.debug)
  584.             if not options.srs_dir:
  585.                 files = move(files, "Sample", "SRS", True, options.debug)
  586.             if options.move_extras:
  587.                 files = move(files, "Sample", "Extras", True, options.debug)
  588.                 if not options.srs_dir:
  589.                     files = move(files, "Sample", "Extras_SRS", True, options.debug)
  590.         else:
  591.             print("Only samples found, not moving.")
  592.    
  593.     if options.move_samples:
  594.         files = move(files, "VobSample", "", True, options.debug)
  595.         files = move(files, "m2tsSample", "", True, options.debug)
  596.         if options.move_extras:
  597.             files = move(files, "VobSample", "Extras", True, options.debug)
  598.             files = move(files, "m2tsSample", "Extras", True, options.debug)
  599.    
  600.     if options.move_cds and not options.delete_rars:
  601.         #print("Moving RAR sets to CD1-N folders.")
  602.         files = move(files, "Video", "CD", True, options.debug)
  603.         if options.move_cds_extracted:
  604.             print("Moving previously extracted video files to CD1-N folders.")
  605.             files = move(files, "Video", "Extracted_CD", True, options.debug)
  606.    
  607.     if options.move_extras:
  608.         files = move(files, "Video", "Extras", True, options.debug)
  609.         files = move(files, "Other", "Extras", True, options.debug)
  610.    
  611.     return files
  612.  
  613.  
  614.  
  615. def move(files, typ, subtyp, overwrite, debug):
  616.     global slash
  617.  
  618.     for i in range(len(files)):
  619.         if files[i][4] != typ or files[i][5] != subtyp or not files[i][6]: continue
  620.        
  621.         file = files[i]
  622.         ok = True
  623.         fset = file[3]
  624.         dest = file[6]
  625.  
  626.         if not os.path.isdir(dest):
  627.             if debug:
  628.                 print("mkdir %s" % dest)
  629.             else:
  630.                 os.makedirs(dest)
  631.             #directory = ""
  632.             #for d in dest.rstrip(slash).split(slash):
  633.             #    directory += d + slash
  634.             #    if not os.path.isdir(directory):
  635.             #        os.mkdir(directory)
  636.        
  637.         if file[2]:#sfv
  638.             fset.append(file[2])
  639.         for f in fset:
  640.             if not os.path.isfile(f): continue
  641.             try:
  642.                 if os.path.isfile(dest+f):
  643.                     if overwrite:
  644.                         if debug:
  645.                             print("remove %s%s to overwrite." % (dest,f))
  646.                         else:
  647.                             os.remove(dest+f)
  648.                     else:
  649.                         if os.path.isfile(dest+"copy.of."+f):
  650.                             if debug:
  651.                                 print("remove %scopy.of.%s to make new copy." %(dest,f))
  652.                             else:
  653.                                 os.remove(dest+"copy.of."+f)
  654.                         if debug:
  655.                             print("rename  %s%s to %scopy.of.%s" (dest,f,dest,f))
  656.                         else:
  657.                             os.rename(dest+f,dest+"copy.of."+f)
  658.                 if debug:
  659.                     print("rename %s to %s%s" % (f,dest,f))
  660.                 else:
  661.                     os.rename(f, dest+f)
  662.             except OSError:
  663.                 ok = False
  664.        
  665.         if ok:
  666.             file[0] = dest #folder = dest
  667.             file[6] = "" #unrar_dir.rstrip(slash) + slash
  668.             files[i] = file
  669.    
  670.     return files
  671.  
  672.  
  673.  
  674. #move full directories post-extraction if unrar_dir set?
  675. def move_dir(file):
  676.     global slash
  677.    
  678.    
  679.    
  680.     return file
  681.  
  682.  
  683.  
  684. def srs_srr(files, options, cwdsolo):
  685.     global slash
  686.    
  687.     code = 0
  688.    
  689.     if options.create_srs:
  690.         code, files = srs(files, options, cwdsolo) #create srs
  691.    
  692.     if options.create_srr: #if srs fails, so be it?
  693.         code, files = srr(files, options, cwdsolo, False) #False to not ignore Extras.  if fail, ignore Extras and try again
  694.    
  695.     if code == 0 and options.create_srr and (options.delete_srs_after_srr and options.include_srs_in_srr):
  696.         if options.debug:
  697.             print("remove *.srs")
  698.         else:
  699.             deleteFiles(["*.srs","*[Ss][Aa][Mm][Pp][Ll][Ee]*/*.srs"], "Re-Sample (SRS)", None, False) #delete *.srs
  700.    
  701.     return code, files
  702.  
  703.  
  704.  
  705. def srs(files, options, cwdsolo):
  706.     global slash, path_to_srs
  707.    
  708.     code = -1
  709.     filesToAdd = []
  710.     onlySamples = only_samples(files)
  711.    
  712.     for i in range(len(files)):
  713.         if files[i][4] != "Sample" or files[i][5] == "SRS" or files[i][5] == "Extras_SRS": continue
  714.         cmd = path_to_srs
  715.         folder = files[i][0]
  716.         file = files[i][1]
  717.         srs_file = file[:-3]+"srs"
  718.        
  719.         if options.srs_namep:
  720.             srs_file = cwdsolo+".srs"
  721.         try:
  722.             cmd += " \"" + folder+file + "\""
  723.             #cmd += opts
  724.             cmd += " -o \""
  725.             if options.srs_dir:
  726.                 if os.path.exists(options.srs_dir):
  727.                     folder = options.srs_dir.rstrip(slash) + slash
  728.                 else: #create srs_dir
  729.                     if os.makedirs(options.srs_dir):
  730.                         folder = options.srs_dir.rstrip(slash) + slash
  731.                         print("SRS directory %s created." % options.srs_dir)
  732.                     else:
  733.                         print("SRS directory %s could not be created.  SRS will default to release directory." % options.srs_dir)
  734.  
  735.             if os.path.isfile(folder+srs_file) and os.path.getsize(folder+srs_file) > 0:
  736.                 print("SRS file exists, skipping %s" % srs_file)
  737.                 code = 0
  738.                 continue
  739.            
  740.             cmd += folder+srs_file + "\""
  741.             print(cmd)
  742.             if options.debug:
  743.                 code = 0
  744.             else:
  745.                 code = os.system(cmd)
  746.            
  747.             if code == 2:
  748.                 print("SRS: Sample file \"%s\" is bad." % file)
  749.                 code = -1
  750.             elif code == 0:
  751.                 files[i][7] = srs_file
  752.                 if files[i][5] == "Extras":
  753.                     subtyp = "Extras_SRS"
  754.                 else:
  755.                     subtyp = "SRS"
  756.                 filesToAdd.append([folder, srs_file, "", [srs_file], "Sample", subtyp, ""])
  757.                 if options.delete_samples and not onlySamples:
  758.                     if options.debug:
  759.                         print("delete %s%s" % (folder,file))
  760.                     else:
  761.                         deleteFiles([folder+file], "AVI Sample", None, False)
  762.             else:
  763.                 print("Error with SRS.")
  764.                 code = -1
  765.         except OSError:
  766.             print("SRS: Error running SRS.")
  767.             return -1, files
  768.    
  769.     files += filesToAdd
  770.    
  771.     return code, files
  772.  
  773.  
  774.  
  775. def srr(files, options, cwdsolo, ignore_extras):
  776.     global slash, path_to_srr
  777.  
  778.     cmd = path_to_srr
  779.     code = -1
  780.     srrNum = 0
  781.     dest = ""
  782.     srr_file = cwdsolo+".srr"
  783.     joined = False
  784.     extras = False
  785.    
  786.     if options.srr_dir:
  787.         if os.path.exists(options.srr_dir):
  788.             dest = options.srr_dir
  789.         else: #create srr_dir
  790.             if os.makedirs(options.srr_dir):
  791.                 dest = options.srr_dir
  792.                 print("SRR directory %s created." % options.srr_dir)
  793.             else:
  794.                 print("SRR directory %s could not be created.  SRR will default to release directory." % options.srr_dir)
  795.     elif options.unrar_dir:
  796.         if not os.path.exists(options.unrar_dir):
  797.             if options.debug:
  798.                 print("mkdir %s" % options.unrar_dir)
  799.                 dest = options.unrar_dir
  800.             elif os.makedirs(options.unrar_dir):
  801.                 dest = options.unrar_dir
  802.         else:
  803.             dest = options.unrar_dir
  804.    
  805.     for file in files:
  806.         if file[4] != "Video" or file[5] == "Extracted" or file[5] == "Extracted_CD" or file[5] == "Compressed": continue
  807.         if file[5] == "Joined":
  808.             joined = True
  809.             continue
  810.         if file[5] == "Extras":
  811.             extras = True
  812.         #if subtyp and file[5] != subtyp: continue
  813.         folder = file[0]
  814.         if file[2]: file = file[2] #sfv
  815.         elif file[1]: file = file[1] #rar
  816.         else: continue
  817.         cmd += " \"" + folder+file + "\""
  818.         srrNum += 1
  819.    
  820.     if joined and srrNum == 0: return 1, files
  821.     elif srrNum == 0: return 1, files
  822.    
  823.     cmd += " -s" #-s include files below (at least *.nfo)
  824.    
  825.     if options.include_srs_in_srr:
  826.         for file in files:
  827.             if file[4] == "Sample" and (file[5] == "SRS" or file[5] == "Extras_SRS"):
  828.                 cmd += " \"%s%s\"" % (file[0],file[1])
  829.     cmd += " *.nfo"
  830.    
  831.     if dest and os.path.isdir(dest):
  832.         cmd += " -o \"%s%s%s\"" % (dest.rstrip(slash),slash,srr_file)
  833.     else:
  834.         cmd += " -o \"%s\"" % srr_file
  835.  
  836.     # we will always do paths when creating the srr file
  837.     cmd += " -p"
  838.  
  839.     try:
  840.         print(cmd)
  841.         if options.debug:
  842.             code = 0
  843.         else:
  844.             code = os.system(cmd)
  845.             print(code)
  846.         if code == 3 or code == 768: #3 for windows, 768 for linux ; compressed RARs
  847.             if extras == True and ignore_extras == False:
  848.                 print("SRR: RARs are compressed.  Re-Trying without Extras.")
  849.                 code, files = srr(files, options, cwdsolo, True)
  850.             else:
  851.                 print("SRR: RARs are compressed.  Continuing like normal, ignoring srs deletion")
  852.             return code, files
  853.         elif code != 0:
  854.             print("SRR: Re-Scene failed.  Skipping the rest.")
  855.             return -1, files
  856.         else:
  857.             return 0, files
  858.     except OSError:
  859.         print("SRR: Error running SRR.")
  860.         return -1, files
  861.    
  862.     return -1, files
  863.  
  864.  
  865. def unrar(files, options, code):
  866.     global slash, path_to_unrar
  867.     #options.unrar_dir, options.extract_to_main_dir, options.delete_rars, options.delete_sfv
  868.     #[folder,main_file,sfv,fset,typ,subtyp,dest]
  869.    
  870.     if not options.extract_rars or code == -1:
  871.         return code, files
  872.    
  873.     maincmd = "%s x -o+ -p-" % path_to_unrar
  874.     if(os.name == "nt"):
  875.         joincmd = "copy /b"
  876.     else:
  877.         joincmd = "cat"
  878.    
  879.     for fileset in files:
  880.         if (fileset[4] != "Video" and fileset[4] != "ISO") or fileset[5] == "Extracted": continue #typ
  881.        
  882.         folder = fileset[0]
  883.         file = fileset[1] #name.rar
  884.         sfv  = fileset[2]
  885.         fset = fileset[3]
  886.         if folder and (not options.extract_to_main_dir or fileset[5] == "Extras"):
  887.             if options.unrar_dir:
  888.                 dest = options.unrar_dir.rstrip(slash) + slash + folder
  889.             else:
  890.                 dest = folder
  891.         else:
  892.             if options.unrar_dir:
  893.                 dest = options.unrar_dir.rstrip(slash) + slash
  894.             else:
  895.                 dest = "."+slash
  896.        
  897.         try:
  898.             #input file
  899.             if fileset[5] != "Joined":
  900.                 cmd = maincmd
  901.                 cmd += " \"" + folder+file + "\""
  902.             else:
  903.                 cmd = joincmd+" "
  904.                 for i in range(len(fset)):
  905.                     cmd += "\"%s\"" % fset[i]
  906.                     if i+1 != len(fset):
  907.                         if(os.name == "nt"):
  908.                             cmd += "+"
  909.                         else:
  910.                             cmd += " "
  911.                 if(os.name != "nt"):
  912.                     cmd += " >"
  913.                 dest = dest+file[:-4]
  914.            
  915.             cmd += " \"" + dest + "\""
  916.            
  917.             print(cmd)
  918.             if options.debug:
  919.                 code = 0
  920.             else:
  921.                 code = os.system(cmd)
  922.            
  923.             if code != 0:
  924.                 print("UnRAR failed.  Skipping the rest.")
  925.                 return -1, files
  926.             elif options.delete_rars:
  927.                 for f in fset:
  928.                     try:
  929.                         if options.debug:
  930.                             print("remove %s%s" % (folder,f))
  931.                         else:
  932.                             os.remove(folder+f)
  933.                     except OSError:
  934.                         print("Error trying to remove %s%s" % (folder,f))
  935.                 print("UnRAR: %s RAR files that were processed have been removed." % folder)
  936.             if options.delete_sfv and sfv:
  937.                 try:
  938.                     if options.debug:
  939.                         print("remove %s%s" % (folder,sfv))
  940.                     else:
  941.                         os.remove(folder+sfv)
  942.                         print("UnRAR: %s%s removed." % (folder,sfv))
  943.                 except OSError:
  944.                     print("UnRAR: Error trying to remove %s%s" % (folder,sfv))
  945.                    
  946.         except OSError:
  947.             print("Error trying to unrar.")
  948.             return -1, files
  949.  
  950.         except KeyboardInterrupt:
  951.             print("\nUnRAR was interrupted by user.  Exiting")
  952.             sys.exit()
  953.    
  954.    
  955.     return code, files
  956.  
  957.  
  958.  
  959. def cleanup(files, options, code):
  960.     global slash
  961.    
  962.     if options.delete_par2 and not (code != 0 and options.extract_rars):
  963.         deleteFiles(["*.[Pp][Aa][Rr]2"], "PAR2", None, options.debug)
  964.     deleteFiles(["*.[Nn][Zz][Bb]"], "NZB", None, options.debug)
  965.    
  966.     #need to delete empty folders
  967.     deleteDirectories(["*[Cc][Dd][1-9]*/","*[Ss][Aa][Mm][Pp][Ll][Ee]*/"], options.debug)
  968.    
  969.    
  970.    
  971.     return
  972.  
  973.  
  974.  
  975. def deleteFiles(wildcards, word, ignoreList, debug):
  976.     fileList = []
  977.     for wc in wildcards:
  978.         fileList += glob.glob(wc)
  979.    
  980.     if len(fileList) == 0:
  981.         print("No %s files to delete." % word)
  982.         return 0
  983.    
  984.     for file in fileList:
  985.         cont = True
  986.         if ignoreList:
  987.             for ignore in ignoreList:
  988.                 if file == ignore:
  989.                     ignoreList.remove(ignore)
  990.                     cont = False
  991.                     break
  992.         if cont:
  993.             try:
  994.                 if debug:
  995.                     print("remove %s" % file)
  996.                 else:
  997.                     os.remove(file)
  998.                     print("%s deleted." % file)
  999.             except OSError:
  1000.                 print("Error trying to remove %s" % file)
  1001.                 return -1
  1002.  
  1003.     return 0
  1004.  
  1005.  
  1006.  
  1007. def deleteDirectories(wildcards, debug):
  1008.     dirs = []
  1009.     for wc in wildcards:
  1010.         dirs += glob.glob(wc)
  1011.     for directory in dirs:
  1012.         if not os.listdir(directory):
  1013.             try:
  1014.                 if debug:
  1015.                     print("rmdir %s" % directory)
  1016.                 else:
  1017.                     os.rmdir(directory)
  1018.                     print("%s was empty and removed." % directory)
  1019.             except OSError:
  1020.                 print("%s was empty but could not be removed." % directory)
  1021.    
  1022.     return
  1023.  
  1024.  
  1025.  
  1026. def main(options, path):
  1027.     global origcwd, cwd, slash
  1028.  
  1029.     if options.exit_if_par2_exists: #altbinz mode - fix for altbinz sending lowercase dirname
  1030.         for p in glob.glob(os.path.normpath(os.path.join(path, '..'))+slash+"*"):
  1031.             if path.lower() == p.lower() or path.lower() == p.lower()[2:]:
  1032.                 os.chdir(p)
  1033.                 break
  1034.     else:
  1035.         os.chdir(path)
  1036.     cwd = os.getcwd()
  1037.     cwdsolo = os.path.split(cwd)[-1]
  1038.    
  1039.     if options.exit_if_par2_exists:
  1040.         if len(glob.glob("*.par2")) > 0:
  1041.             print("PAR2 files exist.  Exiting...")
  1042.             sys.exit()
  1043.    
  1044.     if re.search("(subpack|sub.?fix|subs\.)", cwdsolo, re.IGNORECASE):
  1045.         print("SUBS directory detected.  Not processing.")
  1046.         return
  1047.     elif re.search("(sync.?fix)", cwdsolo, re.IGNORECASE):
  1048.         print("SYNCFiX directory detected.  Not processing.")
  1049.         return
  1050.     elif re.search("(sample.?fix)", cwdsolo, re.IGNORECASE):
  1051.         print("SAMPLEFiX directory detected.  Not processing.")
  1052.         return
  1053.    
  1054.    
  1055.     print("\nProcessing: %s\n" % cwd)
  1056.    
  1057.     files = get_files(cwd, cwdsolo)
  1058.     if len(files) == 0:
  1059.         #print("No files to process.")
  1060.         return
  1061.    
  1062.     #debug
  1063.     if options.debug: #or options.verbose
  1064.         print("\nFiles:\n[folder, filename, sfv, file_list, type, subtype, destination_dir, rescene_dir]\n")
  1065.         for i in range(len(files)):
  1066.             print(str(i+1) + ": " + str(files[i]) + "\n")
  1067.         print("")
  1068.    
  1069.     code = 1
  1070.    
  1071.     files = move_files(files, options, cwdsolo)
  1072.    
  1073.     code, files = srs_srr(files, options, cwdsolo)
  1074.    
  1075.     code, files = unrar(files, options, code)
  1076.    
  1077.     cleanup(files, options, code)
  1078.    
  1079.    
  1080.     return
  1081.  
  1082.  
  1083.  
  1084. if __name__ == '__main__':
  1085.     usage = "usage: %prog -<option 1> -<option N> <@listdirs...>"
  1086.     version = "%prog 0.5b"
  1087.     parser = OptionParser(usage=usage, version=version)
  1088.     parser.add_option("--altbinz", dest="exit_if_par2_exists", action="store_true", default=False,
  1089.                       help="Alt.Binz mode: exit if par2 exists in directory.  Fixes multiple execution issues.")
  1090.    
  1091.     parser.add_option("-R", dest="recursive", action="store_true", default=False,
  1092.                       help="Recursively walk through directories looking for releases and processing each.")
  1093.    
  1094.     parser.add_option("--no-srr", dest="create_srr", action="store_false", default=True,
  1095.                       help="Do not create Re-Scene (SRR) files for RAR sets.")
  1096.     parser.add_option("--no-srs", dest="create_srs", action="store_false", default=True,
  1097.                       help="Do not create Re-Sample (SRS) files for AVI/MKV Samples.")
  1098.     parser.add_option("--separate-srs-srr", dest="include_srs_in_srr", action="store_false", default=True,
  1099.                       help="Do not include SRS files in SRR.  This implies --keep-srs.")
  1100.     parser.add_option("--keep-srs", dest="delete_srs_after_srr", action="store_false", default=True,
  1101.                       help="Do not delete SRS files that are stored in the SRR.")
  1102.     parser.add_option("--srs-namep", dest="srs_namep", action="store_true", default=False,
  1103.                       help="Rename SRS after release name instead of sample name.")
  1104.     parser.add_option("--srs-dir", dest="srs_dir", action="store", default=False,
  1105.                       metavar="DIR",
  1106.                       help="Directory to move SRS files to in case you keep them all in one directory.")
  1107.     parser.add_option("--srr-dir", dest="srr_dir", action="store", default=False,
  1108.                       metavar="DIR",
  1109.                       help="Directory to move SRR files to in case you keep them all in one directory.")
  1110.    
  1111.     parser.add_option("-f", "--filter", dest="filters", action="store", default=["xvid","divx","x264","h264"],
  1112.                       help="List of filters for input directory.  If it doesn't match it will skip.  DOES NOT CURRENTLY WORK!")
  1113.    
  1114.     parser.add_option("--ignore-cds", dest="move_cds", action="store_false", default=True,
  1115.                       help="Do not move rar sets to CD1-N folders.")
  1116.     parser.add_option("--move-extracted-cds", dest="move_cds_extracted", action="store_true", default=False,
  1117.                       help="Move already extracted video files to CD1-N folders.")
  1118.     parser.add_option("--ignore-extras", dest="move_extras", action="store_false", default=True,
  1119.                       help="Do not move EXTRAS to Extras folder.")
  1120.     parser.add_option("--ignore-subs", dest="move_subs", action="store_false", default=True,
  1121.                       help="Do not move subs to Subs directory.")
  1122.     parser.add_option("-i", "--ignore-sample", dest="move_samples", action="store_false", default=True,
  1123.                       help="Do not move sample(s) to Sample directory.")
  1124.     parser.add_option("-d", "--delete-sample", dest="delete_samples", action="store_true", default=False,
  1125.                       help="Delete samples.  Recommended to keep SRS creation enabled (on by default).")
  1126.    
  1127.     parser.add_option("-e", "--extract", dest="extract_rars", action="store_true", default=False,
  1128.                       help="Extract RAR sets.  Specify directory with -u \"dir\" or -m for main directory.")
  1129.     parser.add_option("-u", "--unrar-dir", dest="unrar_dir", action="store",
  1130.                       help="Directory to UnRAR files.  Will unRAR in place if not specified.", metavar="\"DIRECTORY\"")
  1131.     parser.add_option("-m", "--extract-to-main-dir", dest="extract_to_main_dir", action="store_true", default=False,
  1132.                       help="UnRAR to input directory if RAR files are in separate folders within (i.e. CD1/CD2).")
  1133.     parser.add_option("-r", "--delete-rars", dest="delete_rars", action="store_true", default=False,
  1134.                       help="Delete RAR files after successful UnRAR.  You should probably enable SFV deletion with this.")
  1135.    
  1136.     parser.add_option("-s", "--delete-sfv", dest="delete_sfv", action="store_true", default=False,
  1137.                       help="Delete SFV files when done.  Will not delete if UnRAR fails.")
  1138.     parser.add_option("-p", "--delete-par2", dest="delete_par2", action="store_true", default=False,
  1139.                       help="Delete PAR2 files when done.  Will not delete if UnRAR fails.")
  1140.     parser.add_option("-z", "--keep-nzb", dest="delete_nzb", action="store_false", default=True,
  1141.                       help="Do not delete NZB files.")
  1142.    
  1143.     parser.add_option("--debug", dest="debug", action="store_true", default=False,
  1144.                       help="Only list what the program would do.  Will not move, unrar, etc.")
  1145.    
  1146.     (options, args) = parser.parse_args()
  1147.    
  1148.     if len(args) == 0:
  1149.         parser.print_help()
  1150.         sys.exit()
  1151.    
  1152.     if options.extract_to_main_dir and not options.extract_rars: options.extract_rars = True
  1153.     if options.unrar_dir: options.unrar_dir = os.path.abspath(options.unrar_dir)
  1154.    
  1155.     globals()["origcwd"] = os.getcwd()
  1156.     sys.path.append(globals()["origcwd"])
  1157.    
  1158.     if os.name == "nt":
  1159.         globals()["slash"] = "\\"
  1160.     else: globals()["slash"] = "/"
  1161.    
  1162.     for path in args:
  1163.         #file = open(r"E:\DOWNLOAD\xvid.txt", 'a')
  1164.         #file.write(path + '\n')
  1165.         #file.write(str(options.unrar_dir) + '\n')
  1166.         #file.write('\n')
  1167.         #file.close()
  1168.        
  1169.         os.chdir(globals()["origcwd"])
  1170.        
  1171.         if not os.path.isdir(path):
  1172.             print("Argument %s is not a valid directory." % path)
  1173.             continue
  1174.        
  1175.         if not options.recursive:
  1176.             main(options, path)
  1177.         else:
  1178.             #recursive
  1179.             current = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
  1180.             for root,dirs,files in os.walk(path):
  1181.                 found = False
  1182.                 if current in root: continue
  1183.                 for file in files:
  1184.                     if re.search("\.(rar|00[0-1]|avi|mkv|ogm|divx|mpg)$", file):
  1185.                         found = True
  1186.                         break
  1187.                 if not found:
  1188.                     for directory in dirs:
  1189.                         if re.match("^cd[1-9]$", directory, re.IGNORECASE):
  1190.                             found = True
  1191.                             break
  1192.                 if found:
  1193.                     current = root
  1194.                     main(options, root)
  1195.                     os.chdir(origcwd)
  1196.                    
  1197.             print("\n\n\nDone with %s directory.\n\n" % path)