import ipaddress
import re
'''
正则管理类,用来实现对各类字符串进行合法性校验
'''
class ReManager():
    def is_valid_ip(self,ip):
        try:
            ipaddress.ip_address(ip)
            return True
        except ValueError:
            return False

    def is_valid_subnet_mask(self,subnet_mask):
        # 将子网掩码字符串转换为整数列表
        bits = [int(b) for b in subnet_mask.split('.')]
        if len(bits) != 4:
            return False

        # 检查每个部分是否在0-255范围内
        if not all(0 <= b <= 255 for b in bits):
            return False

        # 检查子网掩码是否连续为1后跟连续为0
        mask_int = (bits[0] << 24) + (bits[1] << 16) + (bits[2] << 8) + bits[3]
        binary_mask = bin(mask_int)[2:].zfill(32)
        ones_count = binary_mask.count('1')
        if not all(bit == '1' for bit in binary_mask[:ones_count]) or not all(
                bit == '0' for bit in binary_mask[ones_count:]):
            return False
        return True

    def is_valid_port(self,port):
        try:
            port = int(port)  # 尝试将端口转换为整数
            if 1 <= port <= 65535:  # 检查端口号是否在合法范围内
                return True
            else:
                return False
        except ValueError:
            # 如果端口不是整数,返回False
            return False

    def is_valid_rtsp_url(self,url):
        pattern = re.compile(
            r'^(rtsp:\/\/)'  # Start with rtsp://
            r'(?P<host>(?:[a-zA-Z0-9_\-\.]+)|(?:\[[a-fA-F0-9:]+\]))'  # Hostname or IPv4/IPv6 address
            r'(?::(?P<port>\d+))?'  # Optional port number
            r'(?P<path>\/[a-zA-Z0-9_\-\.\/]*)?$'  # Optional path
        )
        match = pattern.match(url)
        return match is not None

mReM = ReManager()

if __name__ == "__main__":
    urls = [
        "rtsp://192.168.1.1:554/stream1",
        "rtsp://example.com/stream",
        "rtsp://[2001:db8::1]:554/stream",
        "rtsp://localhost",
        "http://example.com",
        "ftp://example.com/stream"
    ]

    for url in urls:
        print(f"{url}: {mReM.is_valid_rtsp_url(url)}")