#!/usr/bin/env python3 from typing import Optional from flask import jsonify, request, abort, current_app from utils import json_required, redis_client from flask_classful import FlaskView import json class AssignmentView(FlaskView): @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}" hard_default_assigned = False 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') if default_target: default_target = default_target.decode('utf-8') if not default_target: default_target = current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0] hard_default_assigned = True if default_target: target_site = default_target 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'] ) resp = self._resolve_response(target_site) # Ah yes, the finest of hacks... if hard_default_assigned: resp['hard_default'] = True # This will report true only the first time trough... but we could survive this # de amugy ez az egész hard default csak felesleges faszverés, úgy is azután fogok mérni, hogy beállt a rendszer # Meg amúgy is ez csak egy információs cucc volt, minek van használva?? # Asking myself... return jsonify(resp) def get(self): current_scheduling_table = {} for key in redis_client.keys("SCHEDULED:*"): target = redis_client.get(key) if target: name = key[10:] current_scheduling_table[name] = target default_target = redis_client.get('DEFAULT:SCHEDULED') return jsonify({"scheduling_table": current_scheduling_table, "default_target": default_target})