import json, hashlib, urllib.request import mongo import logger as log REBUILD = False log.out("reasonCodes.py: reasonCodes module initialised", "DBUG") file_location :str = "reasoncodes.json" file_url :str = "https://git.fjla.uk/OwlBoard/data/raw/branch/main/reasonCodes/reasoncodes.json" def runUpdate(): state = download() if (not state): log.out("reasonCodes.runUpdate: Unable to update reason codes") if (not requiresUpdate()): log.out('reasonCodes.runUpdate: Reason codes do not need updating', 'INFO') return log.out(f"reasonCodes.runUpdate: Update required", "INFO") reason_code_data = load() reason_code_indexes = ["code"] mongo.dropCollection("reasonCodes") mongo.putMany("reasonCodes", reason_code_data, reason_code_indexes) def download(): log.out("pis.download: Downloading reason codes file") try: urllib.request.urlretrieve(file_url, file_location) return True except Exception as e: log.out(f"pis.download: Download error: {e}") return False def requiresUpdate(): if REBUILD: return True current_hash = mongo.getMetaHash("reasonCodes") with open(file_location, "r") as f: text = f.read() newHash = hashlib.md5(text.encode()).hexdigest() log.out(f"reasonCodes.requiresUpdate: Database Hash: {current_hash}","INFO") log.out(f"reasonCodes.requiresUpdate: File hash: {newHash}", "INFO") if current_hash is None or newHash != current_hash: log.out("reasonCodes.requiredUpdate: reasonCodes require updating", "INFO") mongo.putMetaHash("reasonCodes", newHash) return True log.out("reasonCodes.requiredUpdate: reasonCodes are up to date", "INFO") return False def load(): with open(file_location, "r") as data: try: json_data = data.read() reason_code = json.loads(json_data) return reason_code['GetReasonCodeListResult']['reason'] except Exception as exc: log.out(f"reasonCodes.load: {exc}", "EROR") return exc