frontend.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import logging
  2. import time
  3. import json
  4. import pykka
  5. import requests
  6. from mopidy.core import CoreListener
  7. logger = logging.getLogger(__name__)
  8. class WebhooksFrontend(pykka.ThreadingActor, CoreListener):
  9. def __init__(self, config, core):
  10. super().__init__()
  11. self.config = config
  12. self.webhook_urls = []
  13. self.last_start_time = None
  14. def on_start(self):
  15. logger.info("Parsing webhook URLs and tokens")
  16. self.webhook_urls = self.config["webhooks"]["urls"].split(",")
  17. self.webhook_tokens = self.config["webhooks"]["tokens"].split(",")
  18. def _build_post_data(self, track) -> dict:
  19. artists = ", ".join(sorted([a.name for a in track.artists]))
  20. artists_list = [a for a in track.artists]
  21. try:
  22. musicbrainz_artist_id = artists_list[0].musicbrainz_id
  23. except IndexError:
  24. musicbrainz_artist_id = None
  25. duration = track.length and track.length // 1000 or 0
  26. return {
  27. "name": track.name,
  28. "artist": artists,
  29. "album": track.album.name,
  30. "track_number": track.track_no,
  31. "run_time_ticks": track.length,
  32. "run_time": str(duration),
  33. "musicbrainz_track_id": track.musicbrainz_id,
  34. "musicbrainz_album_id": track.album.musicbrainz_id,
  35. "musicbrainz_artist_id": musicbrainz_artist_id,
  36. "mopidy_uri": track.uri,
  37. }
  38. def _post_update_to_webhooks(self, post_data: dict, status: str):
  39. post_data["status"] = status
  40. for index, webhook_url in enumerate(self.webhook_urls):
  41. token = ""
  42. headers = {}
  43. try:
  44. token = self.webhook_tokens[index]
  45. except IndexError:
  46. logger.info(f"No token found for Webhook URL: {webhook_url}")
  47. if token:
  48. headers["Authorization"] = "Token {token}"
  49. response = requests.post(
  50. webhook_url, json=json.dumps(post_data), headers=headers
  51. )
  52. logger.info(response)
  53. def track_playback_started(self, tl_track):
  54. track = tl_track.track
  55. artists = ", ".join(sorted([a.name for a in track.artists]))
  56. self.last_start_time = int(time.time())
  57. logger.debug(f"Now playing track: {artists} - {track.name}")
  58. post_data = self._build_post_data(tl_track.track)
  59. # Build post data to send to urls
  60. if not self.webhook_urls:
  61. logger.info("No webhook URLS are configured ")
  62. return
  63. logger.info(f"Scrobbling via webhooks: {artists} - {track.name}")
  64. self._post_update_to_webhooks(post_data, "started")
  65. def track_playback_ended(self, tl_track, time_position):
  66. track = tl_track.track
  67. artists = ", ".join(sorted([a.name for a in track.artists]))
  68. duration = track.length and track.length // 1000 or 0
  69. time_position = time_position // 1000
  70. post_data = self._build_post_data(tl_track.track)
  71. if time_position < duration // 2 and time_position < 240:
  72. logger.debug(
  73. "Track not played long enough to scrobble. (50% or 240s)"
  74. )
  75. return
  76. if self.last_start_time is None:
  77. self.last_start_time = int(time.time()) - duration
  78. logger.info(
  79. f"Scrobbling finished via webhooks: {artists} - {track.name}"
  80. )
  81. self._post_update_to_webhooks(post_data, "stopped")