From c2842694ce355d3081eeeef9db5aaeb10f7c85b9 Mon Sep 17 00:00:00 2001 From: Carey Metcalfe Date: Mon, 15 Nov 2021 10:03:02 -0500 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=20Provide=20a=20content-length=20for?= =?UTF-8?q?=20streaming=20zip=20downloads=20(#4313)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This allows browsers and other clients to calculate download progress and detect if the download fails (they get less data than expected). This is most useful when downloading multiple timelapses due to their potential size. Also fixes an oversight where the printer's firmware wasn't being added to `systeminfo.txt` when downloading system info. --- AUTHORS.md | 1 + THIRDPARTYLICENSES.md | 1 + setup.py | 2 +- src/octoprint/cli/systeminfo.py | 58 +++++++++++----------------- src/octoprint/server/util/tornado.py | 32 +++++++-------- 5 files changed, 42 insertions(+), 52 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index 104016aa3..211070883 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -154,6 +154,7 @@ date of first contribution): * [Bryan Kenote](https://github.com/bryankenote) * [Quinn Damerell](https://github.com/QuinnDamerell) * [Sven Samoray](https://github.com/thelastWallE) + * [Carey Metcalfe](https://github.com/pR0Ps) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 6b72d4639..befd536a7 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -74,6 +74,7 @@ * [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0 * [websocket-client](https://github.com/liris/websocket-client): LGPLv3 * [wrapt](http://wrapt.readthedocs.org/): BSD + * [zipstream-ng](https://github.com/pR0Ps/zipstream-ng): LGPLv3 ## Development (testing, documentation generation, etc) diff --git a/setup.py b/setup.py index 27299c386..39e27cfdf 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ INSTALL_REQUIRES = [ "sentry-sdk>=0.15.1,<1", "filetype>=1.0.7,<2", "zeroconf>=0.33,<0.34", - "zipstream-new>=1.1.8,<1.2", + "zipstream-ng>=1.3.1,<2.0.0", "pathvalidate>=2.4.1,<3", "colorlog>=5.0.1,<6", # vendor bundled dependencies diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index f069120c9..bb08c31f5 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -6,7 +6,7 @@ import logging import os import click -import zipstream +from zipstream.ng import ZIP_DEFLATED, ZipStream from octoprint.cli import init_platform_for_cli, standard_options @@ -42,39 +42,28 @@ def get_systeminfo(environment_detector, connectivity_checker, additional_fields def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None): from octoprint.util import to_bytes + try: + z = ZipStream(compress_type=ZIP_DEFLATED) + except RuntimeError: + # no zlib support + z = ZipStream(sized=True) + + if printer and printer.is_operational(): + firmware_info = printer.firmware_info + if firmware_info: + # add firmware to systeminfo so it's included in systeminfo.txt + systeminfo["printer.firmware"] = firmware_info["name"] + + # Add printer log, if available + if hasattr(printer, "_log"): + z.add(to_bytes("\n".join(printer._log)), "terminal.txt") + + # add systeminfo systeminfotxt = [] for k in sorted(systeminfo.keys()): systeminfotxt.append("{}: {}".format(k, systeminfo[k])) - terminaltxt = None - if printer and printer.is_operational(): - firmware_info = printer.firmware_info - if firmware_info: - systeminfo["printer.firmware"] = firmware_info["name"] - - if hasattr(printer, "_log"): - terminaltxt = list(printer._log) - - try: - import zlib # noqa: F401 - - compress_type = zipstream.ZIP_DEFLATED - except ImportError: - # no zlib, no compression - compress_type = zipstream.ZIP_STORED - - z = zipstream.ZipFile() - - # add systeminfo - z.writestr( - "systeminfo.txt", to_bytes("\n".join(systeminfotxt)), compress_type=compress_type - ) - - # add terminal.txt, if available - if terminaltxt: - z.writestr( - "terminal.txt", to_bytes("\n".join(terminaltxt)), compress_type=compress_type - ) + z.add(to_bytes("\n".join(systeminfotxt)), arcname="systeminfo.txt") # add logs for log in ( @@ -83,7 +72,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None ): logpath = os.path.join(logbase, log) if os.path.exists(logpath): - z.write(logpath, arcname=log, compress_type=compress_type) + z.add_path(logpath, arcname=log) # add additional bundle contents from bundled plugins if plugin_manager: @@ -103,10 +92,10 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None if isinstance(content, str): # log path if os.path.exists(content) and os.access(content, os.R_OK): - z.write(content, arcname=log, compress_type=compress_type) + z.add_path(content, arcname=log) elif callable(content): # content generating callable - z.writestr(log, to_bytes(content()), compress_type=compress_type) + z.add(to_bytes(content()), arcname=log) except Exception: logging.getLogger(__name__).exception( "Error while retrieving additional bundle contents for plugin {}".format( @@ -170,8 +159,7 @@ def systeminfo_command(ctx, path, **kwargs): ) try: with open(zipfilename, "wb") as f: - for data in z: - f.write(data) + f.writelines(z) except Exception as e: click.echo(str(e), err=True) click.echo(f"There was an error writing to {zipfilename}.", err=True) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 5ac68d3f5..78fe36402 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -20,6 +20,7 @@ import tornado.iostream import tornado.tcpserver import tornado.util import tornado.web +from zipstream.ng import ZIP_DEFLATED, ZipStream import octoprint.util @@ -1434,32 +1435,28 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): f'attachment; filename="{self.get_attachment_name()}"', ) - import zipstream - - compress_type = zipstream.ZIP_STORED + z = ZipStream(sized=True) if self._compress: try: - import zlib # noqa: F401 - - compress_type = zipstream.ZIP_DEFLATED - except ImportError: - # no zlib, no compression + z = ZipStream(compress_type=ZIP_DEFLATED) + except RuntimeError: + # no zlib support pass - z = zipstream.ZipFile() for f in self.normalize_files(files): # noinspection PyCompatibility name = f.get("name") path = f.get("path") - iter = f.get("iter") - content = f.get("content") + data = f.get("iter") or f.get("content") if path: - z.write(path, arcname=name, compress_type=compress_type) - elif iter and name: - z.write_iter(name, iter, compress_type=compress_type) - elif content and name: - z.writestr(name, content, compress_type=compress_type) + z.add_path(path, arcname=name) + elif data and name: + z.add(data, arcname=name) + + if z.sized: + self.set_header("Content-Length", len(z)) + self.set_header("Last-Modified", z.last_modified) for chunk in z: try: @@ -1582,6 +1579,9 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): "Content-Disposition", f'attachment; filename="{get_systeminfo_bundle_name()}"', ) + if z.sized: + self.set_header("Content-Length", len(z)) + self.set_header("Last-Modified", z.last_modified) for chunk in z: try: