import socket
import re
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import socks

def scan_port_with_proxy(host, port, timeout, stop_event, proxy_host, proxy_port):
    if stop_event.is_set():
        return None
    try:
        sock = socks.socksocket()
        # Use SOCKS5 proxy; change to socks.HTTP for HTTP proxy
        sock.set_proxy(socks.SOCKS5, proxy_host, proxy_port)
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        sock.close()
        if result == 0:
            print(f"Port {port} is open (via proxy)")
            return port
    except Exception:
        pass
    return None

def find_first_open_port_multithreaded(host, start_port, end_port, timeout=1.0, max_workers=50, proxy_host=None, proxy_port=None):
    print(f"Scanning {host} from port {start_port} to {end_port} with {max_workers} workers via proxy {proxy_host}:{proxy_port}...")
    stop_event = threading.Event()
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {
            executor.submit(scan_port_with_proxy, host, port, timeout, stop_event, proxy_host, proxy_port): port
            for port in range(start_port, end_port + 1)
        }
        for future in as_completed(futures):
            port = future.result()
            if port is not None:
                stop_event.set()
                return port
    return None

if __name__ == "__main__":
    # 👇 Replace this with your proxy in format ip:port
    proxy_ip_port = "185.176.207.167:5432"   # Example SOCKS5 proxy
    proxy_host, proxy_port = proxy_ip_port.split(":")
    proxy_port = int(proxy_port)

    host = "ortepe.xyz"
    original_file = "/var/www/html/adult/origional_adult.m3u"
    new_file = "/var/www/html/adult/adult.m3u"

    try:
        ip = socket.gethostbyname(host)
        print(f"Resolved host {host} to IP {ip}")

        start_port = 10000
        end_port = 90000

        open_port = find_first_open_port_multithreaded(
            ip,
            start_port,
            end_port,
            timeout=1.0,
            max_workers=50,
            proxy_host=proxy_host,
            proxy_port=proxy_port
        )

        if not open_port:
            print("No open ports found, exiting.")
            exit(1)

        print(f"Open port found: {open_port}")

        # Read original playlist
        with open(original_file, "r", encoding="utf-8") as f:
            lines = f.readlines()

        url_pattern = re.compile(rf"(https://{re.escape(host)}:)(\d+)(/.+)")

        new_lines = []
        for line in lines:
            match = url_pattern.search(line)
            if match:
                new_line = f"{match.group(1)}{open_port}{match.group(3)}\n"
                new_lines.append(new_line)
            else:
                new_lines.append(line)

        # Write updated playlist
        with open(new_file, "w", encoding="utf-8") as f:
            f.writelines(new_lines)

        txt_file = new_file.rsplit(".", 1)[0] + ".txt"
        with open(txt_file, "w", encoding="utf-8") as f_txt:
            f_txt.writelines(new_lines)

        print(f"Updated playlist saved to {new_file}")
        print(f"Copy also saved as {txt_file}")

    except FileNotFoundError:
        print(f"Original file {original_file} not found.")
    except socket.gaierror:
        print(f"Failed to resolve host: {host}")
    except Exception as e:
        print(f"An error occurred: {e}")
