archive_1.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. def extract_archive(filepath):
  2. """
  3. Returns the path of the archive
  4. :param str filepath: Path to file to extract or read
  5. :return: path of the archive
  6. :rtype: str
  7. """
  8. # Checks if file path is a directory
  9. if os.path.isdir(filepath):
  10. path = os.path.abspath(filepath)
  11. print("Archive already extracted. Viewing from {}...".format(path))
  12. return path
  13. # Checks if the filepath is a zipfile and continues to extract if it is
  14. # if not it raises an error
  15. elif not zipfile.is_zipfile(filepath):
  16. # Misuse of TypeError? :P
  17. raise TypeError("{} is not a zipfile".format(filepath))
  18. archive_sha = SHA1_file(
  19. filepath=filepath,
  20. # Add version of slackviewer to hash as well so we can invalidate the cached copy
  21. # if there are new features added
  22. extra=to_bytes(slackviewer.__version__)
  23. )
  24. extracted_path = os.path.join(SLACKVIEWER_TEMP_PATH, archive_sha)
  25. if os.path.exists(extracted_path):
  26. print("{} already exists".format(extracted_path))
  27. else:
  28. # Extract zip
  29. with zipfile.ZipFile(filepath) as zip:
  30. print("{} extracting to {}...".format(filepath, extracted_path))
  31. zip.extractall(path=extracted_path)
  32. print("{} extracted to {}".format(filepath, extracted_path))
  33. # Add additional file with archive info
  34. create_archive_info(filepath, extracted_path, archive_sha)
  35. return extracted_path