Skip to content
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

Make SSLContext a singleton #121

Merged
merged 1 commit into from
May 2, 2023
Merged
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
5 changes: 2 additions & 3 deletions samsungtvws/async_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
MS_CHANNEL_CONNECT_EVENT,
MS_CHANNEL_UNAUTHORIZED,
)
from .helper import get_ssl_context

_LOGGING = logging.getLogger(__name__)

Expand Down Expand Up @@ -66,9 +67,7 @@ async def open(self) -> WebSocketClientProtocol:
_LOGGING.debug("WS url %s", url)
connect_kwargs: Dict[str, Any] = {}
if self._is_ssl_connection():
ssl_context = ssl.SSLContext()
ssl_context.verify_mode = ssl.CERT_NONE
connect_kwargs["ssl"] = ssl_context
connect_kwargs["ssl"] = get_ssl_context()
connection = await connect(url, open_timeout=self.timeout, **connect_kwargs)

event: Optional[str] = None
Expand Down
12 changes: 11 additions & 1 deletion samsungtvws/helper.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import base64
import json
import logging
from typing import Any, Dict, Union
import ssl
from typing import Any, Dict, Optional, Union

from . import exceptions

_LOGGING = logging.getLogger(__name__)
_SSL_CONTEXT: Optional[ssl.SSLContext] = None


def serialize_string(string: Union[str, bytes]) -> str:
Expand All @@ -23,3 +25,11 @@ def process_api_response(response: Union[str, bytes]) -> Dict[str, Any]:
raise exceptions.ResponseError(
"Failed to parse response from TV. Maybe feature not supported on this model"
) from err


def get_ssl_context() -> ssl.SSLContext:
global _SSL_CONTEXT
if not _SSL_CONTEXT:
_SSL_CONTEXT = ssl.SSLContext()
_SSL_CONTEXT.verify_mode = ssl.CERT_NONE
return _SSL_CONTEXT