#!/usr/bin/env python3
"""Rockbro Camera Helper: lets rockbro.vercel.app use a home or security camera (RTSP).

Browsers can't open rtsp:// video, so this small program does it on your computer:
  1. FFmpeg reads your camera's RTSP stream.
  2. The latest picture is offered at http://127.0.0.1:8787/frame.jpg, only to this computer
     and only to the Rockbro website. Your camera address and password never leave this computer.

Needs Python 3.8+ and FFmpeg (https://ffmpeg.org/download.html) installed.

Run:  python rockbro_helper.py                    (then press "Find cameras" on the Rockbro website)
      python rockbro_helper.py rtsp://NAME:PASSWORD@192.168.1.50:554/stream1
      python rockbro_helper.py --forget           (deletes the saved camera address)

Find cameras: the helper looks for cameras on your home network (ONVIF discovery plus a quick check
for the camera video port 554 on your network), and when you pick one it tries the usual video
addresses for Tapo, Reolink, Hikvision, Dahua/Amcrest, Wyze and others, so you only type the
camera's username and password.
Copyright (c) 2026 Rockbro. All rights reserved.
"""
import concurrent.futures, ipaddress, json, os, re, shutil, socket, subprocess, sys, threading, time, uuid, webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs, quote

PORT = 8787
FPS = 20
WIDTH = 960
CONFIG = os.path.join(os.path.expanduser('~'), '.rockbro_helper.json')
# only these websites may read the pictures (stops other sites peeking at your camera)
ALLOWED = ('https://rockbro.vercel.app',)
LOCAL_PREFIXES = ('http://localhost:', 'http://127.0.0.1:')

latest = {'jpg': None, 'n': 0, 't': 0.0, 'w': 0, 'h': 0, 'err': ''}
cond = threading.Condition()


def origin_ok(origin):
    return bool(origin) and (origin in ALLOWED or origin.startswith(LOCAL_PREFIXES))


def hide_password(url):
    p = urlparse(url)
    if p.password:
        return url.replace(':' + p.password + '@', ':****@')
    return url


def find_ffmpeg():
    exe = shutil.which('ffmpeg')
    if not exe:
        print('\nFFmpeg was not found. Install it from https://ffmpeg.org/download.html')
        print('(On Windows you can run:  winget install Gyan.FFmpeg  then open a new window.)')
        sys.exit(1)
    return exe


current = {'url': None, 'proc': None, 'gen': 0}


def switch_camera(url, ffmpeg):
    """Start reading a camera (stops the one before, if any)."""
    current['gen'] += 1
    current['url'] = url
    p = current['proc']
    if p and p.poll() is None:
        p.kill()
    with cond:
        latest.update(jpg=None, err='')
    threading.Thread(target=reader, args=(url, ffmpeg, current['gen']), daemon=True).start()


def reader(url, ffmpeg, gen=0):
    """Runs FFmpeg and keeps the newest JPEG picture. Reconnects if the camera drops."""
    while current['gen'] == gen:
        args = [ffmpeg, '-hide_banner', '-loglevel', 'error']
        if url.lower().startswith('rtsp'):
            args += ['-rtsp_transport', 'tcp']
        else:
            args += ['-re']  # a recorded video over http: play it at normal speed
        args += ['-i', url, '-an', '-vf', f'fps={FPS},scale={WIDTH}:-2', '-q:v', '6', '-f', 'image2pipe', '-vcodec', 'mjpeg', '-']
        proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0)
        current['proc'] = proc
        threading.Thread(target=_errors, args=(proc,), daemon=True).start()
        buf = b''
        got_any = False
        while True:
            chunk = proc.stdout.read(65536)
            if not chunk:
                break
            buf += chunk
            while True:
                start = buf.find(b'\xff\xd8')
                end = buf.find(b'\xff\xd9', start + 2) if start >= 0 else -1
                if start < 0 or end < 0:
                    if start > 0:
                        buf = buf[start:]
                    break
                jpg = buf[start:end + 2]
                buf = buf[end + 2:]
                w, h = _jpeg_size(jpg)
                with cond:
                    latest.update(jpg=jpg, n=latest['n'] + 1, t=time.monotonic(), w=w, h=h, err='')
                    cond.notify_all()
                if not got_any:
                    got_any = True
                    print(f'Camera connected ({w}x{h}). Open https://rockbro.vercel.app, choose "Home or security camera", then Connect.')
        proc.wait()
        if current['gen'] != gen:
            return
        print('The camera stream stopped. Trying again in 3 seconds...')
        time.sleep(3)


# ------------------------------------------------------------------ finding cameras --
def local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('10.255.255.255', 1))   # picks the network card that reaches the home network; sends nothing
        return s.getsockname()[0]
    except OSError:
        return None
    finally:
        s.close()


def local_net(ip):
    """the home network around this computer's address (mesh Wi-Fi like TP-Link Deco uses /22, most use /24)"""
    prefix = 24
    try:
        if os.name == 'nt':
            out = subprocess.run(['ipconfig'], capture_output=True, text=True, timeout=5).stdout
            m = re.search(re.escape(ip) + r'[^\n]*\n[^\n]*?(\d+\.\d+\.\d+\.\d+)', out)
            if m:
                prefix = ipaddress.ip_network('0.0.0.0/' + m.group(1)).prefixlen
        else:
            out = subprocess.run(['ip', '-o', '-f', 'inet', 'addr'], capture_output=True, text=True, timeout=5).stdout
            m = re.search(re.escape(ip) + r'/(\d+)', out)
            if m:
                prefix = int(m.group(1))
            else:
                out = subprocess.run(['ifconfig'], capture_output=True, text=True, timeout=5).stdout
                m = re.search(re.escape(ip) + r'\s+netmask\s+(0x[0-9a-f]+)', out)
                if m:
                    prefix = bin(int(m.group(1), 16)).count('1')
    except (OSError, ValueError, subprocess.SubprocessError):
        pass
    prefix = max(22, min(30, prefix))      # never scan more than about 1000 addresses
    return ipaddress.ip_network(f'{ip}/{prefix}', strict=False)


def onvif_probe(wait=2.5):
    """WS-Discovery: ONVIF cameras answer a multicast 'who is there' on the home network."""
    msg = f'''<?xml version="1.0" encoding="UTF-8"?>
<e:Envelope xmlns:e="http://www.w3.org/2003/05/soap-envelope" xmlns:w="http://schemas.xmlsoap.org/ws/2004/08/addressing"
 xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery" xmlns:dn="http://www.onvif.org/ver10/network/wsdl">
<e:Header><w:MessageID>uuid:{uuid.uuid4()}</w:MessageID><w:To e:mustUnderstand="true">urn:schemas-xmlsoap-org:ws:2005:04:discovery</w:To>
<w:Action e:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</w:Action></e:Header>
<e:Body><d:Probe><d:Types>dn:NetworkVideoTransmitter</d:Types></d:Probe></e:Body></e:Envelope>'''.encode()
    found = {}
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    try:
        ip = local_ip()
        if ip:
            s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(ip))
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        s.settimeout(0.3)
        s.sendto(msg, ('239.255.255.250', 3702))
        end = time.time() + wait
        while time.time() < end:
            try:
                data, addr = s.recvfrom(65535)
            except socket.timeout:
                continue
            except OSError:
                break
            txt = data.decode('utf-8', 'replace')
            scopes = ' '.join(re.findall(r'<[^>]*Scopes[^>]*>([^<]*)<', txt))
            def scope(k):
                m = re.search(r'onvif://www\.onvif\.org/' + k + r'/([^\s]+)', scopes)
                return quote_back(m.group(1)) if m else ''
            found[addr[0]] = {'ip': addr[0], 'name': scope('name'), 'model': scope('hardware'), 'onvif': True}
    finally:
        s.close()
    return found


def miio_probe(net, wait=1.5):
    """Xiaomi / Mi Home devices answer a 'hello' on UDP 54321. Cameras among them have no RTSP."""
    hello = bytes.fromhex('21310020' + 'ff' * 28)
    found = {}
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.settimeout(0.3)
        try:
            s.sendto(hello, (str(net.broadcast_address), 54321))
        except OSError:
            pass
        end = time.time() + wait
        while time.time() < end:
            try:
                data, addr = s.recvfrom(1024)
            except socket.timeout:
                continue
            except OSError:
                break
            if len(data) >= 32 and data[:2] == b'\x21\x31':
                found[addr[0]] = {'ip': addr[0], 'name': '', 'model': 'Xiaomi / Mi Home device', 'onvif': False, 'xiaomi': True}
    finally:
        s.close()
    return found


def quote_back(s):
    from urllib.parse import unquote
    return unquote(s).replace('_', ' ').strip()


def port_open(ip, port, t=0.4):
    try:
        with socket.create_connection((ip, port), timeout=t):
            return True
    except OSError:
        return False


def scan():
    """ONVIF answers + any device on the home network with the camera video port (554) open."""
    ip = local_ip()
    found = {}
    with concurrent.futures.ThreadPoolExecutor(max_workers=200) as ex:
        probe = ex.submit(onvif_probe)
        hosts, mi = [], None
        if ip:
            net = local_net(ip)
            hosts = [str(h) for h in net.hosts() if str(h) != ip]
            mi = ex.submit(miio_probe, net)
        opened = {h: f for h, f in ((h, ex.submit(port_open, h, 554)) for h in hosts)}
        for h, f in opened.items():
            if f.result():
                found[h] = {'ip': h, 'name': '', 'model': '', 'onvif': False}
        for h, info in probe.result().items():
            found[h] = {**found.get(h, {}), **info}
        # Mi Home devices without a camera port are only listed if they look like cameras (port 554 or ONVIF
        # already caught the rest); otherwise lights and plugs would show up too. Xiaomi cameras answer miio
        # and have no RTSP, so list them with a note.
        for h, info in (mi.result() if mi else {}).items():
            if h not in found:
                found[h] = {**info, 'maybe': True}
            else:
                found[h]['xiaomi'] = True
    for h, c in found.items():
        c['rtsp'] = port_open(h, 554)
    return sorted(found.values(), key=lambda c: tuple(int(x) for x in c['ip'].split('.')))


# the usual RTSP video addresses, best quality first
PATHS = [
    ('Tapo / TP-Link', 'stream1'),
    ('Reolink', 'h264Preview_01_main'),
    ('Hikvision / Annke', 'Streaming/Channels/101'),
    ('Dahua / Amcrest / Lorex', 'cam/realmonitor?channel=1&subtype=0'),
    ('Wyze (RTSP firmware)', 'live'),
    ('Imou / EZVIZ', 'h264/ch1/main/av_stream'),
    ('Uniview', 'unicast/c1/s0/live'),
    ('Foscam', 'videoMain'),
    ('Xiaomi / Yi (hacked firmware)', 'ch0_0.h264'),
    ('Generic', 'live/ch00_0'),
    ('Generic', '11'),
    ('Generic', 'h264'),
    ('Generic', ''),
]


def try_url(ffmpeg, url):
    """-> 'ok', 'auth' (wrong username/password) or 'no'"""
    try:
        r = subprocess.run([ffmpeg, '-hide_banner', '-loglevel', 'error', '-rtsp_transport', 'tcp', '-i', url,
                            '-frames:v', '1', '-f', 'null', '-'], capture_output=True, timeout=10)
    except subprocess.TimeoutExpired:
        return 'no'
    err = r.stderr.decode('utf-8', 'replace')
    if r.returncode == 0:
        return 'ok'
    if '401' in err or 'Unauthorized' in err:
        return 'auth'
    return 'no'


def find_stream(ffmpeg, ip, user, password, port=554):
    auth = f'{quote(user, safe="")}:{quote(password, safe="")}@' if user else ''
    auth_fails = 0
    for brand, path in PATHS:
        url = f'rtsp://{auth}{ip}:{port}/{path}'
        res = try_url(ffmpeg, url)
        if res == 'ok':
            return {'ok': True, 'url': url, 'brand': brand}
        if res == 'auth':
            auth_fails += 1
            if auth_fails >= 2:      # the camera answers but says no: it's the username or password
                return {'ok': False, 'error': 'auth'}
    return {'ok': False, 'error': 'auth' if auth_fails else 'nostream'}


def _errors(proc):
    for line in proc.stderr:
        msg = line.decode('utf-8', 'replace').strip()
        if msg:
            latest['err'] = msg
            print('FFmpeg:', msg)


def _jpeg_size(b):
    i = 2
    while i + 9 < len(b):
        if b[i] != 0xFF:
            i += 1
            continue
        marker = b[i + 1]
        if marker in (0xC0, 0xC1, 0xC2):
            return int.from_bytes(b[i + 7:i + 9], 'big'), int.from_bytes(b[i + 5:i + 7], 'big')
        i += 2 + int.from_bytes(b[i + 2:i + 4], 'big')
    return 0, 0


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def _cors(self):
        origin = self.headers.get('Origin', '')
        if origin_ok(origin):
            self.send_header('Access-Control-Allow-Origin', origin)
            self.send_header('Vary', 'Origin')
            self.send_header('Access-Control-Allow-Private-Network', 'true')
            self.send_header('Access-Control-Expose-Headers', 'X-Frame-No, X-Frame-Time')
        return origin_ok(origin)

    def do_OPTIONS(self):
        self.send_response(204 if self.headers.get('Origin', '') and origin_ok(self.headers.get('Origin', '')) else 403)
        self._cors()
        self.send_header('Access-Control-Allow-Methods', 'GET, POST')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.send_header('Access-Control-Max-Age', '600')
        self.end_headers()

    def do_GET(self):
        u = urlparse(self.path)
        origin = self.headers.get('Origin', '')
        # pictures only for the Rockbro site (or a plain visit to /status from this computer)
        if u.path == '/frame.jpg' and not origin_ok(origin):
            self.send_response(403); self.end_headers(); return
        if u.path == '/status':
            return self._json({'ok': latest['jpg'] is not None, 'width': latest['w'], 'height': latest['h'],
                               'frames': latest['n'], 'error': latest['err'], 'camera': bool(current['url']), 'version': 2})
        if u.path == '/scan':
            if not origin_ok(origin):
                self.send_response(403); self.end_headers(); return
            print('Looking for cameras on your network...')
            cams = scan()
            print(f'Found {len(cams)}: ' + ', '.join(c['ip'] for c in cams))
            return self._json({'cameras': cams})
        if u.path == '/xiaomi/cameras':
            if not origin_ok(origin):
                self.send_response(403); self.end_headers(); return
            if not os.path.exists(g2_exe()):
                return self._json({'signed_in': False, 'cameras': []})
            try:
                return self._json(xiaomi_cameras())
            except Exception as e:  # noqa: BLE001
                return self._json({'signed_in': False, 'cameras': [], 'error': str(e)[:200]})
        if u.path == '/frame.jpg':
            try:
                after = int(parse_qs(u.query).get('after', ['0'])[0])
            except ValueError:
                after = 0
            with cond:
                cond.wait_for(lambda: latest['jpg'] is not None and latest['n'] > after, timeout=2.0)
                jpg, n, t = latest['jpg'], latest['n'], latest['t']
            if jpg is None:
                self.send_response(503); self._cors(); self.end_headers(); return
            self.send_response(200); self._cors()
            self.send_header('Content-Type', 'image/jpeg'); self.send_header('Content-Length', str(len(jpg)))
            self.send_header('Cache-Control', 'no-store')
            self.send_header('X-Frame-No', str(n)); self.send_header('X-Frame-Time', f'{t:.4f}')
            self.end_headers(); self.wfile.write(jpg); return
        self.send_response(404); self.end_headers()

    def _json(self, d, code=200):
        body = json.dumps(d).encode()
        self.send_response(code); self._cors()
        self.send_header('Content-Type', 'application/json'); self.send_header('Content-Length', str(len(body)))
        self.send_header('Cache-Control', 'no-store')
        self.end_headers(); self.wfile.write(body)

    def do_POST(self):
        u = urlparse(self.path)
        if not origin_ok(self.headers.get('Origin', '')) or u.path not in ('/connect', '/xiaomi/login', '/xiaomi/use'):
            self.send_response(403); self.end_headers(); return
        try:
            n = min(int(self.headers.get('Content-Length', 0)), 4096)
            d = json.loads(self.rfile.read(n) or b'{}')
        except (ValueError, TypeError):
            return self._json({'ok': False, 'error': 'bad'}, 400)
        if u.path.startswith('/xiaomi/'):
            try:
                if u.path == '/xiaomi/login':
                    return self._json(xiaomi_login(d))
                url = str(d.get('url', ''))
                if not url.startswith('xiaomi://') or url not in [c['url'] for c in xiaomi_cameras()['cameras']]:
                    return self._json({'ok': False, 'error': 'Pick a camera from the list.'}, 400)
                xiaomi_use(url)
                print('Using Xiaomi camera', urlparse(url).hostname)
                return self._json({'ok': True, 'brand': 'Xiaomi'})
            except Exception as e:  # noqa: BLE001
                print('Xiaomi:', e)
                return self._json({'ok': False, 'error': str(e)[:200]})
        try:
            ip = str(ipaddress.ip_address(str(d.get('ip', '')).strip()))
            if not ipaddress.ip_address(ip).is_private:
                raise ValueError('not a home-network address')
            user, password = str(d.get('user', ''))[:64], str(d.get('password', ''))[:128]
            port = int(d.get('port') or 554)
        except (ValueError, TypeError):
            return self._json({'ok': False, 'error': 'bad'}, 400)
        print(f'Trying camera {ip} ...')
        res = find_stream(FFMPEG, ip, user, password, port)
        if res['ok']:
            save_url(res['url'])
            switch_camera(res['url'], FFMPEG)
            print(f'Found the video ({res["brand"]}): {hide_password(res["url"])}')
            return self._json({'ok': True, 'brand': res['brand']})
        print('Could not open the camera:', res['error'])
        return self._json(res)


FFMPEG = None


# ------------------------------------------------------------------ Xiaomi cameras (through go2rtc) --
# Xiaomi cameras have no RTSP. go2rtc (MIT licence, https://github.com/AlexxIT/go2rtc) can sign in to a
# Xiaomi account and turn their video into RTSP. It is downloaded only when someone asks for Xiaomi, runs
# only on this computer (127.0.0.1) and keeps the Xiaomi sign-in in its own config file there.
G2_VERSION = 'v1.9.15'
G2_HOME = os.environ.get('ROCKBRO_HOME') or os.path.join(os.path.expanduser('~'), '.rockbro')
G2_API = 'http://127.0.0.1:1985'
G2_RTSP = 'rtsp://127.0.0.1:8555/rockbro'
G2_ASSETS = {  # (system, machine) -> release file
    ('windows', 'amd64'): 'go2rtc_win64.zip', ('windows', 'arm64'): 'go2rtc_win_arm64.zip',
    ('darwin', 'amd64'): 'go2rtc_mac_amd64.zip', ('darwin', 'arm64'): 'go2rtc_mac_arm64.zip',
    ('linux', 'amd64'): 'go2rtc_linux_amd64', ('linux', 'arm64'): 'go2rtc_linux_arm64',
}
G2_SHA256 = {}   # filled in for files we've checked; others are trusted from GitHub over HTTPS
g2 = {'proc': None}


def g2_exe():
    return os.path.join(G2_HOME, 'go2rtc.exe' if os.name == 'nt' else 'go2rtc')


def g2_install():
    import hashlib, platform, urllib.request, zipfile, io
    if os.path.exists(g2_exe()):
        return
    sysname = platform.system().lower()
    mach = {'x86_64': 'amd64', 'amd64': 'amd64', 'aarch64': 'arm64', 'arm64': 'arm64'}.get(platform.machine().lower(), '')
    asset = G2_ASSETS.get((sysname, mach))
    if not asset:
        raise RuntimeError(f'Xiaomi cameras are not supported on {sysname}/{platform.machine()} yet.')
    url = f'https://github.com/AlexxIT/go2rtc/releases/download/{G2_VERSION}/{asset}'
    print(f'Downloading go2rtc {G2_VERSION} for Xiaomi cameras ({asset}) ...')
    with urllib.request.urlopen(url, timeout=120) as r:
        data = r.read()
    want = G2_SHA256.get(asset)
    if want and hashlib.sha256(data).hexdigest() != want:
        raise RuntimeError('The go2rtc download did not match the expected file, so it was not used.')
    os.makedirs(G2_HOME, exist_ok=True)
    if asset.endswith('.zip'):
        with zipfile.ZipFile(io.BytesIO(data)) as z:
            name = next(n for n in z.namelist() if os.path.basename(n).startswith('go2rtc'))
            data = z.read(name)
    with open(g2_exe(), 'wb') as f:
        f.write(data)
    if os.name != 'nt':
        os.chmod(g2_exe(), 0o755)
    print('go2rtc installed in', G2_HOME)


def g2_start():
    """run go2rtc on this computer only, with its own config in G2_HOME"""
    import urllib.request
    if g2['proc'] and g2['proc'].poll() is None:
        return
    g2_install()
    cfg = os.path.join(G2_HOME, 'go2rtc.yaml')
    if not os.path.exists(cfg):
        with open(cfg, 'w', encoding='utf-8') as f:
            f.write('api:\n  listen: "127.0.0.1:1985"\nrtsp:\n  listen: "127.0.0.1:8555"\n'
                    'webrtc:\n  listen: ""\nsrtp:\n  listen: ""\nrtmp:\n  listen: ""\nlog:\n  level: warn\n')
        if os.name != 'nt':
            os.chmod(cfg, 0o600)
    flags = 0x08000000 if os.name == 'nt' else 0      # no extra console window on Windows
    g2['proc'] = subprocess.Popen([g2_exe(), '-config', cfg], cwd=G2_HOME, stdout=subprocess.DEVNULL,
                                  stderr=subprocess.DEVNULL, creationflags=flags)
    for _ in range(50):
        try:
            urllib.request.urlopen(G2_API + '/api', timeout=1).read()
            return
        except OSError:
            time.sleep(0.2)
    raise RuntimeError('go2rtc did not start.')


def g2_call(method, path, form=None):
    """-> (status, body bytes)"""
    import urllib.request, urllib.error
    from urllib.parse import urlencode
    data = urlencode(form).encode() if form is not None else None
    req = urllib.request.Request(G2_API + path, data=data, method=method)
    if data is not None:
        req.add_header('Content-Type', 'application/x-www-form-urlencoded')
    try:
        with urllib.request.urlopen(req, timeout=40) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        return e.code, e.read()


def xiaomi_login(d):
    g2_start()
    form = {k: str(d[k])[:200] for k in ('username', 'password', 'captcha', 'verify') if d.get(k)}
    code, body = g2_call('POST', '/api/xiaomi', form)
    if code == 200:
        return {'ok': True}
    if code == 401:
        try:
            e = json.loads(body)
        except ValueError:
            e = {}
        if e.get('captcha'):
            return {'ok': False, 'need': 'captcha', 'image': e['captcha']}   # base64 picture of letters
        if e.get('verify_phone') or e.get('verify_email'):
            return {'ok': False, 'need': 'verify', 'to': e.get('verify_phone') or e.get('verify_email')}
    msg = body.decode('utf-8', 'replace').strip()[:200]
    print('Xiaomi sign-in failed:', msg[:120])
    if '70016' in msg:
        return {'ok': False, 'error': 'Wrong Xiaomi account or password.'}
    if '87001' in msg or '70019' in msg:
        return {'ok': False, 'error': "That code wasn't right. Try again."}
    return {'ok': False, 'error': 'Xiaomi sign-in failed. Check the account and password, or try again in a minute.'}


def xiaomi_cameras():
    g2_start()
    code, body = g2_call('GET', '/api/xiaomi')
    users = json.loads(body) if code == 200 else []
    cams, seen = [], set()
    for user in users:
        for region in ('cn', 'de', 'i2', 'ru', 'sg', 'us'):
            code, body = g2_call('GET', f'/api/xiaomi?id={quote(user)}&region={region}')
            if code != 200:
                continue
            try:
                d = json.loads(body)
            except ValueError:
                continue
            for s in (d.get('sources') if isinstance(d, dict) else d) or []:
                url = s.get('url', '')
                did = parse_qs(urlparse(url).query).get('did', [''])[0]
                if url.startswith('xiaomi://') and did not in seen:
                    seen.add(did)
                    ip = (re.search(r'ip: ([\d.]+)', s.get('info', '')) or [None, ''])[1]
                    cams.append({'name': s.get('name') or 'Xiaomi camera', 'ip': ip, 'url': url})
            if cams:
                break           # an account lives in one region
    return {'signed_in': bool(users), 'cameras': cams}


def xiaomi_use(url):
    g2_start()
    code, body = g2_call('PUT', f'/api/streams?name=rockbro&src={quote(url, safe="")}')
    if code >= 300:
        raise RuntimeError(body.decode('utf-8', 'replace')[:200])
    save_url(G2_RTSP, xiaomi=url)
    switch_camera(G2_RTSP, FFMPEG)


def save_url(url, xiaomi=None):
    try:
        with open(CONFIG, 'w', encoding='utf-8') as f:
            json.dump({'url': url, 'xiaomi': xiaomi} if xiaomi else {'url': url}, f)
        if os.name != 'nt':
            os.chmod(CONFIG, 0o600)
    except OSError:
        pass


def get_url():
    args = [a for a in sys.argv[1:] if not a.startswith('--')]
    if '--forget' in sys.argv:
        if os.path.exists(CONFIG):
            os.remove(CONFIG)
        print('Saved camera address deleted.')
        sys.exit(0)
    if args:
        url = args[0]
    else:
        try:
            with open(CONFIG, encoding='utf-8') as f:
                saved = json.load(f)
            url = saved['url']
            if saved.get('xiaomi'):
                try:
                    g2_start()
                    g2_call('PUT', f'/api/streams?name=rockbro&src={quote(saved["xiaomi"], safe="")}')
                except Exception as e:  # noqa: BLE001
                    print('Could not start the Xiaomi camera:', e)
                    return None
                print('Using the saved Xiaomi camera', urlparse(saved['xiaomi']).hostname, '(run with --forget to change it)')
                return url
            print('Using the saved camera:', hide_password(url), '(run with --forget to change it)')
            return url
        except (OSError, ValueError, KeyError):
            return None                    # no camera yet: pick one with "Find cameras" on the website
    if not url.lower().startswith(('rtsp://', 'rtsps://', 'http://', 'https://')):
        print('That does not look like a camera address. It should start with rtsp://')
        sys.exit(1)
    save_url(url)
    return url


def main():
    global FFMPEG
    print('Rockbro Camera Helper')
    url = get_url()
    FFMPEG = find_ffmpeg()
    server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler)
    if url:
        switch_camera(url, FFMPEG)
        print(f'Connecting to {hide_password(url)} ...')
    else:
        print('Ready. On https://rockbro.vercel.app choose "Home or security camera", then press Find cameras.')
        if '--no-browser' not in sys.argv:
            try:
                webbrowser.open('https://rockbro.vercel.app/?cam=helper')
            except Exception:  # noqa: BLE001
                pass
    print('Keep this window open while you play. Press Ctrl+C to stop.')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print('\nStopped.')
    finally:
        if g2['proc'] and g2['proc'].poll() is None:
            g2['proc'].kill()


if __name__ == '__main__':
    main()
