From 319889ee43b264a923cf776ce4134636d056da36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Fri, 12 May 2023 17:12:36 +0200 Subject: [PATCH] (user) better avatar cache-control etag is added to header, If etag is the same a not modified will be respond --- flaschengeist/controller/userController.py | 8 +++++++- flaschengeist/plugins/users/__init__.py | 10 +++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/flaschengeist/controller/userController.py b/flaschengeist/controller/userController.py index 9d8b2ac..a94c022 100644 --- a/flaschengeist/controller/userController.py +++ b/flaschengeist/controller/userController.py @@ -1,8 +1,11 @@ import re import secrets +import hashlib from io import BytesIO from typing import Optional, Union +from flask import make_response +from flask.json import provider from sqlalchemy import exc from sqlalchemy_utils import merge_references from datetime import datetime, timedelta, timezone @@ -273,8 +276,11 @@ def load_avatar(user: User, etag: Union[str, None] = None): else: provider = get_provider(user.userid) avatar = provider.get_avatar(user) + new_etag = hashlib.md5(avatar.binary).hexdigest() + if new_etag == etag: + return make_response("", 304) if len(avatar.binary) > 0: - return send_file(BytesIO(avatar.binary), avatar.mimetype) + return send_file(BytesIO(avatar.binary), avatar.mimetype, etag=new_etag) raise NotFound diff --git a/flaschengeist/plugins/users/__init__.py b/flaschengeist/plugins/users/__init__.py index af344e2..23dac59 100644 --- a/flaschengeist/plugins/users/__init__.py +++ b/flaschengeist/plugins/users/__init__.py @@ -3,8 +3,9 @@ Provides routes used to manage users """ from http.client import CREATED -from flask import Blueprint, request, jsonify, make_response +from flask import Blueprint, request, jsonify, make_response, after_this_request, Response from werkzeug.exceptions import BadRequest, Forbidden, MethodNotAllowed +from datetime import datetime from . import permissions from flaschengeist import logger @@ -118,10 +119,13 @@ def frontend(userid, current_session): @UsersPlugin.blueprint.route("/users//avatar", methods=["GET"]) -@headers({"Cache-Control": "public, max-age=604800"}) +@headers({"Cache-Control": "public, must-revalidate, max-age=10"}) def get_avatar(userid): + etag = None + if "If-None-Match" in request.headers: + etag = request.headers["If-None-Match"] user = userController.get_user(userid) - return userController.load_avatar(user) + return userController.load_avatar(user, etag) @UsersPlugin.blueprint.route("/users//avatar", methods=["POST"])