Source code for s365b.core.zipstream
"""Write a ZIP archive as a stream, for downloads of many files.
The archive is produced while it is sent: nothing is held in memory but
the piece being written, so a download of thousands of messages starts at
once. Python's :mod:`zipfile` writes to a stream it cannot seek by putting
each file's sizes after its data (ZIP64 where needed).
"""
from __future__ import annotations
import zipfile
from collections.abc import AsyncIterator, Iterable
from datetime import datetime
from s365b.modules.sdk import ExportFile
[docs]
CHUNK = 1 << 20 # send at least this much at a time
class _Sink:
"""A write-only file that collects bytes until they are taken."""
def __init__(self) -> None:
"""Start empty."""
self.parts: list[bytes] = []
self.size = 0
def write(self, data: bytes) -> int:
"""Keep a piece; return its length."""
self.parts.append(bytes(data))
self.size += len(data)
return len(data)
def flush(self) -> None:
"""Nothing to flush: :meth:`take` hands the bytes on."""
def close(self) -> None:
"""Nothing to close."""
def take(self) -> bytes:
"""Return what was written since the last call."""
data = b"".join(self.parts)
self.parts, self.size = [], 0
return data
[docs]
async def zip_stream(files: Iterable[ExportFile], when: datetime) -> AsyncIterator[bytes]:
"""Yield a ZIP archive of files, compressed, as it is written.
Args:
files: The files; their paths use ``/`` between folders.
when: Modification time recorded for every file.
Yields:
Pieces of the archive.
"""
sink = _Sink()
stamp = (max(when.year, 1980), when.month, when.day, when.hour, when.minute, when.second)
with zipfile.ZipFile(sink, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for f in files:
info = zipfile.ZipInfo(f.path, date_time=stamp)
info.compress_type = zipfile.ZIP_DEFLATED
with archive.open(info, "w", force_zip64=True) as out:
if isinstance(f.content, bytes):
out.write(f.content)
else:
async for piece in f.content:
out.write(piece)
if sink.size >= CHUNK:
yield sink.take()
if sink.size >= CHUNK:
yield sink.take()
yield sink.take()