Make _check_zip_data() and _adopt_media_changes_from_zip() take a ZipFile

This commit is contained in:
flan 2017-11-04 18:16:39 +01:00
parent 0e5bbf4f9e
commit 978b1d7371

View File

@ -114,9 +114,9 @@ class SyncMediaHandler(anki.sync.MediaSyncer):
yet ('dirty'), and info on files it has deleted from its own media dir. yet ('dirty'), and info on files it has deleted from its own media dir.
""" """
self._check_zip_data(data) with zipfile.ZipFile(BytesIO(data), "r") as z:
self._check_zip_data(z)
processed_count = self._adopt_media_changes_from_zip(data) processed_count = self._adopt_media_changes_from_zip(z)
# We increment our lastUsn once for each file we processed. # We increment our lastUsn once for each file we processed.
# (lastUsn - processed_count) must equal the client's lastUsn. # (lastUsn - processed_count) must equal the client's lastUsn.
@ -129,19 +129,13 @@ class SyncMediaHandler(anki.sync.MediaSyncer):
} }
@staticmethod @staticmethod
def _check_zip_data(zip_data): def _check_zip_data(zip_file):
max_zip_size = 100*1024*1024 max_zip_size = 100*1024*1024
max_meta_file_size = 100000 max_meta_file_size = 100000
file_buffer = BytesIO(zip_data)
zip_file = zipfile.ZipFile(file_buffer, 'r')
meta_file_size = zip_file.getinfo("_meta").file_size meta_file_size = zip_file.getinfo("_meta").file_size
sum_file_sizes = sum(info.file_size for info in zip_file.infolist()) sum_file_sizes = sum(info.file_size for info in zip_file.infolist())
zip_file.close()
file_buffer.close()
if meta_file_size > max_meta_file_size: if meta_file_size > max_meta_file_size:
raise ValueError("Zip file's metadata file is larger than %s " raise ValueError("Zip file's metadata file is larger than %s "
"Bytes." % max_meta_file_size) "Bytes." % max_meta_file_size)
@ -149,15 +143,12 @@ class SyncMediaHandler(anki.sync.MediaSyncer):
raise ValueError("Zip file contents are larger than %s Bytes." % raise ValueError("Zip file contents are larger than %s Bytes." %
max_zip_size) max_zip_size)
def _adopt_media_changes_from_zip(self, zip_data): def _adopt_media_changes_from_zip(self, zip_file):
""" """
Adds and removes files to/from the database and media directory Adds and removes files to/from the database and media directory
according to the data in zip file zipData. according to the data in zip file zipData.
""" """
file_buffer = BytesIO(zip_data)
zip_file = zipfile.ZipFile(file_buffer, 'r')
# Get meta info first. # Get meta info first.
meta = json.loads(zip_file.read("_meta").decode()) meta = json.loads(zip_file.read("_meta").decode())