Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 19 additions & 15 deletions TMWebDriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
import bottle
from bottle import request

def safe_print(*a, **k):
try: print(*a, **k)
except: pass

class Session:
def __init__(self, session_id, info, client=None):
self.id = session_id
Expand All @@ -29,7 +33,7 @@ def reconnect(self, client, info):
self.connect_at = time.time()
self.disconnect_at = None
def mark_disconnected(self):
if self.disconnect_at is None: print(f"Tab disconnected: {self.url} (Session: {self.id})")
if self.disconnect_at is None: safe_print(f"Tab disconnected: {self.url} (Session: {self.id})")
self.disconnect_at = time.time()


Expand All @@ -56,7 +60,7 @@ def long_poll():
session_info = {'url': data.get('url'), 'title': data.get('title', ''), 'type': 'http'}
if session_id not in self.sessions:
session = Session(session_id, session_info, queue.Queue())
print(f"Browser http connected: {session.url} (Session: {session_id})")
safe_print(f"Browser http connected: {session.url} (Session: {session_id})")
self.sessions[session_id] = session
session = self.sessions[session_id]
if session.disconnect_at is not None and session.type != 'http': session.reconnect(queue.Queue(), session_info)
Expand Down Expand Up @@ -95,7 +99,7 @@ def link():
timeout = float(data.get('timeout', 10.0))
try: result = self.execute_js(code, timeout=timeout, session_id=session_id)
except Exception as e: return json.dumps({'r': {'error': str(e)}}, ensure_ascii=False)
try: print('[remote result]', (str(code)[:50] + ' RESULT:' +str(result)[:50]).replace('\n', ' '))
try: safe_print('[remote result]', (str(code)[:50] + ' RESULT:' +str(result)[:50]).replace('\n', ' '))
except Exception: pass
return json.dumps({'r': result}, ensure_ascii=False)
return 'ok'
Expand Down Expand Up @@ -130,7 +134,7 @@ def handle(self) -> None:
elif data.get('type') in ['ext_ready', 'tabs_update']:
tabs = data.get('tabs', [])
current_tab_ids = {str(tab['id']) for tab in tabs}
print(f"Received tabs update: {current_tab_ids}")
safe_print(f"Received tabs update: {current_tab_ids}")
for sid in list(driver.sessions.keys()):
sess = driver.sessions[sid]
if sess.type == 'ext_ws' and sid not in current_tab_ids:
Expand All @@ -147,30 +151,30 @@ def handle(self) -> None:
elif data.get('type') == 'error':
driver.results[data.get('id')] = {'success': False, 'data': data.get('error'), 'newTabs': data.get('newTabs', [])}
except Exception as e:
print(f"Error handling message: {e}")
if hasattr(self, 'data'): print(self.data)
safe_print(f"Error handling message: {e}")
if hasattr(self, 'data'): safe_print(self.data)
def connected(self): (f"New connection from {self.address}")
def handle_close(self):
print(f"WS Connection closed: {self.address}")
safe_print(f"WS Connection closed: {self.address}")
driver._unregister_client(self)

self.server = WebSocketServer(self.host, self.port, JSExecutor)
server_thread = threading.Thread(target=self.server.serve_forever)
server_thread.daemon = True
server_thread.start()
print(f"WebSocket server running on ws://{self.host}:{self.port}")
safe_print(f"WebSocket server running on ws://{self.host}:{self.port}")

def _register_client(self, session_id: str, client: WebSocket, session_info) -> None:
is_new_session = session_id not in self.sessions

if is_new_session:
session = Session(session_id, session_info, client)
self.sessions[session_id] = session
print(f"New tab connected: {session.url} (Session: {session_id})")
safe_print(f"New tab connected: {session.url} (Session: {session_id})")
else:
session = self.sessions[session_id]
session.reconnect(client, session_info)
print(f"Tab reconnected: {session.url} (Session: {session_id})")
safe_print(f"Tab reconnected: {session.url} (Session: {session_id})")

self.latest_session_id = session_id
if self.default_session_id is None: self.default_session_id = session_id
Expand All @@ -182,7 +186,7 @@ def _unregister_client(self, client: WebSocket) -> None:
def execute_js(self, code, timeout=15, session_id=None) -> Any:
if session_id is None: session_id = self.default_session_id
if self.is_remote:
print('remote_execute_js')
safe_print('remote_execute_js')
response = self._remote_cmd({"cmd": "execute_js", "sessionId": session_id,
"code": code, "timeout": str(timeout)}).get('r', {})
if response.get('error'): raise Exception(response['error'])
Expand All @@ -196,7 +200,7 @@ def execute_js(self, code, timeout=15, session_id=None) -> Any:
alive_sessions = [s for s in self.sessions.values() if s.is_active()]
if alive_sessions:
session = alive_sessions[0]
print(f"会话 {session_id} 未连接,自动切换到最新活动会话: {session.id}")
safe_print(f"会话 {session_id} 未连接,自动切换到最新活动会话: {session.id}")
session_id = self.default_session_id = session.id
if not session or not session.is_active():
raise ValueError(f"会话ID {session_id} 未连接")
Expand Down Expand Up @@ -271,10 +275,10 @@ def set_session(self, url_pattern: str) -> bool:
matched = self._remote_cmd({"cmd": "find_session", "url_pattern": url_pattern}).get('r', [])
else:
matched = self.find_session(url_pattern)
if not matched: return print(f"警告: 未找到URL包含 '{url_pattern}' 的会话")
if len(matched) > 1: print(f"警告: 找到多个URL包含 '{url_pattern}' 的会话,选择第一个")
if not matched: return safe_print(f"警告: 未找到URL包含 '{url_pattern}' 的会话")
if len(matched) > 1: safe_print(f"警告: 找到多个URL包含 '{url_pattern}' 的会话,选择第一个")
self.default_session_id, info = matched[0]
print(f"成功设置默认会话: {self.default_session_id}: {info['url']}")
safe_print(f"成功设置默认会话: {self.default_session_id}: {info['url']}")
return self.default_session_id

def jump(self, url, timeout=10): self.execute_js(f"window.location.href='{url}'", timeout=timeout)
Expand Down