Update backend architecture

This commit is contained in:
oitsjustjose 2024-12-11 00:29:12 -06:00
commit 9491692407
30 changed files with 434 additions and 701 deletions

26
.gitignore vendored
View file

@ -1,17 +1,21 @@
__pycache__
.venv
device_id
status
start.bat
status
test.py
geckodriver.log
weapons
templates/rendered*
Lib/
out.log
pixlet
pyvenv.cfg
Scripts/
src/main.build/
src/main.dist/
src/main.onefile-build/
src/main.exe
Lib/
Scripts/
pyvenv.cfg
out.log
src/main.onefile-build/
start.bat
status
status
templates/rendered*
test.py
tmp.star
tmp.webp
weapons

View file

@ -1,4 +0,0 @@
{
"splatoon": false,
"forgeserv": true
}

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View file

@ -1,28 +1,56 @@
async-generator==1.10
attrs==22.1.0
beautifulsoup4==4.11.1
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
comtypes==1.1.14
exceptiongroup==1.0.1
h11==0.14.0
idna==3.4
outcome==1.2.0
Pillow==9.3.0
pycparser==2.21
PySocks==1.7.1
python-dateutil==2.8.2
pywin32==305
pywinauto==0.6.8
requests==2.28.1
selenium==4.6.0
six==1.16.0
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.3.2.post1
trio==0.22.0
trio-websocket==0.9.2
urllib3==1.26.12
uuid==1.30
wsproto==1.2.0
annotated-types==0.7.0
anyio==4.7.0
async-generator==1.10
attrs==22.1.0
beautifulsoup4==4.11.1
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
click==8.1.7
comtypes==1.1.14
dnspython==2.7.0
email_validator==2.2.0
exceptiongroup==1.2.2
fastapi==0.115.6
fastapi-cli==0.0.6
h11==0.14.0
httpcore==1.0.7
httptools==0.6.4
httpx==0.28.1
idna==3.4
Jinja2==3.1.4
markdown-it-py==3.0.0
MarkupSafe==3.0.2
mdurl==0.1.2
outcome==1.2.0
Pillow==9.3.0
pycparser==2.21
pydantic==2.10.3
pydantic_core==2.27.1
Pygments==2.18.0
PySocks==1.7.1
python-dateutil==2.8.2
python-dotenv==1.0.1
python-multipart==0.0.19
PyYAML==6.0.2
requests==2.28.1
rich==13.9.4
rich-toolkit==0.12.0
selenium==4.6.0
shellingham==1.5.4
six==1.16.0
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.3.2.post1
starlette==0.41.3
trio==0.22.0
trio-websocket==0.9.2
typer==0.15.1
typing_extensions==4.12.2
urllib3==1.26.12
uuid==1.30
uvicorn==0.32.1
uvloop==0.21.0
watchfiles==1.0.3
websockets==14.1
wsproto==1.2.0

View file

@ -1,26 +0,0 @@
load("render.star", "render")
load("encoding/base64.star", "base64")
ICON = base64.decode(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAACXBIWXMAAC4jAAAuIwF4pT92AAACQklEQVQ4jaWUQWgTQRSGv5ndJLubNG2JtlpiPPSi1lsPCiJexN70VAQVVBAvHvRSKEJB1JNeiqeKiHfBg/QiQgUVCx70ZNWDoVrSojZRk2yS3e3ujIdsq7ZBCn3weG9mfn7mzf/mCa01WzHzwGx1/d5h4IEQdlOr6hGvftfTqvpSCLsXuAjM/EPQgXQKGIzzk0ATGI7Xd4Chv8GyA8F0O2jAKIBMt3MAwg0ldCAYBx4jjC6tG/No75zA+C/BQWAMcAAFeMBnMIta/XqKagiktYpvxXEiLmvSBJ4DyQ330CtIo9/H6FnSqoYQNkAZOARcj1EnzHpXpgwMKClI+QGWF9BI26hEAsKs23TteXQLRJKaSL1J6bDfISRCAFTMvu/lPcBoYiXMVXK9O0v5bHL3lx+fHE8UQ+lO+8olFN6oCd3H1ML9b6RZEJkxi+gn8MicunS1DrQsz/cWdg2MFwfzwfDb92ec5UBHfRp74h3kwq/SlT15XbtZE5ZRxiolUD5QF5Xe43PAPiUNbK91Ot3wnGo2cy9oJTH7gpHMZFEYufBJ5Bo0SZAkIkWEapdQMutdmb2r79ZI26VyjlMA2jSQ6eT+iFRdItGxlCEmzT/q503gKHADmANeAJcBhKOIFq1C9DFzxRhZ3qZdYwgoABbtBmwBt03gWeyrlgXQgUB2r2i53S9oX76O5Z5dr3anVm5bIBA94bzY4Z/FN2aAV8CtzRA4ayehCAnkEnLtL1zYDME1YBEoAg9j/wAsAefXg8VWB8pv0SnWrEYYD8cAAAAASUVORK5CYII="
)
def main():
return render.Root(
child=render.Column(
expanded=True,
main_align="space_around",
cross_align="center",
children=[
render.Image(src=ICON),
render.Row(
expanded=True,
main_align="space_around",
cross_align="center",
children=[render.Text("In a Huddle"),]
)
],
)
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 654 B

View file

@ -1,21 +0,0 @@
"""A wrapper class for Config"""
import json
from util import rel_to_abspath
class Config:
"""A cheap JSON-based config reader"""
def __init__(self, conf_path=rel_to_abspath("../modules.json")) -> None:
with open(conf_path, "r", encoding="utf-8") as fhandle:
self.data = json.loads(fhandle.read())
def get_option(self, option: str) -> bool:
"""Gets a given option, returning False if the option was not defined"""
return self.data[option] if option in self.data else False
def get_all(self) -> dict:
"""Gets all the options available as a dict"""
return self.data

View file

@ -1,108 +0,0 @@
"""The handler for ForgeServ status updates"""
import datetime
import json
import urllib.request
from dataclasses import dataclass
from time import sleep
from typing import List, Union
import pixlet
from util import Renderable, rel_to_abspath
@dataclass
class Player:
"""Represents a player on the server"""
name: str
head: str
uuid: str
@dataclass
class Server:
"""Represents a single ForgeServ server"""
max_players: int
online_players: int
server_dynmap_url: Union[None, str]
server_health: str
server_icon: str
server_motd: str
server_name: str
server_type: str
server_version: str
players: List[Player]
def parse_servers(json_in: str) -> List[Server]:
"""Parses the raw response JSON from the API into a list of servers"""
# https://cravatar.eu/head/fda160e2-e608-4233-b325-558d92a82a0e
data = json.loads(json_in)
servers: List[Server] = []
for idx, serv in enumerate(data):
try:
servers.append(
Server(
max_players=serv["max"],
online_players=serv["online"],
server_dynmap_url=serv["dynmap"],
server_health=serv["health"],
server_icon=serv["icon"],
server_motd=serv["motd"],
server_name=serv["name"],
server_type=serv["type"],
server_version=serv["version"],
players=[
Player(
name=x["name"],
uuid=x["uuid"],
head=f"https://cravatar.eu/head/{x['uuid']}",
)
for x in serv["players"]
],
)
)
except ValueError:
print(f"Skipping server at index {idx}")
return servers
class ForgeServRenderer(Renderable):
def __init__(self) -> None:
self.last_render = datetime.datetime.now()
self.cached_servers: List[Server] = []
self.render_file = rel_to_abspath("../templates/rendered.star")
self.pixlet_out = self.render_file.replace(".star", ".webp")
def render(self) -> None:
servers: List[Server] = self.cached_servers
if not servers or (datetime.datetime.now() - self.last_render).seconds >= 10:
with urllib.request.urlopen("https://api.forgeserv.net") as response:
servers = parse_servers(response.read().decode())
top_server: Server = servers[0]
for server in servers:
if server.online_players > top_server.online_players:
top_server = server
pixlet.update_template(
rel_to_abspath("../templates/forgeserv.star"),
self.render_file,
{
"<IMAGE>": top_server.server_icon,
"<SERVER-NAME>": top_server.server_name,
"<ONLINE-PLAYERS>": top_server.online_players,
"<MAX-PLAYERS>": top_server.max_players,
"<PLAYER-LIST>": ", ".join([x.name for x in top_server.players]),
},
)
pixlet.render(self.render_file)
pixlet.display(self.pixlet_out, installation_id="status")
sleep(20)

View file

@ -1,130 +0,0 @@
"""The mainfile"""
import json
import traceback
from dataclasses import dataclass
from time import sleep
from typing import Dict
from pywinauto import Desktop
from pywinauto.controls.hwndwrapper import InvalidWindowHandle
import pixlet
from config import Config
from forgeserv import ForgeServRenderer
from salmon_run import SalmonRunRenderer
from util import Renderable, rel_to_abspath
@dataclass
class RenderType:
"""A list of all various render types"""
HUDDLE = "HUDDLE"
OBS_PAUSED = "OBS_PAUSED"
OBS_RECORDING = "OBS_RECORDING"
OBS_STREAMING = "OBS_STREAMING"
SPLATOON = "SPLATOON"
FORGESERV = "FORGESERV"
ZOOM = "ZOOM"
def main():
"""The main run function of the application"""
desktop = Desktop()
config = Config()
rendering = ""
renderers: Dict[str, Renderable] = {
RenderType.SPLATOON: SalmonRunRenderer(),
RenderType.FORGESERV: ForgeServRenderer(),
}
while True:
try:
windows = list(
filter(
lambda x: x, # Filter out empty vals
[w.window_text() for w in desktop.windows()],
)
)
huddle_windows = list(filter(lambda x: "huddle" in x.lower(), windows))
obs_windows = list(
filter(lambda x: "obs" in x.lower() and "64" in x.lower(), windows)
)
if "Zoom Meeting" in windows:
if rendering != RenderType.ZOOM:
pixlet.display(
rel_to_abspath("../zoom/meeting.webp"),
installation_id="status",
)
rendering = RenderType.ZOOM
elif huddle_windows:
if rendering != RenderType.HUDDLE:
pixlet.display(
rel_to_abspath("../slack/huddle.webp"),
installation_id="status",
)
rendering = RenderType.HUDDLE
elif obs_windows:
print("e")
with open(
rel_to_abspath("../status"), "r", encoding="utf-8"
) as file_handle:
data = json.loads(file_handle.read())
if data["STREAMING"]:
if rendering != RenderType.OBS_STREAMING:
pixlet.display(
rel_to_abspath("../streaming/active.webp"),
installation_id="status",
)
rendering = RenderType.OBS_STREAMING
elif data["RECORDING"]:
if rendering != RenderType.OBS_RECORDING:
pixlet.display(
rel_to_abspath("../recording/active.webp"),
installation_id="status",
)
rendering = RenderType.OBS_RECORDING
else:
if rendering != RenderType.OBS_PAUSED:
pixlet.display(
rel_to_abspath("../recording/paused.webp"),
installation_id="status",
)
rendering = RenderType.OBS_PAUSED
else:
if config.get_option("splatoon"):
# If the uploaded render isn't already splatoon, push it
if rendering != RenderType.SPLATOON:
rendering = RenderType.SPLATOON
elif config.get_option("forgeserv"):
if rendering != RenderType.FORGESERV:
rendering = RenderType.FORGESERV
renderers[rendering].render()
except KeyboardInterrupt:
break
except InvalidWindowHandle:
continue
except Exception as ex:
with open(
rel_to_abspath("../out.log"), "a+", encoding="utf-8"
) as log_handle:
log_handle.write(f"{ex}\n")
tb_lines = [
line.rstrip("\n")
for line in traceback.format_exception(
ex.__class__, ex, ex.__traceback__
)
]
_ = [log_handle.write(f"{x}\n") for x in tb_lines]
sleep(1)
if __name__ == "__main__":
with open(rel_to_abspath("../out.log"), "w", encoding="utf-8") as log_handle:
log_handle.write("")
main()

View file

@ -1,30 +0,0 @@
import json
import os
from util import rel_to_abspath
status = {"STREAMING": False, "RECORDING": False}
def on_event(event):
if event == obspython.OBS_FRONTEND_EVENT_RECORDING_STARTED:
status["RECORDING"] = True
__write()
if event == obspython.OBS_FRONTEND_EVENT_RECORDING_STOPPED:
status["RECORDING"] = False
__write()
if event == obspython.OBS_FRONTEND_EVENT_STREAMING_STARTED:
status["STREAMING"] = True
__write()
if event == obspython.OBS_FRONTEND_EVENT_STREAMING_STOPPED:
status["STREAMING"] = False
__write()
def __write():
with open(rel_to_abspath("../status"), "w") as fh:
fh.write(json.dumps(status))
def script_load(settings):
__write()
obspython.obs_frontend_add_event_callback(on_event)

View file

@ -1,71 +0,0 @@
"""
Python wrapper for Pixlet Operations
"""
import subprocess
import os
from util import rel_to_abspath
STARTUP_INFO = subprocess.STARTUPINFO()
STARTUP_INFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
def update_template(template_path: str, out_path: str, replacers: dict):
"""
Opens the template up at template_path, reads it in,
replaces all keys in replacers with their values
then writes it out with the same name in `./out`
Arguments:
template_path (str): the path of the template.star to load
out_path (str): where the output should be saved
replacers (dict): a Dict[str,str] whose keys are in the template,
and whose values will replace their keys in the template
"""
if not os.path.exists(rel_to_abspath("../out")):
os.mkdir(rel_to_abspath("../out"))
with open(template_path, "r", encoding="utf-8") as file_handle:
data = file_handle.read()
for key in replacers:
data = data.replace(key, replacers[key])
with open(out_path, "w", encoding="utf-8") as file_handle:
file_handle.write(data)
def display(file_path: str, installation_id: str = None):
"""
Displays a file (by name) to the Tidbyt, reading the device id from `device_id`
"""
with open(rel_to_abspath("../device_id"), "r", encoding="utf-8") as file_handle:
device_id = file_handle.read()
if installation_id:
args = [
rel_to_abspath("../pixlet.exe"),
"push",
"--installation-id",
installation_id,
device_id,
file_path,
]
else:
args = [
rel_to_abspath("../pixlet.exe"),
"push",
device_id,
file_path,
]
with subprocess.Popen(args, startupinfo=STARTUP_INFO) as process:
process.wait()
def render(file_path: str):
"""
Uses Pixlet to render a `.star` file to webp so that it can be pushed
Args:
file_path (str): the path (relative) to the file you want rendered
"""
with subprocess.Popen(
[rel_to_abspath("../pixlet.exe"), "render", file_path],
startupinfo=STARTUP_INFO,
) as process:
process.wait()

View file

@ -1,131 +0,0 @@
"""All about Splatoon Salmon Run rendering"""
from dataclasses import dataclass
from datetime import datetime
from time import sleep
from typing import List, Union
import dateutil.parser
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import pixlet
from salmon_run.images import loadout_to_b64
from util import Renderable, rel_to_abspath
@dataclass
class SalmonRunEvent:
"""Represents a GrizzCo Job"""
start: datetime
end: datetime
stage_name: str
loadout: List[str]
@dataclass
class Cache:
"""Caching System"""
last_update: datetime
event: list
class SalmonRunRenderer(Renderable):
"""The class-instanced renderer for splatoon, including a little renderer cache"""
def __init__(self) -> None:
self.cache: Union[Cache, None] = None
self.render_file = rel_to_abspath("../templates/rendered.star")
self.pixlet_out = self.render_file.replace(".star", ".webp")
def render(self) -> None:
"""
Renders out the Splatoon module
Arguments: None
Returns: None
"""
if (
self.cache
and self.cache.last_update.date() == datetime.datetime.now().date()
):
pixlet.display(self.pixlet_out, installation_id="status")
return
data = self.__get_salmon_run_data()[0]
pixlet.update_template(
rel_to_abspath("../templates/splatoon.star"),
self.render_file,
{
"<IMAGE>": loadout_to_b64(data.loadout),
"<START_DATE>": f"{data.start.month}/{data.start.day} {data.start.hour%12}:{str(data.start.minute).zfill(2)} {'AM' if data.start.hour < 12 else 'PM'}",
"<END_DATE>": f"{data.end.month}/{data.end.day} {data.end.hour%12}:{str(data.end.minute).zfill(2)} {'AM' if data.end.hour < 12 else 'PM'}",
"<STAGE>": data.stage_name,
},
)
pixlet.render(self.render_file)
pixlet.display(self.pixlet_out, installation_id="status")
sleep(60)
def __get_salmon_run_data(self) -> List[SalmonRunEvent]:
"""
Scrapes salmon run data
Arguments: None
Returns: (List[SalmonRunEvent]): a list of all salmon run events upcoming
"""
if (
self.cache
and self.cache.last_update.date() == datetime.datetime.now().date()
):
return self.cache.event
options = Options()
options.add_argument("--headless")
options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()), options=options
)
driver.get("https://splatoon.oatmealdome.me/three/salmon-run")
main_el = driver.page_source
main_el = BeautifulSoup(main_el, features="html.parser")
main_el = main_el.body.find("main").find("div", attrs={"class": "d-grid gap-3"})
# The row where the datetime is shown when the evt. will occur
times: List[str] = [
x.text.strip()
for x in main_el.find_all("div", attrs={"class": "d-flex flex-row"})
]
# The row where the actual Salmon Run loadout & reward is
events: List[BeautifulSoup] = main_el.find_all(
"div", attrs={"class": "bg-salmon-run"}
)
data: List[SalmonRunEvent] = []
for idx, evt in enumerate(events):
start, end = times[idx].split(" - ")
start = dateutil.parser.parse(start)
end = dateutil.parser.parse(end)
stage_name = evt.find("span", attrs={"class": "text-stage-name"}).text
event_root = evt.find("div", attrs={"class": "col d-flex flex-column"})
# Get the photos of the loadout, then lean on the `title` attr
loadout = [
f"https://splatoon.oatmealdome.me/{x.find('img').attrs['src']}"
for x in event_root.find("div", attrs={"class": "row gx-2"}).find_all(
"picture"
)
]
data.append(SalmonRunEvent(start, end, stage_name, loadout))
driver.close()
self.cache = Cache(last_update=datetime.datetime.now(), event=data)
return data

View file

@ -1,56 +0,0 @@
"""General image magiks"""
import base64
import os
from typing import List
import requests
from PIL import Image
from webptools import dwebp
from util import rel_to_abspath
def download_image(link: str) -> str:
"""Downloads an image via url only if it doesn't exist locally"""
out_dir = rel_to_abspath("../weapons").replace("\\", os.sep).replace("/", os.sep)
file_name = link.split("/")[-1]
full_path = f"{out_dir}/{file_name}".replace("\\", os.sep).replace("/", os.sep)
if not os.path.exists(out_dir):
os.mkdir(out_dir)
if not os.path.exists(full_path):
img_data = requests.get(link).content
with open(full_path, "wb") as handler:
handler.write(img_data)
return full_path
def loadout_to_b64(loadout: List[str]) -> str:
"""
Converts a list of URLs to webp images (of each loadout) into one,
24x24 composite rotating webp as base64
Arguments:
loadout (List[str]): a list of URLs for each weapon
"""
frames: List[Image.Image] = []
for img_url in loadout:
path = download_image(img_url)
frames.append(Image.open(path).convert("RGBA").resize((24, 24)))
gif_path = rel_to_abspath("../temp.gif")
frames[0].save(
gif_path,
format="GIF",
append_images=frames[1:],
save_all=True,
duration=5000,
disposal=2,
loop=0,
)
with open(gif_path, "rb") as fh:
b64 = base64.b64encode(fh.read())
os.unlink(gif_path)
return b64.decode("utf-8")

19
src/server/main.py Normal file
View file

@ -0,0 +1,19 @@
"""
Architecture:
Python App that loops infinitely, pushing the correct Pixlet state to the TidByt
Changes come in via WebAPI so we can make a lightweight desktop client and leave the work to the RasPi
Also allows the TidByt to still have forgeserv.net data without needing to be stood up
"""
from state import AppState, StateManager
from fastapi import FastAPI
app = FastAPI()
state_mgr = StateManager(timeout=10)
@app.post("/")
def change_state(new_state: int):
state_mgr.update(AppState(new_state))
return {"msg": "👍"}

93
src/server/pixlet.py Normal file
View file

@ -0,0 +1,93 @@
"""A Python Wrapper for Pixlet ops"""
import subprocess
from pathlib import Path
from renderables import Renderable
ROOT_PATH = Path("./").resolve()
PIXLET_EXEC = ROOT_PATH.joinpath("pixlet").resolve()
def push_to_tidbyt(renderable: Renderable) -> None:
"""Pushes a renderable to the Tidbyt device
Args:
renderable (Renderable): The Pixlet Configuration for the given state
"""
__display(__render(renderable))
def __render(renderable: Renderable) -> Path:
"""Renders a given PixeltConfiguration (and any template args) to webp
Args:
renderable (Renderable): The Pixlet Configuration for the given state
Returns:
Path: The path to the rendered output file
"""
output_path = __prepare_file(renderable)
with subprocess.Popen([PIXLET_EXEC, "render", str(output_path)]) as proc:
proc.wait()
return ROOT_PATH.joinpath("tmp.webp").resolve()
def __display(path: Path) -> None:
"""Pushes a given rendered webp file to the pixlet on the same installation id
Args:
path (Path): The path to the given rendered webp
"""
with open(
ROOT_PATH.joinpath("device_id").resolve(), "r", encoding="utf8"
) as handle:
dev_id = handle.read()
with subprocess.Popen(
[
PIXLET_EXEC,
"push",
"--installation-id",
"automation",
dev_id,
str(path),
]
) as proc:
proc.wait()
def __prepare_file(renderable: Renderable) -> Path:
"""Prepares a given pixlet star file. If the file is a template, checks the template keys and prepares the template before writing to the temp path
Args:
renderable (Renderable): The Pixlet Configuration for the given state
Raises:
Exception: Thrown if a required key defined in the Renderable is missing
Returns:
Path: The path to the output file
"""
output_path = ROOT_PATH.joinpath("tmp.star").resolve()
with open(renderable.file_path, "r", encoding="utf8") as handle:
data = handle.read()
if renderable.is_dynamic:
args = renderable.resolve_template_keys()
for key in renderable.template_keys:
if not key in args:
raise Exception(
f"Failed to render Pixlet Configuration for {renderable.for_state.name} -- missing key '{key}'"
)
data = data.replace(key, args[key])
with open(output_path, "w", encoding="utf8") as handle:
handle.write(data)
return output_path

View file

@ -0,0 +1,28 @@
from pathlib import Path
from typing import List, Dict
class Renderable:
def __init__(self):
self.is_dynamic: bool = None
self.file_path: Path = None
self.template_keys: List[str] = None
def __init__(self, file_path: Path):
"""Alternative constructor for ease of use to pass in the FilePath for a static Renderable
Args:
file_path (Path): The Path to the .star file
"""
self.is_dynamic: bool = False
self.file_path: Path = file_path
self.template_keys: List[str] = None
def resolve_template_keys(self) -> Dict[str, str]:
"""Should be called before rendering to ensure the data rendered is up to date
Returns:
Dict[str, str]: A mapping of template keys to their most up-to-date values
"""
raise Exception("Default implementation is not supported!")

View file

@ -0,0 +1,104 @@
import json
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import List, Union
from renderables import Renderable
@dataclass
class Player:
"""Represents a player on the server"""
name: str
head: str
uuid: str
@dataclass
class Server:
"""Represents a single ForgeServ server"""
max_players: int
online_players: int
server_dynmap_url: Union[None, str]
server_health: str
server_icon: str
server_motd: str
server_name: str
server_type: str
server_version: str
players: List[Player]
class ForgeServ(Renderable):
def __init__(self):
self.file_path = Path("./templates/forgeserv.star").resolve()
self.is_dynamic = True
self.template_keys = [
"<IMAGE>",
"<SERVER-NAME>",
"<ONLINE-PLAYERS>",
"<MAX-PLAYERS>",
]
self.__server_key = 0
def __parse_servers(self, json_in: str) -> List[Server]:
"""Parses the raw response JSON from the API into a list of servers
Args:
json_in (str): The raw JSON string from the API request
Returns:
List[Server]: A list of parsed server objects
"""
data = json.loads(json_in)
servers: List[Server] = []
for idx, serv in enumerate(data):
try:
servers.append(
Server(
max_players=serv["max"],
online_players=serv["online"],
server_dynmap_url=serv["dynmap"],
server_health=serv["health"],
server_icon=serv["icon"],
server_motd=serv["motd"],
server_name=serv["name"],
server_type=serv["type"],
server_version=serv["version"],
players=[
Player(
name=x["name"],
uuid=x["uuid"],
head=f"https://cravatar.eu/head/{x['uuid']}",
)
for x in serv["players"]
],
)
)
except ValueError:
print(f"Skipping server at index {idx}")
return servers
def resolve_template_keys(self):
with urllib.request.urlopen("https://api.forgeserv.net") as response:
servers: List[Server] = self.__parse_servers(response.read().decode())
if (self.__server_key + 1) > len(servers) - 1:
self.__server_key = 0
else:
self.__server_key += 1
server = servers[self.__server_key]
return {
"<IMAGE>": server.server_icon,
"<SERVER-NAME>": server.server_name,
"<ONLINE-PLAYERS>": server.online_players,
"<MAX-PLAYERS>": server.max_players,
}

80
src/server/state.py Normal file
View file

@ -0,0 +1,80 @@
from enum import Enum
from pathlib import Path
from threading import Thread
from time import sleep
from typing import Dict
from pixlet import push_to_tidbyt
from renderables import Renderable
from renderables.forgeserv import ForgeServ
class AppState(Enum):
IDLE = 0
MEETING = 1
OBS_PAUSED = 2
OBS_RECORDING = 3
OBS_STREAMING = 4
ROOT = Path("./")
class StateManager:
def __init__(self, timeout=1):
"""Manages the state of the Tidbyt manager application
Args:
timeout (int, optional): How long to wait between iterations (in seconds). Defaults to 1.
"""
self.state: AppState = AppState.IDLE
self.renderables: Dict[AppState, Renderable] = {
AppState.IDLE: ForgeServ(),
AppState.MEETING: Renderable(
ROOT.joinpath("templates/meeting.star").resolve()
),
AppState.OBS_PAUSED: Renderable(
ROOT.joinpath("templates/obs/paused.star").resolve()
),
AppState.OBS_RECORDING: Renderable(
ROOT.joinpath("templates/obs/recording.star").resolve()
),
AppState.OBS_STREAMING: Renderable(
ROOT.joinpath("templates/obs/streaming.star").resolve()
),
}
# Thread related activities & vars
self.timeout = timeout
self.thread: Thread = None
self.stop_thread = False
self.__start()
def update(self, new_state: AppState):
"""Update the Tidbyt's state, returning the prior state
Args:
new_state (AppState): The new application state
"""
if self.state == new_state:
return self.state
self.state = new_state
push_to_tidbyt(self.renderables[self.state])
def __start(self):
"""Instantiates and starts the worker thread
Raises:
Exception: thrown if the thread has already been instantiated
"""
if self.thread:
raise Exception("Thread has already been initialized!")
self.thread = Thread(target=self.__thread_task, daemon=True)
self.thread.start()
def __thread_task(self):
"""A looping task that renders and pushes the correct pixlet based on state"""
while not self.stop_thread:
if self.renderables[self.state].is_dynamic:
push_to_tidbyt(self.renderables[self.state])
sleep(self.timeout)

View file

@ -1,21 +0,0 @@
"""
General utils for things - mostly file path resolution
"""
import os
class Renderable:
"""A simple renderable baseclass"""
def render(self) -> None:
"""Renders to Pixlet"""
raise Exception("Default class implementation is not supported!")
def rel_to_abspath(path: str) -> str:
"""
Converts a local path (like '../thing' to the absolute path)
"""
path_root = os.path.realpath(__file__).replace("util.py", "")
return f"{path_root}{path}".replace("\\", os.sep).replace("/", os.sep)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 184 B

View file

@ -12,19 +12,26 @@ def main():
main_align="space_around",
cross_align="center",
children=[
render.Image(ICON, width=16, height=16),
render.Marquee(
width=60,
child=render.Text(
"<SERVER-NAME> (<ONLINE-PLAYERS> / <MAX-PLAYERS>)",
color="#a3be8c",
font="tom-thumb",
),
render.Row(
expanded=True,
main_align="space_evenly",
cross_align="center",
children=[
render.Image(ICON, width=16, height=16),
render.Marquee(
width=40,
child=render.Text(
"<SERVER-NAME>",
color="#a3be8c",
font="tom-thumb",
),
),
],
),
render.Marquee(
width=60,
child=render.Text(
"Players: <PLAYER-LIST>",
"<ONLINE-PLAYERS> of <MAX-PLAYERS> Players",
color="#8fbcbb",
font="tom-thumb",
),

23
templates/meeting.star Normal file
View file

@ -0,0 +1,23 @@
load("render.star", "render")
load("encoding/base64.star", "base64")
ICON = base64.decode(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAA0lBMVEVHcEzAOSshCghHFxIrDgvJQjS4NinnTDzmSzvAOSutOCxpIhtBFRDHQTPnTDzaRzh0Jh7hSjrIQTTOPzFTGBKxNShVGRNsIBgUBgQzDwsaCAZcHhdRGRN9JRyGLCNnIhqRLCEbCAZZGhREFhGDKB6ILCOsOCwxDgvIQTRTGRLbSDgWBgViHRbAOStdHhg4EQ0VBgSwNCdLFhFXGhTKQjRqHxe8NyrnTDzAOSvmSzvPQDHIPS7hSTndRzfgSTnSQTPJPS7KPi/NPzDcRzfLPi/DOix335QqAAAAN3RSTlMA/gshEbLc+PT7ilAfr/vQTOO2/j/ET2EGHgY1QW5bOoULTx5yXIsZrz/TBk76NyEGx0FSumPlq3smowAAAI9JREFUGNNVzucOglAMBeCigODeeyvDvW0v4Nb3fyVvIia9/dcvzekBgGwmAXyKeUzzvV1CTCUZdAUi5hjULxIKDFoVxLLOQ2pX7ChfGqEwFGiagegrUrVv1kCRnhZYDoA+9yexDOkeGeujbOiOfjK16fmSDaPHOL6ZmUSfd0gr75+zPe00ovOSZ28O+wXAF2g4D32JsaTjAAAAAElFTkSuQmCC"
)
def main():
return render.Root(
child=render.Box(
render.Row(
expanded=True,
main_align="space_around",
cross_align="center",
children=[
render.Image(src=ICON, width=16, height=16),
render.Text("On A Call", color="#c83d2e", font="tom-thumb"),
],
)
)
)

View file

@ -1,34 +0,0 @@
load("render.star", "render")
load("encoding/base64.star", "base64")
ICON = base64.decode("<IMAGE>")
def main():
return render.Root(
delay=250,
child=render.Column(
expanded=True,
main_align="space_around",
cross_align="center",
children=[
render.Marquee(
width=60,
child=render.Text(
"<START_DATE> - <END_DATE>",
color="#66ded2",
font="tom-thumb",
),
),
render.Marquee(
width=60,
child=render.Text(
"<STAGE>",
color="#fc9c66",
font="tom-thumb",
),
),
render.Image(ICON),
],
),
)

View file

@ -1,21 +0,0 @@
load("render.star", "render")
load("encoding/base64.star", "base64")
ICON = base64.decode(
"UklGRmAAAABXRUJQVlA4TFMAAAAvD8ADEBcgEEiC33sNgUCS2f5UCwkS/g+2Ov8B/woYtY0kqTTPhtJ8isNoUAyJ/s/eu+G5HCL6H1ohgSa0BfFCdl85XN+wf/W9rnwhF8SEJpBWCAA="
)
def main():
return render.Root(
child=render.Column(
expanded=True,
main_align="space_around",
cross_align="center",
children=[
render.Image(src=ICON),
render.Marquee(width=64, child=render.Text("In a Zoom Meeting")),
],
)
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB