Skip to content

Commit

Permalink
Merge pull request #17 from kingy444/master
Browse files Browse the repository at this point in the history
Add ability to Group Libraries into types
  • Loading branch information
gcorgnet authored Jun 8, 2021
2 parents 9e6f65e + de1348a commit 6c1455e
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 19 deletions.
51 changes: 49 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ This component does not require, nor conflict with, the default [Emby](https://w
| ssl | false | no | Whether or not to use SSL for Emby.
| max | 5 | no | Max number of items in sensor.
| use_backdrop | false | no | Defines whether to use the Backdrop Image, instead of the poster. (Great for using with the `fanart` display mode)
| include| | no | The names or the Emby Libraries you want to include. If not specified, all libraries will be shown and this component will create one sensor per Library
| include| | no | The names of the <strong>Emby Libraries</strong> you want to include. If not specified, all libraries will be shown and this component will create one sensor per Library. This is language specific.
| group_libraries| false| no | This option generates only two sensors (emby_latest_movies / emby_latest_tv_shows), grouping all your movies and tv into seperate sensors despite library setup in Emby. </br>This is useful for when Emby has many libraries but you only want one sensor in Home Assistant
</br>

**Do not just copy examples, please use config options above to build your own!**
### Sample for configuration.yaml:

> This will add items from the 'Movies', 'Kids Movies' and 'Tv Shows' Libraries in Emby, creating a seperate sensor per library
```
sensor:
- platform: emby_upcoming_media
Expand All @@ -41,13 +42,59 @@ sensor:
ssl: True
max: 5
use_backdrop: true
group_libraries: false
include:
- Movies
- Kids Movies
- TV Shows
```

> This will add all items Emby and create one sensor for movies (emby_latest_movies) and one for tv (emby_latest_tv_shows)
```
sensor:
- platform: emby_upcoming_media
api_key: YOUR_EMBY_API_KEY
user_id: YOUR_EMBY_USER_ID
host: 192.168.1.4
port: 8096
ssl: True
max: 5
use_backdrop: true
group_libraries: true
```
### Sample for ui-lovelace.yaml:

- type: custom:upcoming-media-card
entity: sensor.sensor.emby_latest_movies
title: Latest Movies


# Getting Information for the Plugin

## api_key
<ol>
<li>Navigate to the Emby Admin Dashboard (Cog in the top right)</li>
<li>Select <strong>Api Keys</strong> from the side menu</li>
<li>Select <strong>New Api Key</strong> from the top of the page</li>
</ol>

## user_id
### Via Web Interface
> This is just an example, make sure you get your own personal user_id
<ol>
<li>Navigate to the Emby Admin Dashboard (Cog in the top right)</li>
<li>Select <strong>Users</strong> from the side menu</li>
<li>Select the user you plan to use in HA from the list</li>
<li>From the address bar you can get the user id </br>
<i>http://emby_host_ip:8096/emby/web/index.html#!/users/user?userId=<strong>527563753xfd422288a32198522f821a</strong></i>
</li>
</ol>
### Via API Interface
<ol>
<li>Navigate to http://emby_host_ip:8096/emby/Users/Public</li>
<li>You will be provided a JSON response containing all the users details</li>
<li>Find the <strong>Name</strong> attribute for your user in the results</li>
<li>Next to the Name you will see an attribute name <strong>ServerId</strong></li>
<li>Next to the ServerId you will see <strong>Id</strong> - this is your user_id</li>
</ol>
3 changes: 2 additions & 1 deletion custom_components/emby_upcoming_media/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def get_view_categories(self):
url = "http{0}://{1}:{2}/Users/{3}/Views".format(
self.ssl, self.host, self.port, self.user_id
)
_LOGGER.info("Making API call on URL %s", url)
api = requests.get(url, timeout=10)
except OSError:
_LOGGER.warning("Host %s is not available", self.host)
Expand All @@ -42,7 +43,7 @@ def get_view_categories(self):

def get_data(self, categoryId):
try:
url = "http{0}://{1}:{2}/Users/{3}/Items/Latest?Limit={4}&Fields=CommunityRating,Studios,PremiereDate,Genres&ParentId={5}&api_key={6}&GroupItems=false".format(
url = "http{0}://{1}:{2}/Users/{3}/Items/Latest?Limit={4}&Fields=CommunityRating,Studios,PremiereDate,Genres,DateCreated&ParentId={5}&api_key={6}&GroupItems=false".format(
self.ssl,
self.host,
self.port,
Expand Down
22 changes: 11 additions & 11 deletions custom_components/emby_upcoming_media/manifest.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"domain": "emby_upcoming_media",
"name": "Emby Latest Media",
"documentation": "https://github.com/gcorgnet/sensor.emby_upcoming_media",
"dependencies": [],
"codeowners": [
"@gcorgnet"
],
"requirements": ["python-dateutil"],
"version": "0.3.5"
}
{
"domain": "emby_upcoming_media",
"name": "Emby Latest Media",
"documentation": "https://github.com/gcorgnet/sensor.emby_upcoming_media",
"dependencies": [],
"codeowners": [
"@gcorgnet"
],
"requirements": ["python-dateutil"],
"version": "0.3.5"
}
28 changes: 24 additions & 4 deletions custom_components/emby_upcoming_media/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from datetime import date, datetime
from datetime import timedelta
import voluptuous as vol
from itertools import groupby
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.components import sensor
Expand All @@ -30,6 +31,8 @@
DOMAIN_DATA = f"{DOMAIN}_data"
ATTRIBUTION = "Data is provided by Emby."

DICT_LIBRARY_TYPES = {"tvshows": "TV Shows", "movies": "Movies"}

# Configuration
CONF_SENSOR = "sensor"
CONF_ENABLED = "enabled"
Expand All @@ -38,9 +41,12 @@
CONF_MAX = "max"
CONF_USER_ID = "user_id"
CONF_USE_BACKDROP = "use_backdrop"
CONF_GROUP_LIBRARIES = "group_libraries"

CATEGORY_NAME = "CategoryName"
CATEGORY_ID = "CategoryId"
CATEGORY_TYPE = "CollectionType"


SCAN_INTERVAL_SECONDS = 3600 # Scan once per hour

Expand All @@ -59,7 +65,8 @@
vol.Optional(CONF_SSL, default=False): cv.boolean,
vol.Optional(CONF_INCLUDE, default=[]): vol.All(cv.ensure_list),
vol.Optional(CONF_MAX, default=5): cv.Number,
vol.Optional(CONF_USE_BACKDROP, default=False): cv.boolean
vol.Optional(CONF_USE_BACKDROP, default=False): cv.boolean,
vol.Optional(CONF_GROUP_LIBRARIES, default=False): cv.boolean
}
)

Expand All @@ -83,13 +90,19 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
hass.data[DOMAIN_DATA]["client"] = client

categories = client.get_view_categories()

categories = filter(lambda el: 'CollectionType' in el.keys() and el["CollectionType"] in DICT_LIBRARY_TYPES.keys(), categories) #just include supported library types (movie/tv)

if include != []:
categories = filter(lambda el: el["Name"] in include, categories)

if config.get(CONF_GROUP_LIBRARIES) == True:
l=[list(y) for x,y in groupby(sorted(list(categories),key=lambda x: (x['CollectionType'])),lambda x: (x['CollectionType']))]
categories = [{k:(v if k!='Id' else list(set([x['Id'] for x in i]))) for k,v in i[0].items()} for i in l]

mapped = map(
lambda cat: EmbyUpcomingMediaSensor(
hass, {**config, CATEGORY_NAME: cat["Name"], CATEGORY_ID: cat["Id"]}
hass, {**config, CATEGORY_NAME: cat["Name"], CATEGORY_ID: cat["Id"], CATEGORY_TYPE: DICT_LIBRARY_TYPES[cat["CollectionType"]]}
),
categories,
)
Expand All @@ -106,7 +119,7 @@ def __init__(self, hass, conf):
self._state = None
self.data = []
self.use_backdrop = conf.get(CONF_USE_BACKDROP)
self.category_name = conf.get(CATEGORY_NAME)
self.category_name = (conf.get(CATEGORY_TYPE) if conf.get(CONF_GROUP_LIBRARIES) == True else conf.get(CATEGORY_NAME))
self.category_id = conf.get(CATEGORY_ID)
self.friendly_name = "Emby Latest Media " + self.category_name
self.entity_id = sensor.ENTITY_ID_FORMAT.format(
Expand Down Expand Up @@ -278,7 +291,14 @@ def device_state_attributes(self):
return attributes

def update(self):
data = self._client.get_data(self.category_id)
if isinstance(self.category_id, str):
data = self._client.get_data(self.category_id)
else:
data = []
for element in self.category_id:
for res in self._client.get_data(element):
data.append(res)
data.sort(key=lambda item:item['DateCreated'], reverse=True) #as we added all libraries we now resort to get the newest at top

if data is not None:
self._state = "Online"
Expand Down
3 changes: 2 additions & 1 deletion info.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ This component does not require, nor conflict with, the default [Emby](https://w
| ssl | false | no | Whether or not to use SSL for Emby.
| max | 5 | no | Max number of items in sensor.
| use_backdrop | false | no | Defines whether to use the Backdrop Image, instead of the poster. (Great for using with the `fanart` display mode)
| include| | no | The names or the Emby Libraries you want to include. If not specified, all libraries will be shown and this component will create one sensor per Library
| include| | no | The names of the <strong>Emby Libraries</strong> you want to include. If not specified, all libraries will be shown and this component will create one sensor per Library. This is language specific.
| group_libraries| false| no | This option generates only two sensors (emby_latest_movies / emby_latest_tv_shows), grouping all your movies and tv into seperate sensors despite library setup in Emby. </br>This is useful for when Emby has many libraries but you only want one sensor in Home Assistant

0 comments on commit 6c1455e

Please sign in to comment.