Skip to content

Commit

Permalink
Make sure we are connected before we listen
Browse files Browse the repository at this point in the history
  • Loading branch information
LuCkEr- committed Apr 18, 2022
1 parent 398a836 commit 61429a3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
12 changes: 7 additions & 5 deletions src/pyscoresaber/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@


class HttpClient:
_ws_url = "ws://scoresaber.com/ws"
MAX_TIMEOUT = 60

def __init__(self, loop: Optional[AbstractEventLoop] = None):
self.loop = loop
self._aiohttp: Optional[ClientSession] = None
self._ws: Optional[ClientWebSocketResponse] = None
self._ws_url: Optional[str] = None

async def start(self):
if self._aiohttp is None:
Expand Down Expand Up @@ -63,21 +63,23 @@ async def _request(self, *args, **kwargs) -> ClientResponse:

retries += 1

async def ws_connect(self, url: str):
async def ws_connect(self):
if self._ws is None:
self._ws_url = url
self._ws = await self._aiohttp.ws_connect(url)
self._ws = await self._aiohttp.ws_connect(self._ws_url)

async def ws_close(self):
if self._ws is not None:
await self._ws.close()
self._ws = None

async def ws_listen(self) -> AsyncIterable[typing.Dict]:
if self._ws is None:
await self.ws_connect()

async for message in self._ws:
if message.type == aiohttp.WSMsgType.CLOSE:
logging.warning(f"Websocket closed! Reconnecting...")
await self.ws_connect(self._ws_url)
await self.ws_connect()
if message.type == aiohttp.WSMsgType.TEXT:
text = message.data

Expand Down
2 changes: 1 addition & 1 deletion src/pyscoresaber/scoresaber.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()

async def ws_start(self):
await self._http_client.ws_connect("ws://scoresaber.com/ws")
await self._http_client.ws_connect()

async def ws_close(self):
await self._http_client.ws_close()
Expand Down
13 changes: 13 additions & 0 deletions tests/test_scoresaber_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,16 @@ async def test_websocket_live_feed(scoresaber: ScoreSaber):

if score_count > 5:
await scoresaber.ws_close()


async def test_websocket_live_feed_no_start(scoresaber: ScoreSaber):
score_count = 0
async for playerScore in scoresaber.websocket():

assert playerScore.score.id is not None
assert playerScore.leaderboard.id is not None

score_count += 1

if score_count > 5:
await scoresaber.ws_close()

0 comments on commit 61429a3

Please sign in to comment.