OBS hook changes
This commit is contained in:
parent
fed99e8580
commit
07413790f9
16 changed files with 752 additions and 752 deletions
|
|
@ -1,4 +1,4 @@
|
|||
{
|
||||
"splatoon": false,
|
||||
"forgeserv": true
|
||||
}
|
||||
{
|
||||
"splatoon": false,
|
||||
"forgeserv": true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
|
||||
ICON = base64.decode(
|
||||
"UklGRl4AAABXRUJQVlA4TFEAAAAvD8ADEBcgEEhy2p9tDYFAkr/LjAsEkpz2Z3v+A/4VMGojyVFrnwNl+GxEsyT2Hy4X0MMQ0f/QNAnUIUywt13+puHEyP+bhr/t8gnWIQikaQIA"
|
||||
)
|
||||
|
||||
|
||||
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("Now Recording :)")),
|
||||
],
|
||||
)
|
||||
)
|
||||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
|
||||
ICON = base64.decode(
|
||||
"UklGRl4AAABXRUJQVlA4TFEAAAAvD8ADEBcgEEhy2p9tDYFAkr/LjAsEkpz2Z3v+A/4VMGojyVFrnwNl+GxEsyT2Hy4X0MMQ0f/QNAnUIUywt13+puHEyP+bhr/t8gnWIQikaQIA"
|
||||
)
|
||||
|
||||
|
||||
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("Now Recording :)")),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,23 +1,23 @@
|
|||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
|
||||
ICON = base64.decode(
|
||||
"UklGRlQAAABXRUJQVlA4TEcAAAAvD8ADEBcgEEhy2p9tDYFAkr/LjAsEkpz2Z3v+A/4VqIkkRdoiRAoqUbExITU279EQ0f/QpARqiIFcuw42/7XrDGRDCKRJAQA="
|
||||
)
|
||||
|
||||
|
||||
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("Taking a break between recordings (?)")
|
||||
),
|
||||
],
|
||||
)
|
||||
)
|
||||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
|
||||
ICON = base64.decode(
|
||||
"UklGRlQAAABXRUJQVlA4TEcAAAAvD8ADEBcgEEhy2p9tDYFAkr/LjAsEkpz2Z3v+A/4VqIkkRdoiRAoqUbExITU279EQ0f/QpARqiIFcuw42/7XrDGRDCKRJAQA="
|
||||
)
|
||||
|
||||
|
||||
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("Taking a break between recordings (?)")
|
||||
),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,26 +1,26 @@
|
|||
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"),]
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
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"),]
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
"""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
|
||||
"""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
|
||||
|
|
|
|||
|
|
@ -1,108 +1,108 @@
|
|||
"""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)
|
||||
"""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)
|
||||
|
|
|
|||
260
src/main.py
260
src/main.py
|
|
@ -1,130 +1,130 @@
|
|||
"""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()
|
||||
"""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()
|
||||
|
|
|
|||
|
|
@ -1,30 +1,30 @@
|
|||
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)
|
||||
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)
|
||||
|
|
|
|||
142
src/pixlet.py
142
src/pixlet.py
|
|
@ -1,71 +1,71 @@
|
|||
"""
|
||||
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()
|
||||
"""
|
||||
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()
|
||||
|
|
|
|||
|
|
@ -1,131 +1,131 @@
|
|||
"""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
|
||||
"""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
|
||||
|
|
|
|||
|
|
@ -1,56 +1,56 @@
|
|||
"""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")
|
||||
"""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")
|
||||
|
|
|
|||
42
src/util.py
42
src/util.py
|
|
@ -1,21 +1,21 @@
|
|||
"""
|
||||
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)
|
||||
"""
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
|
||||
ICON = base64.decode(
|
||||
"UklGRlgAAABXRUJQVlA4TEsAAAAvD8ADEBcgEEiy259oDSFBwv/oYed//gP+AmoiWa3eUCIFP/n28REdqSiZ0xkREf0PpUugC5bgBVGtBa3BWX9rVGtRm8iHXzCBlC4A"
|
||||
)
|
||||
|
||||
|
||||
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("Now Streaming")),
|
||||
],
|
||||
)
|
||||
)
|
||||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
|
||||
ICON = base64.decode(
|
||||
"UklGRlgAAABXRUJQVlA4TEsAAAAvD8ADEBcgEEiy259oDSFBwv/oYed//gP+AmoiWa3eUCIFP/n28REdqSiZ0xkREf0PpUugC5bgBVGtBa3BWX9rVGtRm8iHXzCBlC4A"
|
||||
)
|
||||
|
||||
|
||||
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("Now Streaming")),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,34 +1,34 @@
|
|||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
ICON = base64.decode("<IMAGE>")
|
||||
|
||||
|
||||
def main():
|
||||
return render.Root(
|
||||
delay=0,
|
||||
child=render.Column(
|
||||
expanded=True,
|
||||
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.Marquee(
|
||||
width=60,
|
||||
child=render.Text(
|
||||
"Players: <PLAYER-LIST>",
|
||||
color="#8fbcbb",
|
||||
font="tom-thumb",
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
load("render.star", "render")
|
||||
load("encoding/base64.star", "base64")
|
||||
|
||||
ICON = base64.decode("<IMAGE>")
|
||||
|
||||
|
||||
def main():
|
||||
return render.Root(
|
||||
delay=0,
|
||||
child=render.Column(
|
||||
expanded=True,
|
||||
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.Marquee(
|
||||
width=60,
|
||||
child=render.Text(
|
||||
"Players: <PLAYER-LIST>",
|
||||
color="#8fbcbb",
|
||||
font="tom-thumb",
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,34 +1,34 @@
|
|||
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),
|
||||
],
|
||||
),
|
||||
)
|
||||
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),
|
||||
],
|
||||
),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
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")),
|
||||
],
|
||||
)
|
||||
)
|
||||
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")),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue