# -*- coding: utf-8 -*-
"""通过 React Fiber 找封面上传组件并触发"""
import sys, socket, json, time
sys.stdout.reconfigure(encoding='utf-8')
HOST = "localhost"; PORT = 28800
PAGE_ID = "70039F329097C14448996F189E3A42A1"

def ws():
    import urllib.parse
    u = "ws://%s:%s/devtools/page/%s" % (HOST, PORT, PAGE_ID)
    p = urllib.parse.urlparse(u)
    s = socket.create_connection((p.hostname, p.port or 80), timeout=15)
    req = ("GET %s HTTP/1.1\r\nHost: %s:%s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n" % (p.path, p.hostname, p.port))
    s.send(req.encode())
    resp = b''
    while b'\r\n\r\n' not in resp: resp += s.recv(4096)
    return s

def send(s, d):
    d = d.encode('utf-8'); n = len(d); m = b'\x01\x02\x03\x04'
    if n <= 125: h = bytes([0x81, n|0x80]) + m
    elif n <= 65535: h = bytes([0x81, 0xFE]) + n.to_bytes(2,'big') + m
    else: h = bytes([0x81, 0xFF]) + n.to_bytes(8,'big') + m
    s.send(h + bytes(d[i]^m[i%4] for i in range(n)))

def recv(s):
    def rx(n):
        b = b''
        while len(b) < n: b += s.recv(n-len(b))
        return b
    h = rx(2); n = h[1]&0x7f
    if n == 126: n = int.from_bytes(rx(2),'big')
    elif n == 127: n = int.from_bytes(rx(8),'big')
    return rx(n).decode('utf-8')

_mid = 0
def cdp(s, js, timeout=20):
    global _mid
    _mid += 1
    send(s, json.dumps({'id':_mid,'method':'Runtime.evaluate','params':{'expression':js,'returnByValue':True}}))
    s.settimeout(timeout)
    for _ in range(300):
        try:
            r = json.loads(recv(s))
            if r.get('id') == _mid:
                return r.get('result',{}).get('result',{}).get('value','')
        except: pass
    return ''

s = ws()
print("[OK] Connected\n")

# 通过 React 事件系统找封面上传
r = cdp(s, """
(function() {
  // 找"选择封面"附近的 DOM 元素
  var all = document.querySelectorAll('span, div, label');
  var result = [];
  for (var el of all) {
    var t = (el.innerText || '').trim();
    if (t === '选择封面' && el.children.length < 5) {
      var rect = el.getBoundingClientRect();
      var s = window.getComputedStyle(el);
      result.push({
        tag: el.tagName,
        class: el.className.substring(0,40),
        text: t,
        x: Math.round(rect.left + rect.width/2),
        y: Math.round(rect.top + rect.height/2),
        display: s.display,
        hasInput: el.querySelector('input') ? 'yes' : 'no',
        parent: el.parentElement ? el.parentElement.tagName + '.' + el.parentElement.className.substring(0,20) : ''
      });
    }
  }
  return JSON.stringify(result);
})()
""")
print("[选择封面元素]", r[:300] if r else 'empty')

# 找 input[type=file] 的父元素链
r = cdp(s, """
(function() {
  var inputs = document.querySelectorAll('input[type=file]');
  var result = [];
  for (var inp of inputs) {
    var parent = inp.parentElement;
    var chain = [inp.tagName];
    for (var i = 0; i < 5; i++) {
      if (parent) {
        chain.push(parent.tagName + (parent.className ? '.' + parent.className.substring(0,15) : ''));
        parent = parent.parentElement;
      }
    }
    result.push({accept: inp.accept, chain: chain.join(' > ')});
  }
  return JSON.stringify(result);
})()
""")
print("[file input 链]", r[:300] if r else 'empty')

# 找封面上传相关的 React state/setState 函数
r = cdp(s, """
(function() {
  // 找包含"cover"或"封面"文本的 React state
  var all = document.querySelectorAll('*');
  var result = [];
  for (var el of all) {
    var keys = Object.keys(el);
    for (var k of keys) {
      if (k.indexOf('cover') > -1 || k.indexOf('Cover') > -1 || k.indexOf('upload') > -1) {
        try {
          var v = el[k];
          if (v && typeof v === 'function') {
            result.push({tag: el.tagName, key: k, fn_preview: v.toString().substring(0,50)});
          }
        } catch(e) {}
      }
    }
  }
  return JSON.stringify(result.slice(0, 10));
})()
""")
print("[cover函数]", r[:400] if r else 'empty')

# 找 __reactFiber 并遍历组件树找封面上传
r = cdp(s, """
(function() {
  // 找所有带 __reactFiber 的元素
  var all = document.querySelectorAll('*');
  var result = [];
  for (var el of all) {
    var keys = Object.keys(el);
    for (var k of keys) {
      if (k.indexOf('__reactFiber') > -1) {
        var fiber = el[k];
        if (fiber && typeof fiber === 'object') {
          var stateNode = fiber.stateNode;
          var memoizedProps = fiber.memoizedProps;
          var name = fiber.type ? (fiber.type.displayName || fiber.type.name || fiber.type) : '';
          if (name.toLowerCase().indexOf('cover') > -1 || name.toLowerCase().indexOf('upload') > -1 || name.toLowerCase().indexOf('image') > -1) {
            result.push({tag: el.tagName, name: name, stateNode: stateNode ? (stateNode.tag || typeof stateNode) : 'null'});
          }
        }
      }
    }
  }
  return JSON.stringify(result);
})()
""")
print("[React封面上传]", r[:400] if r else 'empty')

s.close()
