plexwebsocket 0.0.14__tar.gz → 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 jjlawren
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: plexwebsocket
3
+ Version: 0.1.0
4
+ Summary: Support for issuing callbacks in response to Plex websocket updates.
5
+ Author: Jason Lawrence
6
+ Author-email: Jason Lawrence <jjlawren@users.noreply.github.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Dist: aiohttp
12
+ Requires-Python: >=3.11
13
+ Project-URL: Homepage, https://github.com/jjlawren/python-plexwebsocket
14
+ Description-Content-Type: text/markdown
15
+
16
+ # python-plexwebsocket
17
+ Async library to react to events issued over Plex websockets.
18
+
19
+ ## Example use
20
+ ```python
21
+ import asyncio
22
+ import logging
23
+ from plexapi.server import PlexServer
24
+ from plexwebsocket import PlexWebsocket, SIGNAL_CONNECTION_STATE
25
+
26
+ logging.basicConfig(level=logging.DEBUG)
27
+
28
+ baseurl = "http://<PLEX_SERVER_IP>:32400"
29
+ token = "<YOUR_TOKEN_HERE>"
30
+ plex = PlexServer(baseurl, token)
31
+
32
+
33
+ def print_info(msgtype, data, error):
34
+ if msgtype == SIGNAL_CONNECTION_STATE:
35
+ print(f"State: {data} / Error: {error}")
36
+ else:
37
+ print(f"Data: {data}")
38
+
39
+
40
+ async def main():
41
+ ws = PlexWebsocket(plex, print_info, subscriptions=["playing", "status"])
42
+ await ws.listen()
43
+
44
+
45
+ if __name__ == "__main__":
46
+ loop = asyncio.get_event_loop()
47
+ loop.run_until_complete(main())
48
+ ```
@@ -10,21 +10,24 @@ from plexwebsocket import PlexWebsocket, SIGNAL_CONNECTION_STATE
10
10
 
11
11
  logging.basicConfig(level=logging.DEBUG)
12
12
 
13
- baseurl = 'http://<PLEX_SERVER_IP>:32400'
14
- token = '<YOUR_TOKEN_HERE>'
13
+ baseurl = "http://<PLEX_SERVER_IP>:32400"
14
+ token = "<YOUR_TOKEN_HERE>"
15
15
  plex = PlexServer(baseurl, token)
16
16
 
17
+
17
18
  def print_info(msgtype, data, error):
18
19
  if msgtype == SIGNAL_CONNECTION_STATE:
19
20
  print(f"State: {data} / Error: {error}")
20
21
  else:
21
22
  print(f"Data: {data}")
22
23
 
24
+
23
25
  async def main():
24
26
  ws = PlexWebsocket(plex, print_info, subscriptions=["playing", "status"])
25
27
  await ws.listen()
26
28
 
27
- if __name__ == '__main__':
29
+
30
+ if __name__ == "__main__":
28
31
  loop = asyncio.get_event_loop()
29
32
  loop.run_until_complete(main())
30
33
  ```
@@ -1,10 +1,15 @@
1
1
  """Support for issuing callbacks for Plex client updates via websockets."""
2
+
2
3
  import asyncio
3
- from datetime import datetime
4
4
  import logging
5
+ import re
6
+ from datetime import datetime
7
+ from importlib.metadata import version
5
8
 
6
9
  import aiohttp
7
10
 
11
+ __version__ = version("plexwebsocket")
12
+
8
13
  _LOGGER = logging.getLogger(__name__)
9
14
 
10
15
  SIGNAL_CONNECTION_STATE = "plexwebsocket_state"
@@ -13,13 +18,22 @@ ERROR_AUTH_FAILURE = "Authorization failure"
13
18
  ERROR_TOO_MANY_RETRIES = "Too many retries"
14
19
  ERROR_UNKNOWN = "Unknown"
15
20
 
16
- MAX_FAILED_ATTEMPTS = 5
21
+ MAX_FAILED_ATTEMPTS = 8
17
22
 
18
23
  STATE_CONNECTED = "connected"
19
24
  STATE_DISCONNECTED = "disconnected"
20
25
  STATE_STARTING = "starting"
21
26
  STATE_STOPPED = "stopped"
22
27
 
28
+ PLEX_TOKEN_PARAM = "X-Plex-Token"
29
+
30
+ _TOKEN_RE = re.compile(rf"({PLEX_TOKEN_PARAM}=)[^&'\"\s]+", re.IGNORECASE)
31
+
32
+
33
+ def _redact(error):
34
+ """Return the error text with the Plex token masked."""
35
+ return _TOKEN_RE.sub(r"\1REDACTED", str(error))
36
+
23
37
 
24
38
  class WebsocketPlayer: # pylint: disable=too-few-public-methods
25
39
  """Represent an individual player state in the Plex websocket stream."""
@@ -38,9 +52,7 @@ class WebsocketPlayer: # pylint: disable=too-few-public-methods
38
52
  posdiff = (new_position - self.position) / 1000
39
53
  diffdiff = timediff - posdiff
40
54
 
41
- if abs(diffdiff) > 5:
42
- return True
43
- return False
55
+ return abs(diffdiff) > 5
44
56
 
45
57
 
46
58
  class PlexWebsocket:
@@ -52,7 +64,7 @@ class PlexWebsocket:
52
64
  self,
53
65
  plex_server,
54
66
  callback,
55
- subscriptions=["playing"],
67
+ subscriptions=("playing",),
56
68
  session=None,
57
69
  verify_ssl=True,
58
70
  ):
@@ -144,30 +156,22 @@ class PlexWebsocket:
144
156
  break
145
157
 
146
158
  except aiohttp.ClientResponseError as error:
147
- if error.code == 401:
148
- _LOGGER.error("Credentials rejected: %s", error)
159
+ if error.status >= 500:
160
+ # Transient proxy/server failure, retry
161
+ await self._retry(error)
162
+ return
163
+ if error.status == 401:
164
+ _LOGGER.error("Credentials rejected: %s", _redact(error))
149
165
  self._error_reason = ERROR_AUTH_FAILURE
150
166
  else:
151
- _LOGGER.error("Unexpected response received: %s", error)
167
+ _LOGGER.error("Unexpected response received: %s", _redact(error))
152
168
  self._error_reason = ERROR_UNKNOWN
153
169
  self.state = STATE_STOPPED
154
- except (aiohttp.ClientConnectionError, asyncio.TimeoutError) as error:
155
- if self.failed_attempts >= MAX_FAILED_ATTEMPTS:
156
- self._error_reason = ERROR_TOO_MANY_RETRIES
157
- self.state = STATE_STOPPED
158
- elif self.state != STATE_STOPPED:
159
- retry_delay = min(2 ** (self.failed_attempts - 1) * 30, 300)
160
- self.failed_attempts += 1
161
- _LOGGER.error(
162
- "Websocket connection failed, retrying in %ds: %s",
163
- retry_delay,
164
- error,
165
- )
166
- self.state = STATE_DISCONNECTED
167
- await asyncio.sleep(retry_delay)
168
- except Exception as error: # pylint: disable=broad-except
170
+ except (TimeoutError, aiohttp.ClientConnectionError) as error:
171
+ await self._retry(error)
172
+ except Exception as error: # noqa: BLE001
169
173
  if self.state != STATE_STOPPED:
170
- _LOGGER.exception("Unexpected exception occurred: %s", error)
174
+ _LOGGER.error("Unexpected exception occurred: %s", _redact(error))
171
175
  self._error_reason = ERROR_UNKNOWN
172
176
  self.state = STATE_STOPPED
173
177
  else:
@@ -178,6 +182,22 @@ class PlexWebsocket:
178
182
  self.players.clear()
179
183
  await asyncio.sleep(5)
180
184
 
185
+ async def _retry(self, error):
186
+ """Retry with backoffs."""
187
+ if self.failed_attempts >= MAX_FAILED_ATTEMPTS:
188
+ self._error_reason = ERROR_TOO_MANY_RETRIES
189
+ self.state = STATE_STOPPED
190
+ elif self.state != STATE_STOPPED:
191
+ retry_delay = min(5 * 2**self.failed_attempts, 60)
192
+ self.failed_attempts += 1
193
+ _LOGGER.error(
194
+ "Websocket connection failed, retrying in %ds: %s",
195
+ retry_delay,
196
+ _redact(error),
197
+ )
198
+ self.state = STATE_DISCONNECTED
199
+ await asyncio.sleep(retry_delay)
200
+
181
201
  def player_event(self, msg):
182
202
  """Determine if messages relate to an interesting player event."""
183
203
  should_fire = False
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.9,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "plexwebsocket"
7
+ version = "0.1.0"
8
+ description = "Support for issuing callbacks in response to Plex websocket updates."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ dependencies = ["aiohttp"]
14
+ classifiers = [
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ ]
18
+
19
+ [[project.authors]]
20
+ name = "Jason Lawrence"
21
+ email = "jjlawren@users.noreply.github.com"
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/jjlawren/python-plexwebsocket"
25
+
26
+ [dependency-groups]
27
+ dev = [
28
+ "pre-commit",
29
+ "pytest",
30
+ ]
31
+
32
+ [tool.uv.build-backend]
33
+ module-root = ""
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.9,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "plexwebsocket"
7
+ version = "0.1.0"
8
+ description = "Support for issuing callbacks in response to Plex websocket updates."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Jason Lawrence", email = "jjlawren@users.noreply.github.com" }]
13
+ requires-python = ">=3.11"
14
+ dependencies = ["aiohttp"]
15
+ classifiers = [
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ ]
19
+
20
+ [dependency-groups]
21
+ dev = [
22
+ "pre-commit",
23
+ "pytest",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/jjlawren/python-plexwebsocket"
28
+
29
+ [tool.uv.build-backend]
30
+ module-root = ""
@@ -1,46 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: plexwebsocket
3
- Version: 0.0.14
4
- Summary: Support for issuing callbacks in response to Plex websocket updates.
5
- Home-page: https://github.com/jjlawren/python-plexwebsocket/
6
- Author: Jason Lawrence
7
- Author-email: jjlawren@users.noreply.github.com
8
- License: MIT
9
- Description: # python-plexwebsocket
10
- Async library to react to events issued over Plex websockets.
11
-
12
- ## Example use
13
- ```python
14
- import asyncio
15
- import logging
16
- from plexapi.server import PlexServer
17
- from plexwebsocket import PlexWebsocket, SIGNAL_CONNECTION_STATE
18
-
19
- logging.basicConfig(level=logging.DEBUG)
20
-
21
- baseurl = 'http://<PLEX_SERVER_IP>:32400'
22
- token = '<YOUR_TOKEN_HERE>'
23
- plex = PlexServer(baseurl, token)
24
-
25
- def print_info(msgtype, data, error):
26
- if msgtype == SIGNAL_CONNECTION_STATE:
27
- print(f"State: {data} / Error: {error}")
28
- else:
29
- print(f"Data: {data}")
30
-
31
- async def main():
32
- ws = PlexWebsocket(plex, print_info, subscriptions=["playing", "status"])
33
- await ws.listen()
34
-
35
- if __name__ == '__main__':
36
- loop = asyncio.get_event_loop()
37
- loop.run_until_complete(main())
38
- ```
39
-
40
- Platform: any
41
- Classifier: License :: OSI Approved :: MIT License
42
- Classifier: Operating System :: OS Independent
43
- Classifier: Programming Language :: Python :: 3.6
44
- Classifier: Programming Language :: Python :: 3.7
45
- Classifier: Programming Language :: Python :: 3.8
46
- Description-Content-Type: text/markdown
@@ -1,46 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: plexwebsocket
3
- Version: 0.0.14
4
- Summary: Support for issuing callbacks in response to Plex websocket updates.
5
- Home-page: https://github.com/jjlawren/python-plexwebsocket/
6
- Author: Jason Lawrence
7
- Author-email: jjlawren@users.noreply.github.com
8
- License: MIT
9
- Description: # python-plexwebsocket
10
- Async library to react to events issued over Plex websockets.
11
-
12
- ## Example use
13
- ```python
14
- import asyncio
15
- import logging
16
- from plexapi.server import PlexServer
17
- from plexwebsocket import PlexWebsocket, SIGNAL_CONNECTION_STATE
18
-
19
- logging.basicConfig(level=logging.DEBUG)
20
-
21
- baseurl = 'http://<PLEX_SERVER_IP>:32400'
22
- token = '<YOUR_TOKEN_HERE>'
23
- plex = PlexServer(baseurl, token)
24
-
25
- def print_info(msgtype, data, error):
26
- if msgtype == SIGNAL_CONNECTION_STATE:
27
- print(f"State: {data} / Error: {error}")
28
- else:
29
- print(f"Data: {data}")
30
-
31
- async def main():
32
- ws = PlexWebsocket(plex, print_info, subscriptions=["playing", "status"])
33
- await ws.listen()
34
-
35
- if __name__ == '__main__':
36
- loop = asyncio.get_event_loop()
37
- loop.run_until_complete(main())
38
- ```
39
-
40
- Platform: any
41
- Classifier: License :: OSI Approved :: MIT License
42
- Classifier: Operating System :: OS Independent
43
- Classifier: Programming Language :: Python :: 3.6
44
- Classifier: Programming Language :: Python :: 3.7
45
- Classifier: Programming Language :: Python :: 3.8
46
- Description-Content-Type: text/markdown
@@ -1,8 +0,0 @@
1
- README.md
2
- plexwebsocket.py
3
- setup.py
4
- plexwebsocket.egg-info/PKG-INFO
5
- plexwebsocket.egg-info/SOURCES.txt
6
- plexwebsocket.egg-info/dependency_links.txt
7
- plexwebsocket.egg-info/requires.txt
8
- plexwebsocket.egg-info/top_level.txt
@@ -1 +0,0 @@
1
- aiohttp
@@ -1 +0,0 @@
1
- plexwebsocket
@@ -1,4 +0,0 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
@@ -1,28 +0,0 @@
1
- from setuptools import setup
2
-
3
- with open('README.md') as f:
4
- long_description = f.read()
5
-
6
- VERSION="0.0.14"
7
-
8
- setup(
9
- name='plexwebsocket',
10
- version=VERSION,
11
- description='Support for issuing callbacks in response to Plex websocket updates.',
12
- long_description=long_description,
13
- long_description_content_type='text/markdown',
14
- url='https://github.com/jjlawren/python-plexwebsocket/',
15
- license='MIT',
16
- author='Jason Lawrence',
17
- author_email='jjlawren@users.noreply.github.com',
18
- platforms='any',
19
- py_modules=['plexwebsocket'],
20
- install_requires=['aiohttp'],
21
- classifiers=[
22
- 'License :: OSI Approved :: MIT License',
23
- 'Operating System :: OS Independent',
24
- 'Programming Language :: Python :: 3.6',
25
- 'Programming Language :: Python :: 3.7',
26
- 'Programming Language :: Python :: 3.8',
27
- ]
28
- )