mirror of
https://github.com/home-assistant/core.git
synced 2025-06-25 01:21:51 +02:00
Add PlayStation Network Integration (#133901)
* clean pull request
* Create one device per console
* Requested changes
* Pr/tr4nt0r/1 (#2)
* clean pull request
* Create one device per console
* device setup
* Merge PR1 - Dynamic Device Support
* Merge PR1 - Dynamic Device Support
---------
Co-authored-by: tr4nt0r <4445816+tr4nt0r@users.noreply.github.com>
* nitpicks
* Update config_flow test
* Update quality_scale.yaml
* repair integrations.json
* minor updates
* Add translation string for invalid account
* misc changes post review
* Minor strings updates
* strengthen config_flow test
* Requested changes
* Applied patch to commit a358725
* migrate PlayStationNetwork helper classes to HA
* Revert to standard psn library
* Updates to media_player logic
* add default_factory, change registered_platforms to set
* Improve test coverage
* Add snapshot test for media_player platform
* fix token parse error
* Parametrize media player test
* Add PS3 support
* Add PS3 support
* Add concurrent console support
* Adjust psnawp rate limit
* Convert to package PlatformType
* Update dependency to PSNAWP==3.0.0
* small improvements
* Add PlayStation PC Support
* Refactor active sessions list
* shift async logic to helper
* Implemented suggested changes
* Suggested changes
* Updated tests
* Suggested changes
* Fix test
* Suggested changes
* Suggested changes
* Update config_flow tests
* Group remaining api call in single executor
---------
Co-authored-by: tr4nt0r <4445816+tr4nt0r@users.noreply.github.com>
Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
2
CODEOWNERS
generated
2
CODEOWNERS
generated
@ -1169,6 +1169,8 @@ build.json @home-assistant/supervisor
|
||||
/tests/components/ping/ @jpbede
|
||||
/homeassistant/components/plaato/ @JohNan
|
||||
/tests/components/plaato/ @JohNan
|
||||
/homeassistant/components/playstation_network/ @jackjpowell
|
||||
/tests/components/playstation_network/ @jackjpowell
|
||||
/homeassistant/components/plex/ @jjlawren
|
||||
/tests/components/plex/ @jjlawren
|
||||
/homeassistant/components/plugwise/ @CoMPaTech @bouwew
|
||||
|
@ -1,5 +1,11 @@
|
||||
{
|
||||
"domain": "sony",
|
||||
"name": "Sony",
|
||||
"integrations": ["braviatv", "ps4", "sony_projector", "songpal"]
|
||||
"integrations": [
|
||||
"braviatv",
|
||||
"ps4",
|
||||
"sony_projector",
|
||||
"songpal",
|
||||
"playstation_network"
|
||||
]
|
||||
}
|
||||
|
34
homeassistant/components/playstation_network/__init__.py
Normal file
34
homeassistant/components/playstation_network/__init__.py
Normal file
@ -0,0 +1,34 @@
|
||||
"""The PlayStation Network integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import CONF_NPSSO
|
||||
from .coordinator import PlaystationNetworkConfigEntry, PlaystationNetworkCoordinator
|
||||
from .helpers import PlaystationNetwork
|
||||
|
||||
PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER]
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant, entry: PlaystationNetworkConfigEntry
|
||||
) -> bool:
|
||||
"""Set up Playstation Network from a config entry."""
|
||||
|
||||
psn = PlaystationNetwork(hass, entry.data[CONF_NPSSO])
|
||||
|
||||
coordinator = PlaystationNetworkCoordinator(hass, psn, entry)
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
entry.runtime_data = coordinator
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(
|
||||
hass: HomeAssistant, entry: PlaystationNetworkConfigEntry
|
||||
) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
70
homeassistant/components/playstation_network/config_flow.py
Normal file
70
homeassistant/components/playstation_network/config_flow.py
Normal file
@ -0,0 +1,70 @@
|
||||
"""Config flow for the PlayStation Network integration."""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from psnawp_api.core.psnawp_exceptions import (
|
||||
PSNAWPAuthenticationError,
|
||||
PSNAWPError,
|
||||
PSNAWPInvalidTokenError,
|
||||
PSNAWPNotFoundError,
|
||||
)
|
||||
from psnawp_api.models.user import User
|
||||
from psnawp_api.utils.misc import parse_npsso_token
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
|
||||
from .const import CONF_NPSSO, DOMAIN
|
||||
from .helpers import PlaystationNetwork
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_NPSSO): str})
|
||||
|
||||
|
||||
class PlaystationNetworkConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for Playstation Network."""
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
errors: dict[str, str] = {}
|
||||
npsso: str | None = None
|
||||
if user_input is not None:
|
||||
try:
|
||||
npsso = parse_npsso_token(user_input[CONF_NPSSO])
|
||||
except PSNAWPInvalidTokenError:
|
||||
errors["base"] = "invalid_account"
|
||||
|
||||
if npsso:
|
||||
psn = PlaystationNetwork(self.hass, npsso)
|
||||
try:
|
||||
user: User = await psn.get_user()
|
||||
except PSNAWPAuthenticationError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except PSNAWPNotFoundError:
|
||||
errors["base"] = "invalid_account"
|
||||
except PSNAWPError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
await self.async_set_unique_id(user.account_id)
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(
|
||||
title=user.online_id,
|
||||
data={CONF_NPSSO: npsso},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=STEP_USER_DATA_SCHEMA,
|
||||
errors=errors,
|
||||
description_placeholders={
|
||||
"npsso_link": "https://ca.account.sony.com/api/v1/ssocookie",
|
||||
"psn_link": "https://playstation.com",
|
||||
},
|
||||
)
|
15
homeassistant/components/playstation_network/const.py
Normal file
15
homeassistant/components/playstation_network/const.py
Normal file
@ -0,0 +1,15 @@
|
||||
"""Constants for the Playstation Network integration."""
|
||||
|
||||
from typing import Final
|
||||
|
||||
from psnawp_api.models.trophies import PlatformType
|
||||
|
||||
DOMAIN = "playstation_network"
|
||||
CONF_NPSSO: Final = "npsso"
|
||||
|
||||
SUPPORTED_PLATFORMS = {
|
||||
PlatformType.PS5,
|
||||
PlatformType.PS4,
|
||||
PlatformType.PS3,
|
||||
PlatformType.PSPC,
|
||||
}
|
69
homeassistant/components/playstation_network/coordinator.py
Normal file
69
homeassistant/components/playstation_network/coordinator.py
Normal file
@ -0,0 +1,69 @@
|
||||
"""Coordinator for the PlayStation Network Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
from psnawp_api.core.psnawp_exceptions import (
|
||||
PSNAWPAuthenticationError,
|
||||
PSNAWPServerError,
|
||||
)
|
||||
from psnawp_api.models.user import User
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .const import DOMAIN
|
||||
from .helpers import PlaystationNetwork, PlaystationNetworkData
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
type PlaystationNetworkConfigEntry = ConfigEntry[PlaystationNetworkCoordinator]
|
||||
|
||||
|
||||
class PlaystationNetworkCoordinator(DataUpdateCoordinator[PlaystationNetworkData]):
|
||||
"""Data update coordinator for PSN."""
|
||||
|
||||
config_entry: PlaystationNetworkConfigEntry
|
||||
user: User
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
psn: PlaystationNetwork,
|
||||
config_entry: PlaystationNetworkConfigEntry,
|
||||
) -> None:
|
||||
"""Initialize the Coordinator."""
|
||||
super().__init__(
|
||||
hass,
|
||||
name=DOMAIN,
|
||||
logger=_LOGGER,
|
||||
config_entry=config_entry,
|
||||
update_interval=timedelta(seconds=30),
|
||||
)
|
||||
|
||||
self.psn = psn
|
||||
|
||||
async def _async_setup(self) -> None:
|
||||
"""Set up the coordinator."""
|
||||
|
||||
try:
|
||||
self.user = await self.psn.get_user()
|
||||
except PSNAWPAuthenticationError as error:
|
||||
raise ConfigEntryNotReady(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="not_ready",
|
||||
) from error
|
||||
|
||||
async def _async_update_data(self) -> PlaystationNetworkData:
|
||||
"""Get the latest data from the PSN."""
|
||||
try:
|
||||
return await self.psn.get_data()
|
||||
except (PSNAWPAuthenticationError, PSNAWPServerError) as error:
|
||||
raise UpdateFailed(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="update_failed",
|
||||
) from error
|
151
homeassistant/components/playstation_network/helpers.py
Normal file
151
homeassistant/components/playstation_network/helpers.py
Normal file
@ -0,0 +1,151 @@
|
||||
"""Helper methods for common PlayStation Network integration operations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
|
||||
from psnawp_api import PSNAWP
|
||||
from psnawp_api.core.psnawp_exceptions import PSNAWPNotFoundError
|
||||
from psnawp_api.models.client import Client
|
||||
from psnawp_api.models.trophies import PlatformType
|
||||
from psnawp_api.models.user import User
|
||||
from pyrate_limiter import Duration, Rate
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import SUPPORTED_PLATFORMS
|
||||
|
||||
LEGACY_PLATFORMS = {PlatformType.PS3, PlatformType.PS4}
|
||||
|
||||
|
||||
@dataclass
|
||||
class SessionData:
|
||||
"""Dataclass representing console session data."""
|
||||
|
||||
platform: PlatformType = PlatformType.UNKNOWN
|
||||
title_id: str | None = None
|
||||
title_name: str | None = None
|
||||
format: PlatformType | None = None
|
||||
media_image_url: str | None = None
|
||||
status: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlaystationNetworkData:
|
||||
"""Dataclass representing data retrieved from the Playstation Network api."""
|
||||
|
||||
presence: dict[str, Any] = field(default_factory=dict)
|
||||
username: str = ""
|
||||
account_id: str = ""
|
||||
available: bool = False
|
||||
active_sessions: dict[PlatformType, SessionData] = field(default_factory=dict)
|
||||
registered_platforms: set[PlatformType] = field(default_factory=set)
|
||||
|
||||
|
||||
class PlaystationNetwork:
|
||||
"""Helper Class to return playstation network data in an easy to use structure."""
|
||||
|
||||
def __init__(self, hass: HomeAssistant, npsso: str) -> None:
|
||||
"""Initialize the class with the npsso token."""
|
||||
rate = Rate(300, Duration.MINUTE * 15)
|
||||
self.psn = PSNAWP(npsso, rate_limit=rate)
|
||||
self.client: Client | None = None
|
||||
self.hass = hass
|
||||
self.user: User
|
||||
self.legacy_profile: dict[str, Any] | None = None
|
||||
|
||||
async def get_user(self) -> User:
|
||||
"""Get the user object from the PlayStation Network."""
|
||||
self.user = await self.hass.async_add_executor_job(
|
||||
partial(self.psn.user, online_id="me")
|
||||
)
|
||||
return self.user
|
||||
|
||||
def retrieve_psn_data(self) -> PlaystationNetworkData:
|
||||
"""Bundle api calls to retrieve data from the PlayStation Network."""
|
||||
data = PlaystationNetworkData()
|
||||
|
||||
if not self.client:
|
||||
self.client = self.psn.me()
|
||||
|
||||
data.registered_platforms = {
|
||||
PlatformType(device["deviceType"])
|
||||
for device in self.client.get_account_devices()
|
||||
} & SUPPORTED_PLATFORMS
|
||||
|
||||
data.presence = self.user.get_presence()
|
||||
|
||||
# check legacy platforms if owned
|
||||
if LEGACY_PLATFORMS & data.registered_platforms:
|
||||
self.legacy_profile = self.client.get_profile_legacy()
|
||||
return data
|
||||
|
||||
async def get_data(self) -> PlaystationNetworkData:
|
||||
"""Get title data from the PlayStation Network."""
|
||||
data = await self.hass.async_add_executor_job(self.retrieve_psn_data)
|
||||
data.username = self.user.online_id
|
||||
data.account_id = self.user.account_id
|
||||
|
||||
data.available = (
|
||||
data.presence.get("basicPresence", {}).get("availability")
|
||||
== "availableToPlay"
|
||||
)
|
||||
|
||||
session = SessionData()
|
||||
session.platform = PlatformType(
|
||||
data.presence["basicPresence"]["primaryPlatformInfo"]["platform"]
|
||||
)
|
||||
|
||||
if session.platform in SUPPORTED_PLATFORMS:
|
||||
session.status = data.presence.get("basicPresence", {}).get(
|
||||
"primaryPlatformInfo"
|
||||
)["onlineStatus"]
|
||||
|
||||
game_title_info = data.presence.get("basicPresence", {}).get(
|
||||
"gameTitleInfoList"
|
||||
)
|
||||
|
||||
if game_title_info:
|
||||
session.title_id = game_title_info[0]["npTitleId"]
|
||||
session.title_name = game_title_info[0]["titleName"]
|
||||
session.format = PlatformType(game_title_info[0]["format"])
|
||||
if session.format in {PlatformType.PS5, PlatformType.PSPC}:
|
||||
session.media_image_url = game_title_info[0]["conceptIconUrl"]
|
||||
else:
|
||||
session.media_image_url = game_title_info[0]["npTitleIconUrl"]
|
||||
|
||||
data.active_sessions[session.platform] = session
|
||||
|
||||
if self.legacy_profile:
|
||||
presence = self.legacy_profile["profile"].get("presences", [])
|
||||
game_title_info = presence[0] if presence else {}
|
||||
session = SessionData()
|
||||
|
||||
# If primary console isn't online, check legacy platforms for status
|
||||
if not data.available:
|
||||
data.available = game_title_info["onlineStatus"] == "online"
|
||||
|
||||
if "npTitleId" in game_title_info:
|
||||
session.title_id = game_title_info["npTitleId"]
|
||||
session.title_name = game_title_info["titleName"]
|
||||
session.format = game_title_info["platform"]
|
||||
session.platform = game_title_info["platform"]
|
||||
session.status = game_title_info["onlineStatus"]
|
||||
if PlatformType(session.format) is PlatformType.PS4:
|
||||
session.media_image_url = game_title_info["npTitleIconUrl"]
|
||||
elif PlatformType(session.format) is PlatformType.PS3:
|
||||
try:
|
||||
title = self.psn.game_title(
|
||||
session.title_id, platform=PlatformType.PS3, account_id="me"
|
||||
)
|
||||
except PSNAWPNotFoundError:
|
||||
session.media_image_url = None
|
||||
|
||||
if title:
|
||||
session.media_image_url = title.get_title_icon_url()
|
||||
|
||||
if game_title_info["onlineStatus"] == "online":
|
||||
data.active_sessions[session.platform] = session
|
||||
return data
|
9
homeassistant/components/playstation_network/icons.json
Normal file
9
homeassistant/components/playstation_network/icons.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"entity": {
|
||||
"media_player": {
|
||||
"playstation": {
|
||||
"default": "mdi:sony-playstation"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
11
homeassistant/components/playstation_network/manifest.json
Normal file
11
homeassistant/components/playstation_network/manifest.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"domain": "playstation_network",
|
||||
"name": "PlayStation Network",
|
||||
"codeowners": ["@jackjpowell"],
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/playstation_network",
|
||||
"integration_type": "service",
|
||||
"iot_class": "cloud_polling",
|
||||
"quality_scale": "bronze",
|
||||
"requirements": ["PSNAWP==3.0.0", "pyrate-limiter==3.7.0"]
|
||||
}
|
128
homeassistant/components/playstation_network/media_player.py
Normal file
128
homeassistant/components/playstation_network/media_player.py
Normal file
@ -0,0 +1,128 @@
|
||||
"""Media player entity for the PlayStation Network Integration."""
|
||||
|
||||
import logging
|
||||
|
||||
from psnawp_api.models.trophies import PlatformType
|
||||
|
||||
from homeassistant.components.media_player import (
|
||||
MediaPlayerDeviceClass,
|
||||
MediaPlayerEntity,
|
||||
MediaPlayerState,
|
||||
MediaType,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import PlaystationNetworkConfigEntry, PlaystationNetworkCoordinator
|
||||
from .const import DOMAIN, SUPPORTED_PLATFORMS
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
PLATFORM_MAP = {
|
||||
PlatformType.PS5: "PlayStation 5",
|
||||
PlatformType.PS4: "PlayStation 4",
|
||||
PlatformType.PS3: "PlayStation 3",
|
||||
PlatformType.PSPC: "PlayStation PC",
|
||||
}
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: PlaystationNetworkConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Media Player Entity Setup."""
|
||||
coordinator = config_entry.runtime_data
|
||||
devices_added: set[PlatformType] = set()
|
||||
device_reg = dr.async_get(hass)
|
||||
entities = []
|
||||
|
||||
@callback
|
||||
def add_entities() -> None:
|
||||
nonlocal devices_added
|
||||
|
||||
if not SUPPORTED_PLATFORMS - devices_added:
|
||||
remove_listener()
|
||||
|
||||
new_platforms = set(coordinator.data.active_sessions.keys()) - devices_added
|
||||
if new_platforms:
|
||||
async_add_entities(
|
||||
PsnMediaPlayerEntity(coordinator, platform_type)
|
||||
for platform_type in new_platforms
|
||||
)
|
||||
devices_added |= new_platforms
|
||||
|
||||
for platform in SUPPORTED_PLATFORMS:
|
||||
if device_reg.async_get_device(
|
||||
identifiers={
|
||||
(DOMAIN, f"{coordinator.config_entry.unique_id}_{platform.value}")
|
||||
}
|
||||
):
|
||||
entities.append(PsnMediaPlayerEntity(coordinator, platform))
|
||||
devices_added.add(platform)
|
||||
if entities:
|
||||
async_add_entities(entities)
|
||||
|
||||
remove_listener = coordinator.async_add_listener(add_entities)
|
||||
add_entities()
|
||||
|
||||
|
||||
class PsnMediaPlayerEntity(
|
||||
CoordinatorEntity[PlaystationNetworkCoordinator], MediaPlayerEntity
|
||||
):
|
||||
"""Media player entity representing currently playing game."""
|
||||
|
||||
_attr_media_image_remotely_accessible = True
|
||||
_attr_media_content_type = MediaType.GAME
|
||||
_attr_device_class = MediaPlayerDeviceClass.RECEIVER
|
||||
_attr_translation_key = "playstation"
|
||||
_attr_has_entity_name = True
|
||||
_attr_name = None
|
||||
|
||||
def __init__(
|
||||
self, coordinator: PlaystationNetworkCoordinator, platform: PlatformType
|
||||
) -> None:
|
||||
"""Initialize PSN MediaPlayer."""
|
||||
super().__init__(coordinator)
|
||||
|
||||
self._attr_unique_id = f"{coordinator.config_entry.unique_id}_{platform.value}"
|
||||
self.key = platform
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, self._attr_unique_id)},
|
||||
name=PLATFORM_MAP[platform],
|
||||
manufacturer="Sony Interactive Entertainment",
|
||||
model=PLATFORM_MAP[platform],
|
||||
)
|
||||
|
||||
@property
|
||||
def state(self) -> MediaPlayerState:
|
||||
"""Media Player state getter."""
|
||||
session = self.coordinator.data.active_sessions.get(self.key)
|
||||
if session and session.status == "online":
|
||||
if self.coordinator.data.available and session.title_id is not None:
|
||||
return MediaPlayerState.PLAYING
|
||||
return MediaPlayerState.ON
|
||||
return MediaPlayerState.OFF
|
||||
|
||||
@property
|
||||
def media_title(self) -> str | None:
|
||||
"""Media title getter."""
|
||||
session = self.coordinator.data.active_sessions.get(self.key)
|
||||
return session.title_name if session else None
|
||||
|
||||
@property
|
||||
def media_content_id(self) -> str | None:
|
||||
"""Content ID of current playing media."""
|
||||
session = self.coordinator.data.active_sessions.get(self.key)
|
||||
return session.title_id if session else None
|
||||
|
||||
@property
|
||||
def media_image_url(self) -> str | None:
|
||||
"""Media image url getter."""
|
||||
session = self.coordinator.data.active_sessions.get(self.key)
|
||||
return session.media_image_url if session else None
|
@ -0,0 +1,72 @@
|
||||
rules:
|
||||
# Bronze
|
||||
action-setup:
|
||||
status: exempt
|
||||
comment: Integration has no actions
|
||||
appropriate-polling: done
|
||||
brands: done
|
||||
common-modules: done
|
||||
config-flow-test-coverage: done
|
||||
config-flow: done
|
||||
dependency-transparency: done
|
||||
docs-actions:
|
||||
status: exempt
|
||||
comment: Integration has no actions
|
||||
|
||||
docs-high-level-description: done
|
||||
docs-installation-instructions: done
|
||||
docs-removal-instructions: done
|
||||
entity-event-setup:
|
||||
status: exempt
|
||||
comment: Integration does not register events.
|
||||
entity-unique-id: done
|
||||
has-entity-name: done
|
||||
runtime-data: done
|
||||
test-before-configure: done
|
||||
test-before-setup: done
|
||||
unique-config-entry: done
|
||||
|
||||
# Silver
|
||||
action-exceptions:
|
||||
status: exempt
|
||||
comment: Integration has no actions
|
||||
config-entry-unloading: done
|
||||
docs-configuration-parameters:
|
||||
status: exempt
|
||||
comment: Integration has no configuration options
|
||||
docs-installation-parameters: done
|
||||
entity-unavailable: done
|
||||
integration-owner: done
|
||||
log-when-unavailable: done
|
||||
parallel-updates: done
|
||||
reauthentication-flow: todo
|
||||
test-coverage: todo
|
||||
|
||||
# Gold
|
||||
devices: done
|
||||
diagnostics: todo
|
||||
discovery-update-info:
|
||||
status: exempt
|
||||
comment: Discovery flow is not applicable for this integration
|
||||
discovery: todo
|
||||
docs-data-update: done
|
||||
docs-examples: todo
|
||||
docs-known-limitations: done
|
||||
docs-supported-devices: done
|
||||
docs-supported-functions: done
|
||||
docs-troubleshooting: todo
|
||||
docs-use-cases: done
|
||||
dynamic-devices: todo
|
||||
entity-category: done
|
||||
entity-device-class: done
|
||||
entity-disabled-by-default: done
|
||||
entity-translations: done
|
||||
exception-translations: done
|
||||
icon-translations: done
|
||||
reconfiguration-flow: todo
|
||||
repair-issues: todo
|
||||
stale-devices: todo
|
||||
# Platinum
|
||||
async-dependency: todo
|
||||
inject-websession: todo
|
||||
strict-typing: todo
|
32
homeassistant/components/playstation_network/strings.json
Normal file
32
homeassistant/components/playstation_network/strings.json
Normal file
@ -0,0 +1,32 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"npsso": "NPSSO token"
|
||||
},
|
||||
"data_description": {
|
||||
"npsso": "The NPSSO token is generated during successful login of your PlayStation Network account and is used to authenticate your requests from with Home Assistant."
|
||||
},
|
||||
"description": "To obtain your NPSSO token, log in to your [PlayStation account]({psn_link}) first. Then [click here]({npsso_link}) to retrieve the token."
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
|
||||
"invalid_account": "[%key:common::config_flow::error::invalid_access_token%]",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]"
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
"not_ready": {
|
||||
"message": "Authentication to the PlayStation Network failed."
|
||||
},
|
||||
"update_failed": {
|
||||
"message": "Data retrieval failed when trying to access the PlayStation Network."
|
||||
}
|
||||
}
|
||||
}
|
1
homeassistant/generated/config_flows.py
generated
1
homeassistant/generated/config_flows.py
generated
@ -481,6 +481,7 @@ FLOWS = {
|
||||
"picnic",
|
||||
"ping",
|
||||
"plaato",
|
||||
"playstation_network",
|
||||
"plex",
|
||||
"plugwise",
|
||||
"plum_lightpad",
|
||||
|
@ -6229,6 +6229,12 @@
|
||||
"config_flow": true,
|
||||
"iot_class": "local_push",
|
||||
"name": "Sony Songpal"
|
||||
},
|
||||
"playstation_network": {
|
||||
"integration_type": "service",
|
||||
"config_flow": true,
|
||||
"iot_class": "cloud_polling",
|
||||
"name": "PlayStation Network"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
6
requirements_all.txt
generated
6
requirements_all.txt
generated
@ -24,6 +24,9 @@ HATasmota==0.10.0
|
||||
# homeassistant.components.mastodon
|
||||
Mastodon.py==2.0.1
|
||||
|
||||
# homeassistant.components.playstation_network
|
||||
PSNAWP==3.0.0
|
||||
|
||||
# homeassistant.components.doods
|
||||
# homeassistant.components.generic
|
||||
# homeassistant.components.image_upload
|
||||
@ -2281,6 +2284,9 @@ pyrail==0.4.1
|
||||
# homeassistant.components.rainbird
|
||||
pyrainbird==6.0.1
|
||||
|
||||
# homeassistant.components.playstation_network
|
||||
pyrate-limiter==3.7.0
|
||||
|
||||
# homeassistant.components.recswitch
|
||||
pyrecswitch==1.0.2
|
||||
|
||||
|
6
requirements_test_all.txt
generated
6
requirements_test_all.txt
generated
@ -24,6 +24,9 @@ HATasmota==0.10.0
|
||||
# homeassistant.components.mastodon
|
||||
Mastodon.py==2.0.1
|
||||
|
||||
# homeassistant.components.playstation_network
|
||||
PSNAWP==3.0.0
|
||||
|
||||
# homeassistant.components.doods
|
||||
# homeassistant.components.generic
|
||||
# homeassistant.components.image_upload
|
||||
@ -1899,6 +1902,9 @@ pyrail==0.4.1
|
||||
# homeassistant.components.rainbird
|
||||
pyrainbird==6.0.1
|
||||
|
||||
# homeassistant.components.playstation_network
|
||||
pyrate-limiter==3.7.0
|
||||
|
||||
# homeassistant.components.risco
|
||||
pyrisco==0.6.7
|
||||
|
||||
|
1
tests/components/playstation_network/__init__.py
Normal file
1
tests/components/playstation_network/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Tests for the Playstation Network integration."""
|
113
tests/components/playstation_network/conftest.py
Normal file
113
tests/components/playstation_network/conftest.py
Normal file
@ -0,0 +1,113 @@
|
||||
"""Common fixtures for the Playstation Network tests."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.playstation_network.const import CONF_NPSSO, DOMAIN
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
NPSSO_TOKEN: str = "npsso-token"
|
||||
NPSSO_TOKEN_INVALID_JSON: str = "{'npsso': 'npsso-token'"
|
||||
PSN_ID: str = "my-psn-id"
|
||||
|
||||
|
||||
@pytest.fixture(name="config_entry")
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
"""Mock PlayStation Network configuration entry."""
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="test-user",
|
||||
data={
|
||||
CONF_NPSSO: NPSSO_TOKEN,
|
||||
},
|
||||
unique_id=PSN_ID,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Override async_setup_entry."""
|
||||
with patch(
|
||||
"homeassistant.components.playstation_network.async_setup_entry",
|
||||
return_value=True,
|
||||
) as mock_setup_entry:
|
||||
yield mock_setup_entry
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user() -> Generator[MagicMock]:
|
||||
"""Mock psnawp_api User object."""
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.playstation_network.helpers.User",
|
||||
autospec=True,
|
||||
) as mock_client:
|
||||
client = mock_client.return_value
|
||||
|
||||
client.account_id = PSN_ID
|
||||
client.online_id = "testuser"
|
||||
|
||||
client.get_presence.return_value = {
|
||||
"basicPresence": {
|
||||
"availability": "availableToPlay",
|
||||
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS5"},
|
||||
"gameTitleInfoList": [
|
||||
{
|
||||
"npTitleId": "PPSA07784_00",
|
||||
"titleName": "STAR WARS Jedi: Survivor™",
|
||||
"format": "PS5",
|
||||
"launchPlatform": "PS5",
|
||||
"conceptIconUrl": "https://image.api.playstation.com/vulcan/ap/rnd/202211/2222/l8QTN7ThQK3lRBHhB3nX1s7h.png",
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_psnawpapi(mock_user: MagicMock) -> Generator[MagicMock]:
|
||||
"""Mock psnawp_api."""
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.playstation_network.helpers.PSNAWP",
|
||||
autospec=True,
|
||||
) as mock_client:
|
||||
client = mock_client.return_value
|
||||
|
||||
client.user.return_value = mock_user
|
||||
client.me.return_value.get_account_devices.return_value = [
|
||||
{
|
||||
"deviceId": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234",
|
||||
"deviceType": "PS5",
|
||||
"activationType": "PRIMARY",
|
||||
"activationDate": "2021-01-14T18:00:00.000Z",
|
||||
"accountDeviceVector": "abcdefghijklmnopqrstuv",
|
||||
}
|
||||
]
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_psnawp_npsso(mock_user: MagicMock) -> Generator[MagicMock]:
|
||||
"""Mock psnawp_api."""
|
||||
|
||||
with patch(
|
||||
"psnawp_api.utils.misc.parse_npsso_token",
|
||||
autospec=True,
|
||||
) as mock_parse_npsso_token:
|
||||
npsso = mock_parse_npsso_token.return_value
|
||||
npsso.parse_npsso_token.return_value = NPSSO_TOKEN
|
||||
|
||||
yield npsso
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_token() -> Generator[MagicMock]:
|
||||
"""Mock token generator."""
|
||||
with patch("secrets.token_hex", return_value="123456789") as token:
|
||||
yield token
|
@ -0,0 +1,321 @@
|
||||
# serializer version: 1
|
||||
# name: test_platform[PS4_idle][media_player.playstation_4-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'media_player',
|
||||
'entity_category': None,
|
||||
'entity_id': 'media_player.playstation_4',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'playstation_network',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'playstation',
|
||||
'unique_id': 'my-psn-id_PS4',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS4_idle][media_player.playstation_4-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'receiver',
|
||||
'entity_picture_local': None,
|
||||
'friendly_name': 'PlayStation 4',
|
||||
'media_content_type': <MediaType.GAME: 'game'>,
|
||||
'supported_features': <MediaPlayerEntityFeature: 0>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'media_player.playstation_4',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'on',
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS4_offline][media_player.playstation_4-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'media_player',
|
||||
'entity_category': None,
|
||||
'entity_id': 'media_player.playstation_4',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'playstation_network',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'playstation',
|
||||
'unique_id': 'my-psn-id_PS4',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS4_offline][media_player.playstation_4-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'receiver',
|
||||
'friendly_name': 'PlayStation 4',
|
||||
'supported_features': <MediaPlayerEntityFeature: 0>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'media_player.playstation_4',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'off',
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS4_playing][media_player.playstation_4-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'media_player',
|
||||
'entity_category': None,
|
||||
'entity_id': 'media_player.playstation_4',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'playstation_network',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'playstation',
|
||||
'unique_id': 'my-psn-id_PS4',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS4_playing][media_player.playstation_4-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'receiver',
|
||||
'entity_picture': 'http://gs2-sec.ww.prod.dl.playstation.net/gs2-sec/appkgo/prod/CUSA23081_00/5/i_f5d2adec7665af80b8550fb33fe808df10d292cdd47629a991debfdf72bdee34/i/icon0.png',
|
||||
'entity_picture_local': '/api/media_player_proxy/media_player.playstation_4?token=123456789&cache=924f463745523102',
|
||||
'friendly_name': 'PlayStation 4',
|
||||
'media_content_id': 'CUSA23081_00',
|
||||
'media_content_type': <MediaType.GAME: 'game'>,
|
||||
'media_title': 'Untitled Goose Game',
|
||||
'supported_features': <MediaPlayerEntityFeature: 0>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'media_player.playstation_4',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'playing',
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS5_idle][media_player.playstation_5-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'media_player',
|
||||
'entity_category': None,
|
||||
'entity_id': 'media_player.playstation_5',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'playstation_network',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'playstation',
|
||||
'unique_id': 'my-psn-id_PS5',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS5_idle][media_player.playstation_5-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'receiver',
|
||||
'entity_picture_local': None,
|
||||
'friendly_name': 'PlayStation 5',
|
||||
'media_content_type': <MediaType.GAME: 'game'>,
|
||||
'supported_features': <MediaPlayerEntityFeature: 0>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'media_player.playstation_5',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'on',
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS5_offline][media_player.playstation_5-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'media_player',
|
||||
'entity_category': None,
|
||||
'entity_id': 'media_player.playstation_5',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'playstation_network',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'playstation',
|
||||
'unique_id': 'my-psn-id_PS5',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS5_offline][media_player.playstation_5-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'receiver',
|
||||
'friendly_name': 'PlayStation 5',
|
||||
'supported_features': <MediaPlayerEntityFeature: 0>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'media_player.playstation_5',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'off',
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS5_playing][media_player.playstation_5-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': set({
|
||||
}),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'media_player',
|
||||
'entity_category': None,
|
||||
'entity_id': 'media_player.playstation_5',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <MediaPlayerDeviceClass.RECEIVER: 'receiver'>,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'playstation_network',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'playstation',
|
||||
'unique_id': 'my-psn-id_PS5',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_platform[PS5_playing][media_player.playstation_5-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'device_class': 'receiver',
|
||||
'entity_picture': 'https://image.api.playstation.com/vulcan/ap/rnd/202211/2222/l8QTN7ThQK3lRBHhB3nX1s7h.png',
|
||||
'entity_picture_local': '/api/media_player_proxy/media_player.playstation_5?token=123456789&cache=50dfb7140be0060b',
|
||||
'friendly_name': 'PlayStation 5',
|
||||
'media_content_id': 'PPSA07784_00',
|
||||
'media_content_type': <MediaType.GAME: 'game'>,
|
||||
'media_title': 'STAR WARS Jedi: Survivor™',
|
||||
'supported_features': <MediaPlayerEntityFeature: 0>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'media_player.playstation_5',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'playing',
|
||||
})
|
||||
# ---
|
140
tests/components/playstation_network/test_config_flow.py
Normal file
140
tests/components/playstation_network/test_config_flow.py
Normal file
@ -0,0 +1,140 @@
|
||||
"""Test the Playstation Network config flow."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.playstation_network.config_flow import (
|
||||
PSNAWPAuthenticationError,
|
||||
PSNAWPError,
|
||||
PSNAWPInvalidTokenError,
|
||||
PSNAWPNotFoundError,
|
||||
)
|
||||
from homeassistant.components.playstation_network.const import CONF_NPSSO, DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from .conftest import NPSSO_TOKEN, NPSSO_TOKEN_INVALID_JSON, PSN_ID
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
MOCK_DATA_ADVANCED_STEP = {CONF_NPSSO: NPSSO_TOKEN}
|
||||
|
||||
|
||||
async def test_manual_config(hass: HomeAssistant, mock_psnawpapi: MagicMock) -> None:
|
||||
"""Test creating via manual configuration."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_NPSSO: "TEST_NPSSO_TOKEN"},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["result"].unique_id == PSN_ID
|
||||
assert result["data"] == {
|
||||
CONF_NPSSO: "TEST_NPSSO_TOKEN",
|
||||
}
|
||||
|
||||
|
||||
async def test_form_already_configured(
|
||||
hass: HomeAssistant,
|
||||
config_entry: MockConfigEntry,
|
||||
mock_psnawpapi: MagicMock,
|
||||
) -> None:
|
||||
"""Test we abort form login when entry is already configured."""
|
||||
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_NPSSO: NPSSO_TOKEN},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("raise_error", "text_error"),
|
||||
[
|
||||
(PSNAWPNotFoundError(), "invalid_account"),
|
||||
(PSNAWPAuthenticationError(), "invalid_auth"),
|
||||
(PSNAWPError(), "cannot_connect"),
|
||||
(Exception(), "unknown"),
|
||||
],
|
||||
)
|
||||
async def test_form_failures(
|
||||
hass: HomeAssistant,
|
||||
mock_psnawpapi: MagicMock,
|
||||
raise_error: Exception,
|
||||
text_error: str,
|
||||
) -> None:
|
||||
"""Test we handle a connection error.
|
||||
|
||||
First we generate an error and after fixing it, we are still able to submit.
|
||||
"""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": SOURCE_USER},
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
mock_psnawpapi.user.side_effect = raise_error
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_NPSSO: NPSSO_TOKEN},
|
||||
)
|
||||
|
||||
assert result["step_id"] == "user"
|
||||
assert result["errors"] == {"base": text_error}
|
||||
|
||||
mock_psnawpapi.user.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_NPSSO: NPSSO_TOKEN},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
CONF_NPSSO: NPSSO_TOKEN,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_psnawpapi")
|
||||
async def test_parse_npsso_token_failures(
|
||||
hass: HomeAssistant,
|
||||
mock_psnawp_npsso: MagicMock,
|
||||
) -> None:
|
||||
"""Test parse_npsso_token raises the correct exceptions during config flow."""
|
||||
mock_psnawp_npsso.parse_npsso_token.side_effect = PSNAWPInvalidTokenError
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": SOURCE_USER},
|
||||
data={CONF_NPSSO: NPSSO_TOKEN_INVALID_JSON},
|
||||
)
|
||||
assert result["errors"] == {"base": "invalid_account"}
|
||||
|
||||
mock_psnawp_npsso.parse_npsso_token.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_NPSSO: NPSSO_TOKEN},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
CONF_NPSSO: NPSSO_TOKEN,
|
||||
}
|
123
tests/components/playstation_network/test_media_player.py
Normal file
123
tests/components/playstation_network/test_media_player.py
Normal file
@ -0,0 +1,123 @@
|
||||
"""Test the Playstation Network media player platform."""
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry, snapshot_platform
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def media_player_only() -> AsyncGenerator[None]:
|
||||
"""Enable only the media_player platform."""
|
||||
with patch(
|
||||
"homeassistant.components.playstation_network.PLATFORMS",
|
||||
[Platform.MEDIA_PLAYER],
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"presence_payload",
|
||||
[
|
||||
{
|
||||
"basicPresence": {
|
||||
"availability": "availableToPlay",
|
||||
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS5"},
|
||||
"gameTitleInfoList": [
|
||||
{
|
||||
"npTitleId": "PPSA07784_00",
|
||||
"titleName": "STAR WARS Jedi: Survivor™",
|
||||
"format": "PS5",
|
||||
"launchPlatform": "PS5",
|
||||
"conceptIconUrl": "https://image.api.playstation.com/vulcan/ap/rnd/202211/2222/l8QTN7ThQK3lRBHhB3nX1s7h.png",
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"basicPresence": {
|
||||
"availability": "availableToPlay",
|
||||
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS4"},
|
||||
"gameTitleInfoList": [
|
||||
{
|
||||
"npTitleId": "CUSA23081_00",
|
||||
"titleName": "Untitled Goose Game",
|
||||
"format": "PS4",
|
||||
"launchPlatform": "PS4",
|
||||
"npTitleIconUrl": "http://gs2-sec.ww.prod.dl.playstation.net/gs2-sec/appkgo/prod/CUSA23081_00/5/i_f5d2adec7665af80b8550fb33fe808df10d292cdd47629a991debfdf72bdee34/i/icon0.png",
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"basicPresence": {
|
||||
"availability": "unavailable",
|
||||
"lastAvailableDate": "2025-05-02T17:47:59.392Z",
|
||||
"primaryPlatformInfo": {
|
||||
"onlineStatus": "offline",
|
||||
"platform": "PS5",
|
||||
"lastOnlineDate": "2025-05-02T17:47:59.392Z",
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
"basicPresence": {
|
||||
"availability": "unavailable",
|
||||
"lastAvailableDate": "2025-05-02T17:47:59.392Z",
|
||||
"primaryPlatformInfo": {
|
||||
"onlineStatus": "offline",
|
||||
"platform": "PS4",
|
||||
"lastOnlineDate": "2025-05-02T17:47:59.392Z",
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
"basicPresence": {
|
||||
"availability": "availableToPlay",
|
||||
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS5"},
|
||||
}
|
||||
},
|
||||
{
|
||||
"basicPresence": {
|
||||
"availability": "availableToPlay",
|
||||
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS4"},
|
||||
}
|
||||
},
|
||||
],
|
||||
ids=[
|
||||
"PS5_playing",
|
||||
"PS4_playing",
|
||||
"PS5_offline",
|
||||
"PS4_offline",
|
||||
"PS5_idle",
|
||||
"PS4_idle",
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_psnawpapi", "mock_token")
|
||||
async def test_platform(
|
||||
hass: HomeAssistant,
|
||||
config_entry: MockConfigEntry,
|
||||
snapshot: SnapshotAssertion,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_psnawpapi: MagicMock,
|
||||
presence_payload: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test setup of the PlayStation Network media_player platform."""
|
||||
|
||||
mock_psnawpapi.user().get_presence.return_value = presence_payload
|
||||
config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
|
Reference in New Issue
Block a user