Reinject loader if steam got restarted

This commit is contained in:
WerWolv
2022-04-07 09:58:26 +02:00
parent a3619d1d3a
commit 3dec82672a
2 changed files with 44 additions and 7 deletions
+17 -3
View File
@@ -1,11 +1,13 @@
#Injector code from https://github.com/SteamDeckHomebrew/steamdeck-ui-inject. More info on how it works there. #Injector code from https://github.com/SteamDeckHomebrew/steamdeck-ui-inject. More info on how it works there.
from aiohttp import ClientSession from aiohttp import ClientSession
from logging import debug from logging import debug, getLogger
from asyncio import sleep from asyncio import sleep
BASE_ADDRESS = "http://localhost:8080" BASE_ADDRESS = "http://localhost:8080"
logger = getLogger("Injector")
class Tab: class Tab:
def __init__(self, res) -> None: def __init__(self, res) -> None:
self.title = res["title"] self.title = res["title"]
@@ -68,7 +70,7 @@ async def get_tabs():
res = await web.get("{}/json".format(BASE_ADDRESS)) res = await web.get("{}/json".format(BASE_ADDRESS))
break break
except: except:
print("Steam isn't available yet. Wait for a moment...") logger.info("Steam isn't available yet. Wait for a moment...")
await sleep(5) await sleep(5)
if res.status == 200: if res.status == 200:
@@ -82,4 +84,16 @@ async def inject_to_tab(tab_name, js):
tab = next((i for i in tabs if i.title == tab_name), None) tab = next((i for i in tabs if i.title == tab_name), None)
if not tab: if not tab:
raise ValueError("Tab {} not found in running tabs".format(tab_name)) raise ValueError("Tab {} not found in running tabs".format(tab_name))
debug(await tab.evaluate_js(js)) logger.debug(f"Injected JavaScript Result: {await tab.evaluate_js(js)}")
async def tab_has_element(tab_name, element_name):
tabs = await get_tabs()
tab = next((i for i in tabs if i.title == tab_name), None)
if not tab:
return False
res = await tab.evaluate_js(f"document.getElementById('{element_name}') != null")
if not "result" in res or not "result" in res["result"] or not "value" in res["result"]["result"]:
return False;
return res["result"]["result"]["value"]
+26 -3
View File
@@ -1,5 +1,6 @@
from logging import basicConfig, INFO, DEBUG from logging import getLogger, basicConfig, INFO, DEBUG
from os import getenv from os import getenv
CONFIG = { CONFIG = {
"plugin_path": getenv("PLUGIN_PATH", "/home/deck/homebrew/plugins"), "plugin_path": getenv("PLUGIN_PATH", "/home/deck/homebrew/plugins"),
"server_host": getenv("SERVER_HOST", "127.0.0.1"), "server_host": getenv("SERVER_HOST", "127.0.0.1"),
@@ -13,13 +14,16 @@ from aiohttp.web import Application, run_app, static
from aiohttp_jinja2 import setup as jinja_setup from aiohttp_jinja2 import setup as jinja_setup
from jinja2 import FileSystemLoader from jinja2 import FileSystemLoader
from os import path from os import path
from asyncio import get_event_loop from asyncio import get_event_loop, sleep
from json import loads, dumps from json import loads, dumps
from loader import Loader from loader import Loader
from injector import inject_to_tab, get_tabs from injector import inject_to_tab, get_tabs, tab_has_element
from utilities import util_methods from utilities import util_methods
logger = getLogger("Main")
class PluginManager: class PluginManager:
def __init__(self) -> None: def __init__(self) -> None:
self.loop = get_event_loop() self.loop = get_event_loop()
@@ -30,6 +34,14 @@ class PluginManager:
self.web_app.on_startup.append(self.inject_javascript) self.web_app.on_startup.append(self.inject_javascript)
self.web_app.add_routes([static("/static", path.join(path.dirname(__file__), 'static'))]) self.web_app.add_routes([static("/static", path.join(path.dirname(__file__), 'static'))])
self.loop.create_task(self.method_call_listener()) self.loop.create_task(self.method_call_listener())
self.loop.create_task(self.loader_reinjector())
self.loop.set_exception_handler(self.exception_handler)
def exception_handler(self, loop, context):
if context["message"] == "Unclosed connection":
return
loop.default_exception_handler(context)
async def resolve_method_call(self, tab, call_id, response): async def resolve_method_call(self, tab, call_id, response):
await tab._send_devtools_cmd({ await tab._send_devtools_cmd({
@@ -72,8 +84,19 @@ class PluginManager:
method = loads(data["params"]["args"][0]["value"]) method = loads(data["params"]["args"][0]["value"])
self.loop.create_task(self.handle_method_call(method, tab)) self.loop.create_task(self.handle_method_call(method, tab))
async def loader_reinjector(self):
while True:
await sleep(1)
if not await tab_has_element("QuickAccess", "plugin_iframe"):
logger.info("Plugin loader isn't present in Steam anymore, reinjecting...")
await self.inject_javascript()
async def inject_javascript(self, request=None): async def inject_javascript(self, request=None):
try:
await inject_to_tab("QuickAccess", open(path.join(path.dirname(__file__), "static/plugin_page.js"), "r").read()) await inject_to_tab("QuickAccess", open(path.join(path.dirname(__file__), "static/plugin_page.js"), "r").read())
except:
logger.info("Failed to inject JavaScript into tab")
pass
def run(self): def run(self):
return run_app(self.web_app, host=CONFIG["server_host"], port=CONFIG["server_port"], loop=self.loop) return run_app(self.web_app, host=CONFIG["server_host"], port=CONFIG["server_port"], loop=self.loop)