Skip to content

Commit

Permalink
✨ bilibili和bilibili-live共用http_client
Browse files Browse the repository at this point in the history
  • Loading branch information
AzideCupric committed Feb 19, 2024
1 parent 4d0838f commit 24aa461
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 31 deletions.
51 changes: 20 additions & 31 deletions nonebot_bison/platform/bilibili.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,33 @@
from copy import deepcopy
from enum import Enum, unique
from typing_extensions import Self
from abc import ABC, abstractmethod
from datetime import datetime, timedelta

from httpx import AsyncClient
from nonebot.log import logger
from pydantic import Field, BaseModel

from ..post import Post
from ..utils import SchedulerConfig, text_similarity
from ..types import Tag, Target, RawPost, ApiError, Category
from ..utils import SchedulerConfig, http_client, text_similarity
from .platform import NewMessage, StatusChange, CategoryNotSupport, CategoryNotRecognize


class BilibiliSchedConf(SchedulerConfig):
name = "bilibili.com"
class BaseSchedConf(ABC, SchedulerConfig):
schedule_type = "interval"
schedule_setting = {"seconds": 10}

_client_refresh_time: datetime
cookie_expire_time = timedelta(hours=5)

bili_http_client = http_client()

def __init__(self):
self._client_refresh_time = datetime(year=2000, month=1, day=1) # an expired time
super().__init__()
self.default_http_client = self.bili_http_client

async def _init_session(self):
res = await self.default_http_client.get("https://www.bilibili.com/")
res = await self.default_http_client.get(self.get_api_url())
if res.status_code != 200:
logger.warning("unable to refresh temp cookie")
else:
Expand All @@ -47,37 +48,25 @@ async def get_query_name_client(self) -> AsyncClient:
await self._refresh_client()
return await super().get_query_name_client()

@abstractmethod
def get_api_url(self):
raise NotImplementedError("Not implemented yet.")

class BililiveSchedConf(SchedulerConfig):
name = "live.bilibili.com"
schedule_type = "interval"
schedule_setting = {"seconds": 3}

_client_refresh_time: datetime
cookie_expire_time = timedelta(hours=5)
class BilibiliSchedConf(BaseSchedConf):
name = "bilibili.com"
schedule_setting = {"seconds": 10}

def __init__(self):
self._client_refresh_time = datetime(year=2000, month=1, day=1) # an expired time
super().__init__()
def get_api_url(self):
return "https://www.bilibili.com/"

async def _init_session(self):
res = await self.default_http_client.get("https://www.bilibili.com/")
if res.status_code != 200:
logger.warning("unable to refresh temp cookie")
else:
self._client_refresh_time = datetime.now()

async def _refresh_client(self):
if datetime.now() - self._client_refresh_time > self.cookie_expire_time:
await self._init_session()

async def get_client(self, target: Target) -> AsyncClient:
await self._refresh_client()
return await super().get_client(target)
class BililiveSchedConf(BaseSchedConf):
name = "live.bilibili.com"
schedule_setting = {"seconds": 3}

async def get_query_name_client(self) -> AsyncClient:
await self._refresh_client()
return await super().get_query_name_client()
def get_api_url(self):
return "https://live.bilibili.com/"


class Bilibili(NewMessage):
Expand Down
26 changes: 26 additions & 0 deletions tests/platforms/test_bilibili_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,32 @@ def dummy_only_open_user_subinfo(app: App):
return UserSubInfo(user=user, categories=[1], tags=[])


@pytest.mark.asyncio
async def test_http_client_equal(app: App):
from nonebot_bison.types import Target
from nonebot_bison.utils import ProcessContext
from nonebot_bison.platform import platform_manager

empty_target = Target("0")

bilibili = platform_manager["bilibili"](ProcessContext(), AsyncClient())
bilibili_live = platform_manager["bilibili-live"](ProcessContext(), AsyncClient())

bilibili_scheduler = bilibili.scheduler()
bilibili_live_scheduler = bilibili_live.scheduler()

await bilibili_scheduler._init_session() # type: ignore
await bilibili_live_scheduler._init_session() # type: ignore

assert bilibili_scheduler.default_http_client == bilibili_live_scheduler.default_http_client

assert await bilibili_scheduler.get_client(empty_target) == await bilibili_live_scheduler.get_client(empty_target)
assert await bilibili_live_scheduler.get_client(empty_target) == bilibili_live_scheduler.default_http_client

assert await bilibili_scheduler.get_query_name_client() == await bilibili_live_scheduler.get_query_name_client()
assert await bilibili_scheduler.get_query_name_client() == bilibili_live_scheduler.default_http_client


@pytest.mark.asyncio
@respx.mock
async def test_fetch_bililive_no_room(bili_live, dummy_only_open_user_subinfo):
Expand Down

0 comments on commit 24aa461

Please sign in to comment.