mirror of
https://github.com/rembo10/headphones.git
synced 2026-07-20 16:03:59 +01:00
update Beets
This commit is contained in:
+62
-55
@@ -9,9 +9,10 @@
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from urllib.parse import parse_qs, urlencode, urljoin, urlsplit, urlunsplit
|
||||
|
||||
import requests
|
||||
|
||||
from urllib.parse import urlencode, urljoin, parse_qs, urlsplit, urlunsplit
|
||||
from beets import config
|
||||
from beets.plugins import BeetsPlugin
|
||||
|
||||
@@ -32,24 +33,20 @@ def api_url(host, port, endpoint):
|
||||
"""
|
||||
# check if http or https is defined as host and create hostname
|
||||
hostname_list = [host]
|
||||
if host.startswith('http://') or host.startswith('https://'):
|
||||
hostname = ''.join(hostname_list)
|
||||
if host.startswith("http://") or host.startswith("https://"):
|
||||
hostname = "".join(hostname_list)
|
||||
else:
|
||||
hostname_list.insert(0, 'http://')
|
||||
hostname = ''.join(hostname_list)
|
||||
hostname_list.insert(0, "http://")
|
||||
hostname = "".join(hostname_list)
|
||||
|
||||
joined = urljoin(
|
||||
'{hostname}:{port}'.format(
|
||||
hostname=hostname,
|
||||
port=port
|
||||
),
|
||||
endpoint
|
||||
"{hostname}:{port}".format(hostname=hostname, port=port), endpoint
|
||||
)
|
||||
|
||||
scheme, netloc, path, query_string, fragment = urlsplit(joined)
|
||||
query_params = parse_qs(query_string)
|
||||
|
||||
query_params['format'] = ['json']
|
||||
query_params["format"] = ["json"]
|
||||
new_query_string = urlencode(query_params, doseq=True)
|
||||
|
||||
return urlunsplit((scheme, netloc, path, new_query_string, fragment))
|
||||
@@ -66,9 +63,9 @@ def password_data(username, password):
|
||||
:rtype: dict
|
||||
"""
|
||||
return {
|
||||
'username': username,
|
||||
'password': hashlib.sha1(password.encode('utf-8')).hexdigest(),
|
||||
'passwordMd5': hashlib.md5(password.encode('utf-8')).hexdigest()
|
||||
"username": username,
|
||||
"password": hashlib.sha1(password.encode("utf-8")).hexdigest(),
|
||||
"passwordMd5": hashlib.md5(password.encode("utf-8")).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
@@ -92,10 +89,10 @@ def create_headers(user_id, token=None):
|
||||
'Version="0.0.0"'
|
||||
).format(user_id=user_id)
|
||||
|
||||
headers['x-emby-authorization'] = authorization
|
||||
headers["x-emby-authorization"] = authorization
|
||||
|
||||
if token:
|
||||
headers['x-mediabrowser-token'] = token
|
||||
headers["x-mediabrowser-token"] = token
|
||||
|
||||
return headers
|
||||
|
||||
@@ -114,10 +111,15 @@ def get_token(host, port, headers, auth_data):
|
||||
:returns: Access Token
|
||||
:rtype: str
|
||||
"""
|
||||
url = api_url(host, port, '/Users/AuthenticateByName')
|
||||
r = requests.post(url, headers=headers, data=auth_data)
|
||||
url = api_url(host, port, "/Users/AuthenticateByName")
|
||||
r = requests.post(
|
||||
url,
|
||||
headers=headers,
|
||||
data=auth_data,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
return r.json().get('AccessToken')
|
||||
return r.json().get("AccessToken")
|
||||
|
||||
|
||||
def get_user(host, port, username):
|
||||
@@ -132,9 +134,9 @@ def get_user(host, port, username):
|
||||
:returns: Matched Users
|
||||
:rtype: list
|
||||
"""
|
||||
url = api_url(host, port, '/Users/Public')
|
||||
r = requests.get(url)
|
||||
user = [i for i in r.json() if i['Name'] == username]
|
||||
url = api_url(host, port, "/Users/Public")
|
||||
r = requests.get(url, timeout=10)
|
||||
user = [i for i in r.json() if i["Name"] == username]
|
||||
|
||||
return user
|
||||
|
||||
@@ -144,62 +146,67 @@ class EmbyUpdate(BeetsPlugin):
|
||||
super().__init__()
|
||||
|
||||
# Adding defaults.
|
||||
config['emby'].add({
|
||||
'host': 'http://localhost',
|
||||
'port': 8096,
|
||||
'apikey': None,
|
||||
'password': None,
|
||||
})
|
||||
config["emby"].add(
|
||||
{
|
||||
"host": "http://localhost",
|
||||
"port": 8096,
|
||||
"apikey": None,
|
||||
"password": None,
|
||||
}
|
||||
)
|
||||
|
||||
self.register_listener('database_change', self.listen_for_db_change)
|
||||
self.register_listener("database_change", self.listen_for_db_change)
|
||||
|
||||
def listen_for_db_change(self, lib, model):
|
||||
"""Listens for beets db change and register the update for the end.
|
||||
"""
|
||||
self.register_listener('cli_exit', self.update)
|
||||
"""Listens for beets db change and register the update for the end."""
|
||||
self.register_listener("cli_exit", self.update)
|
||||
|
||||
def update(self, lib):
|
||||
"""When the client exists try to send refresh request to Emby.
|
||||
"""
|
||||
self._log.info('Updating Emby library...')
|
||||
"""When the client exists try to send refresh request to Emby."""
|
||||
self._log.info("Updating Emby library...")
|
||||
|
||||
host = config['emby']['host'].get()
|
||||
port = config['emby']['port'].get()
|
||||
username = config['emby']['username'].get()
|
||||
password = config['emby']['password'].get()
|
||||
token = config['emby']['apikey'].get()
|
||||
host = config["emby"]["host"].get()
|
||||
port = config["emby"]["port"].get()
|
||||
username = config["emby"]["username"].get()
|
||||
password = config["emby"]["password"].get()
|
||||
userid = config["emby"]["userid"].get()
|
||||
token = config["emby"]["apikey"].get()
|
||||
|
||||
# Check if at least a apikey or password is given.
|
||||
if not any([password, token]):
|
||||
self._log.warning('Provide at least Emby password or apikey.')
|
||||
self._log.warning("Provide at least Emby password or apikey.")
|
||||
return
|
||||
|
||||
# Get user information from the Emby API.
|
||||
user = get_user(host, port, username)
|
||||
if not user:
|
||||
self._log.warning(f'User {username} could not be found.')
|
||||
return
|
||||
if not userid:
|
||||
# Get user information from the Emby API.
|
||||
user = get_user(host, port, username)
|
||||
if not user:
|
||||
self._log.warning(f"User {username} could not be found.")
|
||||
return
|
||||
userid = user[0]["Id"]
|
||||
|
||||
if not token:
|
||||
# Create Authentication data and headers.
|
||||
auth_data = password_data(username, password)
|
||||
headers = create_headers(user[0]['Id'])
|
||||
headers = create_headers(userid)
|
||||
|
||||
# Get authentication token.
|
||||
token = get_token(host, port, headers, auth_data)
|
||||
if not token:
|
||||
self._log.warning(
|
||||
'Could not get token for user {0}', username
|
||||
)
|
||||
self._log.warning("Could not get token for user {0}", username)
|
||||
return
|
||||
|
||||
# Recreate headers with a token.
|
||||
headers = create_headers(user[0]['Id'], token=token)
|
||||
headers = create_headers(userid, token=token)
|
||||
|
||||
# Trigger the Update.
|
||||
url = api_url(host, port, '/Library/Refresh')
|
||||
r = requests.post(url, headers=headers)
|
||||
url = api_url(host, port, "/Library/Refresh")
|
||||
r = requests.post(
|
||||
url,
|
||||
headers=headers,
|
||||
timeout=10,
|
||||
)
|
||||
if r.status_code != 204:
|
||||
self._log.warning('Update could not be triggered')
|
||||
self._log.warning("Update could not be triggered")
|
||||
else:
|
||||
self._log.info('Update triggered.')
|
||||
self._log.info("Update triggered.")
|
||||
|
||||
Reference in New Issue
Block a user