jellyfin-kodi/resources/lib/downloadutils.py

416 lines
14 KiB
Python
Raw Normal View History

2015-12-24 20:07:00 +00:00
# -*- coding: utf-8 -*-
##################################################################################################
import json
import requests
import logging
import xbmc
import xbmcgui
import clientinfo
2016-09-27 02:50:58 +00:00
import connect.connectionmanager as connectionmanager
from utils import window, settings, language as lang
2015-12-24 20:07:00 +00:00
##################################################################################################
# Disable requests logging
2016-06-18 03:03:28 +00:00
from requests.packages.urllib3.exceptions import InsecureRequestWarning, InsecurePlatformWarning
2015-12-24 20:07:00 +00:00
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
2016-06-18 03:03:28 +00:00
requests.packages.urllib3.disable_warnings(InsecurePlatformWarning)
log = logging.getLogger("EMBY."+__name__)
2015-12-24 20:07:00 +00:00
##################################################################################################
2016-09-27 02:50:58 +00:00
class DownloadUtils(object):
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
# Borg - multiple instances, shared state
_shared_state = {}
# Requests session
2016-09-27 02:50:58 +00:00
session = {}
session_requests = None
servers = {} # Multi server setup
default_timeout = 30
2015-12-24 20:07:00 +00:00
def __init__(self):
2016-06-18 03:03:28 +00:00
self.__dict__ = self._shared_state
2016-09-27 02:50:58 +00:00
self.client_info = clientinfo.ClientInfo()
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def _set_session(self, **kwargs):
2015-12-24 20:07:00 +00:00
# Reserved for userclient only
2016-09-27 02:50:58 +00:00
info = {}
for key in kwargs:
info[key] = kwargs[key]
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
self.session.update(info)
log.info("Set info for server %s: %s", self.session['ServerId'], self.session)
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def add_server(self, server, ssl):
2015-12-24 20:07:00 +00:00
# Reserved for userclient only
2016-09-27 02:50:58 +00:00
server_id = server['Id']
info = {
'UserId': server['UserId'],
'Server': connectionmanager.getServerAddress(server, server['LastConnectionMode']),
'Token': server['AccessToken'],
'SSL': ssl
}
for s in self.servers:
if s == server_id:
s.update(info)
# Set window prop
self._set_server_properties(server_id, server['Name'], json.dumps(info))
log.info("updating %s to available servers: %s", server_id, self.servers)
break
else:
self.servers[server_id] = info
self._set_server_properties(server_id, server['Name'], json.dumps(info))
log.info("adding %s to available servers: %s", server_id, self.servers)
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def reset_server(self, server_id):
2015-12-24 20:07:00 +00:00
# Reserved for userclient only
2016-09-27 02:50:58 +00:00
for server in self.servers:
if server['ServerId'] == server_id:
self.servers.remove(s)
window('emby_server%s.json' % server_id, clear=True)
window('emby_server%s.name' % server_id, clear=True)
log.info("removing %s from available servers", server_id)
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
@staticmethod
def _set_server_properties(server_id, name, info):
window('emby_server%s.json' % server_id, value=info)
window('emby_server%s.name' % server_id, value=name)
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def post_capabilities(self, device_id):
2015-12-24 20:07:00 +00:00
# Post settings to session
url = "{server}/emby/Sessions/Capabilities/Full?format=json"
data = {
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
'PlayableMediaTypes': "Audio,Video",
'SupportsMediaControl': True,
'SupportedCommands': (
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
"MoveUp,MoveDown,MoveLeft,MoveRight,Select,"
"Back,ToggleContextMenu,ToggleFullscreen,ToggleOsdMenu,"
"GoHome,PageUp,NextLetter,GoToSearch,"
"GoToSettings,PageDown,PreviousLetter,TakeScreenshot,"
"VolumeUp,VolumeDown,ToggleMute,SendString,DisplayMessage,"
"SetAudioStreamIndex,SetSubtitleStreamIndex,"
"Mute,Unmute,SetVolume,"
"Play,Playstate,PlayNext"
)
}
2016-09-27 02:50:58 +00:00
log.debug("capabilities URL: %s" % url)
log.debug("Postdata: %s" % data)
2015-12-24 20:07:00 +00:00
2016-04-04 21:21:05 +00:00
self.downloadUrl(url, postBody=data, action_type="POST")
2016-09-27 02:50:58 +00:00
log.debug("Posted capabilities to %s" % self.session['Server'])
2015-12-24 20:07:00 +00:00
# Attempt at getting sessionId
2016-09-27 02:50:58 +00:00
url = "{server}/emby/Sessions?DeviceId=%s&format=json" % device_id
2015-12-24 20:07:00 +00:00
result = self.downloadUrl(url)
try:
sessionId = result[0]['Id']
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
except (KeyError, TypeError):
log.info("Failed to retrieve sessionId.")
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
else:
log.debug("Session: %s" % result)
log.info("SessionId: %s" % sessionId)
2016-06-18 03:03:28 +00:00
window('emby_sessionId', value=sessionId)
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
# Post any permanent additional users
2016-06-18 03:03:28 +00:00
additionalUsers = settings('additionalUsers')
2015-12-24 20:07:00 +00:00
if additionalUsers:
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
additionalUsers = additionalUsers.split(',')
log.info("List of permanent users added to the session: %s" % additionalUsers)
2015-12-24 20:07:00 +00:00
# Get the user list from server to get the userId
url = "{server}/emby/Users?format=json"
result = self.downloadUrl(url)
for additional in additionalUsers:
addUser = additional.decode('utf-8').lower()
# Compare to server users to list of permanent additional users
for user in result:
username = user['Name'].lower()
if username in addUser:
userId = user['Id']
url = (
"{server}/emby/Sessions/%s/Users/%s?format=json"
% (sessionId, userId)
)
2016-04-04 21:21:05 +00:00
self.downloadUrl(url, postBody={}, action_type="POST")
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def start_session(self):
2015-12-24 20:07:00 +00:00
# User is identified from this point
# Attach authenticated header to the session
# Start session
2016-09-27 02:50:58 +00:00
s = requests.Session()
s.headers = self.get_header()
s.verify = self.session['SSL']
2015-12-24 20:07:00 +00:00
# Retry connections to the server
2016-09-27 02:50:58 +00:00
s.mount("http://", requests.adapters.HTTPAdapter(max_retries=1))
s.mount("https://", requests.adapters.HTTPAdapter(max_retries=1))
self.session_requests = s
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
log.info("Requests session started on: %s" % self.session['Server'])
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def stop_session(self):
2015-12-24 20:07:00 +00:00
try:
2016-09-27 02:50:58 +00:00
self.session_requests.close()
except Exception as error:
log.error(error)
log.warn("requests session could not be terminated")
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def get_header(self, server_id=None, authenticate=True):
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
device_name = self.client_info.get_device_name().encode('utf-8')
device_id = self.client_info.get_device_id()
version = self.client_info.get_version()
2015-12-24 20:07:00 +00:00
if authenticate:
2016-09-27 02:50:58 +00:00
user = self.get_user(server_id)
user_id = user['UserId']
token = user['Token']
2015-12-24 20:07:00 +00:00
auth = (
'MediaBrowser UserId="%s", Client="Kodi", Device="%s", DeviceId="%s", Version="%s"'
2016-09-27 02:50:58 +00:00
% (user_id, device_name, device_id, version)
)
2015-12-24 20:07:00 +00:00
header = {
'Authorization': auth,
2016-09-27 02:50:58 +00:00
'X-MediaBrowser-Token': token
2016-03-31 03:37:37 +00:00
}
2015-12-24 20:07:00 +00:00
else:
auth = (
'MediaBrowser Client="Kodi", Device="%s", DeviceId="%s", Version="%s"'
2016-09-27 02:50:58 +00:00
% (device_name, device_id, version)
)
header = {'Authorization': auth}
2016-09-06 22:43:15 +00:00
2016-09-27 02:50:58 +00:00
header.update({
'Content-type': 'application/json',
'Accept-encoding': 'gzip',
'Accept-Charset': 'UTF-8,*',
})
return header
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
def get_user(self, server_id=None):
2016-03-31 03:37:37 +00:00
2016-09-27 02:50:58 +00:00
if server_id is None:
return {
'UserId': self.session['UserId'],
'Token': self.session['Token']
}
else:
server = self.servers[server_id]
return {
'UserId': server['UserId'],
'Token': server['Token']
}
2015-12-24 20:07:00 +00:00
2016-06-18 03:03:28 +00:00
def downloadUrl(self, url, postBody=None, action_type="GET", parameters=None,
2016-09-27 02:50:58 +00:00
authenticate=True, server_id=None):
2016-03-31 03:37:37 +00:00
log.debug("===== ENTER downloadUrl =====")
session = requests
2016-07-16 00:02:30 +00:00
kwargs = {}
2015-12-24 20:07:00 +00:00
default_link = ""
2016-09-27 02:50:58 +00:00
try: # Ensure server info is loaded
if not self._ensure_server(server_id):
raise AttributeError("unable to load server information: %s" % server_id)
if server_id is None:
if self.session_requests is not None:
session = self.session_requests
else:
kwargs.update({
'verify': self.session['SSL'],
'headers': self.get_header(authenticate=authenticate)
})
# Replace for the real values
url = url.replace("{server}", self.session['Server'])
url = url.replace("{UserId}", self.session['UserId'])
else:
2016-09-27 02:50:58 +00:00
server = self.servers[server_id]
2016-07-16 00:02:30 +00:00
kwargs.update({
2016-09-27 02:50:58 +00:00
'verify': server['SSL'],
'headers': self.get_header(server_id, authenticate)
2016-07-16 00:02:30 +00:00
})
2016-09-27 02:50:58 +00:00
# Replace for the real values
url = url.replace("{server}", server['Server'])
url = url.replace("{UserId}", server['UserId'])
2016-07-16 00:02:30 +00:00
##### PREPARE REQUEST #####
kwargs.update({
'url': url,
'timeout': self.default_timeout,
2016-07-16 00:02:30 +00:00
'json': postBody,
'params': parameters
})
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
##### THE RESPONSE #####
log.debug(kwargs)
r = self._requests(action_type, session, **kwargs)
2015-12-24 20:07:00 +00:00
if r.status_code == 204:
# No body in the response
log.debug("====== 204 Success ======")
# Read response to release connection
r.content
2015-12-24 20:07:00 +00:00
elif r.status_code == requests.codes.ok:
2016-03-31 03:37:37 +00:00
try:
# UNICODE - JSON object
2015-12-24 20:07:00 +00:00
r = r.json()
log.debug("====== 200 Success ======")
log.debug("Response: %s" % r)
2015-12-24 20:07:00 +00:00
return r
except:
if r.headers.get('content-type') != "text/html":
log.info("Unable to convert the response for: %s" % url)
else: # Bad status code
log.error("=== Bad status response: %s ===" % r.status_code)
2015-12-24 20:07:00 +00:00
r.raise_for_status()
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
##### EXCEPTIONS #####
except requests.exceptions.ConnectionError as e:
# Make the addon aware of status
2016-06-18 03:03:28 +00:00
if window('emby_online') != "false":
log.error("Server unreachable at: %s" % url)
2016-06-18 03:03:28 +00:00
window('emby_online', value="false")
2015-12-24 20:07:00 +00:00
except requests.exceptions.ConnectTimeout as e:
log.error("Server timeout at: %s" % url)
2015-12-24 20:07:00 +00:00
except requests.exceptions.HTTPError as e:
if r.status_code == 401:
# Unauthorized
2016-06-18 03:03:28 +00:00
status = window('emby_serverStatus')
2015-12-24 20:07:00 +00:00
if 'X-Application-Error-Code' in r.headers:
# Emby server errors
if r.headers['X-Application-Error-Code'] == "ParentalControl":
# Parental control - access restricted
if status != "restricted":
xbmcgui.Dialog().notification(
heading=lang(29999),
message="Access restricted.",
icon=xbmcgui.NOTIFICATION_ERROR,
time=5000)
2016-06-18 03:03:28 +00:00
window('emby_serverStatus', value="restricted")
raise Warning('restricted')
2016-03-31 03:37:37 +00:00
2015-12-24 20:07:00 +00:00
elif r.headers['X-Application-Error-Code'] == "UnauthorizedAccessException":
# User tried to do something his emby account doesn't allow
pass
elif status not in ("401", "Auth"):
# Tell userclient token has been revoked.
2016-06-18 03:03:28 +00:00
window('emby_serverStatus', value="401")
log.error("HTTP Error: %s" % e)
2015-12-24 20:07:00 +00:00
xbmcgui.Dialog().notification(
heading="Error connecting",
message="Unauthorized.",
icon=xbmcgui.NOTIFICATION_ERROR)
raise Warning('401')
2015-12-24 20:07:00 +00:00
elif r.status_code in (301, 302):
# Redirects
pass
elif r.status_code == 400:
# Bad requests
pass
except requests.exceptions.SSLError as e:
log.error("Invalid SSL certificate for: %s" % url)
2015-12-24 20:07:00 +00:00
except requests.exceptions.RequestException as e:
log.error("Unknown error connecting to: %s" % url)
2015-12-24 20:07:00 +00:00
2016-09-27 02:50:58 +00:00
except AttributeError as error:
log.error(error)
return default_link
2016-09-27 02:50:58 +00:00
def _ensure_server(self, server_id=None):
if server_id is None and self.session_requests is None:
server = self._get_session_info()
self.session.update(server)
elif server_id and server_id not in self.servers:
server = self._get_session_info(server_id)
if server is None:
return False
self.servers[server_id] = server
return True
@classmethod
def _get_session_info(cls, server_id=None):
info = {}
if server_id is None: # Main server
user_id = window('emby_currUser')
info.update({
'UserId': user_id,
'Server': window('emby_server%s' % user_id),
'Token': window('emby_accessToken%s' % user_id)
})
verifyssl = False
# If user enables ssl verification
if settings('sslverify') == "true":
verifyssl = True
if settings('sslcert') != "None":
verifyssl = settings('sslcert')
info['SSL'] = verifyssl
else: # Other connect servers
server = window('emby_server%s.json' % server_id)
if server:
info.update(json.loads(server))
return info
@classmethod
def _requests(cls, action, session=requests, **kwargs):
if action == "GET":
2016-09-27 02:50:58 +00:00
response = session.get(**kwargs)
elif action == "POST":
2016-09-27 02:50:58 +00:00
response = session.post(**kwargs)
elif action == "DELETE":
2016-09-27 02:50:58 +00:00
response = session.delete(**kwargs)
2016-09-27 02:50:58 +00:00
return response