From f32dcd6149d7dfebe4865984e9c70f020e186200 Mon Sep 17 00:00:00 2001 From: Izalia Mae Date: Thu, 18 Mar 2021 21:43:52 -0400 Subject: [PATCH] http: add file nad image commands to HttpClient --- IzzyLib/http.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/IzzyLib/http.py b/IzzyLib/http.py index df75db1..4f915d9 100644 --- a/IzzyLib/http.py +++ b/IzzyLib/http.py @@ -1,9 +1,10 @@ import functools, json, sys from IzzyLib import logging -from IzzyLib.misc import DefaultDict, DotDict +from IzzyLib.misc import DefaultDict, DotDict, Path from base64 import b64decode, b64encode from datetime import datetime +from io import BytesIO from ssl import SSLCertVerificationError from urllib.error import HTTPError from urllib.parse import urlparse @@ -26,6 +27,12 @@ except ImportError: logging.verbose('Sanic module not found. Request verification is disabled') SanicRequest = False +try: + from PIL import Image +except ImportError: + logging.verbose('Pillow module not found. Image downloading is disabled') + Image = False + Client = None @@ -121,6 +128,53 @@ class HttpClient(object): return HttpResponse(response) + def file(self, url, filepath, *args, filename=None, **kwargs): + resp = self.request(url, *args, **kwargs) + + if resp.status != 200: + logging.error(f'Failed to download {url}:', resp.status, resp.body) + return False + + path = Path(filepath) + + if not path.exists(): + logging.error('Path does not exist:', path) + return False + + with path.join(filename).open('wb') as fd: + fd.write(resp.body) + return True + + + def image(self, url, filepath, *args, filename=None, ext='png', dimensions=(50, 50), **kwargs): + if not Image: + logging.error('Pillow module is not installed') + return + + resp = self.request(url, *args, **kwargs) + + if resp.status != 200: + logging.error(f'Failed to download {url}:', resp.status, resp.body) + return False + + if not filename: + filename = Path(url).stem() + + path = Path(filepath) + + if not path.exists(): + logging.error('Path does not exist:', path) + return False + + byte = BytesIO() + image = Image.open(BytesIO(resp.body)) + image.thumbnail(dimensions) + image.save(byte, format=ext.upper()) + + with path.join(filename).open('wb') as fd: + fd.write(byte.getvalue()) + + def json(self, *args, headers={}, activity=True, **kwargs): json_type = 'activity+json' if activity else 'json' headers.update({