Play Tidal playlists through Mopidy

Hello everyone !

So i faced an issue with mopidy integration.

Situation

I want to play Tidal playlist on my mopidy especially for my wake up alarm.
Unfortunatly, HACS mopidy integration doesn’t seems to work well with them.

Solution

A pyscript. (AppDaemon would be like kill a fly with a bazooka.).

Here is the pyscript :

import requests
from homeassistant import config_entries,helpers
from homeassistant.helpers import entity_registry as er


def mopidy_rpc(host, method, params=[]):
    # def mopidy_api(host, method, params=None):
    """ Call mopidy api """
    api_host = "http://" + host + ":6680/mopidy/rpc"
    msg = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
    return task.executor(requests.post,
                         api_host,
                         headers={"content-type": "application/json"},
                         timeout=20,
                         json=msg
                         )


@service
def mopidy_load_playlist(play_a_tracklist):
    """yaml
name: Load Mopidy Playlist
description: Get a mopidy playlist and inject songs in tracklist
fields:
  play_a_tracklist:
    name: Choose and play a tracklist
    description: Chose and play a tracklist on a defined mopidy player
    exemple: "play_a_tracklist: {host: 127.0.0.1, media_content_id: tidal:playlist:c5975061-a57b-4e23-be66-8bb11946ae42 }"
    required: true
    selector:
      media:
"""
    # Get all informations
    # 1. host
    entity_reg = er.async_get(hass)
    entry = entity_reg.async_get(play_a_tracklist.get('entity_id'))
    host = hass.config_entries.async_get_entry(entry.config_entry_id).as_dict()['data']['host']
    # playlist_id
    playlist_id = play_a_tracklist.get('media_content_id')

    # Get the tracklist
    resp = mopidy_rpc(host=host,
                      method='core.playlists.get_items',
                      params={"uri": playlist_id})

    # Format tracklist
    tracks = resp.json().get('result')
    tracklist = list(map(lambda x: x['uri'], tracks))

    # Clear playlist
    resp = mopidy_rpc(host=host,
                      method='core.tracklist.clear')

    # Add Tracklist
    mopidy_rpc(host=host,
               method='core.tracklist.add',
               params={"uris": tracklist})

    # Get up ! (means mopidy play)
    resp = mopidy_rpc(host=host,
                      method='core.playback.play',
                      params={"tl_track": None})

It allow you to select a playlist with UI and a target.

It also create a service you can use in your automations.

My 2 cents.

P.