diff --git a/searx/engines/bilibili.py b/searx/engines/bilibili.py index 3fd613b9c..9168bf733 100644 --- a/searx/engines/bilibili.py +++ b/searx/engines/bilibili.py @@ -8,6 +8,7 @@ import random import string from urllib.parse import urlencode from datetime import datetime, timedelta +from zoneinfo import ZoneInfo from searx import utils @@ -39,6 +40,32 @@ cookie = { "home_feed_column": "4", } +_CN_TZ = ZoneInfo("Asia/Shanghai") + +# Calendar-day time filter (Asia/Shanghai); dict values are days to subtract from today. +time_range_support = True +time_range_dict = {"day": 0, "week": 6, "month": 29, "year": 364} + + +def _pubtime_range(time_range: str) -> tuple[int, int]: + """Return ``(pubtime_begin_s, pubtime_end_s)`` for Bilibili's search API. + + Time ranges follow Bilibili's website semantics: they are counted in + **calendar days** in China Standard Time (``Asia/Shanghai``), not as + sliding 24-hour windows. For example, ``day`` means from 00:00:00 to + 23:59:59 of the current local day; ``week`` spans from 00:00:00 on the + calendar day six days ago through the end of today, and so on. + + The returned Unix timestamps (seconds) map to Bilibili's + ``pubtime_begin_s`` and ``pubtime_end_s`` query parameters. + """ + now = datetime.now(_CN_TZ) + pubtime_end_s = int(now.replace(hour=23, minute=59, second=59, microsecond=0).timestamp()) + begin_day = now - timedelta(days=time_range_dict[time_range]) + pubtime_begin_s = int(begin_day.replace(hour=0, minute=0, second=0, microsecond=0).timestamp()) + + return pubtime_begin_s, pubtime_end_s + def request(query, params): query_params = { @@ -50,6 +77,11 @@ def request(query, params): "search_type": "video", } + if params.get("time_range") in time_range_dict: + pubtime_begin_s, pubtime_end_s = _pubtime_range(params["time_range"]) + query_params["pubtime_begin_s"] = pubtime_begin_s + query_params["pubtime_end_s"] = pubtime_end_s + params["url"] = f"{base_url}?{urlencode(query_params)}" params["headers"]["Referer"] = "https://www.bilibili.com/" params["headers"]["Accept"] = "application/json, text/javascript, */*; q=0.01"