pystations/stations.py
Greg Gauthier 0d48269790
All checks were successful
Pylint / build (3.12) (push) Successful in 7s
massive refactoring, and pylint cleanup
2024-07-22 21:28:45 +01:00

97 lines
2.9 KiB
Python

import argparse
import json
import secrets
import DNS
import requests
from config import api
from radiomenu import RadioMenu
def ipaddr(hostname, rectype='A'):
return DNS.dnslookup(hostname, rectype, 3)
def nsname(ipaddrs):
return DNS.revlookup(ipaddrs, 3)
def get_host():
hosts = ipaddr(api())
preferred_host = secrets.choice(hosts)
return nsname(preferred_host)
def get_stations(qstring, host):
resp = requests.get(
f"https://{host}/json/stations/search?{qstring}&limit=100000", timeout=10
)
if resp.status_code == 200:
return json.loads(resp.text)
return [{"response_code": resp.status_code, "reason": resp.reason}]
def search_stations(query_dict=None):
if query_dict is None:
query_dict = {}
query_string = ""
for key, value in query_dict.items():
if key == "tags":
query_string += f"{key}={','.join(value)}&"
query_string += f"{key}={value}&"
stations = get_stations(query_string, get_host())
filtered_list = []
for station in stations:
station["status"] = "down" # assume down
# if last check and lastcheckok match, the station is up
if str(station["lastchecktime"]) == str(station["lastcheckoktime"]):
station["status"] = "up"
if len(query_dict["tags"]) > 1 and station["tags"] == "":
continue
if station["status"] == "up":
station_entry = {
"name": str(station["name"]).replace('"', "'").replace(",", " - "),
"url": str(station["url"].replace(",", "%2C")),
"codec": str(station["codec"]),
"bitrate": str(station["bitrate"]),
"countrycode": str(station["countrycode"]),
"favicon": str(station["favicon"])\
.replace(" ", "%20").replace("(", "%28").replace(")", "%29"),
"tags": str(station["tags"].split(",")).replace(",", ";"),
"status": str(station["status"])
}
filtered_list.append(station_entry)
return filtered_list
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", type=str,
help="Name of station", default=None)
parser.add_argument("-c", "--country", type=str,
help="Station country", default=None)
parser.add_argument("-s", "--state", type=str,
help="Station state (if in US)", default=None)
parser.add_argument("-t", "--tags", type=str,
help="search tag or tags (if more than one, comma-separated", default="")
args = parser.parse_args()
query = {
"name": args.name,
"country": args.country,
"state": args.state,
"tags": args.tags.split(","),
}
station_list = search_stations(query)
mainMenu = RadioMenu(station_list)
mainMenu.display()