Skip to content

Initialize headers from config in reset_base_headers() #707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 0 additions & 13 deletions plexapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
import logging
import os
from logging.handlers import RotatingFileHandler
from platform import uname
from uuid import getnode

from plexapi.config import PlexConfig, reset_base_headers
import plexapi.const as const
Expand All @@ -21,17 +19,6 @@
X_PLEX_CONTAINER_SIZE = CONFIG.get('plexapi.container_size', 100, int)
X_PLEX_ENABLE_FAST_CONNECT = CONFIG.get('plexapi.enable_fast_connect', False, bool)

# Plex Header Configuration
X_PLEX_PROVIDES = CONFIG.get('header.provides', 'controller')
X_PLEX_PLATFORM = CONFIG.get('header.platform', CONFIG.get('header.platform', uname()[0]))
X_PLEX_PLATFORM_VERSION = CONFIG.get('header.platform_version', uname()[2])
X_PLEX_PRODUCT = CONFIG.get('header.product', PROJECT)
X_PLEX_VERSION = CONFIG.get('header.version', VERSION)
X_PLEX_DEVICE = CONFIG.get('header.device', X_PLEX_PLATFORM)
X_PLEX_DEVICE_NAME = CONFIG.get('header.device_name', uname()[1])
X_PLEX_IDENTIFIER = CONFIG.get('header.identifier', str(hex(getnode())))
BASE_HEADERS = reset_base_headers()

# Logging Configuration
log = logging.getLogger('plexapi')
logfile = CONFIG.get('log.path')
Expand Down
6 changes: 4 additions & 2 deletions plexapi/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from xml.etree import ElementTree

import requests
from plexapi import BASE_HEADERS, CONFIG, TIMEOUT, log, logfilter, utils
from plexapi import CONFIG, TIMEOUT, log, logfilter, reset_base_headers, utils
from plexapi.base import PlexObject
from plexapi.exceptions import BadRequest, NotFound, Unauthorized, Unsupported
from plexapi.playqueue import PlayQueue
Expand Down Expand Up @@ -74,6 +74,8 @@ def __init__(self, server=None, data=None, initpath=None, baseurl=None,
self._last_call = 0
self._timeline_cache = []
self._timeline_cache_timestamp = 0
self._base_headers = reset_base_headers()

if not any([data is not None, initpath, baseurl, token]):
self._baseurl = CONFIG.get('auth.client_baseurl', 'http://localhost:32433')
self._token = logfilter.add_secret(CONFIG.get('auth.client_token'))
Expand Down Expand Up @@ -149,7 +151,7 @@ def _loadData(self, data):

def _headers(self, **kwargs):
""" Returns a dict of all default headers for Client requests. """
headers = BASE_HEADERS
headers = self._base_headers.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
Expand Down
40 changes: 31 additions & 9 deletions plexapi/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,47 @@ def get(self, key, default=None, cast=None):
def _asDict(self):
""" Returns all configuration values as a dictionary. """
config = defaultdict(dict)
config.update(self._defaults())
for section in self._sections:
for name, value in self._sections[section].items():
if name != '__name__':
config[section.lower()][name.lower()] = value
return dict(config)

def _defaults(self):
from uuid import getnode
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don’t in-line std libs.

from platform import uname
from plexapi import PROJECT, VERSION

platform_name, device_name, platform_version = uname()[0:3]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix the slicing.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explain fix how? fix what? what is wrong with the current code?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is the current slicing wrong. how is the correct way?


return {
'header': {
'provides': 'controller',
'platform': platform_name,
'platform_version': platform_version,
'product': PROJECT,
'version': VERSION,
'device': platform_name,
'device_name': device_name,
'identifier': str(hex(getnode())),
}
}


def reset_base_headers():
""" Convenience function returns a dict of all base X-Plex-* headers for session requests. """
import plexapi
from plexapi import CONFIG

return {
'X-Plex-Platform': plexapi.X_PLEX_PLATFORM,
'X-Plex-Platform-Version': plexapi.X_PLEX_PLATFORM_VERSION,
'X-Plex-Provides': plexapi.X_PLEX_PROVIDES,
'X-Plex-Product': plexapi.X_PLEX_PRODUCT,
'X-Plex-Version': plexapi.X_PLEX_VERSION,
'X-Plex-Device': plexapi.X_PLEX_DEVICE,
'X-Plex-Device-Name': plexapi.X_PLEX_DEVICE_NAME,
'X-Plex-Client-Identifier': plexapi.X_PLEX_IDENTIFIER,
'X-Plex-Platform': CONFIG.get('header.platorm', CONFIG.get('header.platform')),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it's about time to drop support for the 'header.platorm' typo?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it was fixed in 2018, matching 3.2.0 version:

'X-Plex-Platform-Version': CONFIG.get('header.platform_version'),
'X-Plex-Provides': CONFIG.get('header.provides'),
'X-Plex-Product': CONFIG.get('header.product'),
'X-Plex-Version': CONFIG.get('header.version'),
'X-Plex-Device': CONFIG.get('header.device'),
'X-Plex-Device-Name': CONFIG.get('header.device_name'),
'X-Plex-Client-Identifier': CONFIG.get('header.identifier'),
'X-Plex-Sync-Version': '2',
'X-Plex-Features': 'external-media',
}
13 changes: 8 additions & 5 deletions plexapi/myplex.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

import requests
from plexapi import (BASE_HEADERS, CONFIG, TIMEOUT, X_PLEX_CONTAINER_SIZE,
X_PLEX_ENABLE_FAST_CONNECT, X_PLEX_IDENTIFIER, log, logfilter, utils)
X_PLEX_ENABLE_FAST_CONNECT, X_PLEX_IDENTIFIER, log,
logfilter, reset_base_headers, utils)
from plexapi.base import PlexObject
from plexapi.client import PlexClient
from plexapi.exceptions import BadRequest, NotFound, Unauthorized
Expand Down Expand Up @@ -94,6 +95,7 @@ def __init__(self, username=None, password=None, token=None, session=None, timeo
self._session = session or requests.Session()
self._sonos_cache = []
self._sonos_cache_timestamp = 0
self._base_headers = reset_base_headers()
data, initpath = self._signin(username, password, code, timeout)
super(MyPlexAccount, self).__init__(self, data, initpath)

Expand Down Expand Up @@ -168,7 +170,7 @@ def devices(self):

def _headers(self, **kwargs):
""" Returns dict containing base headers for all requests to the server. """
headers = BASE_HEADERS.copy()
headers = self._base_headers.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
Expand Down Expand Up @@ -707,7 +709,7 @@ def syncItems(self, client=None, clientId=None):
if client:
clientId = client.clientIdentifier
elif clientId is None:
clientId = X_PLEX_IDENTIFIER
clientId = CONFIG.get('header.identifier')

data = self.query(SyncList.key.format(clientId=clientId))

Expand All @@ -733,7 +735,7 @@ def sync(self, sync_item, client=None, clientId=None):
:exc:`~plexapi.exceptions.BadRequest`: Provided client doesn't provides `sync-target`.
"""
if not client and not clientId:
clientId = X_PLEX_IDENTIFIER
clientId = CONFIG.get('header.identifier')

if not client:
for device in self.devices():
Expand Down Expand Up @@ -1539,6 +1541,7 @@ def __init__(self, session=None, requestTimeout=None, headers=None, oauth=False)
super(MyPlexPinLogin, self).__init__()
self._session = session or requests.Session()
self._requestTimeout = requestTimeout or TIMEOUT
self._base_headers = reset_base_headers()
self.headers = headers

self._oauth = oauth
Expand Down Expand Up @@ -1706,7 +1709,7 @@ def _pollLogin(self):

def _headers(self, **kwargs):
""" Returns dict containing base headers for all requests for pin login. """
headers = BASE_HEADERS.copy()
headers = self._base_headers.copy()
if self.headers:
headers.update(self.headers)
headers.update(kwargs)
Expand Down
5 changes: 3 additions & 2 deletions plexapi/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import requests
import os
from plexapi import (BASE_HEADERS, CONFIG, TIMEOUT, X_PLEX_CONTAINER_SIZE, log,
logfilter)
logfilter, reset_base_headers)
from plexapi import utils
from plexapi.alert import AlertListener
from plexapi.base import PlexObject
Expand Down Expand Up @@ -112,6 +112,7 @@ def __init__(self, baseurl=None, token=None, session=None, timeout=None):
self._myPlexAccount = None # cached myPlexAccount
self._systemAccounts = None # cached list of SystemAccount
self._systemDevices = None # cached list of SystemDevice
self._base_headers = reset_base_headers()
data = self.query(self.key, timeout=self._timeout)
super(PlexServer, self).__init__(self, data, self.key)

Expand Down Expand Up @@ -162,7 +163,7 @@ def _loadData(self, data):

def _headers(self, **kwargs):
""" Returns dict containing base headers for all requests to the server. """
headers = BASE_HEADERS.copy()
headers = self._base_headers.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
Expand Down
4 changes: 2 additions & 2 deletions plexapi/sonos.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
import requests
from plexapi import CONFIG, X_PLEX_IDENTIFIER
from plexapi import CONFIG
from plexapi.client import PlexClient
from plexapi.exceptions import BadRequest
from plexapi.playqueue import PlayQueue
Expand Down Expand Up @@ -105,7 +105,7 @@ def playMedia(self, media, offset=0, **params):
"port": server_port,
"token": media._server.createToken(),
"commandID": self._nextCommandId(),
"X-Plex-Client-Identifier": X_PLEX_IDENTIFIER,
"X-Plex-Client-Identifier": CONFIG.get('header.identifier'),
"X-Plex-Token": media._server._token,
"X-Plex-Target-Client-Identifier": self.machineIdentifier,
},
Expand Down