Skip to content

Commit

Permalink
feat: set danmaku protocol version via environment variable
Browse files Browse the repository at this point in the history
  • Loading branch information
acgnhik committed Dec 24, 2023
1 parent 71ca3f8 commit d00c504
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/blrec/bili/danmaku_client.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import asyncio
import json
import os
import struct
import zlib
from contextlib import suppress
from enum import Enum, IntEnum
from typing import Any, Dict, Final, List, Optional, Tuple, Union, cast

import aiohttp
import brotli
from aiohttp import ClientSession
from loguru import logger
from tenacity import retry, retry_if_exception_type, wait_exponential

from blrec.logging.context import async_task_with_logger_context
Expand All @@ -23,9 +26,6 @@
__all__ = 'DanmakuClient', 'DanmakuListener', 'Danmaku', 'DanmakuCommand'


from loguru import logger


class DanmakuListener(EventListener):
async def on_client_connected(self) -> None:
...
Expand Down Expand Up @@ -74,6 +74,20 @@ def __init__(
self._retry_delay: int = 0
self._MAX_RETRIES: Final[int] = max_retries

self._protover: int = WS.BODY_PROTOCOL_VERSION_BROTLI
if ver := os.environ.get('BLREC_DANMAKU_PROTOCOL_VERSION'):
if ver in (
str(WS.BODY_PROTOCOL_VERSION_NORMAL),
str(WS.BODY_PROTOCOL_VERSION_DEFLATE),
str(WS.BODY_PROTOCOL_VERSION_BROTLI),
):
self._protover = int(ver)
else:
self._logger.warning(
f'Invalid value of BLREC_DANMAKU_PROTOCOL_VERSION: {ver}'
)
self._logger.debug(f'protover: {self._protover}')

@property
def headers(self) -> Dict[str, str]:
return self._headers
Expand Down Expand Up @@ -157,7 +171,7 @@ async def _send_auth(self) -> None:
{
"uid": self._uid,
'roomid': self._room_id, # must not be the short id!
'protover': WS.BODY_PROTOCOL_VERSION_BROTLI,
'protover': self._protover,
"buvid": self._buvid,
'platform': 'web',
'type': 2,
Expand Down Expand Up @@ -372,6 +386,12 @@ def decode(data: bytes) -> Tuple[int, Union[int, str, List[str]]]:
if op == WS.OP_MESSAGE:
if ver == WS.BODY_PROTOCOL_VERSION_BROTLI:
data = brotli.decompress(body)
elif ver == WS.BODY_PROTOCOL_VERSION_DEFLATE:
data = zlib.decompress(body)
elif ver == WS.BODY_PROTOCOL_VERSION_NORMAL:
pass
else:
raise NotImplementedError(f'Unsupported protocol version: {ver}')

msg_list = []
offset = 0
Expand Down Expand Up @@ -408,6 +428,7 @@ class WS(IntEnum):
OPERATION_OFFSET = 8
SEQUENCE_OFFSET = 12
BODY_PROTOCOL_VERSION_NORMAL = 0
BODY_PROTOCOL_VERSION_DEFLATE = 2
BODY_PROTOCOL_VERSION_BROTLI = 3
HEADER_DEFAULT_VERSION = 1
HEADER_DEFAULT_OPERATION = 1
Expand Down

0 comments on commit d00c504

Please sign in to comment.