Files

44 lines
2.4 KiB
Python

"""Temporary app-scoped WebView2 debugging for the installed Desktop session."""
from contextlib import contextmanager
import json, socket, subprocess, time, urllib.request
KEY=r'Software\Policies\Microsoft\Edge\WebView2\AdditionalBrowserArguments'
APP='WhatsApp.Root.exe'
ACTIVATE=r"Get-Process -Name WhatsApp.Root -ErrorAction SilentlyContinue | Stop-Process; Start-Process -FilePath explorer.exe -ArgumentList 'shell:AppsFolder\5319275A.WhatsAppDesktop_cv1g1gvanyjgm!App' -WindowStyle Hidden"
def restart():
subprocess.run(['powershell.exe','-NoProfile','-NonInteractive','-Command',ACTIVATE],capture_output=True,text=True,check=True)
@contextmanager
def temporary_desktop_cdp():
import winreg
with socket.socket() as sock:
sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
key=winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER,KEY,0,winreg.KEY_READ|winreg.KEY_SET_VALUE)
try:
try:old=winreg.QueryValueEx(key,APP)
except FileNotFoundError:old=None
flags=f'--remote-debugging-address=127.0.0.1 --remote-debugging-port={port}'
if old and old[1]!=winreg.REG_SZ:raise RuntimeError('Unexpected existing WebView2 policy value type')
if old and '--remote-debugging' in old[0]:raise RuntimeError('Existing debug policy requires explicit endpoint selection')
winreg.SetValueEx(key,APP,0,winreg.REG_SZ,((old[0]+' ') if old else '')+flags)
try:
print('Restarting WhatsApp Desktop with a temporary loopback execution interface.',flush=True)
restart();endpoint=f'http://127.0.0.1:{port}'
deadline=time.monotonic()+60
while time.monotonic()<deadline:
try:
with urllib.request.urlopen(endpoint+'/json/list',timeout=2) as response:targets=json.load(response)
if any(t.get('type')=='page' and t.get('url','').startswith('https://web.whatsapp.com/') for t in targets):
yield endpoint
return
except OSError:pass
time.sleep(1)
raise RuntimeError('Desktop did not expose its WhatsApp page within 60 seconds')
finally:
if old is None:winreg.DeleteValue(key,APP)
else:winreg.SetValueEx(key,APP,0,old[1],old[0])
restart()
print('Temporary setting restored; Desktop restarted normally.',flush=True)
finally:winreg.CloseKey(key)