55import urllib .parse
66import uuid
77
8- __version__ = '0.0.1 '
8+ __version__ = '0.0.3 '
99
1010CODES_URL = 'https://plex.tv/api/v2/pins.json?strong=true'
1111AUTH_URL = 'https://app.plex.tv/auth#!?{}'
1212TOKEN_URL = 'https://plex.tv/api/v2/pins/{}'
1313
1414class PlexAuth ():
1515
16- def __init__ (self , payload ):
16+ def __init__ (self , payload , session = None ):
1717 '''Create PlexAuth instance.'''
1818 self ._client_identifier = str (uuid .uuid4 ())
1919 self ._code = None
2020 self ._identifier = None
2121 self ._payload = payload
2222 self ._payload ['X-Plex-Client-Identifier' ] = self ._client_identifier
2323
24+ self ._local_session = False
25+ self ._session = session
26+ if session is None :
27+ self ._session = aiohttp .ClientSession ()
28+ self ._local_session = True
29+
2430 async def initiate_auth (self ):
2531 '''Request codes needed to create an auth URL. Starts external timeout.'''
26- async with aiohttp .ClientSession () as session :
27- async with session .post (CODES_URL , data = self ._payload ) as resp :
28- response = await resp .json ()
29- self ._code = response ['code' ]
30- self ._identifier = response ['id' ]
32+ async with self ._session .post (CODES_URL , data = self ._payload ) as resp :
33+ response = await resp .json ()
34+ self ._code = response ['code' ]
35+ self ._identifier = response ['id' ]
3136
3237 def auth_url (self , forward_url = None ):
3338 '''Return an auth URL for the user to follow.'''
@@ -44,13 +49,12 @@ def auth_url(self, forward_url=None):
4449 async def request_auth_token (self ):
4550 '''Request an auth token from Plex.'''
4651 token_url = TOKEN_URL .format (self ._code )
47- async with aiohttp .ClientSession () as session :
48- payload = dict (self ._payload )
49- payload ['Accept' ] = 'application/json'
50- async with session .get (TOKEN_URL .format (self ._identifier ), headers = payload ) as resp :
51- response = await resp .json ()
52- token = response ['authToken' ]
53- return token
52+ payload = dict (self ._payload )
53+ payload ['Accept' ] = 'application/json'
54+ async with self ._session .get (TOKEN_URL .format (self ._identifier ), headers = payload ) as resp :
55+ response = await resp .json ()
56+ token = response ['authToken' ]
57+ return token
5458
5559 async def token (self , timeout = 60 ):
5660 '''Poll Plex endpoint until a token is retrieved or times out.'''
@@ -64,3 +68,16 @@ async def token(self, timeout=60):
6468 break_loop = True
6569
6670 return token
71+
72+ async def close (self ):
73+ """Close open client session."""
74+ if self ._local_session :
75+ await self ._session .close ()
76+
77+ async def __aenter__ (self ):
78+ """Async enter."""
79+ return self
80+
81+ async def __aexit__ (self , * exc_info ):
82+ """Async exit."""
83+ await self .close ()
0 commit comments