import os
import requests
import time
import json
import websocket
import mimetypes

from tqdm import tqdm
from tqdm.utils import CallbackIOWrapper

import sys


path = sys.argv[1]
mime = mimetypes.guess_type(path)[0]

print("[.] MIME type from ext:", mime)


def get_token():
    WS = "wss://weblink05.netease.im/socket.io/1/websocket/"

    resp = requests.get(
        "https://weblink07.netease.im/socket.io/1/?t=" + str(int(time.time() * 1000))
    )
    sid = resp.text.split(":")[0]
    WS += sid

    print("[.] Connecting to", WS, "...")
    ws = websocket.create_connection(WS, header=["Origin: https://qiyukf.com"])
    resp = ws.recv()

    if resp != "1::":
        print("[-] Unexpected response:", resp)
        exit(1)

    print("[+] Connected")

    # First: send client identification
    payload = {
        "SID": 2,
        "CID": 3,
        "SER": 1,
        "timeout": 8000,
        "hasPacketResponse": True,
        "hasPacketTimer": True,
        "Q": [
            {
                "t": "Property",
                "v": {
                    "3": 16,
                    "4": "Linux 64-bit",
                    "6": "91703",
                    "8": 1,
                    "9": 1,
                    "13": "bc93249d76dc1b781ab6cacd473f7fc3",
                    "18": "c694d17083d50a8a482aeeb6c0072af2",
                    "19": "af7a346eae9bc8c3308eef0d9bdfb4f5",
                    "24": "Chrome 128.0.0.0",
                    "26": "5615bd2cb5dfe173b397e63c8558df81",
                    "38": "",
                    "40": "9.17.3",
                    "41": 100,
                    "42": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
                    "44": "BROWSER",
                    "112": 0,
                    "1000": "7c38df2e0f184b59b3bd5f336f1def9d",
                },
            }
        ],
    }

    print("[.] Sending first payload...")
    ws.send("3:::" + json.dumps(payload))

    resp = str(ws.recv())

    if '"code":200' not in resp:
        print("[-] Unexpected response:", resp)
        exit(1)

    print("[+] Client identified")

    inner_payload = {
        "md5": "$(Etag)",
        "size": "$(ObjectSize)",
        "w": "$(ImageInfo.Width)",
        "h": "$(ImageInfo.Height)",
        "orientation": "$(ImageInfo.Orientation)",
    }
    payload = {
        "CID": 2,
        "SER": 69,
        "SID": 6,
        "hasPacketResponse": True,
        "hasPacketTimer": True,
        "timeout": 8000,
        "Q": [
            {"t": "String", "v": json.dumps(inner_payload).replace('"', '\\"')},
            {"t": "Property", "v": {"8": "im"}},
        ],
    }

    print("[.] Sending token payload...")
    ws.send("3:::" + json.dumps(payload))

    resp = str(ws.recv())
    resp = resp.strip("3:::")

    resp = json.loads(resp)
    print("[+] Token received")

    path = resp["r"][0]["1"]
    token = resp["r"][0]["2"]

    return path, token


obj_path, token = get_token()


URL = "https://cdn-nimup-chunk.qiyukf.net/nim/"
URL = URL + obj_path
URL += "?offset=0&complete=true&version=1.0"

headers = {
    "x-nos-token": token,
    # content
    "content-type": mime,
}


# POST
print("[.] Uploading file...")
file_size = os.stat(path).st_size


five_mb = 5 * 1024 * 1024
with open(path, "rb") as f:
    if file_size > five_mb:
        print("[!] File larger than 5MB. Showing progress...")
        with tqdm(total=file_size, unit="B", unit_scale=True, unit_divisor=1024) as t:
            wrapped_file = CallbackIOWrapper(t.update, f, "read")
            resp = requests.post(URL, data=wrapped_file, headers=headers)
    else:
        resp = requests.post(URL, data=f.read(), headers=headers)

BASE_URL = "https://szsbjkjyxgs1.cdn.qiyukf.net/"

if resp.ok:
    print("[+] File uploaded")
    print("[+] File URL:", BASE_URL + obj_path)
else:
    print("[-] Error uploading file")
    print("[-] Status code:", resp.status_code)
    print("[-] Response:", resp.text)
    exit(1)
