unzipper.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import zipfile,os.path
  2. import subprocess
  3. USE_UNRAR=True
  4. def unar(source,dest_dir):
  5. if source.lower().endswith("zip"):
  6. return unzip(source,dest_dir)
  7. if source.lower().endswith("rar"):
  8. return unrar(source,dest_dir)
  9. print("NOT RAR? NOT ZIP? I'm panicking.")
  10. print("I got %s" % source)
  11. return [source]
  12. def unzip(source_filename, dest_dir):
  13. out=[]
  14. with zipfile.ZipFile(source_filename) as zf:
  15. for member in zf.infolist():
  16. # Path traversal defense copied from
  17. # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
  18. words = member.filename.split('/')
  19. path = dest_dir
  20. for word in words[:-1]:
  21. drive, word = os.path.splitdrive(word)
  22. head, word = os.path.split(word)
  23. if word in (os.curdir, os.pardir, ''): continue
  24. path = os.path.join(path, word)
  25. out.append(os.path.join(path,member.filename.split('/')[-1]))
  26. zf.extract(member, path)
  27. return out
  28. def unrar(source, dest_dir):
  29. out=[]
  30. list_files=[]
  31. extract_files=[]
  32. if USE_UNRAR:
  33. list_files=["unrar","lb",source]
  34. extract_files=["unrar","x","-o+",source,dest_dir]
  35. else:
  36. list_files=["lsar",source]
  37. extract_files=["unar","-f","-o",dest_dir,source]
  38. with subprocess.Popen(list_files, stdout=subprocess.PIPE) as proc:
  39. out=proc.stdout.read().decode('utf-8').split("\n")
  40. if out[0].endswith(": RAR"):
  41. del out[0] #header
  42. if len(out[-1])==0:
  43. del out[-1]
  44. #print(out)
  45. subprocess.run(extract_files,stdout=subprocess.DEVNULL)
  46. return [os.path.join(dest_dir,file) for file in out ]