Files
radio2/nporadio2/notifications.py
2022-05-26 14:20:13 +02:00

83 lines
2.1 KiB
Python

from UserNotifications import (
UNAuthorizationOptionAlert,
UNMutableNotificationContent,
UNNotificationAttachment,
UNNotificationRequest,
UNUserNotificationCenter,
)
from Foundation import NSURL
from radiotrack import RadioTrack
from top2000 import Top200Song
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, top2000: Top200Song = None):
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
if top2000:
title = f"{top2000.position}: {song.title}"
else:
title = song.title
self.create_notification(
title,
song.artist,
attachments=[atachement],
)