This commit is contained in:
2021-12-28 12:56:43 +01:00
commit ec7cb4ca57
9 changed files with 36463 additions and 0 deletions

0
nporadio2/__init__.py Normal file
View File

50
nporadio2/__main__.py Normal file
View File

@@ -0,0 +1,50 @@
import sys
import requests
from time import sleep
from radiotrack import RadioTrack
from notifications import SongNotification
def get_current_song():
result = requests.get(
"https://www.nporadio2.nl/api/miniplayer/info?channel=npo-radio-2"
)
data = result.json()
radio_tracks = data["data"]["radio_track_plays"]["data"][0]["radio_tracks"]
track = RadioTrack(radio_tracks)
return track
def putchar(char):
print(char, end="")
sys.stdout.flush()
if __name__ == "__main__":
un = SongNotification()
previous = None
try:
while True:
try:
track = get_current_song()
except requests.exceptions.SSLError:
putchar(",")
continue
if previous != track:
print(f"\nNew track: {track}")
track.save_image()
un.notify_song(track)
else:
putchar(".")
previous = track
sleep(10)
except KeyboardInterrupt:
print("\nBye!")

View File

@@ -0,0 +1,77 @@
from UserNotifications import (
UNAuthorizationOptionAlert,
UNMutableNotificationContent,
UNNotificationAttachment,
UNNotificationRequest,
UNUserNotificationCenter,
)
from Foundation import NSURL
from radiotrack import RadioTrack
class UserNotification:
def __init__(self):
self._center = UNUserNotificationCenter.currentNotificationCenter()
self._center.requestAuthorizationWithOptions_completionHandler_(
UNAuthorizationOptionAlert, self._auth_callback
)
def create_notification(
self, title=None, subtitle=None, body=None, attachments=None
):
content = UNMutableNotificationContent.alloc().init()
content.setTitle_(title)
content.setSubtitle_(subtitle)
content.setBody_(body)
if attachments:
content.setAttachments_(attachments)
request = UNNotificationRequest.requestWithIdentifier_content_trigger_(
"top2000_id", content, None
)
self._center.addNotificationRequest_withCompletionHandler_(
request, self._notification_callback
)
content.dealloc()
@staticmethod
def _auth_callback(granted, err):
if not granted:
print(granted, err)
@staticmethod
def _notification_callback(err):
if err:
print(err)
class SongNotification(UserNotification):
def __init__(self):
super().__init__()
def notify_song(self, song: RadioTrack):
url = NSURL.URLWithString_(f"file://{song.cover_path}")
err = None
atachement = (
UNNotificationAttachment.attachmentWithIdentifier_URL_options_error_(
"",
url,
None,
err,
)
)[0]
if err:
print(err)
atachement = None
self.create_notification(
song.title,
song.artist,
attachments=[atachement],
)

30
nporadio2/radiotrack.py Normal file
View File

@@ -0,0 +1,30 @@
from typing import Optional
import requests
import tempfile
class RadioTrack:
def __init__(self, data: dict) -> None:
self.artist = data["artist"]
self.title = data["name"]
self.cover = data["cover_url"]
self.cover_path: Optional[str] = None
def save_image(self):
r = requests.get(self.cover)
if r.status_code == 200:
with tempfile.NamedTemporaryFile("wb", suffix=".jpg", delete=False) as f:
f.write(r.content)
self.cover_path = f.name
else:
print(r.status_code)
def __str__(self) -> str:
return f"{self.artist} - {self.title}"
def __eq__(self, other: object) -> bool:
if isinstance(other, RadioTrack):
return self.title == other.title and self.artist == other.artist
return False