Skip to content

Commit

Permalink
Only fetch translations when connected to Steam
Browse files Browse the repository at this point in the history
  • Loading branch information
suchmememanyskill committed Aug 20, 2024
1 parent e21965d commit 698719e
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 71 deletions.
9 changes: 7 additions & 2 deletions css_browserhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import css_inject

MAX_QUEUE_SIZE = 500
ON_WEBSOCKET_CONNECT = asyncio.Event()

class BrowserTabHook:
def __init__(self, browserHook, sessionId : str, targetInfo : dict):
Expand Down Expand Up @@ -232,8 +233,8 @@ def get_id(self) -> int:
return self.current_id

async def open_websocket(self):
self.client = aiohttp.ClientSession()
self.websocket = await self.client.ws_connect(self.ws_url)
self.client = aiohttp.ClientSession(trust_env=True)
self.websocket = await self.client.ws_connect(self.ws_url, ssl=False)

async def close_websocket(self):
self.connected_tabs.clear()
Expand Down Expand Up @@ -427,6 +428,8 @@ async def health_check(self):
Log("Connected to Steam Browser")
await self.send_command("Target.setDiscoverTargets", {"discover": True}, None, False)

ON_WEBSOCKET_CONNECT.set()

async for message in self.websocket:
data = message.json()
for x in self.ws_response:
Expand All @@ -436,6 +439,8 @@ async def health_check(self):
except Exception as e:
Result(False, f"[Health Check] {str(e)}")

ON_WEBSOCKET_CONNECT.clear()

try:
await self.close_websocket()
except:
Expand Down
13 changes: 12 additions & 1 deletion css_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from os import listdir, path, mkdir
import json

LOADER_INSTANCE = None

class Loader:
def __init__(self):
self.busy = False
Expand Down Expand Up @@ -374,4 +376,13 @@ async def _generate_preset_theme_internal(self, name : str, deps : dict) -> Resu
x.dependencies = deps
break

return Result(True)
return Result(True)


def get_loader_instance() -> Loader:
global LOADER_INSTANCE

if LOADER_INSTANCE == None:
LOADER_INSTANCE = Loader()

return LOADER_INSTANCE
63 changes: 63 additions & 0 deletions css_mappings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import os, asyncio, aiohttp
from css_loader import get_loader_instance
from css_utils import Log, store_read, is_steam_beta_active, get_theme_path
from css_inject import initialize_class_mappings
from css_browserhook import ON_WEBSOCKET_CONNECT

STARTED_FETCHING_TRANSLATIONS = False
SUCCESSFUL_FETCH_THIS_RUN = False

async def __fetch_class_mappings(css_translations_path : str):
global SUCCESSFUL_FETCH_THIS_RUN

if SUCCESSFUL_FETCH_THIS_RUN:
return

setting = store_read("beta_translations")

if ((len(setting.strip()) <= 0 or setting == "-1" or setting == "auto") and is_steam_beta_active()) or (setting == "1" or setting == "true"):
css_translations_url = "https://api.deckthemes.com/beta.json"
else:
css_translations_url = "https://api.deckthemes.com/stable.json"

Log(f"Fetching CSS mappings from {css_translations_url}")

try:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False, use_dns_cache=False), timeout=aiohttp.ClientTimeout(total=30)) as session:
async with session.get(css_translations_url) as response:
if response.status == 200:
text = await response.text()

if len(text.strip()) <= 0:
raise Exception("Empty response")

with open(css_translations_path, "w", encoding="utf-8") as fp:
fp.write(text)

SUCCESSFUL_FETCH_THIS_RUN = True
Log(f"Fetched css translations from server")
initialize_class_mappings()
asyncio.get_running_loop().create_task(get_loader_instance().reset(silent=True))

except Exception as ex:
Log(f"Failed to fetch css translations from server [{type(ex).__name__}]: {str(ex)}")

async def __every(__seconds: float, func, *args, **kwargs):
global SUCCESSFUL_FETCH_THIS_RUN

await ON_WEBSOCKET_CONNECT.wait()

while not SUCCESSFUL_FETCH_THIS_RUN:
await func(*args, **kwargs)
await asyncio.sleep(__seconds)

async def force_fetch_translations():
global SUCCESSFUL_FETCH_THIS_RUN

SUCCESSFUL_FETCH_THIS_RUN = False
css_translations_path = os.path.join(get_theme_path(), "css_translations.json")
await __fetch_class_mappings(css_translations_path)

def start_fetch_translations():
css_translations_path = os.path.join(get_theme_path(), "css_translations.json")
asyncio.get_event_loop().create_task(__every(60, __fetch_class_mappings, css_translations_path))
74 changes: 6 additions & 68 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@

from css_server import start_server
from css_browserhook import initialize
from css_loader import Loader
from css_loader import Loader, get_loader_instance
from css_mappings import force_fetch_translations, start_fetch_translations


ALWAYS_RUN_SERVER = False
IS_STANDALONE = False
Expand All @@ -26,60 +28,6 @@

Initialized = False

SUCCESSFUL_FETCH_THIS_RUN = False

async def fetch_class_mappings(css_translations_path : str, loader : Loader):
global SUCCESSFUL_FETCH_THIS_RUN, GOOGLE_PING_COUNT

if SUCCESSFUL_FETCH_THIS_RUN:
return

if GOOGLE_PING_COUNT < 5:
try:
socket.setdefaulttimeout(3)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("8.8.8.8", 53))
except Exception as e:
Log(f"No internet connection. Not fetching css translations. (Error: {str(e)})")
GOOGLE_PING_COUNT += 1
return
else:
Log("Skipping internet check...")


setting = util_store_read("beta_translations")

if ((len(setting.strip()) <= 0 or setting == "-1" or setting == "auto") and is_steam_beta_active()) or (setting == "1" or setting == "true"):
css_translations_url = "https://api.deckthemes.com/beta.json"
else:
css_translations_url = "https://api.deckthemes.com/stable.json"

Log(f"Fetching CSS mappings from {css_translations_url}")

try:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False, use_dns_cache=False), timeout=aiohttp.ClientTimeout(total=30)) as session:
async with session.get(css_translations_url) as response:
if response.status == 200:
text = await response.text()

if len(text.strip()) <= 0:
raise Exception("Empty response")

with open(css_translations_path, "w", encoding="utf-8") as fp:
fp.write(text)

SUCCESSFUL_FETCH_THIS_RUN = True
Log(f"Fetched css translations from server")
initialize_class_mappings()
asyncio.get_running_loop().create_task(loader.reset(silent=True))

except Exception as ex:
Log(f"Failed to fetch css translations from server [{type(ex).__name__}]: {str(ex)}")

async def every(__seconds: float, func, *args, **kwargs):
while True:
await func(*args, **kwargs)
await asyncio.sleep(__seconds)

class FileChangeHandler(FileSystemEventHandler):
def __init__(self, loader : Loader, loop):
self.loader = loader
Expand Down Expand Up @@ -208,19 +156,9 @@ async def upload_theme(self, name : str, base_url : str, bearer_token : str) ->
return (await self.loader.upload_theme(name, base_url, bearer_token)).to_dict()

async def fetch_class_mappings(self):
await self._fetch_class_mappings(self)
await force_fetch_translations()
return Result(True).to_dict()

async def _fetch_class_mappings(self, run_in_bg : bool = False):
global SUCCESSFUL_FETCH_THIS_RUN

SUCCESSFUL_FETCH_THIS_RUN = False
css_translations_path = os.path.join(get_theme_path(), "css_translations.json")
if run_in_bg:
asyncio.get_event_loop().create_task(every(60, fetch_class_mappings, css_translations_path, self.loader))
else:
await fetch_class_mappings(css_translations_path, self.loader)

async def _main(self):
global Initialized
if Initialized:
Expand All @@ -236,7 +174,7 @@ async def _main(self):

create_steam_symlink()

self.loader = Loader()
self.loader = get_loader_instance()
await self.loader.load(False)

if (store_or_file_config("watch")):
Expand All @@ -249,7 +187,7 @@ async def _main(self):
if (ALWAYS_RUN_SERVER or store_or_file_config("server")):
await self.enable_server(self)

await self._fetch_class_mappings(self, True)
start_fetch_translations()
await initialize()

if __name__ == '__main__':
Expand Down

0 comments on commit 698719e

Please sign in to comment.