| 1 |
"""Updates the Emby Library whenever the beets library is changed. |
| 2 |
|
| 3 |
emby: |
| 4 |
host: localhost |
| 5 |
port: 8096 |
| 6 |
username: user |
| 7 |
apikey: apikey |
| 8 |
password: password |
| 9 |
""" |
| 10 |
|
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
import hashlib |
| 14 |
from typing import TYPE_CHECKING |
| 15 |
from urllib.parse import parse_qs, urlencode, urljoin, urlsplit, urlunsplit |
| 16 |
|
| 17 |
import requests |
| 18 |
|
| 19 |
from beets.plugins import BeetsPlugin |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
from beets.library import LibModel, Library |
| 23 |
|
| 24 |
from ._typing import JSONDict |
| 25 |
|
| 26 |
|
| 27 |
def api_url(host: str, port: int, endpoint: str) -> str: |
| 28 |
"""Returns a joined url. |
| 29 |
|
| 30 |
Takes host, port and endpoint and generates a valid emby API url. |
| 31 |
|
| 32 |
:param host: Hostname of the emby server |
| 33 |
:param port: Portnumber of the emby server |
| 34 |
:param endpoint: API endpoint |
| 35 |
:type host: str |
| 36 |
:type port: int |
| 37 |
:type endpoint: str |
| 38 |
:returns: Full API url |
| 39 |
:rtype: str |
| 40 |
""" |
| 41 |
# check if http or https is defined as host and create hostname |
| 42 |
hostname_list = [host] |
| 43 |
if host.startswith(("http://", "https://")): |
| 44 |
hostname = "".join(hostname_list) |
| 45 |
else: |
| 46 |
hostname_list.insert(0, "http://") |
| 47 |
hostname = "".join(hostname_list) |
| 48 |
|
| 49 |
joined = urljoin(f"{hostname}:{port}", endpoint) |
| 50 |
|
| 51 |
scheme, netloc, path, query_string, fragment = urlsplit(joined) |
| 52 |
query_params = parse_qs(query_string) |
| 53 |
|
| 54 |
query_params["format"] = ["json"] |
| 55 |
new_query_string = urlencode(query_params, doseq=True) |
| 56 |
|
| 57 |
return urlunsplit((scheme, netloc, path, new_query_string, fragment)) |
| 58 |
|
| 59 |
|
| 60 |
def password_data(username: str, password: str) -> JSONDict: |
| 61 |
"""Returns a dict with username and its encoded password. |
| 62 |
|
| 63 |
:param username: Emby username |
| 64 |
:param password: Emby password |
| 65 |
:type username: str |
| 66 |
:type password: str |
| 67 |
:returns: Dictionary with username and encoded password |
| 68 |
:rtype: dict |
| 69 |
""" |
| 70 |
return { |
| 71 |
"username": username, |
| 72 |
"password": hashlib.sha1(password.encode("utf-8")).hexdigest(), |
| 73 |
"passwordMd5": hashlib.md5(password.encode("utf-8")).hexdigest(), |
| 74 |
} |
| 75 |
|
| 76 |
|
| 77 |
def create_headers(user_id: str, token: str | None = None) -> dict[str, str]: |
| 78 |
"""Return header dict that is needed to talk to the Emby API. |
| 79 |
|
| 80 |
:param user_id: Emby user ID |
| 81 |
:param token: Authentication token for Emby |
| 82 |
:type user_id: str |
| 83 |
:type token: str |
| 84 |
:returns: Headers for requests |
| 85 |
:rtype: dict |
| 86 |
""" |
| 87 |
headers = {} |
| 88 |
|
| 89 |
authorization = ( |
| 90 |
f'MediaBrowser UserId="{user_id}", ' |
| 91 |
'Client="other", ' |
| 92 |
'Device="beets", ' |
| 93 |
'DeviceId="beets", ' |
| 94 |
'Version="0.0.0"' |
| 95 |
) |
| 96 |
|
| 97 |
headers["x-emby-authorization"] = authorization |
| 98 |
|
| 99 |
if token: |
| 100 |
headers["x-mediabrowser-token"] = token |
| 101 |
|
| 102 |
return headers |
| 103 |
|
| 104 |
|
| 105 |
def get_token( |
| 106 |
host: str, port: int, headers: dict[str, str], auth_data: JSONDict |
| 107 |
) -> str | None: |
| 108 |
"""Return token for a user. |
| 109 |
|
| 110 |
:param host: Emby host |
| 111 |
:param port: Emby port |
| 112 |
:param headers: Headers for requests |
| 113 |
:param auth_data: Username and encoded password for authentication |
| 114 |
:type host: str |
| 115 |
:type port: int |
| 116 |
:type headers: dict |
| 117 |
:type auth_data: dict |
| 118 |
:returns: Access Token |
| 119 |
:rtype: str |
| 120 |
""" |
| 121 |
url = api_url(host, port, "/Users/AuthenticateByName") |
| 122 |
r = requests.post(url, headers=headers, data=auth_data, timeout=10) |
| 123 |
|
| 124 |
return r.json().get("AccessToken") |
| 125 |
|
| 126 |
|
| 127 |
def get_user(host: str, port: int, username: str) -> list[JSONDict]: |
| 128 |
"""Return user dict from server or None if there is no user. |
| 129 |
|
| 130 |
:param host: Emby host |
| 131 |
:param port: Emby port |
| 132 |
:username: Username |
| 133 |
:type host: str |
| 134 |
:type port: int |
| 135 |
:type username: str |
| 136 |
:returns: Matched Users |
| 137 |
:rtype: list |
| 138 |
""" |
| 139 |
url = api_url(host, port, "/Users/Public") |
| 140 |
r = requests.get(url, timeout=10) |
| 141 |
return [i for i in r.json() if i["Name"] == username] |
| 142 |
|
| 143 |
|
| 144 |
class EmbyUpdate(BeetsPlugin): |
| 145 |
def __init__(self) -> None: |
| 146 |
super().__init__("emby") |
| 147 |
|
| 148 |
# Adding defaults. |
| 149 |
self.config.add( |
| 150 |
{ |
| 151 |
"host": "http://localhost", |
| 152 |
"port": 8096, |
| 153 |
"username": None, |
| 154 |
"password": None, |
| 155 |
"userid": None, |
| 156 |
"apikey": None, |
| 157 |
} |
| 158 |
) |
| 159 |
self.config["username"].redact = True |
| 160 |
self.config["password"].redact = True |
| 161 |
self.config["userid"].redact = True |
| 162 |
self.config["apikey"].redact = True |
| 163 |
|
| 164 |
self.register_listener("database_change", self.listen_for_db_change) |
| 165 |
|
| 166 |
def listen_for_db_change(self, lib: Library, model: LibModel) -> None: |
| 167 |
"""Listens for beets db change and register the update for the end.""" |
| 168 |
self.register_listener("cli_exit", self.update) |
| 169 |
|
| 170 |
def update(self, lib: Library) -> None: |
| 171 |
"""When the client exists try to send refresh request to Emby.""" |
| 172 |
self._log.info("Updating Emby library...") |
| 173 |
|
| 174 |
host = self.config["host"].get() |
| 175 |
port = self.config["port"].get() |
| 176 |
username = self.config["username"].get() |
| 177 |
password = self.config["password"].get() |
| 178 |
userid = self.config["userid"].get() |
| 179 |
token = self.config["apikey"].get() |
| 180 |
|
| 181 |
# Check if at least a apikey or password is given. |
| 182 |
if not any([password, token]): |
| 183 |
self._log.warning("Provide at least Emby password or apikey.") |
| 184 |
return |
| 185 |
|
| 186 |
if not userid: |
| 187 |
# Get user information from the Emby API. |
| 188 |
user = get_user(host, port, username) |
| 189 |
if not user: |
| 190 |
self._log.warning("User {} could not be found.", username) |
| 191 |
return |
| 192 |
userid = user[0]["Id"] |
| 193 |
|
| 194 |
if not token: |
| 195 |
# Create Authentication data and headers. |
| 196 |
auth_data = password_data(username, password) |
| 197 |
headers = create_headers(userid) |
| 198 |
|
| 199 |
# Get authentication token. |
| 200 |
token = get_token(host, port, headers, auth_data) |
| 201 |
if not token: |
| 202 |
self._log.warning("Could not get token for user {}", username) |
| 203 |
return |
| 204 |
|
| 205 |
# Recreate headers with a token. |
| 206 |
headers = create_headers(userid, token=token) |
| 207 |
|
| 208 |
# Trigger the Update. |
| 209 |
url = api_url(host, port, "/Library/Refresh") |
| 210 |
r = requests.post(url, headers=headers, timeout=10) |
| 211 |
if r.status_code != 204: |
| 212 |
self._log.warning("Update could not be triggered") |
| 213 |
else: |
| 214 |
self._log.info("Update triggered.") |