Skip to content

Commit

Permalink
Add video id to youtube sensor state attributes (#93668)
Browse files Browse the repository at this point in the history
* Add video id to state attributes

* Make extra state attributes not optional

* Revert "Make extra state attributes not optional"

This reverts commit d2f9e93.
  • Loading branch information
joostlek committed Jun 1, 2023
1 parent a4b8b4f commit a6b6b03
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
13 changes: 13 additions & 0 deletions homeassistant/components/youtube/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
ATTR_SUBSCRIBER_COUNT,
ATTR_THUMBNAIL,
ATTR_TITLE,
ATTR_VIDEO_ID,
COORDINATOR,
DOMAIN,
)
Expand All @@ -30,6 +31,7 @@ class YouTubeMixin:

value_fn: Callable[[Any], StateType]
entity_picture_fn: Callable[[Any], str]
attributes_fn: Callable[[Any], dict[str, Any]] | None


@dataclass
Expand All @@ -44,6 +46,9 @@ class YouTubeSensorEntityDescription(SensorEntityDescription, YouTubeMixin):
icon="mdi:youtube",
value_fn=lambda channel: channel[ATTR_LATEST_VIDEO][ATTR_TITLE],
entity_picture_fn=lambda channel: channel[ATTR_LATEST_VIDEO][ATTR_THUMBNAIL],
attributes_fn=lambda channel: {
ATTR_VIDEO_ID: channel[ATTR_LATEST_VIDEO][ATTR_VIDEO_ID]
},
),
YouTubeSensorEntityDescription(
key="subscribers",
Expand All @@ -52,6 +57,7 @@ class YouTubeSensorEntityDescription(SensorEntityDescription, YouTubeMixin):
native_unit_of_measurement="subscribers",
value_fn=lambda channel: channel[ATTR_SUBSCRIBER_COUNT],
entity_picture_fn=lambda channel: channel[ATTR_ICON],
attributes_fn=None,
),
]

Expand Down Expand Up @@ -84,3 +90,10 @@ def native_value(self) -> StateType:
def entity_picture(self) -> str:
"""Return the value reported by the sensor."""
return self.entity_description.entity_picture_fn(self._channel)

@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the extra state attributes."""
if self.entity_description.attributes_fn:
return self.entity_description.attributes_fn(self._channel)
return None
1 change: 1 addition & 0 deletions tests/components/youtube/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ async def test_sensor(hass: HomeAssistant, setup_integration: ComponentSetup) ->
state.attributes["entity_picture"]
== "https://i.ytimg.com/vi/wysukDrMdqU/sddefault.jpg"
)
assert state.attributes["video_id"] == "wysukDrMdqU"

state = hass.states.get("sensor.google_for_developers_subscribers")
assert state
Expand Down

0 comments on commit a6b6b03

Please sign in to comment.