Main refactoring

This commit is contained in:
2024-11-10 15:03:44 +01:00
parent 28fdfa0982
commit 9a0f869839
20 changed files with 2349 additions and 2280 deletions
+47 -28
View File
@@ -1,11 +1,11 @@
import logging
import threading
import json
import time
import logging
import re
import threading
import time
from queue import Empty, Queue
from urllib import request as urequest
from queue import Queue, Empty
from flask import Flask, jsonify, request
from waitress import serve
@@ -14,28 +14,30 @@ PORT_ADDRESS = 5000
ICECAST_ADDRESS = "http://192.168.1.15:8000"
OUT_COMM_Q = Queue()
IN_COMM_Q = Queue()
SRCHTITLE = re.compile(br'StreamTitle=\\*(?P<title>[^;]*);').search
SRCHTITLE = re.compile(rb"StreamTitle=\\*(?P<title>[^;]*);").search
awaiting_q = []
incoming_q = Queue()
app = Flask(__name__)
PREPPED_TRACKS = {
"requests" : "",
"hit" : "",
"requests": "",
"hit": "",
"all": "",
"priority":"",
"jingles":"",
"now_playing":"",
"priority": "",
"jingles": "",
"now_playing": "",
"next": "",
"meta" : ""
"meta": "",
}
logger = logging.getLogger("discord")
class QueryControl:
"""
This class `QueryControl` is used to manage queries with information about the author, UUID,
content, logger, context, and replies.
"""
def __init__(self, query_author, query_uuid, query_content, ctx) -> None:
self.author = query_author
self.uuid = query_uuid
@@ -48,6 +50,7 @@ class QueryControl:
)
self.replies = []
@app.route("/prepped_tracks", methods=["POST"])
def log_radio_tracks():
app.logger = logging.getLogger("discord")
@@ -59,7 +62,14 @@ def log_radio_tracks():
metadata = id3(ICECAST_ADDRESS)
PREPPED_TRACKS["now_playing"] = PREPPED_TRACKS["next"]
if metadata:
PREPPED_TRACKS["meta"] = metadata["name"] + " - " + metadata["title"] + "(" + metadata["genre"] + ")"
PREPPED_TRACKS["meta"] = (
metadata["name"]
+ " - "
+ metadata["title"]
+ "("
+ metadata["genre"]
+ ")"
)
else:
PREPPED_TRACKS["meta"] = "Nie znaju"
PREPPED_TRACKS[record[0]] = record[1]
@@ -83,6 +93,7 @@ def answer_external_command():
incoming_q.put(record)
return jsonify("SUCCESS")
@app.route("/conjurer", methods=["GET"])
def check_alive():
"""
@@ -94,6 +105,7 @@ def check_alive():
"""
return jsonify("ALIVE")
def flask_debug():
"""
The `flask_debug` function starts a Flask application in debug mode without using the reloader.
@@ -116,6 +128,7 @@ def waitress_run():
logger.info("Attempt waitress")
serve(app, host=HOST_ADDRESS, port=PORT_ADDRESS)
def scan_queue():
"""
The function `scan_queue` reads data from a queue, logs it, and appends it to another queue.
@@ -131,6 +144,7 @@ def scan_queue():
logger.info(data)
awaiting_q.append(data)
def scan_incoming():
"""
The `scan_incoming` function continuously checks for incoming data, processes it, and logs when data
@@ -162,26 +176,31 @@ def scan_incoming():
except Empty:
time.sleep(1)
def get_stream_title(tag:bytes) -> str:
title = ''
def get_stream_title(tag: bytes) -> str:
title = ""
if m := SRCHTITLE(tag):
#decode, strip, unescape and remove surrounding quotes (may not even be the same type of quote)
title = m.group('title').decode('utf-8').strip().replace('\\', '')[1:-1]
# decode, strip, unescape and remove surrounding quotes (may not even be the same type of quote)
title = m.group("title").decode("utf-8").strip().replace("\\", "")[1:-1]
return title
def id3(url:str) -> dict:
request = urequest.Request(url, headers={'Icy-MetaData': 1})
def id3(url: str) -> dict:
request = urequest.Request(url, headers={"Icy-MetaData": 1})
with urequest.urlopen(request) as resp:
metaint = int(resp.headers.get('icy-metaint', '-1'))
if metaint<0:
metaint = int(resp.headers.get("icy-metaint", "-1"))
if metaint < 0:
return False
resp.read(metaint) #this isn't seekable so, arbitrarily read to the point we want
resp.read(
metaint
) # this isn't seekable so, arbitrarily read to the point we want
tagdata = dict(
site_url = resp.headers.get('icy-url' ) ,
name = resp.headers.get('icy-name' ).title(),
genre = resp.headers.get('icy-genre').title(),
title = get_stream_title(resp.read(255)) )
site_url=resp.headers.get("icy-url"),
name=resp.headers.get("icy-name").title(),
genre=resp.headers.get("icy-genre").title(),
title=get_stream_title(resp.read(255)),
)
return tagdata
@@ -193,20 +212,20 @@ def comm_subroutine():
object that is used for logging messages at various levels (e.g., debug, info, warning, error). In
the provided code snippet, the logger is used to log messages at the "info" level
"""
#logger.setLevel(logging.DEBUG)
# logger.setLevel(logging.DEBUG)
logger = logging.getLogger("discord")
logger.info("Started comms")
threads = []
#threads.append(threading.Thread(target=flask_debug))
# threads.append(threading.Thread(target=flask_debug))
threads.append(threading.Thread(target=waitress_run))
threads.append(threading.Thread(target=scan_queue))
threads.append(threading.Thread(target=scan_incoming))
for worker in threads:
worker.start()
for worker in threads:
worker.join()
if __name__ == "__main__":
comm_subroutine()