nonebot-plugin-bugu 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nonebot_plugin_bugu/__init__.py +31 -0
- nonebot_plugin_bugu/api.py +282 -0
- nonebot_plugin_bugu/collection.py +166 -0
- nonebot_plugin_bugu/commands.py +234 -0
- nonebot_plugin_bugu/config.py +91 -0
- nonebot_plugin_bugu/draw.py +406 -0
- nonebot_plugin_bugu/features/__init__.py +0 -0
- nonebot_plugin_bugu/features/collection.py +247 -0
- nonebot_plugin_bugu/features/common.py +100 -0
- nonebot_plugin_bugu/features/flowers/__init__.py +0 -0
- nonebot_plugin_bugu/features/flowers/data.py +167 -0
- nonebot_plugin_bugu/features/flowers/render.py +300 -0
- nonebot_plugin_bugu/features/flowers/reply.py +123 -0
- nonebot_plugin_bugu/features/neighbors/__init__.py +0 -0
- nonebot_plugin_bugu/features/neighbors/data.py +143 -0
- nonebot_plugin_bugu/features/neighbors/render.py +225 -0
- nonebot_plugin_bugu/features/neighbors/reply.py +149 -0
- nonebot_plugin_bugu/features/recipes/__init__.py +0 -0
- nonebot_plugin_bugu/features/recipes/data.py +313 -0
- nonebot_plugin_bugu/features/recipes/render.py +371 -0
- nonebot_plugin_bugu/features/recipes/reply.py +219 -0
- nonebot_plugin_bugu/features/recipes/search.py +151 -0
- nonebot_plugin_bugu/features/starsea/__init__.py +0 -0
- nonebot_plugin_bugu/features/starsea/data.py +267 -0
- nonebot_plugin_bugu/features/starsea/render.py +579 -0
- nonebot_plugin_bugu/features/starsea/reply.py +356 -0
- nonebot_plugin_bugu/features/starsea/search.py +271 -0
- nonebot_plugin_bugu/fonts.py +152 -0
- nonebot_plugin_bugu/runtime.py +109 -0
- nonebot_plugin_bugu/values.py +87 -0
- nonebot_plugin_bugu-0.2.0.dist-info/METADATA +257 -0
- nonebot_plugin_bugu-0.2.0.dist-info/RECORD +35 -0
- nonebot_plugin_bugu-0.2.0.dist-info/WHEEL +4 -0
- nonebot_plugin_bugu-0.2.0.dist-info/entry_points.txt +3 -0
- nonebot_plugin_bugu-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""布谷工具箱(星布谷地小助手)NoneBot2 插件。"""
|
|
2
|
+
|
|
3
|
+
from nonebot import require
|
|
4
|
+
from nonebot.plugin import PluginMetadata
|
|
5
|
+
|
|
6
|
+
from .config import Config
|
|
7
|
+
|
|
8
|
+
__plugin_meta__ = PluginMetadata(
|
|
9
|
+
name="布谷工具箱",
|
|
10
|
+
description=(
|
|
11
|
+
"星布谷地小助手:菜谱查询、星海地图、友邻备忘、鲜花培育,"
|
|
12
|
+
"外加按 QQ 号记录的收集进度。数据来自布谷工具箱"
|
|
13
|
+
),
|
|
14
|
+
usage=(
|
|
15
|
+
"/布谷 —— 查看全部指令\n"
|
|
16
|
+
"/菜谱 <菜名 / 编号> —— 菜谱卡片;/菜谱查 <食材 / 类型 / 厨具> 搜索\n"
|
|
17
|
+
"/星海 <词> —— 星海智能查询;/星海地图 / /星海点位 / /星海查\n"
|
|
18
|
+
"/友邻 [名字] [喜爱/好感/反感/关于] —— 友邻档案\n"
|
|
19
|
+
"/鲜花 [品种 / 花名] —— 培育配方与花色\n"
|
|
20
|
+
"/收藏 [名字] —— 标记收集进度\n"
|
|
21
|
+
"/布谷刷新 —— 超管:刷新数据并清空图片缓存"
|
|
22
|
+
),
|
|
23
|
+
type="application",
|
|
24
|
+
homepage="https://github.com/TonyLiangP2010405/nonebot-plugin-bugu",
|
|
25
|
+
config=Config,
|
|
26
|
+
supported_adapters={"~onebot.v11"},
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
require("nonebot_plugin_localstore")
|
|
30
|
+
|
|
31
|
+
from . import commands as commands # noqa: E402,F401
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""布谷工具箱接口客户端:拉数据、下图片、做缓存。
|
|
2
|
+
|
|
3
|
+
四个模块共用一套连接池和磁盘图片缓存:
|
|
4
|
+
|
|
5
|
+
* ``/api/bootstrap`` → 菜谱
|
|
6
|
+
* ``/api/starsea`` → 星海地图
|
|
7
|
+
* ``/api/neighbors`` → 友邻备忘
|
|
8
|
+
* ``/api/flowers`` → 鲜花培育
|
|
9
|
+
|
|
10
|
+
数据按 ``bugu_data_cache_ttl`` 缓存在内存;图片按 URL 的 sha1 落盘。
|
|
11
|
+
所有网络异常收敛成 :class:`BuguError`,带可以直接发给用户的中文说明。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
import time
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from .features.flowers.data import FlowerBook, parse_flowers
|
|
26
|
+
from .features.neighbors.data import NeighborBook, parse_neighbors
|
|
27
|
+
from .features.recipes.data import RecipeBook, parse_recipes
|
|
28
|
+
from .features.starsea.data import StarSeaData, parse_starsea
|
|
29
|
+
|
|
30
|
+
DEFAULT_USER_AGENT = (
|
|
31
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
|
32
|
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 nonebot-plugin-bugu"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class BuguError(RuntimeError):
|
|
37
|
+
"""接口 / 渲染过程中可以直接展示给用户的错误。"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, message: str, detail: str = "") -> None:
|
|
40
|
+
super().__init__(message)
|
|
41
|
+
self.message = message
|
|
42
|
+
self.detail = detail
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ImageCache:
|
|
46
|
+
"""按 URL 哈希落盘的图片缓存。"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, root: Path, ttl: int) -> None:
|
|
49
|
+
self.root = Path(root)
|
|
50
|
+
self.ttl = max(0, int(ttl))
|
|
51
|
+
|
|
52
|
+
def path_for(self, url: str) -> Path:
|
|
53
|
+
digest = hashlib.sha1(url.encode("utf-8")).hexdigest()
|
|
54
|
+
suffix = ".png"
|
|
55
|
+
raw_suffix = Path(url.split("?", 1)[0]).suffix.lower()
|
|
56
|
+
if raw_suffix in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:
|
|
57
|
+
suffix = raw_suffix
|
|
58
|
+
return self.root / digest[:2] / f"{digest}{suffix}"
|
|
59
|
+
|
|
60
|
+
def read(self, url: str, *, ignore_ttl: bool = False) -> Optional[bytes]:
|
|
61
|
+
path = self.path_for(url)
|
|
62
|
+
try:
|
|
63
|
+
stat = path.stat()
|
|
64
|
+
except OSError:
|
|
65
|
+
return None
|
|
66
|
+
if not ignore_ttl and self.ttl and time.time() - stat.st_mtime > self.ttl:
|
|
67
|
+
return None
|
|
68
|
+
try:
|
|
69
|
+
return path.read_bytes()
|
|
70
|
+
except OSError:
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
def write(self, url: str, data: bytes) -> None:
|
|
74
|
+
path = self.path_for(url)
|
|
75
|
+
try:
|
|
76
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
78
|
+
tmp.write_bytes(data)
|
|
79
|
+
tmp.replace(path)
|
|
80
|
+
except OSError:
|
|
81
|
+
# 缓存写失败不影响本次结果,下次重新下载即可
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
def clear(self) -> int:
|
|
85
|
+
"""清空缓存目录,返回删掉的文件数。"""
|
|
86
|
+
removed = 0
|
|
87
|
+
if not self.root.exists():
|
|
88
|
+
return removed
|
|
89
|
+
for path in self.root.rglob("*"):
|
|
90
|
+
if path.is_file():
|
|
91
|
+
try:
|
|
92
|
+
path.unlink()
|
|
93
|
+
removed += 1
|
|
94
|
+
except OSError:
|
|
95
|
+
continue
|
|
96
|
+
return removed
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class BuguClient:
|
|
100
|
+
"""四个模块的数据 + 图片统一入口。"""
|
|
101
|
+
|
|
102
|
+
def __init__(
|
|
103
|
+
self,
|
|
104
|
+
*,
|
|
105
|
+
api_base: str,
|
|
106
|
+
timeout: float = 15.0,
|
|
107
|
+
data_ttl: int = 6 * 60 * 60,
|
|
108
|
+
image_cache: Optional[ImageCache] = None,
|
|
109
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
110
|
+
transport: Optional[httpx.AsyncBaseTransport] = None,
|
|
111
|
+
) -> None:
|
|
112
|
+
self.api_base = api_base.rstrip("/")
|
|
113
|
+
self.timeout = timeout
|
|
114
|
+
self.data_ttl = max(0, int(data_ttl))
|
|
115
|
+
self.image_cache = image_cache
|
|
116
|
+
self.user_agent = user_agent
|
|
117
|
+
self.transport = transport
|
|
118
|
+
|
|
119
|
+
self._client: Optional[httpx.AsyncClient] = None
|
|
120
|
+
# 锁惰性创建:Python 3.9 的 asyncio.Lock 构造时会绑事件循环,
|
|
121
|
+
# 客户端如果在没有运行循环时被创建就麻烦了。
|
|
122
|
+
self._locks: Dict[str, asyncio.Lock] = {}
|
|
123
|
+
self._cache: Dict[str, Tuple[float, Any]] = {}
|
|
124
|
+
|
|
125
|
+
# ------------------------------------------------------------ 生命周期
|
|
126
|
+
|
|
127
|
+
def _lock(self, key: str) -> asyncio.Lock:
|
|
128
|
+
lock = self._locks.get(key)
|
|
129
|
+
if lock is None:
|
|
130
|
+
lock = asyncio.Lock()
|
|
131
|
+
self._locks[key] = lock
|
|
132
|
+
return lock
|
|
133
|
+
|
|
134
|
+
def _http(self) -> httpx.AsyncClient:
|
|
135
|
+
if self._client is None or self._client.is_closed:
|
|
136
|
+
self._client = httpx.AsyncClient(
|
|
137
|
+
timeout=self.timeout,
|
|
138
|
+
transport=self.transport,
|
|
139
|
+
follow_redirects=True,
|
|
140
|
+
headers={
|
|
141
|
+
"User-Agent": self.user_agent,
|
|
142
|
+
"Referer": self.api_base + "/",
|
|
143
|
+
"Accept": "application/json,image/*,*/*",
|
|
144
|
+
},
|
|
145
|
+
)
|
|
146
|
+
return self._client
|
|
147
|
+
|
|
148
|
+
async def aclose(self) -> None:
|
|
149
|
+
if self._client is not None and not self._client.is_closed:
|
|
150
|
+
await self._client.aclose()
|
|
151
|
+
self._client = None
|
|
152
|
+
|
|
153
|
+
def clear_image_cache(self) -> int:
|
|
154
|
+
return self.image_cache.clear() if self.image_cache is not None else 0
|
|
155
|
+
|
|
156
|
+
# ---------------------------------------------------------------- 请求
|
|
157
|
+
|
|
158
|
+
async def _get_bytes(self, url: str) -> bytes:
|
|
159
|
+
last_error: Optional[Exception] = None
|
|
160
|
+
for attempt in range(2):
|
|
161
|
+
try:
|
|
162
|
+
response = await self._http().get(url)
|
|
163
|
+
if response.status_code == 429:
|
|
164
|
+
raise BuguError("布谷工具箱请求太频繁了(HTTP 429),过一会儿再试")
|
|
165
|
+
if response.status_code >= 400:
|
|
166
|
+
raise BuguError(f"布谷工具箱返回了 HTTP {response.status_code}")
|
|
167
|
+
return response.content
|
|
168
|
+
except BuguError:
|
|
169
|
+
raise
|
|
170
|
+
except httpx.TimeoutException as exc:
|
|
171
|
+
last_error = exc
|
|
172
|
+
except httpx.HTTPError as exc:
|
|
173
|
+
last_error = exc
|
|
174
|
+
if attempt == 0:
|
|
175
|
+
await asyncio.sleep(0.6)
|
|
176
|
+
raise BuguError("连不上布谷工具箱(网络超时或站点不可达)", detail=str(last_error or ""))
|
|
177
|
+
|
|
178
|
+
async def _get_json(self, path: str) -> Any:
|
|
179
|
+
raw = await self._get_bytes(f"{self.api_base}{path}")
|
|
180
|
+
try:
|
|
181
|
+
payload = json.loads(raw.decode("utf-8", errors="replace"))
|
|
182
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
183
|
+
raise BuguError("布谷工具箱返回的内容不是合法 JSON", detail=str(exc)) from exc
|
|
184
|
+
if isinstance(payload, dict) and payload.get("error"):
|
|
185
|
+
raise BuguError(f"布谷工具箱提示:{payload['error']}")
|
|
186
|
+
return payload
|
|
187
|
+
|
|
188
|
+
async def _cached(
|
|
189
|
+
self,
|
|
190
|
+
key: str,
|
|
191
|
+
path: str,
|
|
192
|
+
parser: Callable[[Dict[str, Any], str], Any],
|
|
193
|
+
*,
|
|
194
|
+
force: bool = False,
|
|
195
|
+
) -> Any:
|
|
196
|
+
now = time.monotonic()
|
|
197
|
+
entry = self._cache.get(key)
|
|
198
|
+
if not force and entry is not None and now - entry[0] < self.data_ttl:
|
|
199
|
+
return entry[1]
|
|
200
|
+
|
|
201
|
+
async with self._lock(f"data:{key}"):
|
|
202
|
+
entry = self._cache.get(key)
|
|
203
|
+
now = time.monotonic()
|
|
204
|
+
if not force and entry is not None and now - entry[0] < self.data_ttl:
|
|
205
|
+
return entry[1]
|
|
206
|
+
payload = await self._get_json(path)
|
|
207
|
+
try:
|
|
208
|
+
value = parser(payload, self.api_base)
|
|
209
|
+
except ValueError as exc:
|
|
210
|
+
raise BuguError(f"布谷工具箱的数据解析失败:{exc}") from exc
|
|
211
|
+
self._cache[key] = (time.monotonic(), value)
|
|
212
|
+
return value
|
|
213
|
+
|
|
214
|
+
# ---------------------------------------------------------------- 数据
|
|
215
|
+
|
|
216
|
+
async def get_starsea(self, *, force: bool = False) -> StarSeaData:
|
|
217
|
+
return await self._cached("starsea", "/api/starsea", parse_starsea, force=force)
|
|
218
|
+
|
|
219
|
+
async def get_recipes(self, *, force: bool = False) -> RecipeBook:
|
|
220
|
+
return await self._cached("recipes", "/api/bootstrap", parse_recipes, force=force)
|
|
221
|
+
|
|
222
|
+
async def get_neighbors(self, *, force: bool = False) -> NeighborBook:
|
|
223
|
+
return await self._cached("neighbors", "/api/neighbors", parse_neighbors, force=force)
|
|
224
|
+
|
|
225
|
+
async def get_flowers(self, *, force: bool = False) -> FlowerBook:
|
|
226
|
+
return await self._cached("flowers", "/api/flowers", parse_flowers, force=force)
|
|
227
|
+
|
|
228
|
+
async def preload_all(self, *, force: bool = False) -> Dict[str, Any]:
|
|
229
|
+
"""一次把四套数据都拉一遍(超管刷新用)。"""
|
|
230
|
+
stars, recipes, neighbors, flowers = await asyncio.gather(
|
|
231
|
+
self.get_starsea(force=force),
|
|
232
|
+
self.get_recipes(force=force),
|
|
233
|
+
self.get_neighbors(force=force),
|
|
234
|
+
self.get_flowers(force=force),
|
|
235
|
+
)
|
|
236
|
+
return {
|
|
237
|
+
"starsea": stars,
|
|
238
|
+
"recipes": recipes,
|
|
239
|
+
"neighbors": neighbors,
|
|
240
|
+
"flowers": flowers,
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
# ---------------------------------------------------------------- 图片
|
|
244
|
+
|
|
245
|
+
async def get_image(self, url: str) -> Optional[bytes]:
|
|
246
|
+
"""取一张图片,优先磁盘缓存;失败返回 ``None``(渲染端会画占位)。"""
|
|
247
|
+
if not url:
|
|
248
|
+
return None
|
|
249
|
+
cache = self.image_cache
|
|
250
|
+
if cache is not None:
|
|
251
|
+
cached = cache.read(url)
|
|
252
|
+
if cached is not None:
|
|
253
|
+
return cached
|
|
254
|
+
|
|
255
|
+
async with self._lock(f"image:{url}"):
|
|
256
|
+
if cache is not None:
|
|
257
|
+
cached = cache.read(url)
|
|
258
|
+
if cached is not None:
|
|
259
|
+
return cached
|
|
260
|
+
try:
|
|
261
|
+
data = await self._get_bytes(url)
|
|
262
|
+
except BuguError:
|
|
263
|
+
return None
|
|
264
|
+
if not data:
|
|
265
|
+
return None
|
|
266
|
+
if cache is not None:
|
|
267
|
+
cache.write(url, data)
|
|
268
|
+
return data
|
|
269
|
+
|
|
270
|
+
async def get_images(self, urls, *, concurrency: int = 8) -> Dict[str, Optional[bytes]]:
|
|
271
|
+
"""并发下载一组图片(``{url: bytes|None}``)。"""
|
|
272
|
+
unique = [url for url in dict.fromkeys(urls) if url]
|
|
273
|
+
if not unique:
|
|
274
|
+
return {}
|
|
275
|
+
semaphore = asyncio.Semaphore(max(1, concurrency))
|
|
276
|
+
|
|
277
|
+
async def worker(url: str) -> Tuple[str, Optional[bytes]]:
|
|
278
|
+
async with semaphore:
|
|
279
|
+
return url, await self.get_image(url)
|
|
280
|
+
|
|
281
|
+
results = await asyncio.gather(*(worker(url) for url in unique))
|
|
282
|
+
return dict(results)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""收集进度(本地)。
|
|
2
|
+
|
|
3
|
+
站点自己的「我已获得 / 我已解锁」进度要邮箱 + 密码登录才能同步。
|
|
4
|
+
在 bot 里保存用户的站点密码是不合适的,所以这里做一份**本机进度**:
|
|
5
|
+
按 QQ 号分开,存在 localstore 的 data 目录里,和站点账号互不影响。
|
|
6
|
+
|
|
7
|
+
进度分三类:
|
|
8
|
+
|
|
9
|
+
* ``starsea`` —— 星海物种,key 是物种 id
|
|
10
|
+
* ``flower`` —— 鲜花,key 是花名
|
|
11
|
+
* ``recipe`` —— 菜谱,key 是菜谱编号
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import json
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Dict, Optional, Set
|
|
20
|
+
|
|
21
|
+
from nonebot.log import logger
|
|
22
|
+
|
|
23
|
+
KIND_STARSEA = "starsea"
|
|
24
|
+
KIND_FLOWER = "flower"
|
|
25
|
+
KIND_RECIPE = "recipe"
|
|
26
|
+
KINDS = (KIND_STARSEA, KIND_FLOWER, KIND_RECIPE)
|
|
27
|
+
|
|
28
|
+
KIND_LABELS = {
|
|
29
|
+
KIND_STARSEA: "星海物种",
|
|
30
|
+
KIND_FLOWER: "鲜花",
|
|
31
|
+
KIND_RECIPE: "菜谱",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CollectionStore:
|
|
36
|
+
"""按用户保存的收集进度,进程内缓存 + 原子落盘。"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, path: Optional[Path]) -> None:
|
|
39
|
+
self.path = Path(path) if path is not None else None
|
|
40
|
+
self._data: Dict[str, Dict[str, Set[str]]] = {}
|
|
41
|
+
self._loaded = False
|
|
42
|
+
self._lock: Optional[asyncio.Lock] = None
|
|
43
|
+
|
|
44
|
+
# ------------------------------------------------------------ 读写
|
|
45
|
+
|
|
46
|
+
def _guard(self) -> asyncio.Lock:
|
|
47
|
+
if self._lock is None:
|
|
48
|
+
self._lock = asyncio.Lock()
|
|
49
|
+
return self._lock
|
|
50
|
+
|
|
51
|
+
async def ensure_loaded(self) -> None:
|
|
52
|
+
if self._loaded:
|
|
53
|
+
return
|
|
54
|
+
async with self._guard():
|
|
55
|
+
if self._loaded:
|
|
56
|
+
return
|
|
57
|
+
self._load()
|
|
58
|
+
self._loaded = True
|
|
59
|
+
|
|
60
|
+
def _load(self) -> None:
|
|
61
|
+
if self.path is None or not self.path.exists():
|
|
62
|
+
return
|
|
63
|
+
try:
|
|
64
|
+
raw = json.loads(self.path.read_text(encoding="utf-8"))
|
|
65
|
+
except (OSError, ValueError) as exc:
|
|
66
|
+
logger.warning(f"布谷收集进度文件读取失败,先当作空进度:{exc}")
|
|
67
|
+
return
|
|
68
|
+
users = raw.get("users") if isinstance(raw, dict) else None
|
|
69
|
+
if not isinstance(users, dict):
|
|
70
|
+
return
|
|
71
|
+
for user_id, kinds in users.items():
|
|
72
|
+
if not isinstance(kinds, dict):
|
|
73
|
+
continue
|
|
74
|
+
bucket: Dict[str, Set[str]] = {kind: set() for kind in KINDS}
|
|
75
|
+
for kind in KINDS:
|
|
76
|
+
values = kinds.get(kind)
|
|
77
|
+
if isinstance(values, list):
|
|
78
|
+
bucket[kind] = {str(value) for value in values}
|
|
79
|
+
self._data[str(user_id)] = bucket
|
|
80
|
+
|
|
81
|
+
def _serialize(self) -> str:
|
|
82
|
+
payload = {
|
|
83
|
+
"version": 1,
|
|
84
|
+
"users": {
|
|
85
|
+
user_id: {kind: sorted(bucket[kind]) for kind in KINDS}
|
|
86
|
+
for user_id, bucket in self._data.items()
|
|
87
|
+
},
|
|
88
|
+
}
|
|
89
|
+
return json.dumps(payload, ensure_ascii=False, indent=1)
|
|
90
|
+
|
|
91
|
+
def _save(self) -> None:
|
|
92
|
+
if self.path is None:
|
|
93
|
+
return
|
|
94
|
+
try:
|
|
95
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
96
|
+
tmp = self.path.with_suffix(self.path.suffix + ".tmp")
|
|
97
|
+
tmp.write_text(self._serialize(), encoding="utf-8")
|
|
98
|
+
tmp.replace(self.path)
|
|
99
|
+
except OSError as exc:
|
|
100
|
+
logger.warning(f"布谷收集进度写入失败(本次仅内存生效):{exc}")
|
|
101
|
+
|
|
102
|
+
def _bucket(self, user_id: str, *, create: bool = False) -> Optional[Dict[str, Set[str]]]:
|
|
103
|
+
bucket = self._data.get(str(user_id))
|
|
104
|
+
if bucket is None and create:
|
|
105
|
+
bucket = {kind: set() for kind in KINDS}
|
|
106
|
+
self._data[str(user_id)] = bucket
|
|
107
|
+
return bucket
|
|
108
|
+
|
|
109
|
+
# ------------------------------------------------------------ 查询
|
|
110
|
+
|
|
111
|
+
def items(self, user_id: str, kind: str) -> Set[str]:
|
|
112
|
+
bucket = self._bucket(user_id)
|
|
113
|
+
return set(bucket.get(kind, set())) if bucket else set()
|
|
114
|
+
|
|
115
|
+
def has(self, user_id: str, kind: str, key) -> bool:
|
|
116
|
+
return str(key) in self.items(user_id, kind)
|
|
117
|
+
|
|
118
|
+
def stats(self, user_id: str) -> Dict[str, int]:
|
|
119
|
+
return {kind: len(self.items(user_id, kind)) for kind in KINDS}
|
|
120
|
+
|
|
121
|
+
def total(self, user_id: str) -> int:
|
|
122
|
+
return sum(self.stats(user_id).values())
|
|
123
|
+
|
|
124
|
+
# ------------------------------------------------------------ 修改
|
|
125
|
+
|
|
126
|
+
async def set(self, user_id: str, kind: str, key, value: bool) -> bool:
|
|
127
|
+
await self.ensure_loaded()
|
|
128
|
+
async with self._guard():
|
|
129
|
+
bucket = self._bucket(user_id, create=True)
|
|
130
|
+
assert bucket is not None
|
|
131
|
+
if value:
|
|
132
|
+
bucket[kind].add(str(key))
|
|
133
|
+
else:
|
|
134
|
+
bucket[kind].discard(str(key))
|
|
135
|
+
self._save()
|
|
136
|
+
return value
|
|
137
|
+
|
|
138
|
+
async def toggle(self, user_id: str, kind: str, key) -> bool:
|
|
139
|
+
"""返回切换后的状态(True = 已收集)。"""
|
|
140
|
+
await self.ensure_loaded()
|
|
141
|
+
async with self._guard():
|
|
142
|
+
bucket = self._bucket(user_id, create=True)
|
|
143
|
+
assert bucket is not None
|
|
144
|
+
text = str(key)
|
|
145
|
+
if text in bucket[kind]:
|
|
146
|
+
bucket[kind].discard(text)
|
|
147
|
+
new_value = False
|
|
148
|
+
else:
|
|
149
|
+
bucket[kind].add(text)
|
|
150
|
+
new_value = True
|
|
151
|
+
self._save()
|
|
152
|
+
return new_value
|
|
153
|
+
|
|
154
|
+
async def clear(self, user_id: str, kind: Optional[str] = None) -> int:
|
|
155
|
+
"""清空某类(或全部)进度,返回清掉的条数。"""
|
|
156
|
+
await self.ensure_loaded()
|
|
157
|
+
async with self._guard():
|
|
158
|
+
bucket = self._bucket(user_id)
|
|
159
|
+
if bucket is None:
|
|
160
|
+
return 0
|
|
161
|
+
kinds = [kind] if kind in KINDS else list(KINDS)
|
|
162
|
+
removed = sum(len(bucket[kind_name]) for kind_name in kinds)
|
|
163
|
+
for kind_name in kinds:
|
|
164
|
+
bucket[kind_name].clear()
|
|
165
|
+
self._save()
|
|
166
|
+
return removed
|