| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
import json |
| 6 |
import logging |
| 7 |
import time |
| 8 |
import urllib |
| 9 |
from .api import jellyfin_url |
| 10 |
|
| 11 |
import requests |
| 12 |
|
| 13 |
from .exceptions import HTTPException |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
LOG = logging.getLogger('Jellyfin.' + __name__) |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
class HTTP(object): |
| 23 |
|
| 24 |
session = None |
| 25 |
keep_alive = False |
| 26 |
|
| 27 |
def __init__(self, client): |
| 28 |
|
| 29 |
self.client = client |
| 30 |
self.config = client.config |
| 31 |
|
| 32 |
def start_session(self): |
| 33 |
self.session = requests.Session() |
| 34 |
|
| 35 |
max_retries = self.config.data['http.max_retries'] |
| 36 |
|
| 37 |
|
| 38 |
if 'auth.tls_client_cert' in self.client.config.data and 'auth.tls_client_key' in self.client.config.data: |
| 39 |
self.session.cert = (self.client.config.data['auth.tls_client_cert'], |
| 40 |
self.client.config.data['auth.tls_client_key']) |
| 41 |
|
| 42 |
if self.client.config.data['auth.tls_server_ca']: |
| 43 |
self.session.verify = self.client.config.data['auth.tls_server_ca'] |
| 44 |
|
| 45 |
self.session.mount("http://", requests.adapters.HTTPAdapter(max_retries=max_retries)) |
| 46 |
self.session.mount("https://", requests.adapters.HTTPAdapter(max_retries=max_retries)) |
| 47 |
|
| 48 |
def stop_session(self): |
| 49 |
|
| 50 |
if self.session is None: |
| 51 |
return |
| 52 |
|
| 53 |
try: |
| 54 |
LOG.info("--<[ session/%s ]", id(self.session)) |
| 55 |
self.session.close() |
| 56 |
except Exception as error: |
| 57 |
LOG.warning("The requests session could not be terminated: %s", error) |
| 58 |
|
| 59 |
def _replace_user_info(self, string): |
| 60 |
|
| 61 |
if '{server}' in string: |
| 62 |
if self.config.data.get('auth.server', None): |
| 63 |
string = string.replace("{server}", self.config.data['auth.server']) |
| 64 |
else: |
| 65 |
LOG.debug("Server address not set") |
| 66 |
raise ValueError("Server is not set.") |
| 67 |
|
| 68 |
if '{UserId}'in string: |
| 69 |
if self.config.data.get('auth.user_id', None): |
| 70 |
string = string.replace("{UserId}", self.config.data['auth.user_id']) |
| 71 |
else: |
| 72 |
LOG.debug("UserId is not set.") |
| 73 |
raise ValueError("UserId is not set. If using API_KEY, some endpoint require a user context.") |
| 74 |
|
| 75 |
if '{DeviceId}'in string: |
| 76 |
if self.config.data.get('app.device_id', None): |
| 77 |
string = string.replace("{DeviceId}", self.config.data['app.device_id']) |
| 78 |
else: |
| 79 |
LOG.debug("DeviceId is not set.") |
| 80 |
raise ValueError("DeviceId is not set.") |
| 81 |
|
| 82 |
return string |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
cy |
| 95 |
|
| 96 |
|
| 97 |
APIKEY_PARAM = "ApiKey" |
| 98 |
|
| 99 |
def request_url(self, data, include_apikey=True): |
| 100 |
"""Build a URL without issuing it. |
| 101 |
|
| 102 |
``include_apikey=False`` leaves the token out entirely, for callers |
| 103 |
that can authenticate the eventual request themselves -- mpv takes |
| 104 |
``--http-header-fields``, for instance. Prefer it: a token in a URL |
| 105 |
is a token in logs, in ``ps`` output and in any proxy in the path. |
| 106 |
""" |
| 107 |
if not data: |
| 108 |
raise AttributeError("Request cannot be empty") |
| 109 |
|
| 110 |
data = self._request(data) |
| 111 |
|
| 112 |
params = data["params"] |
| 113 |
if include_apikey and self.APIKEY_PARAM not in params: |
| 114 |
params[self.APIKEY_PARAM] = self.config.data.get('auth.token') |
| 115 |
|
| 116 |
encoded_params = urllib.parse.urlencode(data["params"]) |
| 117 |
return "%s?%s" % (data["url"], encoded_params) |
| 118 |
|
| 119 |
def request(self, data, session=None, dest_file=None): |
| 120 |
|
| 121 |
''' Give a chance to retry the connection. Jellyfin sometimes can be slow to answer back |
| 122 |
data dictionary can contain: |
| 123 |
type: GET, POST, etc. |
| 124 |
url: (optional) |
| 125 |
handler: not considered when url is provided (optional) |
| 126 |
params: request parameters (optional) |
| 127 |
json: request body (optional) |
| 128 |
headers: (optional), |
| 129 |
verify: ssl certificate, True (verify using device built-in library) or False |
| 130 |
''' |
| 131 |
if not data: |
| 132 |
raise AttributeError("Request cannot be empty") |
| 133 |
|
| 134 |
data = self._request(data) |
| 135 |
LOG.debug("--->[ http ] %s", json.dumps(data, indent=4)) |
| 136 |
retry = data.pop('retry', 5) |
| 137 |
stream = dest_file is not None |
| 138 |
|
| 139 |
server_id = None |
| 140 |
if 'auth.server-id' in self.config.data: |
| 141 |
server_id = self.config.data['auth.server-id'] |
| 142 |
|
| 143 |
while True: |
| 144 |
|
| 145 |
try: |
| 146 |
r = self._requests(session or self.session or requests, data.pop('type', "GET"), **data, stream=stream) |
| 147 |
if stream: |
| 148 |
for chunk in r.iter_content(chunk_size=8192): |
| 149 |
if chunk: |
| 150 |
dest_file.write(chunk) |
| 151 |
else: |
| 152 |
r.content |
| 153 |
|
| 154 |
if not self.keep_alive and self.session is not None: |
| 155 |
self.stop_session() |
| 156 |
|
| 157 |
r.raise_for_status() |
| 158 |
|
| 159 |
except requests.exceptions.ConnectionError as error: |
| 160 |
if retry: |
| 161 |
|
| 162 |
retry -= 1 |
| 163 |
time.sleep(1) |
| 164 |
|
| 165 |
continue |
| 166 |
|
| 167 |
LOG.error(error) |
| 168 |
if server_id is not None: |
| 169 |
self.client.callback("ServerUnreachable", {'ServerId': server_id}) |
| 170 |
|
| 171 |
raise HTTPException("ServerUnreachable", error) |
| 172 |
|
| 173 |
except requests.exceptions.ReadTimeout as error: |
| 174 |
if retry: |
| 175 |
|
| 176 |
retry -= 1 |
| 177 |
time.sleep(1) |
| 178 |
|
| 179 |
continue |
| 180 |
|
| 181 |
LOG.error(error) |
| 182 |
|
| 183 |
raise HTTPException("ReadTimeout", error) |
| 184 |
|
| 185 |
except requests.exceptions.HTTPError as error: |
| 186 |
LOG.error(error) |
| 187 |
|
| 188 |
if r.status_code == 401: |
| 189 |
|
| 190 |
if 'X-Application-Error-Code' in r.headers: |
| 191 |
if server_id is not None: |
| 192 |
self.client.callback("AccessRestricted", {'ServerId': server_id}) |
| 193 |
|
| 194 |
raise HTTPException("AccessRestricted", error) |
| 195 |
else: |
| 196 |
if server_id is not None: |
| 197 |
self.client.callback("Unauthorized", {'ServerId': server_id}) |
| 198 |
self.client.auth.revoke_token() |
| 199 |
|
| 200 |
raise HTTPException("Unauthorized", error) |
| 201 |
|
| 202 |
elif r.status_code == 500: |
| 203 |
LOG.error("--[ 500 response ] %s", error) |
| 204 |
|
| 205 |
return |
| 206 |
|
| 207 |
elif r.status_code == 502: |
| 208 |
if retry: |
| 209 |
|
| 210 |
retry -= 1 |
| 211 |
time.sleep(1) |
| 212 |
|
| 213 |
continue |
| 214 |
|
| 215 |
raise HTTPException(r.status_code, error) |
| 216 |
|
| 217 |
except requests.exceptions.MissingSchema as error: |
| 218 |
LOG.error("Request missing Schema. " + str(error)) |
| 219 |
raise HTTPException("MissingSchema", {'Id': self.config.data.get('auth.server', "None")}) |
| 220 |
|
| 221 |
except Exception: |
| 222 |
raise |
| 223 |
|
| 224 |
else: |
| 225 |
try: |
| 226 |
if stream: |
| 227 |
return |
| 228 |
self.config.data['server-time'] = r.headers['Date'] |
| 229 |
elapsed = int(r.elapsed.total_seconds() * 1000) |
| 230 |
response = r.json() |
| 231 |
LOG.debug("---<[ http ][%s ms]", elapsed) |
| 232 |
LOG.debug(json.dumps(response, indent=4)) |
| 233 |
|
| 234 |
return response |
| 235 |
except ValueError: |
| 236 |
return |
| 237 |
|
| 238 |
def _request(self, data): |
| 239 |
|
| 240 |
if 'url' not in data: |
| 241 |
data['url'] = jellyfin_url(self, data.pop('handler', "")) |
| 242 |
|
| 243 |
headers = self._get_default_headers() |
| 244 |
user_specified_headers = (data.get('headers', None) or {}) |
| 245 |
headers.update(user_specified_headers) |
| 246 |
|
| 247 |
data['headers'] = headers |
| 248 |
data['timeout'] = data.get('timeout') or self.config.data['http.timeout'] |
| 249 |
data['verify'] = data.get('verify') or self.config.data.get('auth.ssl', False) |
| 250 |
data['url'] = self._replace_user_info(data['url']) |
| 251 |
self._process_params(data.get('params') or {}) |
| 252 |
self._process_params(data.get('json') or {}) |
| 253 |
|
| 254 |
return data |
| 255 |
|
| 256 |
def _process_params(self, params): |
| 257 |
if isinstance(params, str): |
| 258 |
|
| 259 |
return |
| 260 |
|
| 261 |
for key in params: |
| 262 |
value = params[key] |
| 263 |
|
| 264 |
if isinstance(value, dict): |
| 265 |
self._process_params(value) |
| 266 |
|
| 267 |
if isinstance(value, str): |
| 268 |
params[key] = self._replace_user_info(value) |
| 269 |
|
| 270 |
def _get_authenication_header(self): |
| 271 |
params = {} |
| 272 |
if "app.device_name" in self.config.data: |
| 273 |
params.update({ |
| 274 |
"Client": self.config.data['app.name'], |
| 275 |
"Device": self.config.data['app.device_name'], |
| 276 |
"DeviceId": self.config.data['app.device_id'], |
| 277 |
"Version": self.config.data['app.version'] |
| 278 |
}) |
| 279 |
if "auth.token" in self.config.data: |
| 280 |
params["Token"] = self.config.data['auth.token'] |
| 281 |
param_line = ", ".join(f'{k}="{v}"' for k, v in params.items()) |
| 282 |
return f"MediaBrowser {param_line}" |
| 283 |
|
| 284 |
def _get_default_headers(self, content_type="application/json"): |
| 285 |
app_name = f"{self.config.data.get('app.name', 'Jellyfin for Kodi')}/{self.config.data.get('app.version', '0.0.0')}" |
| 286 |
return { |
| 287 |
"Accept": "application/json", |
| 288 |
"Content-type": content_type, |
| 289 |
"X-Application": app_name, |
| 290 |
"Accept-Charset": "UTF-8,*", |
| 291 |
"Accept-encoding": "gzip", |
| 292 |
"User-Agent": self.config.data['http.user_agent'] or app_name, |
| 293 |
"Authorization": self._get_authenication_header() |
| 294 |
} |
| 295 |
|
| 296 |
def _requests(self, session, action, **kwargs): |
| 297 |
|
| 298 |
if action == "GET": |
| 299 |
return session.get(**kwargs) |
| 300 |
elif action == "POST": |
| 301 |
return session.post(**kwargs) |
| 302 |
elif action == "HEAD": |
| 303 |
return session.head(**kwargs) |
| 304 |
elif action == "DELETE": |
| 305 |
return session.delete(**kwargs) |