# -*- coding: utf-8 -*-
"""测试填写文章内容"""
import sys, socket, json, base64, urllib.request, time, os
sys.stdout.reconfigure(encoding='utf-8', errors='replace')

HOST = 'localhost'
PORT = 9222

def get_first_page():
    pages = json.loads(urllib.request.urlopen(f'http://{HOST}:{PORT}/json', timeout=5).read())
    for p in pages:
        if p.get('type') == 'page':
            return p
    return None

def ws_connect(url):
    import urllib.parse
    parsed = urllib.parse.urlparse(url)
    sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=10)
    key = 'dGhlIHNhbXBsZSBub25jZQ=='
    hs = f'GET {parsed.path} HTTP/1.1\r\nHost: {parsed.hostname}:{parsed.port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n'
    sock.send(hs.encode())
    resp = b''
    while b'\r\n\r\n' not in resp:
        resp += sock.recv(4096)
    return sock

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

def recv_frame(sock):
    def rx(n):
        buf = b''
        while len(buf) < n:
            buf += sock.recv(n - len(buf))
        return buf
    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_call(sock, method, params=None):
    global _mid
    _mid += 1
    msg = {'id': _mid, 'method': method}
    if params:
        msg['params'] = params
    send_frame(sock, json.dumps(msg))
    sock.settimeout(30)
    while True:
        raw = recv_frame(sock)
        obj = json.loads(raw)
        if obj.get('id') == _mid:
            return obj.get('result', {})

page = get_first_page()
print(f'Page: {page["id"]}')
sock = ws_connect(page['webSocketDebuggerUrl'])

# 检查页面元素
result = cdp_call(sock, 'Runtime.evaluate', {'expression': '''
var info = [];
var title = document.querySelector('#title');
if(title) info.push('title found: ' + title.value);
else info.push('title NOT found');
var editor = document.querySelector('.edit_area');
if(editor) info.push('editor found, length: ' + editor.innerText.length);
else info.push('editor NOT found');
info.join(' | ');
'''})
print('Page info:', result)

# 填写标题
title = '考公"P图诈胡"事件反转'
result = cdp_call(sock, 'Runtime.evaluate', {'expression': f'''
var titleEl = document.querySelector('#title');
if(titleEl) {{
    titleEl.value = "{title}";
    titleEl.dispatchEvent(new Event('input', {{bubbles: true}}));
    'OK: 标题已填';
}} else {{
    'ERROR: 标题框未找到';
}}
'''})
print('Title result:', result)

# 填写正文
content = '这是一篇测试文章内容。0.05分的差距，有人选择全力以赴，有人选择P图骗人。'
result = cdp_call(sock, 'Runtime.evaluate', {'expression': f'''
var editor = document.querySelector('.edit_area');
if(editor) {{
    editor.innerHTML = "{content}";
    editor.dispatchEvent(new Event('input', {{bubbles: true}}));
    'OK: 正文已填';
}} else {{
    'ERROR: 编辑器未找到';
}}
'''})
print('Content result:', result)

sock.close()
print('Done - 请查看Chrome确认内容')
