twitch.py 3.2.2__tar.gz → 3.2.4__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.
- {twitch_py-3.2.2/twitch.py.egg-info → twitch_py-3.2.4}/PKG-INFO +1 -1
- {twitch_py-3.2.2 → twitch_py-3.2.4}/pyproject.toml +2 -1
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/__init__.py +1 -1
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/chat.py +14 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/client.py +14 -1
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/ext/bot/bot.py +1 -1
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/ext/oauth/oauth.py +2 -1
- twitch_py-3.2.4/twitch/ext/overlay/__init__.py +12 -0
- twitch_py-3.2.4/twitch/ext/overlay/attachment.py +108 -0
- twitch_py-3.2.4/twitch/ext/overlay/geteway.py +117 -0
- twitch_py-3.2.4/twitch/ext/overlay/overlay.py +239 -0
- twitch_py-3.2.4/twitch/ext/overlay/route.py +73 -0
- twitch_py-3.2.4/twitch/ext/overlay/template.py +483 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/http.py +144 -120
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/state.py +22 -8
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/chat.py +25 -1
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/chat.py +69 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4/twitch.py.egg-info}/PKG-INFO +1 -1
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch.py.egg-info/SOURCES.txt +6 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/LICENSE +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/MANIFEST.in +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/README.md +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/requirements.txt +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/setup.cfg +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/setup.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/channel.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/errors.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/ext/bot/__init__.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/ext/oauth/__init__.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/ext/oauth/enums.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/ext/oauth/http.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/gateway.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/py.typed +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/stream.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/__init__.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/activity.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/analytics.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/bits.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/channels.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/__init__.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/activity.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/bits.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/channels.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/interaction.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/moderation.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/streams.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/eventsub/users.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/interaction.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/moderation.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/search.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/streams.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/types/users.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/user.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch/utils.py +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch.py.egg-info/dependency_links.txt +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch.py.egg-info/requires.txt +0 -0
- {twitch_py-3.2.2 → twitch_py-3.2.4}/twitch.py.egg-info/top_level.txt +0 -0
|
@@ -67,6 +67,20 @@ class Chat:
|
|
|
67
67
|
self._auth_user_id)
|
|
68
68
|
return data['data'][0]
|
|
69
69
|
|
|
70
|
+
|
|
71
|
+
async def get_shared_chat_session(self) -> Optional[chat.SharedChatSession]:
|
|
72
|
+
"""
|
|
73
|
+
Retrieve the shared chat session details for the broadcaster.
|
|
74
|
+
|
|
75
|
+
Returns
|
|
76
|
+
-------
|
|
77
|
+
chat.SharedChatSession
|
|
78
|
+
A dictionary containing details about the shared chat session.
|
|
79
|
+
"""
|
|
80
|
+
data: Data[List[chat.SharedChatSession]] = await self._state.http.get_shared_chat_session(self._auth_user_id,
|
|
81
|
+
self._user_id)
|
|
82
|
+
return data['data'][0] if len(data['data']) != 0 else None
|
|
83
|
+
|
|
70
84
|
async def update_settings(self,
|
|
71
85
|
emote_mode: Optional[bool] = None,
|
|
72
86
|
follower_mode: Optional[bool] = None,
|
|
@@ -79,7 +79,7 @@ class Client:
|
|
|
79
79
|
**Default**: `8080`
|
|
80
80
|
___
|
|
81
81
|
|
|
82
|
-
- socket_debug:
|
|
82
|
+
- socket_debug: [False][bool]
|
|
83
83
|
|
|
84
84
|
Flag indicating if raw WebSocket messages should be dispatched for debugging purposes.
|
|
85
85
|
If enabled, raw WebSocket messages are dispatched to the on_socket_raw_receive.
|
|
@@ -270,6 +270,18 @@ class Client:
|
|
|
270
270
|
self.loop = loop
|
|
271
271
|
self.http.loop = loop
|
|
272
272
|
|
|
273
|
+
async def setup_hook(self) -> None:
|
|
274
|
+
"""
|
|
275
|
+
Perform additional setup before the client is ready.
|
|
276
|
+
|
|
277
|
+
???+ Warning
|
|
278
|
+
Do not use `wait_until_ready()` within this method as it may cause
|
|
279
|
+
it to freeze.
|
|
280
|
+
|
|
281
|
+
You can configure or set up additional extensions or services as required.
|
|
282
|
+
"""
|
|
283
|
+
pass
|
|
284
|
+
|
|
273
285
|
@staticmethod
|
|
274
286
|
async def on_error(event_name: str, error: Exception, /, *args: Any, **kwargs: Any) -> None:
|
|
275
287
|
"""
|
|
@@ -449,6 +461,7 @@ class Client:
|
|
|
449
461
|
self._connection.ready = asyncio.Event()
|
|
450
462
|
data: users.OAuthToken = await self.http.initialize_authorization(access_token, refresh_token)
|
|
451
463
|
await self._connection.initialize_client(user_id=data['user_id'])
|
|
464
|
+
await self.setup_hook()
|
|
452
465
|
|
|
453
466
|
async def connect(self, *, reconnect: bool = True) -> None:
|
|
454
467
|
"""
|
|
@@ -69,7 +69,7 @@ class Bot(twitch.Client):
|
|
|
69
69
|
**Default**: `8080`
|
|
70
70
|
___
|
|
71
71
|
|
|
72
|
-
- socket_debug:
|
|
72
|
+
- socket_debug: [False][bool]
|
|
73
73
|
|
|
74
74
|
Flag indicating if raw WebSocket messages should be dispatched for debugging purposes.
|
|
75
75
|
If enabled, raw WebSocket messages are dispatched to the on_socket_raw_receive.
|
|
@@ -24,7 +24,7 @@ DEALINGS IN THE SOFTWARE.
|
|
|
24
24
|
|
|
25
25
|
from __future__ import annotations
|
|
26
26
|
|
|
27
|
-
from twitch import
|
|
27
|
+
from twitch import utils
|
|
28
28
|
from typing import TYPE_CHECKING
|
|
29
29
|
from .http import HTTPClient
|
|
30
30
|
from .enums import Scopes
|
|
@@ -34,6 +34,7 @@ if TYPE_CHECKING:
|
|
|
34
34
|
from typing import Optional, Type, Self, List, Union, Tuple
|
|
35
35
|
from types import TracebackType
|
|
36
36
|
from twitch.types import users
|
|
37
|
+
from twitch import Client
|
|
37
38
|
|
|
38
39
|
import logging
|
|
39
40
|
_logger = logging.getLogger(__name__)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""
|
|
2
|
+
twitch.ext.overlay
|
|
3
|
+
|
|
4
|
+
An extension that provides functionalities to manage and send overlay alerts,
|
|
5
|
+
handle WebSocket connections, and manage file attachments.
|
|
6
|
+
|
|
7
|
+
:copyright: (c) 2024-present Snifo
|
|
8
|
+
:license: MIT, see LICENSE for more details.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
from .overlay import Overlay
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The MIT License (MIT)
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2024-present Snifo
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
7
|
+
copy of this software and associated documentation files (the "Software"),
|
|
8
|
+
to deal in the Software without restriction, including without limitation
|
|
9
|
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
10
|
+
and/or sell copies of the Software, and to permit persons to whom the
|
|
11
|
+
Software is furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in
|
|
14
|
+
all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
17
|
+
OR IMPLIED, INCLUDING BUT NOT firstED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
+
DEALINGS IN THE SOFTWARE.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from typing import TYPE_CHECKING
|
|
28
|
+
import gzip
|
|
29
|
+
import io
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from typing import Optional, Dict
|
|
33
|
+
|
|
34
|
+
import logging
|
|
35
|
+
_logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Attachment:
|
|
39
|
+
"""
|
|
40
|
+
Manages file attachments in memory, including loading, compressing,
|
|
41
|
+
decompressing, and retrieving files.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
__slots__ = ('attachments', 'path_keys')
|
|
45
|
+
|
|
46
|
+
def __init__(self) -> None:
|
|
47
|
+
self.attachments: Dict[str, bytes] = {}
|
|
48
|
+
self.path_keys: Dict[str, str] = {}
|
|
49
|
+
|
|
50
|
+
def clear(self) -> None:
|
|
51
|
+
"""Clears all attachments and path keys from memory."""
|
|
52
|
+
self.attachments.clear()
|
|
53
|
+
self.path_keys.clear()
|
|
54
|
+
_logger.debug('All attachments have been cleared from memory.')
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def compress_data(data: bytes) -> bytes:
|
|
58
|
+
"""Compresses data using gzip."""
|
|
59
|
+
buffer = io.BytesIO()
|
|
60
|
+
with gzip.GzipFile(fileobj=buffer, mode='wb') as gzip_file:
|
|
61
|
+
gzip_file.write(data)
|
|
62
|
+
return buffer.getvalue()
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def decompress_data(compressed_data: bytes) -> bytes:
|
|
66
|
+
"""Decompresses gzip-compressed data."""
|
|
67
|
+
buffer = io.BytesIO(compressed_data)
|
|
68
|
+
with gzip.GzipFile(fileobj=buffer, mode='rb') as gzip_file:
|
|
69
|
+
return gzip_file.read()
|
|
70
|
+
|
|
71
|
+
@staticmethod
|
|
72
|
+
def convert_path_to_key(path: str) -> str:
|
|
73
|
+
"""Converts a file path to a hash-based key with the file extension."""
|
|
74
|
+
ext = f'.{path.rsplit(".", 1)[-1]}' if '.' in path else ''
|
|
75
|
+
key = f"{abs(hash(path))}{ext}"
|
|
76
|
+
_logger.debug('Converted path `%s` to key `%s`.', path, key)
|
|
77
|
+
return key
|
|
78
|
+
|
|
79
|
+
def load_file_into_memory(self, name: str, path: str) -> None:
|
|
80
|
+
"""Loads a file from the filesystem into memory and compresses it."""
|
|
81
|
+
with open(path, 'rb') as file:
|
|
82
|
+
file_data = file.read()
|
|
83
|
+
compressed_data = self.compress_data(file_data)
|
|
84
|
+
path_key = self.convert_path_to_key(path)
|
|
85
|
+
self.attachments[path_key] = compressed_data
|
|
86
|
+
self.path_keys[name] = path_key
|
|
87
|
+
_logger.debug('File `%s` loaded into memory with name `%s`.', path, name)
|
|
88
|
+
|
|
89
|
+
def get_attachment(self, path_key: str) -> Optional[bytes]:
|
|
90
|
+
"""Retrieves and decompresses a file from memory."""
|
|
91
|
+
compressed_file_content = self.attachments.get(path_key)
|
|
92
|
+
if compressed_file_content:
|
|
93
|
+
return self.decompress_data(compressed_file_content)
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
def get_path_key(self, name: str) -> Optional[str]:
|
|
97
|
+
"""Retrieves the path key for a given name."""
|
|
98
|
+
return self.path_keys.get(name, name)
|
|
99
|
+
|
|
100
|
+
def remove_attachment(self, name: str) -> None:
|
|
101
|
+
"""Removes a file from memory based on its name."""
|
|
102
|
+
try:
|
|
103
|
+
if name in self.path_keys:
|
|
104
|
+
path_key = self.path_keys.pop(name)
|
|
105
|
+
self.attachments.pop(path_key, None)
|
|
106
|
+
_logger.debug('Removed attachment with name `%s`.', name)
|
|
107
|
+
except Exception as exc:
|
|
108
|
+
_logger.exception('Failed to remove attachment', exc)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The MIT License (MIT)
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2024-present Snifo
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
7
|
+
copy of this software and associated documentation files (the "Software"),
|
|
8
|
+
to deal in the Software without restriction, including without limitation
|
|
9
|
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
10
|
+
and/or sell copies of the Software, and to permit persons to whom the
|
|
11
|
+
Software is furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in
|
|
14
|
+
all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
17
|
+
OR IMPLIED, INCLUDING BUT NOT firstED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
+
DEALINGS IN THE SOFTWARE.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from urllib.parse import urlparse
|
|
28
|
+
from typing import TYPE_CHECKING
|
|
29
|
+
from aiohttp import web
|
|
30
|
+
import json
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from typing import Dict, List, Any
|
|
34
|
+
|
|
35
|
+
import logging
|
|
36
|
+
_logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class WebSocket:
|
|
40
|
+
"""
|
|
41
|
+
Manages WebSocket connections, client subscriptions, and data distribution.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
__slots__ = ('clients',)
|
|
45
|
+
|
|
46
|
+
def __init__(self) -> None:
|
|
47
|
+
self.clients: Dict[str, List[web.WebSocketResponse]] = {}
|
|
48
|
+
|
|
49
|
+
def add_client(self, ws: web.WebSocketResponse, filter_param: str) -> None:
|
|
50
|
+
"""Add a WebSocket client to the list associated with the filter parameter."""
|
|
51
|
+
if filter_param not in self.clients:
|
|
52
|
+
self.clients[filter_param] = []
|
|
53
|
+
self.clients[filter_param].append(ws)
|
|
54
|
+
_logger.debug('Client added with default `%s`. Total clients: %s',
|
|
55
|
+
filter_param, len(self.clients[filter_param]))
|
|
56
|
+
|
|
57
|
+
def remove_client(self, ws: web.WebSocketResponse) -> None:
|
|
58
|
+
"""Remove a WebSocket client from the list of clients for its filter parameter."""
|
|
59
|
+
for filter_param, clients_list in self.clients.items():
|
|
60
|
+
if ws in clients_list:
|
|
61
|
+
clients_list.remove(ws)
|
|
62
|
+
if not clients_list: # Clean up if no clients left for this filter
|
|
63
|
+
del self.clients[filter_param]
|
|
64
|
+
_logger.debug('Client removed with default `%s`. Total clients: %s',
|
|
65
|
+
filter_param, len(clients_list))
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
async def handle_connection(self, request: web.Request) -> web.WebSocketResponse:
|
|
69
|
+
"""Handle WebSocket connection, prepare, and start interaction."""
|
|
70
|
+
ws = web.WebSocketResponse()
|
|
71
|
+
await ws.prepare(request)
|
|
72
|
+
|
|
73
|
+
# Extract the filter parameter from the URL query
|
|
74
|
+
filter_param = request.query.get('default', 'all')
|
|
75
|
+
self.add_client(ws, filter_param)
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
await self.receive_and_echo(ws)
|
|
79
|
+
finally:
|
|
80
|
+
self.remove_client(ws)
|
|
81
|
+
await ws.close()
|
|
82
|
+
return ws
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def _format_attachment_url(path: str) -> str:
|
|
86
|
+
"""Prepend '/upload/' to local file names; leave URLs unchanged."""
|
|
87
|
+
if urlparse(path).scheme:
|
|
88
|
+
return path
|
|
89
|
+
return f"/upload/{path}"
|
|
90
|
+
|
|
91
|
+
async def send_data(self, data: Dict[str, Any], filter_key: str):
|
|
92
|
+
"""Send data to all clients associated with the given filter parameter."""
|
|
93
|
+
clients_list = self.clients.get(filter_key, [])
|
|
94
|
+
|
|
95
|
+
# Update 'image' and 'audio' fields with formatted URLs if necessary
|
|
96
|
+
for key in ['image', 'audio']:
|
|
97
|
+
if data.get(key):
|
|
98
|
+
data[key] = self._format_attachment_url(data[key])
|
|
99
|
+
|
|
100
|
+
for client in clients_list[:]:
|
|
101
|
+
try:
|
|
102
|
+
await client.send_str(json.dumps(data))
|
|
103
|
+
except Exception as exc:
|
|
104
|
+
clients_list.remove(client)
|
|
105
|
+
_logger.exception('Error sending message to WebSocket client', exc)
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
async def receive_and_echo(ws: web.WebSocketResponse) -> None:
|
|
109
|
+
"""Receive and echo back any message received from the WebSocket."""
|
|
110
|
+
try:
|
|
111
|
+
async for msg in ws:
|
|
112
|
+
if msg.type == web.WSMsgType.TEXT: # type: ignore
|
|
113
|
+
await ws.send_str(f'Echo: {msg.data}') # type: ignore
|
|
114
|
+
elif msg.type == web.WSMsgType.ERROR: # type: ignore
|
|
115
|
+
_logger.error('WebSocket error: {ws.exception()}')
|
|
116
|
+
except Exception as exc:
|
|
117
|
+
_logger.exception('Exception while receiving WebSocket message', exc)
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The MIT License (MIT)
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2024-present Snifo
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
7
|
+
copy of this software and associated documentation files (the "Software"),
|
|
8
|
+
to deal in the Software without restriction, including without limitation
|
|
9
|
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
10
|
+
and/or sell copies of the Software, and to permit persons to whom the
|
|
11
|
+
Software is furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in
|
|
14
|
+
all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
17
|
+
OR IMPLIED, INCLUDING BUT NOT firstED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
+
DEALINGS IN THE SOFTWARE.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from .attachment import Attachment
|
|
28
|
+
from typing import TYPE_CHECKING
|
|
29
|
+
from .geteway import WebSocket
|
|
30
|
+
from .route import Route
|
|
31
|
+
from aiohttp import web
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from typing import Dict, Any, Optional, Tuple
|
|
35
|
+
from twitch import Client
|
|
36
|
+
|
|
37
|
+
import logging
|
|
38
|
+
_logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Overlay:
|
|
42
|
+
"""
|
|
43
|
+
Represents the overlay server application.
|
|
44
|
+
|
|
45
|
+
This class sets up and manages the overlay server, including routing,
|
|
46
|
+
handling WebSocket connections, managing file attachments, and sending alerts.
|
|
47
|
+
|
|
48
|
+
???+ Notes
|
|
49
|
+
- If sound is not working in the web browser, make sure to set the website
|
|
50
|
+
permissions for sound to "Allow."
|
|
51
|
+
|
|
52
|
+
- To change the default template used by the server, you can set
|
|
53
|
+
`route.default_template = 'Your HTML'` on setup.
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
client: Optional[Client]
|
|
58
|
+
An optional `Client` instance for event dispatching.
|
|
59
|
+
host: str
|
|
60
|
+
The host address for the server (default is 'localhost').
|
|
61
|
+
port: int
|
|
62
|
+
The port number for the server (default is 5050).
|
|
63
|
+
**options: Dict[str, Any]
|
|
64
|
+
Additional options to configure the `web.Application` instance.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
__slots__ = ('app', 'host', 'port', 'gateway', '_attachment', 'route', '_client')
|
|
68
|
+
|
|
69
|
+
def __init__(self, client: Optional[Client] = None, host: str = 'localhost', port: int = 5050, **options) -> None:
|
|
70
|
+
self.app = web.Application(**options)
|
|
71
|
+
self.host = host
|
|
72
|
+
self.port = port
|
|
73
|
+
self.gateway = WebSocket()
|
|
74
|
+
self._attachment = Attachment()
|
|
75
|
+
self.route = Route(self.app.router, self.gateway, self._attachment)
|
|
76
|
+
self._client: Optional[Client] = client
|
|
77
|
+
|
|
78
|
+
def url(self, default: str = 'all') -> str:
|
|
79
|
+
"""
|
|
80
|
+
Get the server URI.
|
|
81
|
+
|
|
82
|
+
Parameters
|
|
83
|
+
----------
|
|
84
|
+
default: str
|
|
85
|
+
The filter parameter for the alert.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
str
|
|
90
|
+
The full URL of the server with the specified filter parameter.
|
|
91
|
+
"""
|
|
92
|
+
return f'http://{self.host}:{self.port}/?default={default}'
|
|
93
|
+
|
|
94
|
+
async def start_app(self, handle_signals: bool = False, **options) -> Tuple[web.AppRunner, web.TCPSite]:
|
|
95
|
+
"""
|
|
96
|
+
Start the overlay server.
|
|
97
|
+
|
|
98
|
+
Sets up the application runner and site, and starts the server.
|
|
99
|
+
|
|
100
|
+
???+ Note
|
|
101
|
+
Call this method within your `setup_hook()`.
|
|
102
|
+
|
|
103
|
+
Parameters
|
|
104
|
+
----------
|
|
105
|
+
handle_signals: bool
|
|
106
|
+
Whether to handle signals for graceful shutdown (default is False).
|
|
107
|
+
**options
|
|
108
|
+
Additional options to pass to the `web.TCPSite` constructor.
|
|
109
|
+
|
|
110
|
+
Returns
|
|
111
|
+
-------
|
|
112
|
+
Tuple[web.AppRunner, web.TCPSite]
|
|
113
|
+
The application runner and TCP site objects.
|
|
114
|
+
"""
|
|
115
|
+
runner = web.AppRunner(self.app, handle_signals=handle_signals)
|
|
116
|
+
await runner.setup()
|
|
117
|
+
site = web.TCPSite(runner, self.host, self.port, **options)
|
|
118
|
+
_logger.debug('Starting overlay server on http://%s:%s', self.host, self.port)
|
|
119
|
+
await site.start()
|
|
120
|
+
_logger.debug('Overlay server started successfully.')
|
|
121
|
+
if self._client is not None:
|
|
122
|
+
self._client.dispatch('overlay_ready')
|
|
123
|
+
return runner, site
|
|
124
|
+
|
|
125
|
+
async def alert(
|
|
126
|
+
self,
|
|
127
|
+
text: str,
|
|
128
|
+
font_name: str = 'Roboto',
|
|
129
|
+
font_size: float = 64.0,
|
|
130
|
+
text_color: str = '#FFFFFF',
|
|
131
|
+
text_highlight_color: str = '#6441a5',
|
|
132
|
+
text_animation: str = 'pulse',
|
|
133
|
+
start_animation: str = 'fadeIn',
|
|
134
|
+
end_animation: str = 'fadeOut',
|
|
135
|
+
image: Optional[str] = None,
|
|
136
|
+
audio: Optional[str] = None,
|
|
137
|
+
alert_duration: float = 5.0,
|
|
138
|
+
default: str = 'all'):
|
|
139
|
+
"""
|
|
140
|
+
Send an alert with specified parameters.
|
|
141
|
+
|
|
142
|
+
???+ Info
|
|
143
|
+
The overlay uses [Animate.css](https://animate.style/).
|
|
144
|
+
|
|
145
|
+
Be careful with animation names as they are **case-sensitive**.
|
|
146
|
+
|
|
147
|
+
Parameters
|
|
148
|
+
----------
|
|
149
|
+
text: str
|
|
150
|
+
The text message to display.
|
|
151
|
+
font_name: str
|
|
152
|
+
The name of the font to use.
|
|
153
|
+
font_size: float
|
|
154
|
+
The size of the text font.
|
|
155
|
+
text_color: str
|
|
156
|
+
The color of the text.
|
|
157
|
+
text_highlight_color: str
|
|
158
|
+
The highlight color for text.
|
|
159
|
+
text_animation: str
|
|
160
|
+
The animation applied to the text.
|
|
161
|
+
Refer to [Animate.css](https://animate.style/) for available text animations.
|
|
162
|
+
start_animation: str
|
|
163
|
+
The animation applied at the start of the alert.
|
|
164
|
+
Refer to [Animate.css](https://animate.style/) for available start animations.
|
|
165
|
+
end_animation: str
|
|
166
|
+
The animation applied at the end of the alert.
|
|
167
|
+
Refer to [Animate.css](https://animate.style/) for available end animations.
|
|
168
|
+
image: Optional[str]
|
|
169
|
+
The path to the image to display.
|
|
170
|
+
audio: Optional[str]
|
|
171
|
+
The path to the audio file to play.
|
|
172
|
+
alert_duration: float
|
|
173
|
+
The duration of the alert in seconds.
|
|
174
|
+
default: str
|
|
175
|
+
The `default` parameter specifies which filter key will trigger alerts.
|
|
176
|
+
If set to a specific value (e.g., `'special'`), only alerts with that key will be processed.
|
|
177
|
+
For example, if you set `default='special'`, alerts will only be triggered for the 'special' filter.
|
|
178
|
+
To ensure the alert is processed, include this filter in the request URL.
|
|
179
|
+
Example URL: `http://localhost:5050/?default=special`
|
|
180
|
+
"""
|
|
181
|
+
data: Dict[str, Any] = {
|
|
182
|
+
'text': text,
|
|
183
|
+
'font_name': font_name,
|
|
184
|
+
'font_size': font_size,
|
|
185
|
+
'text_color': text_color,
|
|
186
|
+
'text_highlight_color': text_highlight_color,
|
|
187
|
+
'text_animation': text_animation,
|
|
188
|
+
'start_animation': start_animation,
|
|
189
|
+
'end_animation': end_animation,
|
|
190
|
+
'image': self._attachment.get_path_key(image),
|
|
191
|
+
'audio': self._attachment.get_path_key(audio),
|
|
192
|
+
'alert_duration': alert_duration
|
|
193
|
+
}
|
|
194
|
+
await self.gateway.send_data(data, default)
|
|
195
|
+
_logger.debug('Alert sent to default `%s` with data: %s', default, data)
|
|
196
|
+
if self._client is not None:
|
|
197
|
+
self._client.dispatch('overlay_alert', default, data)
|
|
198
|
+
|
|
199
|
+
def add_attachment(self, name: str, path: str) -> None:
|
|
200
|
+
"""
|
|
201
|
+
Add a new file attachment.
|
|
202
|
+
|
|
203
|
+
Parameters
|
|
204
|
+
----------
|
|
205
|
+
name: str
|
|
206
|
+
The name of the attachment.
|
|
207
|
+
path: str
|
|
208
|
+
The file path of the attachment.
|
|
209
|
+
"""
|
|
210
|
+
self._attachment.load_file_into_memory(name, path)
|
|
211
|
+
|
|
212
|
+
def remove_attachment(self, name: str) -> None:
|
|
213
|
+
"""
|
|
214
|
+
Remove an existing file attachment.
|
|
215
|
+
|
|
216
|
+
Parameters
|
|
217
|
+
----------
|
|
218
|
+
name: str
|
|
219
|
+
The name of the attachment to remove.
|
|
220
|
+
"""
|
|
221
|
+
self._attachment.remove_attachment(name)
|
|
222
|
+
|
|
223
|
+
def clear_attachments(self) -> None:
|
|
224
|
+
"""
|
|
225
|
+
Clear all attachments.
|
|
226
|
+
"""
|
|
227
|
+
self._attachment.clear()
|
|
228
|
+
|
|
229
|
+
def get_attachments(self) -> Dict[str, str]:
|
|
230
|
+
"""
|
|
231
|
+
Retrieve all file attachments.
|
|
232
|
+
|
|
233
|
+
Returns
|
|
234
|
+
-------
|
|
235
|
+
Dict[str, str]
|
|
236
|
+
A dictionary where the keys represent attachment names and
|
|
237
|
+
the values represent their corresponding upload paths.
|
|
238
|
+
"""
|
|
239
|
+
return self._attachment.path_keys
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The MIT License (MIT)
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2024-present Snifo
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
7
|
+
copy of this software and associated documentation files (the "Software"),
|
|
8
|
+
to deal in the Software without restriction, including without limitation
|
|
9
|
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
10
|
+
and/or sell copies of the Software, and to permit persons to whom the
|
|
11
|
+
Software is furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in
|
|
14
|
+
all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
17
|
+
OR IMPLIED, INCLUDING BUT NOT firstED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
+
DEALINGS IN THE SOFTWARE.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from typing import TYPE_CHECKING
|
|
28
|
+
from .template import Template
|
|
29
|
+
from aiohttp import web
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from .attachment import Attachment
|
|
33
|
+
from .geteway import WebSocket
|
|
34
|
+
from typing import Optional
|
|
35
|
+
|
|
36
|
+
import logging
|
|
37
|
+
_logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Route:
|
|
41
|
+
"""
|
|
42
|
+
Handles HTTP and WebSocket routes for the application.
|
|
43
|
+
"""
|
|
44
|
+
__slots__ = ('gateway', 'attachment', 'default_template')
|
|
45
|
+
|
|
46
|
+
def __init__(self, router: web.Application.router, gateway: WebSocket, attachment: Attachment):
|
|
47
|
+
self.gateway: WebSocket = gateway
|
|
48
|
+
self.attachment: Attachment = attachment
|
|
49
|
+
router.add_get('/', self.handle_request)
|
|
50
|
+
router.add_get('/ws', self.websocket_handler)
|
|
51
|
+
router.add_get('/upload/{filename}', self.serve_file)
|
|
52
|
+
|
|
53
|
+
# Loading template.
|
|
54
|
+
self.default_template: str = str(Template())
|
|
55
|
+
|
|
56
|
+
async def handle_request(self, request: web.Request) -> web.Response:
|
|
57
|
+
"""Handle HTTP requests to the main page."""
|
|
58
|
+
response = web.Response(text=self.default_template, content_type='text/html')
|
|
59
|
+
return response
|
|
60
|
+
|
|
61
|
+
async def serve_file(self, request: web.Request) -> web.Response:
|
|
62
|
+
"""Serve uploaded files from the /upload endpoint."""
|
|
63
|
+
filename: str = request.match_info['filename']
|
|
64
|
+
file_content: Optional[bytes] = self.attachment.get_attachment(filename)
|
|
65
|
+
if not file_content:
|
|
66
|
+
_logger.warning('File not found: %s', filename)
|
|
67
|
+
return web.Response(text='File not found', status=404)
|
|
68
|
+
return web.Response(body=file_content, content_type='application/octet-stream')
|
|
69
|
+
|
|
70
|
+
async def websocket_handler(self, request: web.Request) -> web.WebSocketResponse:
|
|
71
|
+
"""Handle WebSocket connections."""
|
|
72
|
+
ws = await self.gateway.handle_connection(request)
|
|
73
|
+
return ws
|