Advertisement
Gfy

nzb_sample_extract.py

Gfy
Jan 18th, 2012
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.67 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: latin-1 -*-
  3.  
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program.  If not, see <http://www.gnu.org/licenses/>
  16.  
  17. """ Only leave everything related to the samples in the NZB file.
  18. This are the .avi or .mkv files and sometimes par2 files. No new file
  19. will be created if there is no sample data.
  20.  
  21. python nzb_sample_extract.py file1.nzb dir/file2.nzb
  22. will create file1.nzb and file2.nzb with less data in ./samples in the
  23. directory of file1.nzb and dir/file2.nzb respectively.
  24.  
  25. python nzb_sample_extract.py /home/user/nzbdir -o /home/user/samples
  26. sets one output directory.
  27.  
  28. Changelog:
  29. ----------
  30.  
  31. 0.1 (2011-12-24)
  32. - Initial version
  33. 0.2 (2012-01-18)
  34. - Made the regex more strict
  35. - A bit more documentation
  36. 0.3 (2012-01-23)
  37. - Added option for VOB samples
  38. - Refactoring bug fixed
  39. - Made the regex more strict
  40. - Option to limit the maximum size
  41. """
  42.  
  43. import os
  44. import sys
  45. import optparse
  46. import re
  47. import unittest
  48.  
  49. # for running the script directly from command line
  50. sys.path.append(os.path.join(os.path.dirname(
  51.                 os.path.realpath(sys.argv[0])), '..', 'rescene'))
  52.  
  53. try:
  54.     import nzb_utils
  55. except ImportError:
  56.     print("Can't import the nzb_utils module.")
  57.    
  58. def is_sample(file_name, is_vobsample=False):
  59.     MATCH_SAMPLE = ".*(\.avi|\.mkv)((\.vol\d+\+\d+)?.par2)?$"
  60.     MATCH_VOBSAMPLE = ".*(\.vob)((\.vol\d+\+\d+)?.par2)?$"
  61.  
  62.     if is_vobsample:
  63.         match = MATCH_VOBSAMPLE
  64.     else:
  65.         match = MATCH_SAMPLE
  66.            
  67.     return re.match(match, file_name.lower())
  68.    
  69. def extract_sample(nzb_file, output_dir):
  70.     sample_nzb = nzb_utils.empty_nzb_document()
  71.     sample_found = False
  72.    
  73.     for file in nzb_utils.read_nzb(nzb_file):
  74.         file_name = nzb_utils.parse_name(file.subject)
  75.    
  76.         if is_sample(file_name, options.vobsample):
  77.             if int(options.max_size) > 0: # we need to check the size
  78.                 size = sum([seg.bytes for seg in file.segments])
  79.                 if int(options.max_size) < size:
  80.                     continue # not a sample, skip it
  81.             sample_found = True
  82.             nzb_utils.add_file(sample_nzb, file)
  83.  
  84.     if sample_found:
  85.         snzb_file = os.path.join(output_dir, os.path.basename(nzb_file))
  86.         try:
  87.             os.makedirs(os.path.dirname(snzb_file))
  88.         except:
  89.             pass
  90.         with open(snzb_file, "w") as sample:
  91.             sample.write(nzb_utils.get_xml(sample_nzb))
  92.    
  93. def main(options, args):
  94.     def check_file(file):
  95.         if file[-4:].lower() == ".nzb":
  96.             if options.output_dir:
  97.                 output_dir = options.output_dir
  98.             else:
  99.                 output_dir = os.path.join(os.path.dirname(file), "samples")
  100.             extract_sample(file, output_dir)
  101.    
  102.     for element in args:
  103.         if os.path.isdir(element):
  104.             for file in os.listdir(element):
  105.                 check_file(file)
  106.         elif os.path.isfile(element):
  107.             check_file(element)
  108.         else:
  109.             print("Only existing files or directories are accepted.")
  110.            
  111. class TestRegex(unittest.TestCase):
  112.     """ Code to test the correctness of the sample detection. """
  113.     def test_avi_in_name(self):
  114.         avi = ("[1080]-[FULL]-[#a.b.foreign@EFNet]-[ UCL.2010-2011.Play-Offs."
  115.             "Salzburg.vs.Tel.Aviv.DUTCH.WS.PDTV.XviD-iFH ]-[03/97] \"ucl."
  116.             "2010.2011.playoffs.salzburg.tel.aviv-ifh.r00\" yEnc (1/61)")
  117.        
  118.         file_name = nzb_utils.parse_name(avi)
  119.         self.assertEqual(file_name,
  120.                         "ucl.2010.2011.playoffs.salzburg.tel.aviv-ifh.r00")
  121.         self.assertFalse(is_sample(file_name), "detected as sample")
  122.        
  123.        
  124. if __name__ == '__main__':
  125.     parser = optparse.OptionParser(
  126.         usage="Usage: %prog [directories] [NZBs] [options]'\n"
  127.         "This tool will create new NZB files with only the sample "
  128.         "related data in the 'samples' subdir.\n",
  129.         version="%prog 0.2 (2012-01-18)") # --help, --version
  130.  
  131.     parser.add_option("-o", dest="output_dir", metavar="DIRECTORY",
  132.                     help="moves the new NZB files to DIRECTORY and a "
  133.                     "'samples' subfolder will be used if not specified")
  134.     parser.add_option("-v", "--vobsample", dest="vobsample",
  135.                     help="only create NZBs for vobsamples",
  136.                     action="store_true")
  137.     parser.add_option("-s", dest="max_size", metavar="SIZE", default=-1,
  138.                     help="the sample can be max SIZE bytes large")
  139.    
  140.     # no arguments given
  141.     if len(sys.argv) < 2:
  142.         print(parser.format_help())
  143.     else:
  144.         (options, args) = parser.parse_args()
  145.         main(options, args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement