Skip to content

Commit

Permalink
Merge pull request #98 from suchmememanyskill/dev
Browse files Browse the repository at this point in the history
Release v2.0.0
  • Loading branch information
suchmememanyskill authored Sep 19, 2023
2 parents e801cf3 + 204e4f9 commit b2b10f9
Show file tree
Hide file tree
Showing 68 changed files with 3,191 additions and 1,653 deletions.
62 changes: 56 additions & 6 deletions css_browserhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ async def _init(self):
if res != None:
self.title = res["title"]
self.html_classes = res["classes"]
else:
Log(f"Failed to connect to tab with id {self.id}")
self.hook.connected_tabs.remove(self)
return

self.init_done = True
Log(f"Connected to tab: {self.title}")
Expand Down Expand Up @@ -214,14 +218,14 @@ def __init__(self):
self.ws_url = None
self.ws_response : List[asyncio.Queue] = []
self.connected_tabs : List[BrowserTabHook] = []
self.tab_names = {}

asyncio.create_task(self.on_new_tab())
asyncio.create_task(self.on_tab_update())
asyncio.create_task(self.on_tab_attach())
asyncio.create_task(self.on_tab_detach())
asyncio.create_task(self.health_check())
asyncio.create_task(self.css_health_check())
asyncio.create_task(self.sanity_check_tabs())

def get_id(self) -> int:
self.current_id += 1
Expand Down Expand Up @@ -265,7 +269,7 @@ async def send_command(self, method : str, params : dict, sessionId : str|None,
result = await queue.get()

if (start_time + 5) < time.time():
Result(False, f"Request for {method} took more than 5s. Assuming it failed")
Result(False, f"Request for {method} took more than 5s. Assuming it failed ({len(self.connected_tabs)})")
self.ws_response.remove(queue)
del queue
return None
Expand All @@ -278,6 +282,10 @@ async def send_command(self, method : str, params : dict, sessionId : str|None,
return None
raise RuntimeError("Websocket not opened")

async def _tab_exists(self, tab_id : str):
result = await self.send_command("Target.getTargets", {}, None)
return tab_id in [x["targetId"] for x in result["result"]["targetInfos"] if x["type"] == "page"]

async def on_new_tab(self):
queue = asyncio.Queue(maxsize=MAX_QUEUE_SIZE)
self.ws_response.append(queue)
Expand All @@ -289,6 +297,9 @@ async def on_new_tab(self):
if message["params"]["targetInfo"]["type"] != "page":
continue

if not await self._tab_exists(message["params"]["targetInfo"]["targetId"]):
continue

await self.send_command("Target.attachToTarget", {"targetId": message["params"]["targetInfo"]["targetId"], "flatten": True}, None, False)

async def on_tab_update(self):
Expand All @@ -301,6 +312,9 @@ async def on_tab_update(self):
if "method" in message and message["method"] == "Target.targetInfoChanged":
target_info = message["params"]["targetInfo"]

if not await self._tab_exists(message["params"]["targetInfo"]["targetId"]):
continue

for connected_tab in self.connected_tabs:
if target_info["targetId"] == connected_tab.id:
reinject = False
Expand Down Expand Up @@ -350,6 +364,42 @@ async def on_tab_detach(self):
Log(f"Disconnected from tab: {tab.title}")
self.connected_tabs.remove(tab)

async def sanity_check_tabs(self):
while True:
try:
result = await self.send_command("Target.getTargets", {}, None, True)
target_infos = result["result"]["targetInfos"]
target_ids = [x["targetId"] for x in target_infos if x["type"] == "page"]
for x in self.connected_tabs: # Remove tabs that are no longer connected
if x.id not in target_ids:
Log(f"Disconnected from tab: {x.title}")
self.connected_tabs.remove(x)

connected_ids = [x.id for x in self.connected_tabs]
for x in target_infos:
if x["targetId"] not in connected_ids: # Attach tabs that are not connected
await self.send_command("Target.attachToTarget", {"targetId": x["targetId"], "flatten": True}, None, False)
else:
for connected_tab in self.connected_tabs: # Update info on tabs that are connected
if connected_tab.id == x["targetId"]:
reinject = False
if (x["title"] != connected_tab.title):
connected_tab.title = x["title"]
reinject = True

if (x["url"] != connected_tab.url):
connected_tab.url = x["url"]
reinject = True

if reinject:
asyncio.create_task(connected_tab.force_reinject())

break
except:
pass

await asyncio.sleep(5)

async def css_health_check(self):
while True:
for tab in self.connected_tabs:
Expand All @@ -365,7 +415,7 @@ async def health_check(self):
await asyncio.sleep(3)
try:
async with aiohttp.ClientSession() as web:
res = await web.get(f"http://localhost:8080/json/version", timeout=3)
res = await web.get(f"http://127.0.0.1:8080/json/version", timeout=3)

if (res.status != 200):
raise Exception(f"/json/version returned {res.status}")
Expand All @@ -384,7 +434,7 @@ async def health_check(self):
x.put_nowait(data)

except Exception as e:
Log(f"[Browser Health Check] {str(e)}")
Result(False, f"[Health Check] {str(e)}")

try:
await self.close_websocket()
Expand All @@ -404,8 +454,8 @@ def get_tabs(tab_name : str) -> List[BrowserTabHook]:
if tab.compare(tab_name):
tabs.append(tab)

if tabs == []:
Log(f"[Warn] get_tabs({tab_name}) returned []. All tabs: {str([x.title for x in HOOK.connected_tabs])}")
#if tabs == []:
# Log(f"[Warn] get_tabs({tab_name}) returned []. All tabs: {str([x.title for x in HOOK.connected_tabs])}")

return tabs

Expand Down
8 changes: 3 additions & 5 deletions css_inject.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ async def load(self) -> Result:
async def inject(self) -> Result:
for tab_name in self.tabs:
for uuid in self.uuids[tab_name]:
Log(f"-{uuid} @ {tab_name}")
res = await remove(tab_name, uuid)

if (self.css is None):
Expand All @@ -51,7 +50,7 @@ async def inject(self) -> Result:
if not res.success:
return res

Log(f"+{str(res.message)} @ {tab_name}")
# Log(f"+{str(res.message)} @ {tab_name}")
self.uuids[tab_name].append(str(res.message))
except Exception as e:
return Result(False, str(e))
Expand All @@ -75,7 +74,7 @@ async def inject_with_tab(self, tab : CssTab) -> Result:
if not res.success:
return res

Log(f"+{str(res.message)} @ {tab_name}")
# Log(f"+{str(res.message)} @ {tab_name}")
self.uuids[tab_name].append(str(res.message))
except Exception as e:
return Result(False, str(e))
Expand All @@ -89,7 +88,6 @@ async def remove(self) -> Result:

try:
for x in self.uuids[tab_name]:
Log(f"-{x} @ {tab_name}")
res = await remove(tab_name, x)
#if not res["success"]:
# return Result(False, res["result"])
Expand All @@ -103,7 +101,7 @@ async def remove(self) -> Result:
return Result(True)

DEFAULT_MAPPINGS = {
"desktop": ["Steam.*"],
"desktop": ["Steam|SteamLibraryWindow"],
"desktopchat": ["!friendsui-container"],
"desktoppopup": ["OverlayBrowser_Browser", "SP Overlay:.*", "notificationtoasts_.*", "SteamBrowser_Find", "OverlayTab\\d+_Find", "!ModalDialogPopup", "!FullModalOverlay"],
"desktopoverlay": ["desktoppopup"],
Expand Down
Loading

0 comments on commit b2b10f9

Please sign in to comment.