2018-07-10 23:13:12 -04:00
|
|
|
from django.db.models import Q
|
2018-03-22 21:56:13 -04:00
|
|
|
from django.http import HttpResponse, HttpResponseRedirect
|
2018-06-08 00:47:34 -04:00
|
|
|
from django.views.decorators.cache import cache_page
|
2018-03-22 21:56:13 -04:00
|
|
|
from PIL import Image
|
|
|
|
|
|
|
|
from lemoncurry import utils
|
|
|
|
from .models import User
|
|
|
|
|
|
|
|
|
|
|
|
def try_libravatar_org(hash, get):
|
|
|
|
url = 'https://seccdn.libravatar.org/avatar/' + hash
|
|
|
|
if get:
|
|
|
|
url += '?' + get.urlencode()
|
|
|
|
return HttpResponseRedirect(url)
|
|
|
|
|
|
|
|
|
2018-06-08 00:47:34 -04:00
|
|
|
@cache_page(60 * 15)
|
2018-03-22 21:56:13 -04:00
|
|
|
def libravatar(request, hash):
|
|
|
|
g = request.GET
|
|
|
|
size = g.get('s', g.get('size', 80))
|
|
|
|
try:
|
|
|
|
size = int(size)
|
|
|
|
except ValueError:
|
2021-08-22 09:08:45 -04:00
|
|
|
size = 80
|
2018-06-04 20:14:24 -04:00
|
|
|
if not 1 <= size <= 512:
|
2021-08-22 09:08:45 -04:00
|
|
|
size = 512
|
2018-03-22 21:56:13 -04:00
|
|
|
|
|
|
|
if len(hash) == 32:
|
2018-07-10 23:13:12 -04:00
|
|
|
where = Q(email_md5=hash)
|
2018-03-22 21:56:13 -04:00
|
|
|
elif len(hash) == 64:
|
2018-07-10 23:13:12 -04:00
|
|
|
where = Q(email_sha256=hash) | Q(openid_sha256=hash)
|
2018-03-22 21:56:13 -04:00
|
|
|
else:
|
|
|
|
return utils.bad_req('hash must be either md5 or sha256')
|
|
|
|
|
|
|
|
# If the user doesn't exist or lacks an avatar, see if libravatar.org has
|
|
|
|
# one for them - libravatar.org falls back to Gravatar when possible (only
|
|
|
|
# for MD5 hashes, since Gravatar doesn't support SHA-256), so this ensures
|
|
|
|
# all the most likely places are checked.
|
|
|
|
try:
|
2018-07-10 23:13:12 -04:00
|
|
|
user = User.objects.get(where)
|
2018-03-22 21:56:13 -04:00
|
|
|
except User.DoesNotExist:
|
|
|
|
return try_libravatar_org(hash, g)
|
|
|
|
|
|
|
|
if not user.avatar:
|
|
|
|
return try_libravatar_org(hash, g)
|
|
|
|
|
|
|
|
im = Image.open(user.avatar)
|
2018-06-08 00:47:34 -04:00
|
|
|
image_type = im.format
|
|
|
|
natural_size = min(im.size)
|
2018-03-22 21:56:13 -04:00
|
|
|
|
2018-06-08 00:47:34 -04:00
|
|
|
im = im.crop((0, 0, natural_size, natural_size))
|
|
|
|
im = im.resize((size, size), resample=Image.HAMMING)
|
|
|
|
|
|
|
|
response = HttpResponse(content_type='image/'+image_type.lower())
|
|
|
|
im.save(response, image_type)
|
2018-03-22 21:56:13 -04:00
|
|
|
return response
|