|
from .api import MikrotikAPI |
|
from .Config import RouterConfig |
|
from fastapi import HTTPException |
|
|
|
import re |
|
from typing import Tuple |
|
|
|
|
|
class PhoneValidator: |
|
"""Validator for Tanzanian phone numbers""" |
|
|
|
|
|
VALID_PREFIXES = [ |
|
"071", |
|
"074", |
|
"075", |
|
"076", |
|
"077", |
|
"068", |
|
"069", |
|
"065", |
|
"067", |
|
"078", |
|
"079", |
|
"073", |
|
"061", |
|
"062", |
|
] |
|
|
|
@staticmethod |
|
def validate_and_format(phone: str) -> Tuple[bool, str]: |
|
""" |
|
Validates and formats Tanzanian phone numbers. |
|
Returns (is_valid, formatted_number) |
|
|
|
Valid format: |
|
- 255712345678 (12 digits starting with 255) |
|
""" |
|
|
|
phone = re.sub(r"[\s\-\(\)]", "", phone) |
|
|
|
|
|
if phone.startswith("+255"): |
|
phone = "255" + phone[4:] |
|
elif phone.startswith("0"): |
|
phone = "255" + phone[1:] |
|
elif not phone.startswith("255"): |
|
return False, "" |
|
|
|
|
|
if not re.match(r"^255\d{9}$", phone): |
|
return False, "" |
|
|
|
|
|
prefix = "0" + phone[3:5] |
|
if prefix not in PhoneValidator.VALID_PREFIXES: |
|
return False, "" |
|
|
|
return True, phone |
|
|
|
|
|
|
|
def get_mikrotik(): |
|
config = RouterConfig() |
|
mikrotik = MikrotikAPI(config) |
|
try: |
|
if mikrotik.connect(): |
|
yield mikrotik |
|
else: |
|
raise HTTPException( |
|
status_code=503, |
|
detail={"success": False, "message": "Could not connect to router"}, |
|
) |
|
finally: |
|
mikrotik.close() |
|
|