47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
import json
|
|
import time
|
|
from flask import request, current_app, jsonify
|
|
from flask_classful import FlaskView
|
|
from db import redis_client
|
|
|
|
|
|
class SyncView(FlaskView):
|
|
|
|
def post(self):
|
|
remote_uuid = request.json['uuid']
|
|
|
|
if 'ip' in request.json:
|
|
remote_ip = request.json['ip']
|
|
|
|
if request.remote_addr != remote_ip:
|
|
current_app.logger.debug(f"IP was overriden by the remote consumer {remote_ip} instead of {request.remote_addr}")
|
|
|
|
else:
|
|
remote_ip = request.remote_addr
|
|
|
|
cust_key = f"consumer_{remote_uuid}"
|
|
|
|
last_known_info = json.loads((redis_client.get(cust_key) or b"{}").decode('utf-8'))
|
|
|
|
if not last_known_info:
|
|
current_app.logger.info(f"New consumer registered (unknown UUID): {remote_uuid} at {remote_ip}")
|
|
|
|
else:
|
|
if last_known_info['ip'] != remote_ip:
|
|
current_app.logger.info(f"Address of consumer {remote_uuid} changed to {remote_ip}")
|
|
|
|
info = {
|
|
"uuid": remote_uuid,
|
|
"ip": remote_ip,
|
|
"last_seen": time.time()
|
|
}
|
|
|
|
redis_client.set(cust_key, json.dumps(info).encode('utf-8'))
|
|
redis_client.expire(cust_key, current_app.config["CUSTOMER_TIMEOUT"])
|
|
|
|
# return with the current UUID
|
|
response = {
|
|
"uuid": current_app.config['LOCAL_UUID']
|
|
}
|
|
return jsonify(response)
|