Adds an optional API field to follow the filenaming format when creating a bulk download zip

This commit is contained in:
Trenton Holmes
2022-11-19 17:37:32 -08:00
committed by Trenton H
parent ff4a8b37bd
commit 54bb1ae27d
5 changed files with 181 additions and 11 deletions

View File

@@ -1,18 +1,29 @@
import os
from zipfile import ZipFile
from documents.models import Document
class BulkArchiveStrategy:
def __init__(self, zipf: ZipFile):
def __init__(self, zipf: ZipFile, follow_formatting: bool = False):
self.zipf = zipf
if follow_formatting:
self.make_unique_filename = self._formatted_filepath
else:
self.make_unique_filename = self._filename_only
def make_unique_filename(
def _filename_only(
self,
doc: Document,
archive: bool = False,
folder: str = "",
):
"""
Constructs a unique name for the given document to be used inside the
zip file.
The filename might not be unique enough, so a counter is appended if needed
"""
counter = 0
while True:
filename = folder + doc.get_public_filename(archive, counter)
@@ -21,6 +32,25 @@ class BulkArchiveStrategy:
else:
return filename
def _formatted_filepath(
self,
doc: Document,
archive: bool = False,
folder: str = "",
):
"""
Constructs a full file path for the given document to be used inside
the zipfile.
The path is already unique, as handled when a document is consumed or updated
"""
if archive and doc.has_archive_version:
in_archive_path = os.path.join(folder, doc.archive_filename)
else:
in_archive_path = os.path.join(folder, doc.filename)
return in_archive_path
def add_document(self, doc: Document):
raise NotImplementedError() # pragma: no cover
@@ -31,9 +61,6 @@ class OriginalsOnlyStrategy(BulkArchiveStrategy):
class ArchiveOnlyStrategy(BulkArchiveStrategy):
def __init__(self, zipf):
super().__init__(zipf)
def add_document(self, doc: Document):
if doc.has_archive_version:
self.zipf.write(