Skip to content

Commit

Permalink
Moved stats to sensor section, allow user to select which stats to load
Browse files Browse the repository at this point in the history
  • Loading branch information
downey-lv committed Jun 4, 2024
1 parent b6c03e2 commit 2fa088c
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 41 deletions.
68 changes: 41 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ Add it as a top-level key (i.e., `trakt_tv:` is not indented) in the `configurat
trakt_tv:
language: en # Prefered language for movie/show title
timezone: Europe/Paris # Prefered timezone
stats: True # Enable stats sensors
sensors:
upcoming:
show:
Expand Down Expand Up @@ -105,7 +104,6 @@ trakt_tv:
- `language` should be an [ISO 639-1 codes](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (default is "en")
- `timezone` should be a [pytz timezone](https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568) (default is the server timezone)
- `stats` should be True if you want to create sensors for your stats (default is False)

#### Available Sensors

Expand Down Expand Up @@ -180,31 +178,47 @@ There are three parameters for each sensor:
##### Stats sensors

Creates individual sensors giving all of your stats about the movies, shows, and episodes you have watched, collected, and rated.
To enable set `stats` to True in the integration settings.

The following sensors are available:
- Episodes Collected
- Episodes Comments
- Episodes Minutes
- Episodes Plays
- Episodes Ratings
- Episodes Watched
- Movies Collected
- Movies Comments
- Movies Minutes
- Movies Plays
- Movies Ratings
- Movies Watched
- Network Followers
- Network Following
- Network Friends
- Ratings Total
- Seasons Comments
- Seasons Ratings
- Shows Collected
- Shows Comments
- Shows Ratings
- Shows Watched
Add `sensors` > `stats` with a list of the sensors you want to enable. You can enable all of them instead by adding `all` to the list.

The available stats are available:
- `movies_plays`
- `movies_watched`
- `movies_minutes`
- `movies_collected`
- `movies_ratings`
- `movies_comments`
- `shows_watched`
- `shows_collected`
- `shows_ratings`
- `shows_comments`
- `seasons_ratings`
- `seasons_comments`
- `episodes_plays`
- `episodes_watched`
- `episodes_minutes`
- `episodes_collected`
- `episodes_ratings`
- `episodes_comments`
- `network_friends`
- `network_followers`
- `network_following`
- `ratings_total`

###### Stats Example
```yaml
trakt_tv:
sensors:
# Create sensors for all available stats
stats:
- all
# OR
# Create sensors for specific stats (see available stats above)
stats:
- episodes_plays
- movies_minutes
```

#### Example

Expand Down
2 changes: 1 addition & 1 deletion custom_components/trakt_tv/apis/trakt.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ async def retrieve_data(self):
coroutine_sources_data.append(source_function.get(sub_source)())

""" Load user stats """
if configuration.should_load_stats():
if configuration.source_exists("stats"):
sources.append("stats")
coroutine_sources_data.append(source_function.get("stats")())

Expand Down
9 changes: 3 additions & 6 deletions custom_components/trakt_tv/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,6 @@ def get_timezone(self) -> str:
except KeyError:
return datetime.now(tzlocal()).tzname()

def should_load_stats(self):
try:
return self.conf["stats"]
except KeyError:
return False

def identifier_exists(self, identifier: str, source: str) -> bool:
try:
self.conf["sensors"][source][identifier]
Expand Down Expand Up @@ -84,6 +78,9 @@ def recommendation_identifier_exists(self, identifier: str) -> bool:
def get_recommendation_max_medias(self, identifier: str) -> int:
return self.get_max_medias(identifier, "recommendation")

def stats_key_exists(self, key: str) -> bool:
return key in self.conf["sensors"]["stats"]

def source_exists(self, source: str) -> bool:
try:
self.conf["sensors"][source]
Expand Down
32 changes: 30 additions & 2 deletions custom_components/trakt_tv/schema.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from typing import Any, Dict
from typing import Any, Dict, List

import pytz
from dateutil.tz import tzlocal
Expand Down Expand Up @@ -31,7 +31,6 @@ def domain_schema() -> Schema:
Required("timezone", default=datetime.now(tzlocal()).tzname()): In(
pytz.all_timezones_set
),
Required("stats", default=False): bool,
}
}

Expand All @@ -42,6 +41,7 @@ def sensors_schema() -> Dict[str, Any]:
"all_upcoming": upcoming_schema(),
"next_to_watch": next_to_watch_schema(),
"recommendation": recommendation_schema(),
"stats": Schema(stats_schema()),
}


Expand Down Expand Up @@ -77,4 +77,32 @@ def recommendation_schema() -> Dict[str, Any]:
return subschemas


def stats_schema() -> list[str]:
return [
"all",
"movies_plays",
"movies_watched",
"movies_minutes",
"movies_collected",
"movies_ratings",
"movies_comments",
"shows_watched",
"shows_collected",
"shows_ratings",
"shows_comments",
"seasons_ratings",
"seasons_comments",
"episodes_plays",
"episodes_watched",
"episodes_minutes",
"episodes_collected",
"episodes_ratings",
"episodes_comments",
"network_friends",
"network_followers",
"network_following",
"ratings_total",
]


configuration_schema = dictionary_to_schema(domain_schema(), extra=ALLOW_EXTRA)
17 changes: 12 additions & 5 deletions custom_components/trakt_tv/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,21 +70,28 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
sensors.append(sensor)

# Add sensors for stats
if configuration.should_load_stats():
if configuration.source_exists("stats"):
stats = {}
# Check if the coordinator has data
if coordinator.data:
stats = coordinator.data.get("stats", {})

# Check if all stats are allowed
allow_all = configuration.stats_key_exists("all")

# Create a sensor for each key in the stats
for key, value in stats.items():
# Transform the key to a more readable format
title = key.replace("_", " ").title()

# Skip the key if it is not a valid state
# Skip the key if it is not a valid state (e.g. rating distribution dict)
if isinstance(value, dict):
continue

# Skip if not allowed in config
if not allow_all and not configuration.stats_key_exists(key):
continue

# Transform the key to a more readable format
title = key.replace("_", " ").title()

# Create the sensor
sensor = TraktStateSensor(
hass=hass,
Expand Down

0 comments on commit 2fa088c

Please sign in to comment.