2020-03-29 18:12:16 +02:00
|
|
|
import json
|
2020-05-08 19:34:29 +02:00
|
|
|
import time
|
2020-03-29 18:12:16 +02:00
|
|
|
from flask import request, current_app, jsonify
|
2020-03-29 17:08:53 +02:00
|
|
|
from flask_classful import FlaskView
|
2020-04-04 13:53:26 +02:00
|
|
|
from db import redis_client
|
2020-03-29 17:08:53 +02:00
|
|
|
|
|
|
|
|
|
|
|
class SyncView(FlaskView):
|
|
|
|
|
2020-03-29 18:12:16 +02:00
|
|
|
def post(self):
|
|
|
|
remote_uuid = request.json['uuid']
|
2020-05-14 22:37:30 +02:00
|
|
|
|
|
|
|
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
|
2020-03-29 18:12:16 +02:00
|
|
|
|
2020-05-08 19:57:42 +02:00
|
|
|
cust_key = f"consumer_{remote_uuid}"
|
2020-03-29 18:12:16 +02:00
|
|
|
|
2020-05-08 19:57:42 +02:00
|
|
|
last_known_info = json.loads((redis_client.get(cust_key) or b"{}").decode('utf-8'))
|
2020-05-08 19:34:29 +02:00
|
|
|
|
|
|
|
if not last_known_info:
|
2020-03-29 18:12:16 +02:00
|
|
|
current_app.logger.info(f"New consumer registered (unknown UUID): {remote_uuid} at {remote_ip}")
|
2020-05-08 19:34:29 +02:00
|
|
|
|
2020-04-04 13:53:26 +02:00
|
|
|
else:
|
2020-05-08 19:34:29 +02:00
|
|
|
if last_known_info['ip'] != remote_ip:
|
2020-03-29 18:12:16 +02:00
|
|
|
current_app.logger.info(f"Address of consumer {remote_uuid} changed to {remote_ip}")
|
|
|
|
|
2020-05-08 19:34:29 +02:00
|
|
|
info = {
|
|
|
|
"uuid": remote_uuid,
|
|
|
|
"ip": remote_ip,
|
|
|
|
"last_seen": time.time()
|
|
|
|
}
|
2020-03-29 18:12:16 +02:00
|
|
|
|
2020-05-08 19:34:29 +02:00
|
|
|
redis_client.set(cust_key, json.dumps(info).encode('utf-8'))
|
2020-05-08 19:44:42 +02:00
|
|
|
redis_client.expire(cust_key, current_app.config["CUSTOMER_TIMEOUT"])
|
2020-03-29 18:12:16 +02:00
|
|
|
|
2020-04-04 13:53:26 +02:00
|
|
|
# return with the current UUID
|
2020-03-29 18:12:16 +02:00
|
|
|
response = {
|
|
|
|
"uuid": current_app.config['LOCAL_UUID']
|
|
|
|
}
|
|
|
|
return jsonify(response)
|