diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 42bbe0aa2..149ee90b6 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -23,7 +23,7 @@ from octoprint.server.util.flask import ( no_firstrun_access, with_revalidation_checking, ) -from octoprint.util import count, utmify +from octoprint.util import count, deserialize, serialize, utmify from octoprint.util.text import sanitize @@ -428,12 +428,22 @@ class AnnouncementPlugin( ttl *= 60 now = time.time() - if os.stat(channel_path).st_mtime + ttl > now: - d = feedparser.parse(channel_path) + if now > os.stat(channel_path).st_mtime + ttl: + return None + + try: + d = deserialize(channel_path) self._logger.debug(f"Loaded channel {key} from cache at {channel_path}") return d - - return None + except Exception: + self._logger.exception( + f"Could not read channel {key} from cache {channel_path}" + ) + try: + os.remove(channel_path) + except OSError: + pass + return None def _get_channel_data_from_network(self, key, config): """Fetch channel feed from network.""" @@ -456,11 +466,12 @@ class AnnouncementPlugin( ) return None - response = r.text - channel_path = self._get_channel_cache_path(key) - with open(channel_path, mode="wt", encoding="utf-8") as f: - f.write(response) - return feedparser.parse(response) + response = feedparser.parse(r.text) + try: + serialize(self._get_channel_cache_path(key), response) + except Exception: + self._logger.exception(f"Failed to cache data for channel {key}") + return response def _to_internal_feed(self, feed, read_until=None): """Convert feed to internal data structure.""" diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 342bc5494..0ee114743 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -275,7 +275,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): try: additional = hook(initial=initial) if additional and isinstance(additional, dict): - octoprint.util.json.dump({name: additional}) + octoprint.util.json.dumps({name: additional}) plugin_data[name] = additional except ValueError: self._logger.exception( diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index f57283093..88bcacf94 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -24,7 +24,7 @@ from octoprint.access.permissions import Permissions from octoprint.access.users import LoginStatusListener from octoprint.events import Events from octoprint.settings import settings -from octoprint.util.json import dump as json_dump +from octoprint.util.json import dumps as json_dumps from octoprint.util.version import get_python_version_string @@ -65,7 +65,7 @@ class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session): class JsonEncodingSessionWrapper(wrapt.ObjectProxy): def send_message(self, msg, stats=True, binary=False): self.send_jsonified( - json_dump(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg)), + json_dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg)), stats, ) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 14a24c900..a5500b48b 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -11,7 +11,6 @@ import codecs import collections import contextlib import copy -import json import logging import os import pickle @@ -1712,9 +1711,13 @@ def serialize(filename, data, encoding="utf-8", compressed=True): """ Serializes data to a file - In the current implementation this uses json.dumps and - if compressed is True (the - default) - zlib.compress. Only data that can be serialized by json.dumps in the stock - configuration is supported. + In the current implementation this uses json.dumps. + + If `compressed` is True (the default), the serialized data put through zlib.compress. + + Supported data types are listed at the bottom of + :ref:`octoprint.util.comprehensive_json`, and include some data types that are not + supported by json.dumps by default. This is not thread-safe, if concurrent access is required, the caller needs to ensure that only one thread is writing to the file at any given time. @@ -1725,7 +1728,9 @@ def serialize(filename, data, encoding="utf-8", compressed=True): encoding (str): The encoding to use for the file compressed (bool): Whether to compress the data before writing it to the file """ - serialized = json.dumps(data).encode(encoding) + from octoprint.util import json + + serialized = json.serializing.dumps(data).encode(encoding) if compressed: serialized = zlib.compress(serialized) @@ -1756,4 +1761,6 @@ def deserialize(filename, encoding="utf-8"): except zlib.error: pass - return json.loads(serialized.decode(encoding)) + from octoprint.util import json + + return json.serializing.loads(serialized.decode(encoding)) diff --git a/src/octoprint/util/json/__init__.py b/src/octoprint/util/json/__init__.py index 0f1976392..6e011f529 100644 --- a/src/octoprint/util/json/__init__.py +++ b/src/octoprint/util/json/__init__.py @@ -1,46 +1,13 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" -__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" +from octoprint.util import deprecated -import collections -import json +from . import serializing # noqa: F401 +from .encoding import JsonEncoding, dumps, loads # noqa: F401 -from frozendict import frozendict - -from octoprint.util import to_unicode - - -def dump(obj): - return json.dumps( - obj, - separators=(",", ":"), - default=JsonEncoding.encode, - allow_nan=False, - ) - - -class JsonEncoding: - - encoders = collections.OrderedDict() - - @classmethod - def add_encoder(cls, type, encoder): - cls.encoders[type] = encoder - - @classmethod - def remove_encoder(cls, type): - try: - del cls.encoders[type] - except KeyError: - pass - - @classmethod - def encode(cls, obj): - for type, encoder in cls.encoders.items(): - if isinstance(obj, type): - return encoder(obj) - raise TypeError - - -JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj)) -JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj)) +dump = deprecated( + "dump has been renamed to dumps, please adjust your implementation", + includedoc="dump has been renamed to dumps", + since="1.8.0", +)(dumps) diff --git a/src/octoprint/util/json/encoding.py b/src/octoprint/util/json/encoding.py new file mode 100644 index 000000000..dc2fcc6ac --- /dev/null +++ b/src/octoprint/util/json/encoding.py @@ -0,0 +1,69 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import json +from collections import OrderedDict +from typing import Any, Callable, Dict + +try: + from typing import OrderedDict as OrderedDictType +except ImportError: + OrderedDictType = Dict # py3.7.{0,1} + +from frozendict import frozendict + +from octoprint.util import to_unicode + + +class JsonEncoding: + encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict() + + @classmethod + def add_encoder(cls, typ: type, encoder: Callable[[Any], Any]) -> None: + """ + Add an encoder for a type. + + :param typ: the type to add an encoder for + :param encoder: the encoder. Must take a single argument and return a + tuple (name, parameters...) + """ + cls.encoders[typ] = encoder + + @classmethod + def remove_encoder(cls, typ): + try: + del cls.encoders[typ] + except KeyError: + pass + + @classmethod + def dumps(cls, obj: Any) -> str: + """ + Dump an object to JSON, handles additional types that the JSON encoder can't, like + bytes and frozendicts. + """ + return json.dumps( + obj, + default=cls.encode, + separators=(",", ":"), + indent=None, + allow_nan=False, + ) + + @classmethod + def loads(cls, s: str) -> Any: + return json.loads(s) + + @classmethod + def encode(cls, obj): + for type, encoder in cls.encoders.items(): + if isinstance(obj, type): + return encoder(obj) + raise TypeError(f"Unserializable type {type(obj)}") + + +JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj)) +JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj)) + +dumps = JsonEncoding.dumps +loads = JsonEncoding.loads diff --git a/src/octoprint/util/json/serializing.py b/src/octoprint/util/json/serializing.py new file mode 100644 index 000000000..668bf4bd7 --- /dev/null +++ b/src/octoprint/util/json/serializing.py @@ -0,0 +1,158 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import base64 +import datetime +import json +import time +from collections import OrderedDict +from typing import Any, Callable, Dict, List + +try: + from typing import OrderedDict as OrderedDictType +except ImportError: + OrderedDictType = Dict # py3.7.{0,1} + +from frozendict import frozendict + +from .encoding import JsonEncoding + + +class SerializableJsonEncoding(JsonEncoding): + """ + A JSON encoding that can serialize and deserialize objects, including additional + objects otherwise not serializable by the standard JSON encoder: + + * ``bytes`` + * ``frozendict.frozendict`` + * ``datetime.datetime`` + * ``time.struct_time`` + """ + + encoders: OrderedDictType[type, Callable[[Any], Any]] = OrderedDict() + decoders: OrderedDictType[str, Callable[[dict], object]] = OrderedDict() + + @classmethod + def add_decoder(cls, classname, decoder): + cls.decoders[classname] = decoder + + @classmethod + def remove_decoder(cls, classname): + try: + del cls.decoders[classname] + except KeyError: + pass + + @classmethod + def dumps(cls, obj: Any) -> str: + return json.dumps( + cls.encode(obj), separators=(",", ":"), indent=None, allow_nan=False + ) + + @classmethod + def loads(cls, s: str) -> Any: + return json.loads(s, object_hook=cls.decode) + + @classmethod + def encode(cls, val): + """ + Recursively replace all instances of encodable types with their encoded + value. This is useful over the ``default=`` functionallity of the JSON + encoder because JSON will not call default for tuples, lists, ints, etc: + https://docs.python.org/3/library/json.html#json.JSONEncoder + + Cannot handle circular references. + """ + + if isinstance(val, tuple(cls.encoders.keys())): + # we can't directly index into the encoders dict because + # we need to be able to handle subclasses + encoder = next( + encoder for typ, encoder in cls.encoders.items() if isinstance(val, typ) + ) + return cls.encode(encoder(val)) + elif isinstance(val, dict): + return {k: cls.encode(v) for k, v in val.items()} + elif isinstance(val, (tuple, list)): + return [cls.encode(v) for v in val] + elif isinstance(val, (bool, int, float, str)) or val is None: + return val + else: + raise TypeError(f"Unserializable type {type(val)}") + + @classmethod + def decode(cls, dct): + """ + Recursively replace all instances of decodable types with their decoded + values. + + You'll want to have used ``class_encode()`` in your encoder to get this + to work properly. + """ + if "__jsonclass__" not in dct: + return dct + + if len(dct["__jsonclass__"]) == 0: + raise ValueError("__jsonclass__ must not be empty") + + decoded_name = dct["__jsonclass__"][0] + params = dct["__jsonclass__"][1:] + + for classname, decoder in cls.decoders.items(): + if decoded_name == classname: + return decoder(*params) + return dct + + +def class_encode(name: str, *params: Any) -> Dict[str, List]: + """ + Encode a class name and parameters into a serializable dict. You'll + probably want to use this if you're going to set a custom decoder. + + This stores the class names in a format inspired by the JSON-RPC spec at + https://www.jsonrpc.org/specification_v1#a3.JSONClasshinting + """ + return {"__jsonclass__": [name] + list(params)} + + +# frozendict + +SerializableJsonEncoding.add_encoder( + frozendict, lambda obj: class_encode("frozendict.frozendict", dict(obj)) +) +SerializableJsonEncoding.add_decoder("frozendict.frozendict", lambda obj: frozendict(obj)) + +# bytes + +SerializableJsonEncoding.add_encoder( + bytes, lambda obj: class_encode("bytes", base64.b85encode(obj).decode("ascii")) +) +SerializableJsonEncoding.add_decoder("bytes", lambda obj: base64.b85decode(obj)) + +# time.struct_time + + +def _struct_time_decoder(params): + if len(params) == 9 and all(isinstance(p, int) and p >= 0 for p in params): + return time.struct_time(params) + raise ValueError(f"Invalid time.struct_time params `{params}`") + + +SerializableJsonEncoding.add_encoder( + time.struct_time, lambda obj: class_encode("time.struct_time", list(obj)) +) +SerializableJsonEncoding.add_decoder("time.struct_time", _struct_time_decoder) + +# datetime.datetime + +SerializableJsonEncoding.add_encoder( + datetime.datetime, lambda obj: class_encode("datetime.datetime", obj.isoformat()) +) +SerializableJsonEncoding.add_decoder( + "datetime.datetime", lambda params: datetime.datetime.fromisoformat(params) +) + +# shortcut for dumps and loads + +dumps = SerializableJsonEncoding.dumps +loads = SerializableJsonEncoding.loads diff --git a/tests/plugins/test_announcements.py b/tests/plugins/test_announcements.py new file mode 100644 index 000000000..075882e7f --- /dev/null +++ b/tests/plugins/test_announcements.py @@ -0,0 +1,52 @@ +__author__ = "Gina Häußge " +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import unittest +from unittest import mock + +from octoprint.util import TemporaryDirectory + +RSS_EXAMPLE = """ + + + RSS Title + This is an example of an RSS feed + https://www.example.com/main.html + 2020 Example.com All rights reserved + Mon, 06 Sep 2010 00:01:00 +0000 + Sun, 06 Sep 2009 16:20:00 +0000 + 1800 + + Example entry + Here is some text containing an interesting description. + https://www.example.com/blog/post/1 + 7bd204c6-1655-4c27-aeee-53f933c5395f + Sun, 06 Sep 2009 16:20:00 +0000 + + + +""" + + +class TestAnnouncements(unittest.TestCase): + def test_caches(self): + from octoprint.plugins.announcements import AnnouncementPlugin + + plugin = AnnouncementPlugin() + plugin._logger = mock.MagicMock() + + with TemporaryDirectory() as data_folder: + plugin._data_folder = data_folder + with mock.patch("requests.get") as mock_get: + mock_get.return_value = mock.MagicMock(status_code=200) + mock_get.return_value.text = RSS_EXAMPLE + + network_response = plugin._get_channel_data_from_network( + "test", {"url": "https://example.com/feed.xml"} + ) + + cache_response = plugin._get_channel_data_from_cache("test", {"ttl": 1000}) + + self.maxDiff = 100000 + self.assertDictEqual(network_response, cache_response) diff --git a/tests/util/test_json.py b/tests/util/test_json.py new file mode 100644 index 000000000..5a22da171 --- /dev/null +++ b/tests/util/test_json.py @@ -0,0 +1,80 @@ +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import datetime +import time +import warnings + +import pytest +from frozendict import frozendict + +from octoprint.util import json + + +class SomeClass: + ... + + +class SomeSubclass(frozendict): + ... + + +def test_deprecated_dump(): + warnings.simplefilter("always") + with warnings.catch_warnings(record=True) as w: + assert json.dump({"foo": "bar"}) == '{"foo":"bar"}' + + assert len(w) == 1 + assert issubclass(w[-1].category, DeprecationWarning) + assert "dump has been renamed to dumps" in str(w[-1].message) + + +@pytest.mark.parametrize( + "val,expected", + [ + pytest.param({"foo": "bar"}, '{"foo":"bar"}', id="dict"), + pytest.param(frozendict({"foo": "bar"}), '{"foo":"bar"}', id="frozendict"), + pytest.param(b"foo", '"foo"', id="bytes"), + ], +) +def test_encoding_dumps(val, expected): + assert json.encoding.dumps(val) == expected + + +def test_encoding_loads(): + assert json.encoding.loads('{"foo":"bar"}') == {"foo": "bar"} + + +def test_encoding_dumps_typeerror(): + with pytest.raises(TypeError): + json.encoding.dumps(SomeClass()) + + +@pytest.mark.parametrize( + "val", + [ + pytest.param({"foo": "bar"}, id="dict"), + pytest.param(b"\x00\x01\x02\x03", id="bytes"), + # invalid bytes from https://stackoverflow.com/a/3886015 + pytest.param( + b"\xc3\x28\xa0\xa1\xe2\x28\xa1\xe2\x82\x28\xf0" + b"\x28\x8c\xbc\xf0\x90\x28\xbc\xf0\x28\x8c\x28", + id="invalid utf-8", + ), + pytest.param(frozendict({"foo": "bar"}), id="frozendict"), + pytest.param(time.struct_time((2018, 1, 1, 0, 0, 0, 0, 0, 0)), id="struct_time"), + pytest.param( + datetime.datetime(2022, 3, 21, 5, 24, 0, 0, tzinfo=datetime.timezone.utc), + id="datetime", + ), + pytest.param(frozendict({"a": b"b"}), id="nested"), + pytest.param(SomeSubclass({"a": b"b"}), id="subclass"), + ], +) +def test_serializing_roundtrips(val): + assert json.serializing.loads(json.serializing.dumps(val)) == val + + +def test_serializing_dumps_typeerror(): + with pytest.raises(TypeError): + json.serializing.dumps(SomeClass())