http: add file nad image commands to HttpClient

This commit is contained in:
Izalia Mae 2021-03-18 21:43:52 -04:00
parent d746216c49
commit f32dcd6149

View file

@ -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({