Skip to content

Commit

Permalink
Merge branch 'dev' of https://github.com/fondberg/spotcast into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
fcusson committed Dec 14, 2024
2 parents d1da218 + b9c19df commit 94c74f2
Show file tree
Hide file tree
Showing 63 changed files with 1,958 additions and 579 deletions.
9 changes: 9 additions & 0 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ name: Run Coverage Test

on:
workflow_dispatch:
push:
branches:
- main
- dev
- release/*
paths-ignore:
- docs/*
- "*.md"
pull_request:

jobs:
Coverage:
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/hassfest.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
name: Validate with hassfest

on:
workflow_dispatch:
push:
branches:
- main
- dev
- release/*
paths-ignore:
- docs/*
Expand Down
12 changes: 10 additions & 2 deletions .github/workflows/linter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ name: Run Linter Test

on:
workflow_dispatch:
push:
branches:
- main
- dev
- release/*
paths-ignore:
- docs/*
- "*.md"
pull_request:

jobs:
Linter:
Expand All @@ -15,5 +24,4 @@ jobs:
python -m pip install --upgrade pip
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi
- run: |
pylint --fail-under 9 $(pwd)/custom_components
- run: PYTHONPATH=$(pwd)/ pylint --fail-under 9 $(pwd)/custom_components
9 changes: 9 additions & 0 deletions .github/workflows/unittest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ name: Run Unit Tests

on:
workflow_dispatch:
push:
branches:
- main
- dev
- release/*
paths-ignore:
- docs/*
- "*.md"
pull_request:

jobs:
Test:
Expand Down
6 changes: 2 additions & 4 deletions custom_components/spotcast/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@
from custom_components.spotcast.services.const import SERVICE_SCHEMAS
from custom_components.spotcast.sessions.exceptions import TokenRefreshError
from custom_components.spotcast.websocket import async_setup_websocket
from custom_components.spotcast.config_flow.option_flow_handler import (
DEFAULT_OPTIONS
)
from custom_components.spotcast.config_flow import DEFAULT_OPTIONS

__version__ = "5.0.0-b16"

Expand All @@ -44,7 +42,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""

# ensure default options
updated_options = {**DEFAULT_OPTIONS, **entry.options}
updated_options = DEFAULT_OPTIONS | entry.options

if updated_options != entry.options:
hass.config_entries.async_update_entry(entry, options=updated_options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,142 @@
from logging import getLogger
from typing import Any
from unittest.mock import MagicMock
from types import MappingProxyType

from homeassistant.config_entries import CONN_CLASS_CLOUD_POLL
from homeassistant.helpers import config_validation as cv
from homeassistant.components.spotify.config_flow import SpotifyFlowHandler
from homeassistant.config_entries import (
ConfigFlowResult,
OptionsFlow,
ConfigEntry,
FlowResult,
SOURCE_REAUTH,
)
import voluptuous as vol
from spotipy import Spotify

from custom_components.spotcast import DOMAIN
from custom_components.spotcast.utils import copy_to_dict
from custom_components.spotcast.spotify import SpotifyAccount
from custom_components.spotcast.sessions import PrivateSession
from custom_components.spotcast.config_flow.option_flow_handler import (
SpotcastOptionsFlowHandler
)

LOGGER = getLogger(__name__)

DEFAULT_OPTIONS = MappingProxyType({
"is_default": False,
"base_refresh_rate": 30,
})


class SpotcastOptionsFlowHandler(OptionsFlow):
"""Handles option configuration via the Integration page"""

SCHEMAS = {
"init": vol.Schema(
{
vol.Required("set_default"): bool,
vol.Required("base_refresh_rate"): cv.positive_int,
}
)
}

async def async_step_init(
self,
user_input: dict[str] | None = None
) -> FlowResult:
"""Initial Step for the Option Configuration Flow"""

options = copy_to_dict(self.config_entry.options)

LOGGER.debug("Opening Config menu for `%s`", self.config_entry.title)

self._options = DEFAULT_OPTIONS | options

LOGGER.debug("Options set to `%s`", self._options)

return self.async_show_form(
step_id="apply_options",
data_schema=self.add_suggested_values_to_schema(
self.SCHEMAS["init"],
self._options,
),
errors={},
)

def set_default_user(self) -> dict:
"""Set the current user as default for spotcast"""

entries = self.hass.config_entries.async_entries(DOMAIN)
old_default = None

for entry in entries:

is_default = entry.options["is_default"]
options = copy_to_dict(entry.options)
options["is_default"] = False

if is_default:
old_default = entry.title
self.hass.data[DOMAIN][entry.entry_id]["account"]\
.is_default = False

self.hass.config_entries.async_update_entry(
entry,
options=options,
)

LOGGER.info(
"Switching Default Spotcast account from `%s` to `%s`",
old_default,
self.config_entry.title,
)

self._options["is_default"] = True
self.hass.data[DOMAIN][self.config_entry.entry_id]["account"]\
.is_default = True

def set_base_refresh_rate(self, new_refresh_rate: int):
"""Sets the base refresh rate for the account
Args:
- new_refresh_rate(int): the new refresh rate to set for
the account
"""

if new_refresh_rate == self._options["base_refresh_rate"]:
LOGGER.debug("Same refresh rate. Skipping")
return

LOGGER.info(
"Setting spotcast entry `%s` to a base refresh rate of %d",
self.config_entry.title,
new_refresh_rate,
)
entry_id = self.config_entry.entry_id
self.hass.data[DOMAIN][entry_id]["account"]\
.base_refresh_rate = new_refresh_rate

self._options["base_refresh_rate"] = new_refresh_rate

async def async_step_apply_options(
self,
user_input: dict[str]
) -> FlowResult:
"""Step to apply the options configured"""

if user_input["set_default"]:
self.set_default_user()

self.set_base_refresh_rate(user_input["base_refresh_rate"])

self.hass.config_entries.async_update_entry(
self.config_entry,
options=self._options,
)

return self.async_abort(reason="Successfull")


class SpotcastFlowHandler(SpotifyFlowHandler, domain=DOMAIN):
"""Hnadler of the Config Flow for Spotcast
Expand Down Expand Up @@ -117,7 +232,7 @@ async def async_oauth_create_entry(
await private_session.async_ensure_token_valid()
accounts: dict[str, Spotify] = {
"public": Spotify(auth=external_api["token"]["access_token"]),
"private": Spotify(auth=private_session.token)
"private": Spotify(auth=private_session.clean_token)
}

profiles = {}
Expand All @@ -127,7 +242,7 @@ async def async_oauth_create_entry(
account.current_user
)

except Exception as exc: # pylint: disable=W0718
except Exception: # pylint: disable=W0718
return self.async_abort(reason="connection_error")

ids = [x["id"] for x in profiles.values()]
Expand Down Expand Up @@ -195,4 +310,4 @@ def async_get_options_flow(
) -> SpotcastOptionsFlowHandler:
"""Tells Home Assistant this integration supports configuration
options"""
return SpotcastOptionsFlowHandler(config_entry)
return SpotcastOptionsFlowHandler()
5 changes: 0 additions & 5 deletions custom_components/spotcast/config_flow/__init__.py

This file was deleted.

Loading

0 comments on commit 94c74f2

Please sign in to comment.