Skip to content

Commit

Permalink
Merge pull request #287 from Darkfull-Dante/random_category
Browse files Browse the repository at this point in the history
made the sensor functional with country code from the user.
Added information in the README
  • Loading branch information
fcusson authored Jan 10, 2022
2 parents c25d6f8 + 20c7931 commit f4af3d9
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 41 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Add the following to your configuration.yaml:
spotcast:
sp_dc: !secret sp_dc
sp_key: !secret sp_key
country: SE #optinal, added in 3.6.24
```
### Multiple accounts
Expand All @@ -85,6 +86,7 @@ If you are using v3.5.2 or greater and thus also have the core Spotify Integrati
spotcast:
sp_dc: !secret primary_sp_dc
sp_key: !secret primary_sp_key
country: SE #optional, added in 3.6.24
accounts:
niklas:
sp_dc: !secret niklas_sp_dc
Expand Down Expand Up @@ -226,7 +228,7 @@ Play the latest episode of a given podcast show.
{
"account":"niklas",
"device_name" : "Kök",
"uri" : "spotify:show:6PeAI9SHRZhghU7NRPXvT3"
"uri" : "spotify:show:6PeAI9SHRZhghU7NRPXvT3",
"ignore_fully_played": true
}
```
Expand All @@ -247,8 +249,11 @@ Add the following to the sensor section of the configuration:
```yaml
sensor:
- platform: spotcast
country: SE
```

The country tag was added in v3.6.24. This tag is optional. If ommited or if you haven't updated the configuration since the update, it will default to "SE" (which it always did before)

Sensor name:

```yaml
Expand Down
32 changes: 21 additions & 11 deletions custom_components/spotcast/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import collections
import logging
import time
import homeassistant

from homeassistant.components import websocket_api
from homeassistant.const import CONF_ENTITY_ID, CONF_OFFSET, CONF_REPEAT
from homeassistant.core import callback
import homeassistant.core as ha_core

from .const import (
CONF_ACCOUNTS,
Expand Down Expand Up @@ -44,7 +47,7 @@
_LOGGER = logging.getLogger(__name__)


def setup(hass, config):
def setup(hass: ha_core.HomeAssistant, config: collections.OrderedDict) -> bool:

# get spotify core integration status
# if return false, could indicate a bad spotify integration. Race
Expand All @@ -66,7 +69,7 @@ def setup(hass, config):
hass.data[DOMAIN]["controller"] = spotcast_controller

@callback
def websocket_handle_playlists(hass, connection, msg):
def websocket_handle_playlists(hass: ha_core.HomeAssistant, connection, msg):
@async_wrap
def get_playlist():
"""Handle to get playlist"""
Expand All @@ -85,7 +88,7 @@ def get_playlist():
hass.async_add_job(get_playlist())

@callback
def websocket_handle_devices(hass, connection, msg):
def websocket_handle_devices(hass: ha_core.HomeAssistant, connection, msg):
@async_wrap
def get_devices():
"""Handle to get devices. Only for default account"""
Expand All @@ -98,7 +101,7 @@ def get_devices():
hass.async_add_job(get_devices())

@callback
def websocket_handle_player(hass, connection, msg):
def websocket_handle_player(hass: ha_core.HomeAssistant, connection, msg):
@async_wrap
def get_player():
"""Handle to get player"""
Expand All @@ -111,15 +114,15 @@ def get_player():
hass.async_add_job(get_player())

@callback
def websocket_handle_accounts(hass, connection, msg):
def websocket_handle_accounts(hass: ha_core.HomeAssistant, connection, msg):
"""Handle to get accounts"""
_LOGGER.debug("websocket_handle_accounts msg: %s", msg)
resp = list(accounts.keys()) if accounts is not None else []
resp.append("default")
connection.send_message(websocket_api.result_message(msg["id"], resp))

@callback
def websocket_handle_castdevices(hass, connection, msg):
def websocket_handle_castdevices(hass: ha_core.HomeAssistant, connection, msg):
"""Handle to get cast devices for debug purposes"""
_LOGGER.debug("websocket_handle_castdevices msg: %s", msg)

Expand All @@ -136,7 +139,7 @@ def websocket_handle_castdevices(hass, connection, msg):

connection.send_message(websocket_api.result_message(msg["id"], resp))

def start_casting(call):
def start_casting(call: ha_core.ServiceCall):
"""service called."""
uri = call.data.get(CONF_SPOTIFY_URI)
category = call.data.get(CONF_SPOTIFY_CATEGORY)
Expand All @@ -155,10 +158,17 @@ def start_casting(call):
device_name = call.data.get(CONF_DEVICE_NAME)
entity_id = call.data.get(CONF_ENTITY_ID)

# if no market information try to get global setting
if helpers.is_empty_str(country):
try:
country = config[DOMAIN][CONF_SPOTIFY_COUNTRY]
except KeyError:
country = None

client = spotcast_controller.get_spotify_client(account)

# verify the uri provided and clean-up if required
if not (uri is None or uri.strip() == ""):
if not helpers.is_empty_str(uri):
if not helpers.is_valid_uri(uri):
_LOGGER.error("Invalid URI provided, aborting casting")
return
Expand All @@ -171,7 +181,7 @@ def start_casting(call):
account, spotify_device_id, device_name, entity_id
)

if (uri is None or uri.strip() == "") and (search is None or search.strip() == "") and (category is None or category.strip() == ""):
if helpers.is_empty_str(uri) and helpers.is_empty_str(search) and helpers.is_empty_str(category):
_LOGGER.debug("Transfering playback")
current_playback = client.current_playback()
if current_playback is not None:
Expand All @@ -198,9 +208,9 @@ def start_casting(call):
)
else:

if uri is None or uri.strip() == "":
if helpers.is_empty_str(uri):
# get uri from search request
uri = helpers.get_search_results(search, client)
uri = helpers.get_search_results(search, client, country)

spotcast_controller.play(
client,
Expand Down
1 change: 1 addition & 0 deletions custom_components/spotcast/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
vol.Required(CONF_SP_DC): cv.string,
vol.Required(CONF_SP_KEY): cv.string,
vol.Optional(CONF_ACCOUNTS): cv.schema_with_slug_keys(ACCOUNTS_SCHEMA),
vol.Optional(CONF_SPOTIFY_COUNTRY): cv.string,
}
),
},
Expand Down
8 changes: 6 additions & 2 deletions custom_components/spotcast/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ async def run(*args, loop=None, executor=None, **kwargs):

return run

def get_search_results(search:str, spotify_client:spotipy.Spotify) -> str:
def get_search_results(search:str, spotify_client:spotipy.Spotify, country:str=None) -> str:

_LOGGER.debug("using search query to find uri")

Expand All @@ -99,7 +99,8 @@ def get_search_results(search:str, spotify_client:spotipy.Spotify) -> str:
searchType + ":" + search,
limit=1,
offset=0,
type=searchType)[searchType + 's']['items'][0]
type=searchType,
market=country)[searchType + 's']['items'][0]

results.append(
{
Expand Down Expand Up @@ -175,3 +176,6 @@ def is_valid_uri(uri: str) -> bool:

# return True if all test passes
return True

def is_empty_str(string:str) -> bool:
return string is None or string.strip() == ""
27 changes: 22 additions & 5 deletions custom_components/spotcast/sensor.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
"""Sensor platform for Chromecast devices."""
import collections
import json
import logging
from datetime import timedelta
import homeassistant.core as ha_core

from homeassistant.components.sensor import SensorEntity
from homeassistant.const import STATE_OK, STATE_UNKNOWN
from homeassistant.util import dt

from .helpers import get_cast_devices
from .const import DOMAIN
from .const import (
DOMAIN,
CONF_SPOTIFY_COUNTRY
)

_LOGGER = logging.getLogger(__name__)

SENSOR_SCAN_INTERVAL_SECS = 60
SCAN_INTERVAL = timedelta(seconds=SENSOR_SCAN_INTERVAL_SECS)


def setup_platform(hass, config, add_devices, discovery_info=None):
def setup_platform(hass:ha_core.HomeAssistant, config:collections.OrderedDict, add_devices, discovery_info=None):

try:
country = config[CONF_SPOTIFY_COUNTRY]
except KeyError:
country = None

add_devices([ChromecastDevicesSensor(hass)])
add_devices([ChromecastPlaylistSensor(hass)])
add_devices([ChromecastPlaylistSensor(hass, country)])


class ChromecastDevicesSensor(SensorEntity):
Expand Down Expand Up @@ -66,9 +77,10 @@ def update(self):


class ChromecastPlaylistSensor(SensorEntity):
def __init__(self, hass):
def __init__(self, hass: ha_core, country=None):
self.hass = hass
self._state = STATE_UNKNOWN
self.country = country
self._attributes = {"playlists": [], "last_update": None}
_LOGGER.debug("initiating playlist sensor")

Expand All @@ -88,8 +100,13 @@ def extra_state_attributes(self):
def update(self):
_LOGGER.debug("Getting playlists")

if self.country is not None:
country_code = self.country
else:
# kept the country code to SE if not provided by the user for retrocompatibility
country_code = "SE"

playlist_type = "user"
country_code = "SE"
locale = "en"
limit = 10
account = None
Expand Down
Loading

0 comments on commit f4af3d9

Please sign in to comment.