minor refactoring (discord_presence needs full rewrite, obviously) + discord_presence enhancement: read correct station from ff to remove the need to manually edit the script every-fucking-time

This commit is contained in:
2025-07-23 16:03:16 -04:00
parent 3d94d385c3
commit 1d9c094853
3 changed files with 69 additions and 79 deletions

View File

@@ -19,9 +19,7 @@ HEADERS = {
class Catbox:
def generateRandomFileName(self, fileExt=""):
if len(fileExt) < 1:
fileExt = "db"

View File

@@ -1,17 +1,22 @@
#!/usr/bin/env python3.12
#!/usr/bin/env python3.13
import time
import traceback
import requests
import dbus
import re
import sys
import os
import random
import discord_presence_priv
import catbox
import logging
from ff_brotab import query_ff
from setproctitle import setproctitle
from typing import Optional
from pypresence import Presence, ActivityType
setproctitle("disc-presence")
@@ -49,19 +54,23 @@ class DBus:
"elapsed": None,
"duration": None,
}
except:
pass
except Exception as e:
logging.debug("Exception: %s", str(e))
def is_plexing(self) -> bool:
try:
self.interface_metadata = self.player_interface.GetAll(
"org.mpris.MediaPlayer2.Player"
).get("Metadata")
if "app.plex.tv" in self.interface_metadata.get("xesam:url"):
if self.interface_metadata and "app.plex.tv" in self.interface_metadata.get(
"xesam:url"
):
return True
print(f"WTF, NO PLEX?")
except:
print(traceback.format_exc())
logging.debug("Plex not found")
return False
except Exception as e:
logging.debug("Exception: %s", str(e))
traceback.print_exc()
return False
def get_now_playing(self):
@@ -115,15 +124,17 @@ class DBus:
"elapsed": None,
"duration": None,
}
print(traceback.format_exc())
traceback.print_exc()
return False
class DiscordPresence:
def __init__(self):
self.dbus = DBus()
self.radio_station = None
self.last_updated = None
self.last_track = None
self.last_track_title = None
self.client_id = discord_presence_priv.CLIENT_ID
self.client_id_plex = discord_presence_priv.CLIENT_ID_PLEX
self.api_key = discord_presence_priv.API_KEY
@@ -212,8 +223,17 @@ class DiscordPresence:
time.sleep(1)
continue
ff_brotab = query_ff()
if ff_brotab:
(station, _track) = ff_brotab
self.radio_station = station
if self.last_track_title == _track.strip():
continue
else:
self.last_track_title = _track.strip()
request = requests.post(
f"{self.api_url}/radio/np",
f"{self.api_url}/radio/np?station={self.radio_station}",
headers={"content-type": "application/json; charset=utf-8"},
timeout=(2, 10),
)
@@ -230,60 +250,9 @@ class DiscordPresence:
end_time = data.get("end")
if self.last_uuid == track_uuid:
print("Track has not changed")
continue
# if self.last_updated and (now - self.last_updated < 15):
# time.sleep(0.7)
# continue
# if self.last_track and self.last_track == track:
# lyr_start_idx = lyr_end_idx
# lyr_end_idx += 1
# elif self.last_track:
# lyr_start_idx = 0
# lyr_end_idx = 1
# try:
# # rand_msg_request = requests.post(f'{self.api_url}/randmsg/',
# # headers={
# # 'content-type': 'application/json; charset=utf-8'
# # }, json={
# # 'short': True,
# # }, timeout=(1, 2))
# # rand_msg = rand_msg_request.json().get('msg').strip()
# # rand_msg = re.sub(r'(<b>|</b>)', '', re.sub(r'(<br>|<br/>|<br />|\n|\r\n)', ' ', rand_msg))
# # if len(rand_msg) > 126:
# # rand_msg = None
# if not self.last_track or not self.last_track == track:
# lyrics = requests.post(f'{self.api_url}/lyric/search',
# headers={
# 'content-type': 'application/json; charset=utf-8',
# },
# json={
# 'a': track_artist,
# 's': track_title,
# 'src': 'WEB-RADIO',
# }, timeout=(2,10))
# lyrics.raise_for_status()
# lyrics_content = lyrics.json().get("lyrics")
# lyrics_current_iteration = " / ".join(lyrics_content.split("<br>")[lyr_start_idx:lyr_end_idx]).strip()
# if not lyrics_current_iteration.strip():
# lyr_start_idx = 0
# lyr_end_idx = 1
# if len(lyrics_current_iteration) > 128:
# lyrics_current_iteration = lyrics_current_iteration.split(" / ", maxsplit=1)[0].strip()
# except:
# try:
# lyrics_current_iteration = " / ".join(lyrics_content.split("<br>")[0]).strip()
# except:
# lyrics_content = lyrics_current_iteration = None
# print("FAILED TO GET RANDMSG/LYRICS")
# print(traceback.format_exc())
self.last_updated = now
self.last_track = track
self.last_uuid = track_uuid
@@ -308,26 +277,18 @@ class DiscordPresence:
)
)
# match chosen_image.get('image'):
# case "rooster":
# chosen_image = {
# 'image': "qu",
# 'label': "rubber duck :3"
# }
# case "qu":
# chosen_image = {
# 'image': "rooster",
# 'label': ":3",
# }
except:
print(traceback.format_exc())
except Exception as e:
logging.debug("Exception: %s", str(e))
traceback.print_exc()
time.sleep(0.7)
continue
except:
print(traceback.format_exc())
except Exception as e:
logging.debug("Exception: %s", str(e))
traceback.print_exc()
try:
self.loop()
except:
except Exception as e:
logging.debug("Exception: %s", str(e))
pass

31
ff_brotab.py Normal file
View File

@@ -0,0 +1,31 @@
"""Radio Info (FF Tab Info Grabber)"""
import subprocess
import sys
import logging
import os
logging.getLogger().setLevel(logging.DEBUG)
bin_path = os.path.join(os.path.expanduser("~"), ".local", "bin", "bt")
def query_ff() -> tuple[str, str] | None:
res: str | None = subprocess.check_output(
f"{bin_path} query -title 'CODEY STUFF*'", shell=True
).decode() # Utilize brotab to get open tab info
if not res:
logging.debug("brotab: No matching (radio) tab found")
return None
tab_name = res.split("\t", maxsplit=1)[
1
] # Discard brotab output before first \t (tab character)
station = tab_name.split("[")[-1].split("]", maxsplit=1)[
0
] # Extract station from page title
track = tab_name.split(" - Radio - ")[1].split(f"[{station}]")[
0
] # Extract track from page title
return (station, track)
print(query_ff())