import os
import re
import sys
import requests

os.makedirs("images", exist_ok=True)

url = "http://localhost/discuz5/"

i = 0

while True:
    i += 1
    
    res = requests.get(url + "member.php?mod=logging&action=login")
    
    if (res.status_code != 200):
        sys.exit(f"[!] Unexpected response at iteration {i}")
    
    match = re.search(r"updateseccode\('([^']+)", res.text)
    seccode = match.group(1) if match else False
    login_cookies = res.cookies
    
    if not seccode:
        sys.exit("[!] Failed, unable to find seccode")
    
    res = requests.get(url + f"misc.php?mod=seccode&action=update&modid=member::logging&idhash={seccode}", cookies=login_cookies)
    match = re.search(r'update=(\d+)', res.text)
    magic_number = match.group(1) if match else sys.exit("[!] Failed, magic number not found!")
    res = requests.get(url + f"misc.php?mod=seccode&update={magic_number}&idhash={seccode}", cookies=login_cookies, headers={"Referer": url})
    
    if (res.status_code != 200):
    	sys.exit("[!] Failed, unable to download CAPTCHA")

    parts = res.content.split(b'\n\n\n\n', 1)
    
    if len(parts) < 2:
        sys.exit(f"[!] Unexpected response format at iteration {i}")

    filename_part, image_data = parts
    filename = f"images/{filename_part.decode(errors='ignore')}.png"

    print(f"{i} ({filename_part.decode(errors='ignore')})")

    if not os.path.exists(filename) and image_data:
        print(f"[+] Writing {filename}")
        with open(filename, "wb") as f:
            f.write(image_data)
