unzipper.py 1.5 KB

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