diff --git a/plugin-server.py b/plugin-server.py index 0125fb0..148f371 100644 --- a/plugin-server.py +++ b/plugin-server.py @@ -68,31 +68,45 @@ def plugin_file(plugin, path): return "File not found", 404 mt, _encoding = mimetypes.guess_type(path) + + # if in cache, load etag and content, set status code to 304 if check_cache(full_path): result = redis.get(full_path + ":content") + etag = str(redis.get(full_path + ":etag")) status_code = 304 + + # else, make search-and-replace and save to redis (+etag) else: replace_with = "{}/{}".format(URL, plugin) status_code = 200 + etag = generate_etag() + with open(full_path, 'rb') as fp: content_bytes = fp.read() - try: - content = content_bytes.decode('UTF-8') - result = content.replace(REPLACE_STRING, replace_with) - result = result.encode('UTF-8') - except UnicodeDecodeError: - result = content_bytes + + try: + content = content_bytes.decode('UTF-8') + result = content.replace(REPLACE_STRING, replace_with) + result = result.encode('UTF-8') + except UnicodeDecodeError: + result = content_bytes redis.set(full_path + ":content", result) + redis.set(full_path + ":etag", etag) resp = Response(result, mimetype=mt) resp.headers.add('Access-Control-Allow-Origin', '*') - resp.headers.add('ETag', generate_etag()) - resp.status_code = status_code + resp.headers.add('ETag', etag) - # return everything if cached response is not allowed + # if browser does not have a cached etag -> 200 if 'If-None-Match' not in request.headers: resp.status_code = 200 + # then check if it is the latest etag, else -> 200 + elif request.headers['If-None-Match'] != etag: + resp.status_code = 200 + # else just set whatever was predetermined + else: + resp.status_code = status_code return resp