Improve Sonarr Upcoming Time Handling (#34224)

This commit is contained in:
Chris Talkington 2020-04-16 16:11:00 -05:00 committed by GitHub
parent ab352c3bc9
commit ede432ba71
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 24 deletions

View File

@ -352,6 +352,7 @@ homeassistant/components/solarlog/* @Ernst79
homeassistant/components/solax/* @squishykid homeassistant/components/solax/* @squishykid
homeassistant/components/soma/* @ratsept homeassistant/components/soma/* @ratsept
homeassistant/components/somfy/* @tetienne homeassistant/components/somfy/* @tetienne
homeassistant/components/sonarr/* @ctalkington
homeassistant/components/songpal/* @rytilahti homeassistant/components/songpal/* @rytilahti
homeassistant/components/sonos/* @amelchio homeassistant/components/sonos/* @amelchio
homeassistant/components/spaceapi/* @fabaff homeassistant/components/spaceapi/* @fabaff

View File

@ -2,5 +2,5 @@
"domain": "sonarr", "domain": "sonarr",
"name": "Sonarr", "name": "Sonarr",
"documentation": "https://www.home-assistant.io/integrations/sonarr", "documentation": "https://www.home-assistant.io/integrations/sonarr",
"codeowners": [] "codeowners": ["@ctalkington"]
} }

View File

@ -1,9 +1,7 @@
"""Support for Sonarr.""" """Support for Sonarr."""
from datetime import datetime from datetime import timedelta
import logging import logging
import time
from pytz import timezone
import requests import requests
import voluptuous as vol import voluptuous as vol
@ -27,6 +25,7 @@ from homeassistant.const import (
) )
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -93,13 +92,13 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
def setup_platform(hass, config, add_entities, discovery_info=None): def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Sonarr platform.""" """Set up the Sonarr platform."""
conditions = config.get(CONF_MONITORED_CONDITIONS) conditions = config.get(CONF_MONITORED_CONDITIONS)
add_entities([SonarrSensor(hass, config, sensor) for sensor in conditions], True) add_entities([SonarrSensor(config, sensor) for sensor in conditions], True)
class SonarrSensor(Entity): class SonarrSensor(Entity):
"""Implementation of the Sonarr sensor.""" """Implementation of the Sonarr sensor."""
def __init__(self, hass, conf, sensor_type): def __init__(self, conf, sensor_type):
"""Create Sonarr entity.""" """Create Sonarr entity."""
self.conf = conf self.conf = conf
@ -114,7 +113,6 @@ class SonarrSensor(Entity):
self.ssl = "https" if conf.get(CONF_SSL) else "http" self.ssl = "https" if conf.get(CONF_SSL) else "http"
self._state = None self._state = None
self.data = [] self.data = []
self._tz = timezone(str(hass.config.time_zone))
self.type = sensor_type self.type = sensor_type
self._name = SENSOR_TYPES[self.type][0] self._name = SENSOR_TYPES[self.type][0]
if self.type == "diskspace": if self.type == "diskspace":
@ -150,6 +148,9 @@ class SonarrSensor(Entity):
attributes = {} attributes = {}
if self.type == "upcoming": if self.type == "upcoming":
for show in self.data: for show in self.data:
if show["series"]["title"] in attributes:
continue
attributes[show["series"]["title"]] = "S{:02d}E{:02d}".format( attributes[show["series"]["title"]] = "S{:02d}E{:02d}".format(
show["seasonNumber"], show["episodeNumber"] show["seasonNumber"], show["episodeNumber"]
) )
@ -205,12 +206,17 @@ class SonarrSensor(Entity):
def update(self): def update(self):
"""Update the data for the sensor.""" """Update the data for the sensor."""
start = get_date(self._tz) start = dt_util.utcnow().replace(microsecond=0)
end = get_date(self._tz, self.days) end = start + timedelta(days=self.days)
try: try:
res = requests.get( res = requests.get(
ENDPOINTS[self.type].format( ENDPOINTS[self.type].format(
self.ssl, self.host, self.port, self.urlbase, start, end self.ssl,
self.host,
self.port,
self.urlbase,
start.isoformat().replace("+00:00", "Z"),
end.isoformat().replace("+00:00", "Z"),
), ),
headers={"X-Api-Key": self.apikey}, headers={"X-Api-Key": self.apikey},
timeout=10, timeout=10,
@ -223,14 +229,7 @@ class SonarrSensor(Entity):
if res.status_code == HTTP_OK: if res.status_code == HTTP_OK:
if self.type in ["upcoming", "queue", "series", "commands"]: if self.type in ["upcoming", "queue", "series", "commands"]:
if self.days == 1 and self.type == "upcoming": self.data = res.json()
# Sonarr API returns an empty array if start and end dates
# are the same, so we need to filter to just today
self.data = list(
filter(lambda x: x["airDate"] == str(start), res.json())
)
else:
self.data = res.json()
self._state = len(self.data) self._state = len(self.data)
elif self.type == "wanted": elif self.type == "wanted":
data = res.json() data = res.json()
@ -264,12 +263,6 @@ class SonarrSensor(Entity):
self._available = True self._available = True
def get_date(zone, offset=0):
"""Get date based on timezone and offset of days."""
day = 60 * 60 * 24
return datetime.date(datetime.fromtimestamp(time.time() + day * offset, tz=zone))
def to_unit(value, unit): def to_unit(value, unit):
"""Convert bytes to give unit.""" """Convert bytes to give unit."""
return value / 1024 ** BYTE_SIZES.index(unit) return value / 1024 ** BYTE_SIZES.index(unit)