2021-12-10 21:59:56 +01:00
|
|
|
#!/usr/bin/env python3
|
2021-12-10 23:04:41 +01:00
|
|
|
from typing import Optional
|
|
|
|
from flask import jsonify, request, abort, current_app
|
|
|
|
from utils import json_required, redis_client
|
2021-12-10 21:59:56 +01:00
|
|
|
from flask_classful import FlaskView
|
|
|
|
|
2021-12-10 23:04:41 +01:00
|
|
|
import json
|
|
|
|
|
2021-12-10 21:59:56 +01:00
|
|
|
|
2021-12-10 22:02:30 +01:00
|
|
|
class AssignmentView(FlaskView):
|
2021-12-10 23:04:41 +01:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _resolve_response(site: Optional[str]) -> dict:
|
|
|
|
site_url_map = redis_client.get("SITEURLMAP")
|
|
|
|
|
|
|
|
if site_url_map:
|
|
|
|
site_url_map = json.loads(site_url_map.decode('utf-8'))
|
|
|
|
|
|
|
|
if not site_url_map:
|
|
|
|
return {
|
|
|
|
"site": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0],
|
|
|
|
"url": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][1],
|
|
|
|
"hard_default": True
|
|
|
|
}
|
|
|
|
|
|
|
|
if not site:
|
|
|
|
return {
|
|
|
|
"site": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0],
|
|
|
|
"url": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][1],
|
|
|
|
"hard_default": True
|
|
|
|
}
|
|
|
|
|
|
|
|
if site not in site_url_map.keys():
|
|
|
|
# This should be an internal server error instead
|
|
|
|
return {
|
|
|
|
"site": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0],
|
|
|
|
"url": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][1],
|
|
|
|
"hard_default": True
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
"site": site,
|
|
|
|
"url": site_url_map[site],
|
|
|
|
"hard_default": False
|
|
|
|
}
|
|
|
|
|
|
|
|
@json_required
|
|
|
|
def post(self):
|
|
|
|
device_id = request.json['device_id']
|
|
|
|
|
|
|
|
schedule_store_key = f"SCHEDULED:{device_id}"
|
|
|
|
|
|
|
|
target_site = redis_client.get(schedule_store_key)
|
|
|
|
|
|
|
|
if target_site:
|
|
|
|
target_site = target_site.decode('utf-8')
|
|
|
|
|
|
|
|
if not target_site:
|
|
|
|
default_target = redis_client.get('DEFAULT:SCHEDULED')
|
|
|
|
|
2021-12-11 00:02:36 +01:00
|
|
|
if default_target:
|
|
|
|
default_target = default_target.decode('utf-8')
|
|
|
|
|
2021-12-10 23:57:28 +01:00
|
|
|
if not default_target:
|
|
|
|
default_target = current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0]
|
|
|
|
|
2021-12-10 23:04:41 +01:00
|
|
|
if default_target:
|
2021-12-11 00:02:36 +01:00
|
|
|
target_site = default_target
|
2021-12-11 00:08:17 +01:00
|
|
|
redis_client.set(schedule_store_key, default_target, ex=current_app.config['DEVICE_TIMEOUT'])
|
|
|
|
|
|
|
|
else:
|
|
|
|
# Just Update TTL
|
|
|
|
redis_client.expire(
|
|
|
|
schedule_store_key,
|
|
|
|
current_app.config['DEVICE_TIMEOUT']
|
|
|
|
)
|
2021-12-10 23:04:41 +01:00
|
|
|
|
|
|
|
return jsonify(self._resolve_response(target_site))
|