code

import re
import json
import requests
from datetime import datetime
import time


# url = "http://127.0.0.1:8000/encryption-status/new/ATM001"

# response = requests.get(url)

# print("Status Code:", response.status_code)
# print("Response:", response.json())

old_data = None
new_data = None

def fetch_atm_data():
    global old_data, new_data

    ATM_API = "http://127.0.0.1:8000/encryption-status/old"
    i = 0

    while i<=1:
        try:
            response = requests.get(
                ATM_API,
                timeout=60,
                verify=False
            )
            response.raise_for_status()

            old_data = new_data
            new_data = response.json()

            print(f"Encryption API snapshot {i+1}")

        except Exception as e:
            print("API Error:", e)

        i = i+1

        time.sleep(5)  # 10 minutes
    return old_data, new_data

def get_data(old_data,new_data):
    old_data = old_data.get("data")
    new_data = new_data.get("data")
    old_data = next(
        (record for record in old_data if record.get("atm_id") == atm_id),
                None)
    new_data = next(
        (record for record in new_data if record.get("atm_id") == atm_id),
                        None)
   
    encryption_status = check_encryption_status(old_data, new_data)
    return encryption_status


def is_velox_docket_email(subject):
    if not subject:
        return False

    subject = subject.lower()

    # Replace anything other than letters/numbers with spaces
    normalized = re.sub(r"[^a-z0-9]+", " ", subject)

    # Normalize spaces
    normalized = re.sub(r"\s+", " ", normalized).strip()

    pattern = r"\bvelox\s+docket\b"

    return bool(re.search(pattern, normalized))

def check_encryption_status(response1, response2):

    drives1 = response1["drives"]
    drives2 = response2["drives"]

    # 1. Check whether all drives are 100%
    all_completed = all(
        value == 100
        for value in drives2.values()
    )

    if all_completed:
        return "Complete"

    # 2. Compare drive values
    progress_found = False

    for drive in drives1:

        old_value = drives1.get(drive, 0)
        new_value = drives2.get(drive, 0)

        if new_value > old_value:
            progress_found = True
            break

    if progress_found:
        return "In Progress"

    # 3. If both responses are same
    if drives1 == drives2:
        return "Stop"

    return "Stop"

def Extract_atm_data(email):
    # Convert JSON string to Python dictionary
    subject = email.get("subject", "")
    body = email.get("body", "")

    # Check subject
    if "velox docket number" in subject.lower():
        # Extract ATM ID
        atm_id_match = re.search(
            r'ATM\s*ID\s*[-:]\s*([A-Za-z0-9]+)',
            body,
            re.IGNORECASE
        )
       
        # Extract ATM IP
        atm_ip_match = re.search(
            r'ATM\s*IP\s*[-:]\s*(\d{1,3}(?:\.\d{1,3}){3})',
            body,
            re.IGNORECASE
        )

        result = {
            "atm_id": atm_id_match.group(1) if atm_id_match else None,
            "atm_ip": atm_ip_match.group(1) if atm_ip_match else None
        }

        return result
    else:
        return {
            result:"Email subject does not match."
        }

def output(status):
    date = datetime.now().strftime("%d%m%Y")
    time = datetime.now().strftime("%H%M")

    if(status == "Complete"):
        return f"Velox docket number:- HDE/{date}/{time}"
    elif(status == "In Progress"):
        return f"Velox docket number:-  HDEPRE/{date}/{time}"
    else:
        return"Terminal disconnected"

if __name__ == "__main__":
    email_json = '''
    {
        "subject": "Velox Docket Number",
        "body": "Dear Team,\\n\\nPls share docket no\\n\\nATM ID -ATM001\\nATM IP - 10.85.39.43\\nATM - ABC"
    }
    '''
    try:

        email_data = json.loads(email_json)

        subject = email_data.get("subject", "")
        body = email_data.get("body", "")

        if is_velox_docket_email(subject):

            atm = Extract_atm_data(email_data)
            atm_id = atm.get("atm_id")

            if not atm_id:
                print("ATM ID not found.")
            else:
                old_data,new_data = fetch_atm_data()
                result = get_data(old_data,new_data)

                output1 = output(result)

                print(output1)

        else:
            print("Not a Velox Docket Number email.")

    except json.JSONDecodeError as e:

        print("Invalid JSON:", e)

    except Exception as e:

        print("Error:", e)

Comments

Popular posts from this blog