Mercurial > libervia-backend
diff sat/core/sat_main.py @ 3201:439e2f88c3a9
core, bridge: new `imageGeneratePreview` helped method to generate a thumbnail
author | Goffi <goffi@goffi.org> |
---|---|
date | Sun, 01 Mar 2020 18:48:06 +0100 |
parents | 84a94b385760 |
children | ae09989e9feb |
line wrap: on
line diff
--- a/sat/core/sat_main.py Sun Mar 01 18:47:05 2020 +0100 +++ b/sat/core/sat_main.py Sun Mar 01 18:48:06 2020 +0100 @@ -20,6 +20,8 @@ import sys import os.path import uuid +import hashlib +from pathlib import Path import sat from sat.core.i18n import _, D_, languageSwitch from sat.core import patches @@ -173,6 +175,7 @@ self.bridge.register_method("namespacesGet", self.getNamespaces) self.bridge.register_method("imageCheck", self._imageCheck) self.bridge.register_method("imageResize", self._imageResize) + self.bridge.register_method("imageGeneratePreview", self._imageGeneratePreview) self.memory.initialized.addCallback(lambda __: defer.ensureDeferred(self._postMemoryInit())) @@ -684,6 +687,45 @@ d.addCallback(lambda new_image_path: str(new_image_path)) return d + def _imageGeneratePreview(self, path, profile_key): + client = self.getClient(profile_key) + d = defer.ensureDeferred(self.imageGeneratePreview(client, Path(path))) + d.addCallback(lambda preview_path: str(preview_path)) + return d + + async def imageGeneratePreview(self, client, path): + """Helper method to generate in cache a preview of an image + + @param path(Path): path to the image + @return (Path): path to the generated preview + """ + report = images.checkImage(self, path, max_size=(300, 300)) + + if not report['too_large']: + # in the unlikely case that image is already smaller than a preview + preview_path = path + else: + # we use hash as id, to re-use potentially existing preview + path_hash = hashlib.sha256(str(path).encode()).hexdigest() + uid = f"{path.stem}_{path_hash}_preview" + filename = f"{uid}{path.suffix.lower()}" + metadata = client.cache.getMetadata(uid=uid) + if metadata is not None: + preview_path = metadata['path'] + else: + with client.cache.cacheData( + source='HOST_PREVIEW', + uid=uid, + filename=filename) as cache_f: + + preview_path = await images.resizeImage( + path, + new_size=report['recommended_size'], + dest=cache_f + ) + + return preview_path + # local dirs def getLocalPath(self, client, dir_name, *extra_path, **kwargs):