Created
June 5, 2019 01:01
-
-
Save ctkirkman/7d4d2c74f1424cbb51f5142347d20b08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
from io import BytesIO | |
from zipfile import ZipFile | |
from operator import itemgetter | |
def read_zip(contentBytes): | |
zip_metadata = dict() | |
file_list = None | |
errors = None | |
try: | |
zip_bytes = BytesIO(contentBytes) | |
zip_object = ZipFile(zip_bytes) | |
file_list = [read_zip_file(z, zip_object) for z in zip_object.filelist] | |
if len(file_list) > 30: | |
file_list = sorted(file_list, key=itemgetter("size"), reverse=True)[0:30] | |
file_list.append("(List Truncated)") | |
if file_list is not None: | |
zip_metadata["contents"] = file_list | |
except Exception as e: | |
if str(e).strip() != "": | |
errors = str(e).strip()[0:100] | |
finally: | |
if bool(zip_metadata) is True: | |
return zip_metadata | |
elif errors is not None: | |
return {"error": errors} | |
else: | |
return None | |
def read_zip_file(zip_file, zip_object): | |
zip_info = dict() | |
try: | |
zip_info["name"] = zip_file.filename[0:100] | |
if zip_file.is_dir() is False: | |
zip_info["size"] = zip_file.file_size | |
if bool(zip_file.flag_bits & 0x1) is True: | |
zip_info["protected"] = True | |
else: | |
try: | |
zip_file_bytes = zip_object.read(zip_file.filename) | |
zip_info["md5"] = hashlib.md5(zip_file_bytes).hexdigest() | |
zip_info["sha1"] = hashlib.sha1(zip_file_bytes).hexdigest() | |
except Exception as e: | |
zip_info["error"] = str(e).strip()[0:100] | |
pass | |
finally: | |
return zip_info |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment