Skip to content

Commit

Permalink
Merge pull request #116 from DeckThemes/profile-uploading-rebase
Browse files Browse the repository at this point in the history
Merge main into profile-uploading
  • Loading branch information
beebls committed May 6, 2024
2 parents 9985da7 + ff42d50 commit ffc8373
Show file tree
Hide file tree
Showing 15 changed files with 401 additions and 5,020 deletions.
4 changes: 2 additions & 2 deletions css_browserhook.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os, re, uuid, asyncio, json, aiohttp, time
from typing import List
from css_utils import get_theme_path, Log, Result
from css_utils import get_theme_path, Log, Result, PLATFORM_WIN
import css_inject

MAX_QUEUE_SIZE = 500
Expand Down Expand Up @@ -414,7 +414,7 @@ async def health_check(self):
while True:
await asyncio.sleep(3)
try:
async with aiohttp.ClientSession() as web:
async with aiohttp.ClientSession(trust_env=PLATFORM_WIN) as web:
res = await web.get(f"http://127.0.0.1:8080/json/version", timeout=3)

if (res.status != 200):
Expand Down
54 changes: 49 additions & 5 deletions css_inject.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,45 @@
import json
import re
import os
import aiohttp
import asyncio
from typing import List
from css_utils import Result, Log
from css_utils import Result, Log, store_read, get_theme_path
from css_browserhook import BrowserTabHook as CssTab, inject, remove
import uuid

CLASS_MAPPINGS = {}

def initialize_class_mappings():
css_translations_path = os.path.join(get_theme_path(), "css_translations.json")

if not os.path.exists(css_translations_path):
Log("Failed to get css translations from local file")
return

try:
with open(css_translations_path, "r", encoding="utf-8") as fp:
data : dict = json.load(fp)
except Exception as e:
Log(f"Failed to load css translations from local file: {str(e)}")
return

CLASS_MAPPINGS.clear()

# Data is in the format of { "uid": ["ver1", "ver2", "ver3"]}
for uid in data:
latest_value = data[uid][-1]
for y in data[uid][:-1]:
CLASS_MAPPINGS[y] = latest_value

Log("Loaded css translations from local file")

ALL_INJECTS = []

def helper_get_tab_from_list(tab_list : List[str], cssTab : CssTab) -> str|None:
for x in tab_list:
if cssTab.compare(x):
return x

return None

class Inject:
Expand All @@ -28,8 +58,22 @@ async def load(self) -> Result:
with open(self.cssPath, "r") as fp:
self.css = fp.read()

split_css = re.split(r"(\.[_a-zA-Z]+[_a-zA-Z0-9-]*)", self.css)

for x in range(len(split_css)):
if split_css[x].startswith(".") and split_css[x][1:] in CLASS_MAPPINGS:
split_css[x] = "." + CLASS_MAPPINGS[split_css[x][1:]]

self.css = ("".join(split_css)).replace("\\", "\\\\").replace("`", "\\`")

split_css = re.split(r"(\[class[*^|~]=\"[_a-zA-Z0-9-]*\"\])", self.css)

for x in range(len(split_css)):
if split_css[x].startswith("[class") and split_css[x].endswith("\"]") and split_css[x][9:-2] in CLASS_MAPPINGS:
split_css[x] = split_css[x][0:9] + CLASS_MAPPINGS[split_css[x][9:-2]] + split_css[x][-2:]

self.css = ("".join(split_css)).replace("\\", "\\\\").replace("`", "\\`")
Log(f"Loaded css at {self.cssPath}")
self.css = self.css.replace("\\", "\\\\").replace("`", "\\`")

return Result(True)
except Exception as e:
Expand Down Expand Up @@ -106,7 +150,7 @@ async def remove(self) -> Result:
"desktoppopup": ["OverlayBrowser_Browser", "SP Overlay:.*", "notificationtoasts_.*", "SteamBrowser_Find", "OverlayTab\\d+_Find", "!ModalDialogPopup", "!FullModalOverlay"],
"desktopoverlay": ["desktoppopup"],
"desktopcontextmenu": [".*Menu", ".*Supernav"],
"bigpicture": ["~Valve Steam Gamepad/default~", "~Valve%20Steam%20Gamepad/default~"],
"bigpicture": ["~Valve Steam Gamepad/default~", "~Valve%20Steam%20Gamepad~"],
"bigpictureoverlay": ["QuickAccess", "MainMenu"],
"store": ["~https://store.steampowered.com~", "~https://steamcommunity.com~"],

Expand Down
14 changes: 14 additions & 0 deletions css_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,20 @@ def get_steam_path() -> str:
else:
return f"{get_user_home()}/.steam/steam"

def is_steam_beta_active() -> bool:
beta_path = os.path.join(get_steam_path(), "package", "beta")
if not os.path.exists(beta_path):
return False

with open(beta_path, 'r') as fp:
content = fp.read().strip()

stable_branches = [
"steamdeck_stable",
]

return content not in stable_branches

def create_steam_symlink() -> Result:
return create_symlink(get_theme_path(), os.path.join(get_steam_path(), "steamui", "themes_custom"))

Expand Down
60 changes: 57 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import os, asyncio, sys, time
import os, asyncio, sys, time, aiohttp, json

from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

sys.path.append(os.path.dirname(__file__))

from css_utils import Log, create_steam_symlink, Result, get_theme_path, store_read as util_store_read, store_write as util_store_write, store_or_file_config
from css_inject import ALL_INJECTS
from css_utils import Log, create_steam_symlink, Result, get_theme_path, store_read as util_store_read, store_write as util_store_write, store_or_file_config, is_steam_beta_active
from css_inject import ALL_INJECTS, initialize_class_mappings
from css_theme import CSS_LOADER_VER
from css_remoteinstall import install

Expand All @@ -25,6 +25,44 @@

Initialized = False

SUCCESSFUL_FETCH_THIS_RUN = False

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

if SUCCESSFUL_FETCH_THIS_RUN:
return

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(verify_ssl=False), timeout=aiohttp.ClientTimeout(total=2)) as session:
async with session.get(css_translations_url) as response:
if response.status == 200:
with open(css_translations_path, "w", encoding="utf-8") as fp:
fp.write(await response.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: {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 @@ -148,6 +186,20 @@ async def get_last_load_errors(self):
async def upload_theme(self, name : str, base_url : str, bearer_token : str) -> dict:
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)
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 @@ -158,6 +210,7 @@ async def _main(self):
self.server_loaded = False

Log("Initializing css loader...")
initialize_class_mappings()
Log(f"Max supported manifest version: {CSS_LOADER_VER}")

create_steam_symlink()
Expand All @@ -175,6 +228,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)
await initialize()

if __name__ == '__main__':
Expand Down
Loading

0 comments on commit ffc8373

Please sign in to comment.