Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
7943 lines (7371 loc) · 356 KB
/
Copy pathmain.py
File metadata and controls
7943 lines (7371 loc) · 356 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import base64
import tempfile
import asyncio
import re
import json
import random
import shutil
import zipfile
from difflib import SequenceMatcher
from datetime import datetime, timedelta, timezone
from typing import Dict, Any, List, Callable, Awaitable
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import httpx
from astrbot.api import logger
from astrbot.api.event import filter, AstrMessageEvent, MessageChain
from astrbot.api.star import Context, Star, register, StarTools
from astrbot.core import AstrBotConfig
from astrbot.core.message.components import Plain, Image
from .core.client import RocomClient
from .core.user import (
UserManager,
MerchantSubscriptionManager,
HomeSubscriptionManager,
AnnouncementSubscriptionManager,
)
from .core.render import Renderer
from .core.egg_service import EggService, SearchResult
from .core.font_assets import FontAssetManager
from .core.ranking_service import build_ranking_render_data, build_ranking_text
from .core.share_code_service import (
build_share_code_render_data,
build_share_code_text,
extract_share_code,
)
from .core.wiki_catalog import (
WIKI_CATALOG_ROUTES_BY_ALIAS,
WIKI_CATALOG_ROUTES_BY_KEY,
)
@register("astrbot_plugin_rocom", "bvzrays & 熵增项目组", "洛克王国插件", "v4.3.0", "https://github.com/Entropy-Increase-Team/astrbot_plugin_rocom")
class RocomPlugin(Star):
_BACKGROUND_REGISTRY_KEY = "_astrbot_plugin_rocom_background_tasks"
def __init__(self, context: Context, config: AstrBotConfig = None):
super().__init__(context)
self._instance_id = f"{id(self):x}"
self.config = config or {}
self.merchant_group_admin_enabled = bool(
self.config.get("merchant_group_admin_enabled", True)
)
self.merchant_bot_admin_enabled = bool(
self.config.get("merchant_bot_admin_enabled", True)
)
self._install_qq_official_role_compat()
base_url = self.config.get("api_base_url", "https://wegame.shallow.ink")
wegame_api_key = self.config.get("wegame_api_key", "")
self.client = RocomClient(
base_url=base_url,
wegame_api_key=wegame_api_key,
)
self._wiki_catalogs_cache: Dict[str, Any] | None = None
self._wiki_catalogs_cache_ts = 0.0
self._wiki_options_cache: Dict[str, Any] | None = None
self._wiki_options_cache_ts = 0.0
self._wiki_skill_detail_cache: Dict[str, Dict[str, Any]] = {}
self._wiki_pet_size_cache: Dict[str, Dict[str, Any]] = {}
data_dir = str(StarTools.get_data_dir())
self.data_dir = data_dir
self.atlas_dir = os.path.join(data_dir, "rocom_atlas")
self.user_mgr = UserManager(data_dir)
self.merchant_sub_mgr = MerchantSubscriptionManager(data_dir)
self.home_sub_mgr = HomeSubscriptionManager(data_dir)
self.announcement_sub_mgr = AnnouncementSubscriptionManager(data_dir)
render_timeout = self.config.get("render_timeout", 30000)
self.low_bandwidth_mode = bool(self.config.get("low_bandwidth_mode", False))
self.help_prefix_display = str(self.config.get("help_prefix_display", "") or "")
# res_path point to astrbot_plugin_rocom directory
res_path = os.path.abspath(os.path.dirname(__file__))
self.font_asset_manager = FontAssetManager(res_path=res_path, data_dir=data_dir)
self.font_paths: Dict[str, str] = {}
self._font_prepare_task: asyncio.Task | None = None
self.renderer = Renderer(
res_path=res_path,
render_timeout=render_timeout,
font_paths=self.font_paths,
prepare_fonts=self._ensure_fonts_ready,
)
self.home_plant_map = self._load_home_plant_map(res_path)
# 自动刷新配置
self.auto_refresh_enabled = self.config.get("auto_refresh_enabled", False)
self.auto_refresh_time = self.config.get("auto_refresh_time", ["00:00", "12:00"])
self.auto_refresh_notify_group = self.config.get("auto_refresh_notify_group", "")
self._auto_refresh_task = None
# 初始化查蛋模块(数据自包含在 render/searcheggs/ 下)
searcheggs_dir = os.path.join(res_path, "render", "searcheggs")
self.egg_searcher = EggService(searcheggs_dir)
self.merchant_subscription_enabled = self.config.get(
"merchant_subscription_enabled", True
)
self.merchant_subscription_items = self.config.get(
"merchant_subscription_items", ["国王球", "棱镜球", "炫彩精灵蛋"]
)
self.merchant_private_subscription_enabled = self.config.get(
"merchant_private_subscription_enabled", True
)
self.merchant_all_day_once_enabled = bool(
self.config.get("merchant_all_day_once_enabled", False)
)
self.merchant_timezone_name = str(
self.config.get("merchant_timezone", "Asia/Shanghai") or "Asia/Shanghai"
).strip()
(
self._merchant_timezone,
self.merchant_timezone_label,
) = self._resolve_merchant_timezone(self.merchant_timezone_name)
self._merchant_subscription_task = None
self._merchant_retry_delay_seconds = 240
self._merchant_retry_times = 3
self._merchant_jitter_seconds = 30
self.home_subscription_enabled = self.config.get(
"home_subscription_enabled", True
)
try:
self.home_subscription_interval_minutes = int(
self.config.get("home_subscription_interval_minutes", 5) or 5
)
except (TypeError, ValueError):
self.home_subscription_interval_minutes = 5
self._home_subscription_task = None
self.announcement_subscription_enabled = self.config.get(
"announcement_subscription_enabled", True
)
try:
self.announcement_poll_interval_minutes = int(
self.config.get("announcement_poll_interval_minutes", 10) or 10
)
except (TypeError, ValueError):
self.announcement_poll_interval_minutes = 10
self._announcement_subscription_task = None
# 启动时检查是否需要开启自动刷新
logger.info(f"[Rocom] 插件初始化完成,自动刷新启用状态:{self.auto_refresh_enabled}, 刷新时间:{self.auto_refresh_time}, 通知群:{self.auto_refresh_notify_group}")
self._cancel_stale_background_tasks()
if self.auto_refresh_enabled:
self._auto_refresh_task = self._register_background_task(
"auto_refresh",
self._auto_refresh_loop(),
)
logger.info("[Rocom] 自动刷新任务已启动")
else:
logger.info("[Rocom] 自动刷新功能未启用")
if self.merchant_subscription_enabled:
self._merchant_subscription_task = self._register_background_task(
"merchant_subscription",
self._merchant_subscription_loop(),
)
if self.home_subscription_enabled:
self._home_subscription_task = self._register_background_task(
"home_subscription",
self._home_subscription_loop(),
)
if self.announcement_subscription_enabled:
self._announcement_subscription_task = self._register_background_task(
"announcement_subscription",
self._announcement_subscription_loop(),
)
def _background_task_registry(self) -> Dict[str, asyncio.Task]:
loop = asyncio.get_running_loop()
registry = getattr(loop, self._BACKGROUND_REGISTRY_KEY, None)
if not isinstance(registry, dict):
registry = {}
setattr(loop, self._BACKGROUND_REGISTRY_KEY, registry)
return registry
def _cancel_stale_background_tasks(self):
registry = self._background_task_registry()
for name, task in list(registry.items()):
if task and not task.done():
logger.warning(f"[Rocom] 取消旧后台任务:{name}")
task.cancel()
registry.clear()
def _register_background_task(self, name: str, coro) -> asyncio.Task:
task = asyncio.create_task(
coro,
name=f"rocom:{name}:{self._instance_id}",
)
self._background_task_registry()[name] = task
return task
async def _ensure_fonts_ready(self) -> None:
if self._font_prepare_task is None:
self._font_prepare_task = asyncio.create_task(
self.font_asset_manager.ensure_fonts(),
name=f"rocom:fonts:{self._instance_id}",
)
try:
self.font_paths = await self._font_prepare_task
self.renderer.font_paths = self.font_paths
except asyncio.CancelledError:
raise
except Exception as e:
logger.warning(f"[Rocom Fonts] 字体准备失败,将使用系统字体兜底: {e}")
self.font_paths = {}
self.renderer.font_paths = {}
def _unregister_background_task(self, name: str, task: asyncio.Task | None):
if not task:
return
registry = self._background_task_registry()
if registry.get(name) is task:
registry.pop(name, None)
async def terminate(self):
if self._announcement_subscription_task and not self._announcement_subscription_task.done():
self._announcement_subscription_task.cancel()
try:
await self._announcement_subscription_task
except asyncio.CancelledError:
pass
self._unregister_background_task(
"announcement_subscription",
self._announcement_subscription_task,
)
if self._home_subscription_task and not self._home_subscription_task.done():
self._home_subscription_task.cancel()
try:
await self._home_subscription_task
except asyncio.CancelledError:
pass
self._unregister_background_task(
"home_subscription",
self._home_subscription_task,
)
if self._merchant_subscription_task and not self._merchant_subscription_task.done():
self._merchant_subscription_task.cancel()
try:
await self._merchant_subscription_task
except asyncio.CancelledError:
pass
self._unregister_background_task(
"merchant_subscription",
self._merchant_subscription_task,
)
if self._auto_refresh_task and not self._auto_refresh_task.done():
self._auto_refresh_task.cancel()
try:
await self._auto_refresh_task
except asyncio.CancelledError:
pass
self._unregister_background_task("auto_refresh", self._auto_refresh_task)
await self.client.close()
await self.renderer.close()
if self._font_prepare_task and not self._font_prepare_task.done():
self._font_prepare_task.cancel()
try:
await self._font_prepare_task
except asyncio.CancelledError:
pass
async def _send_and_get_msg_id(self, event: AstrMessageEvent, obmsg: list):
"""发送消息并获取 ID 以支持撤回"""
try:
if event.get_platform_name() == "aiocqhttp":
from astrbot.core.platform.sources.aiocqhttp.aiocqhttp_message_event import AiocqhttpMessageEvent
if isinstance(event, AiocqhttpMessageEvent):
client = event.bot
group_id = event.get_group_id()
if group_id:
res = await client.send_group_msg(group_id=int(group_id), message=obmsg)
else:
res = await client.send_private_msg(user_id=int(event.get_sender_id()), message=obmsg)
if res:
return client, int(res.get("message_id"))
except Exception as e:
logger.warning(f"获取消息 ID 失败: {e}")
return None, None
def _schedule_recall(self, client, message_id: int, delay: float):
async def _do_recall():
await asyncio.sleep(delay)
try:
await client.delete_msg(message_id=message_id)
except Exception:
pass
return asyncio.create_task(_do_recall())
async def _get_primary_token(self, event: AstrMessageEvent) -> str:
user_id = event.get_sender_id()
logger.debug(f"[Rocom] 获取主账号 Token,user_id: {user_id}")
binding = await self.user_mgr.get_primary_binding(user_id)
if not binding:
logger.warning(f"[Rocom] 用户 {user_id} 未绑定账号")
return ""
fw_token = binding.get("framework_token", "")
logger.debug(f"[Rocom] 用户 {user_id} 的主账号 Token: {fw_token[:8]}...")
return fw_token
async def _resolve_ingame_identity(
self, event: AstrMessageEvent, uid: str = ""
) -> tuple[str, str, str]:
uid = str(uid or "").strip()
user_identifier = self._get_user_identifier(event)
if uid:
return uid, "", user_identifier
binding = await self.user_mgr.get_primary_binding(event.get_sender_id())
if not binding:
return "", "", user_identifier
return (
str(binding.get("role_id", "") or ""),
str(binding.get("framework_token", "") or ""),
user_identifier,
)
async def _auto_refresh_loop(self):
"""自动刷新循环任务(非必要不要使用)"""
logger.info("[自动刷新] 任务已启动")
# 记录上次刷新的时间点,避免同一分钟内重复刷新
last_refresh_minute = None
while True:
try:
now = datetime.now()
current_time = f"{now.hour:02d}:{now.minute:02d}"
current_minute_ts = int(now.timestamp()) // 60 # 当前分钟的 timestamp
# 调试:每分钟记录一次当前时间和配置时间
logger.debug(f"[自动刷新] 当前时间:{current_time}, 配置的刷新时间:{self.auto_refresh_time}, 类型:{type(self.auto_refresh_time)}")
# 检查是否到达刷新时间
# 确保 auto_refresh_time 是列表
refresh_times = self.auto_refresh_time if isinstance(self.auto_refresh_time, list) else [self.auto_refresh_time]
# 如果当前时间在刷新时间列表中,并且这一分钟内还没有刷新过
if current_time in refresh_times and last_refresh_minute != current_minute_ts:
logger.info(f"[自动刷新] 检测到刷新时间 {current_time},开始执行...")
await self._do_auto_refresh()
last_refresh_minute = current_minute_ts
logger.info(f"[自动刷新] 刷新任务完成,下次刷新时间:{refresh_times}")
# 每分钟检查一次
await asyncio.sleep(60)
except asyncio.CancelledError:
logger.info("[自动刷新] 任务已取消")
break
except Exception as e:
logger.error(f"[自动刷新] 任务异常:{e}")
await asyncio.sleep(60)
async def _do_auto_refresh(self):
"""执行自动刷新"""
all_users_data = await self.user_mgr.get_all_users_bindings()
total_users = len(all_users_data)
success_count = 0
fail_count = 0
results = []
for user_id, bindings in all_users_data.items():
if not bindings:
continue
for binding in bindings:
binding_id = binding.get("binding_id", "")
if not binding_id:
continue
# 只刷新 QQ 登录的凭证(只有 QQ 扫码支持刷新)
if binding.get("login_type") != "qq":
continue
try:
res = await self.client.refresh_binding(binding_id, user_id)
if res and res.get("framework_token"):
new_token = res["framework_token"]
binding["framework_token"] = new_token
# 更新本地存储
user_bindings = await self.user_mgr.get_user_bindings(user_id)
for i, b in enumerate(user_bindings):
if b.get("binding_id") == binding_id:
user_bindings[i] = binding
break
await self.user_mgr.save_user_bindings(user_id, user_bindings)
success_count += 1
results.append(f"✅ 用户 {user_id} ({binding.get('nickname', '未知')}) 刷新成功")
logger.info(f"[自动刷新] 用户 {user_id} 凭证刷新成功")
else:
fail_count += 1
results.append(f"❌ 用户 {user_id} ({binding.get('nickname', '未知')}) 刷新失败")
logger.warning(f"[自动刷新] 用户 {user_id} 凭证刷新失败")
except Exception as e:
fail_count += 1
results.append(f"❌ 用户 {user_id} ({binding.get('nickname', '未知')}) 异常:{e}")
logger.error(f"[自动刷新] 用户 {user_id} 凭证刷新异常:{e}")
# 发送通知
msg = f"【自动刷新结果】\n时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
msg += f"总用户数:{total_users}\n"
msg += f"成功:{success_count} | 失败:{fail_count}\n\n"
if results:
msg += "\n".join(results[:10]) # 最多显示 10 条
if len(results) > 10:
msg += f"\n... 还有 {len(results) - 10} 条结果"
# 发送到指定群
if self.auto_refresh_notify_group and success_count > 0 or fail_count > 0:
try:
from astrbot.core.platform.sources.aiocqhttp.aiocqhttp_message_event import AiocqhttpMessageEvent
# 创建一个假 event 用于发送消息
await self._send_notify_to_group(msg)
except Exception as e:
logger.error(f"[自动刷新] 发送通知失败:{e}")
logger.info(f"[自动刷新] 执行完成:成功{success_count},失败{fail_count}")
@filter.command("洛克刷新所有凭证")
async def rocom_refresh_all(self, event: AstrMessageEvent):
"""刷新所有用户的凭证(需要 bot 管理员权限,同时非必要不要使用)"""
# 检查 bot 管理员权限
if not self._is_bot_admin(event):
yield event.plain_result("⚠️ 此指令仅限 bot 管理员使用。")
return
yield event.plain_result("⚠️ 非必要不要手动刷新凭证,服务端会自动刷新。本指令仅用于调试或强制兜底。\n\n正在刷新所有用户的凭证...")
all_users_data = await self.user_mgr.get_all_users_bindings()
total_users = len(all_users_data)
success_count = 0
fail_count = 0
skipped_count = 0
results = []
for user_id, bindings in all_users_data.items():
if not bindings:
continue
for binding in bindings:
binding_id = binding.get("binding_id", "")
if not binding_id:
continue
# 只刷新 QQ 登录的凭证(只有 QQ 扫码支持刷新)
login_type = binding.get("login_type", "")
if login_type != "qq":
skipped_count += 1
continue
try:
res = await self.client.refresh_binding(binding_id, user_id)
if res and res.get("framework_token"):
new_token = res["framework_token"]
binding["framework_token"] = new_token
# 更新本地存储
user_bindings = await self.user_mgr.get_user_bindings(user_id)
for i, b in enumerate(user_bindings):
if b.get("binding_id") == binding_id:
user_bindings[i] = binding
break
await self.user_mgr.save_user_bindings(user_id, user_bindings)
success_count += 1
results.append(f"✅ 用户 {user_id} ({binding.get('nickname', '未知')}) 刷新成功")
logger.info(f"[手动刷新所有] 用户 {user_id} 凭证刷新成功")
else:
fail_count += 1
results.append(f"❌ 用户 {user_id} ({binding.get('nickname', '未知')}) 刷新失败")
logger.warning(f"[手动刷新所有] 用户 {user_id} 凭证刷新失败")
except Exception as e:
fail_count += 1
results.append(f"❌ 用户 {user_id} ({binding.get('nickname', '未知')}) 异常:{e}")
logger.error(f"[手动刷新所有] 用户 {user_id} 凭证刷新异常:{e}")
msg = f"【刷新所有凭证完成】\n"
msg += f"总用户数:{total_users}\n"
msg += f"成功:{success_count} | 失败:{fail_count} | 跳过(非 QQ): {skipped_count}\n\n"
if results:
msg += "\n".join(results[:20]) # 最多显示 20 条
if len(results) > 20:
msg += f"\n... 还有 {len(results) - 20} 条结果"
yield event.plain_result(msg)
async def _send_notify_to_group(self, message: str):
"""发送通知到指定群"""
try:
if self.auto_refresh_notify_group:
session_id = self.auto_refresh_notify_group.strip()
# 创建 MessageChain 对象
chain = MessageChain()
chain.chain.append(Plain(message))
# 直接使用用户填写的完整 UMO
await self.context.send_message(
session_id,
chain
)
logger.info(f"[自动刷新] 通知已发送到 {session_id}")
except Exception as e:
logger.error(f"[自动刷新] 发送群消息失败:{e}")
async def _resolve_home_uid(self, event: AstrMessageEvent, uid: str = "") -> str:
uid = str(uid or "").strip()
if uid:
return uid
binding = await self.user_mgr.get_primary_binding(event.get_sender_id())
return str((binding or {}).get("role_id", "") or "")
def _home_subscription_key(self, session_id: str, uid: str, kind: str) -> str:
return f"{session_id}:{uid}:{kind}"
def _normalize_epoch_seconds(self, value: Any) -> int:
try:
ts = int(float(value))
except (TypeError, ValueError):
return 0
if ts > 10_000_000_000_000:
return ts // 1_000_000
if ts > 10_000_000_000:
return ts // 1000
return ts
def _normalize_duration_seconds(self, value: Any) -> int:
try:
seconds = int(float(value))
except (TypeError, ValueError):
return 0
if seconds > 1_000_000_000:
return seconds // 1_000_000
if seconds > 1_000_000:
return seconds // 1000
return seconds
def _format_home_remaining(self, target_ts: int, now_ts: int | None = None) -> str:
if not target_ts:
return "未开始"
now_ts = now_ts or int(time.time())
remain = max(0, int(target_ts) - now_ts)
if remain <= 0:
return "已完成"
hours, remainder = divmod(remain, 3600)
minutes, _ = divmod(remainder, 60)
if hours >= 24:
days, hours = divmod(hours, 24)
return f"{days}天{hours}小时"
if hours > 0:
return f"{hours}小时{minutes}分钟"
return f"{minutes}分钟"
def _home_info_payload(self, res: Dict[str, Any] | None) -> Dict[str, Any]:
payload = res or {}
if isinstance(payload.get("result"), dict) and isinstance(payload["result"].get("home_info"), dict):
return payload["result"]["home_info"]
if isinstance(payload.get("home_info"), dict):
return payload["home_info"]
if isinstance(payload.get("data"), dict):
data = payload["data"]
if isinstance(data.get("result"), dict) and isinstance(data["result"].get("home_info"), dict):
return data["result"]["home_info"]
if isinstance(data.get("home_info"), dict):
return data["home_info"]
return payload if isinstance(payload, dict) else {}
def _home_brief_info(self, home_info: Dict[str, Any]) -> Dict[str, Any]:
return home_info.get("friend_home_brief_info") or home_info.get("home_brief_info") or home_info or {}
def _home_cell_info(self, home_info: Dict[str, Any]) -> Dict[str, Any]:
return home_info.get("friend_cell_home_brief_info") or home_info.get("cell_home_brief_info") or {}
def _home_pet_icon(self, pet_id: Any, icon_url: str = "") -> str:
if icon_url:
return icon_url
try:
asset_id = int(str(pet_id))
except (TypeError, ValueError):
return ""
if asset_id <= 0:
return ""
if asset_id < 3000:
asset_id += 3000
return f"https://game.gtimg.cn/images/rocom/rocodata/jingling/{asset_id}/icon.png"
def _extract_home_pet(self, raw: Dict[str, Any], index: int, guard: bool = False) -> Dict[str, Any] | None:
if not isinstance(raw, dict):
return None
home_pet = raw.get("home_pet_info") if isinstance(raw.get("home_pet_info"), dict) else raw
display = raw.get("display_info") if isinstance(raw.get("display_info"), dict) else {}
pet_id = home_pet.get("pet_cfg_id") or home_pet.get("pet_id") or home_pet.get("pet_base_id") or raw.get("pet_cfg_id") or raw.get("pet_id") or raw.get("id")
if str(pet_id or "0") in {"", "0"} and not guard:
return None
name = home_pet.get("name") or home_pet.get("pet_name") or raw.get("name") or raw.get("pet_name") or f"精灵 {pet_id}"
feed_info = home_pet.get("feed_info") if isinstance(home_pet.get("feed_info"), dict) else {}
begin_time = self._normalize_epoch_seconds(feed_info.get("begin_time"))
time_cost = self._normalize_duration_seconds(feed_info.get("time_cost"))
rip_time = self._normalize_epoch_seconds(home_pet.get("pet_rip_time") or raw.get("pet_rip_time") or raw.get("rip_time"))
if not rip_time and begin_time and time_cost:
rip_time = begin_time + time_cost
now_ts = int(time.time())
has_inspiration = bool(rip_time)
inspire_ready = has_inspiration and now_ts >= rip_time
egg_time = self._normalize_epoch_seconds(
raw.get("predicted_egg_time")
or home_pet.get("predicted_egg_time")
or raw.get("egg_time")
or home_pet.get("egg_time")
)
egg_ready = bool(egg_time and now_ts >= egg_time)
speciality_values = []
for value in (
home_pet.get("real_speciality_ids"),
raw.get("real_speciality_ids"),
home_pet.get("speciality_id"),
raw.get("speciality_id"),
):
if isinstance(value, list):
speciality_values.extend(value)
elif value not in (None, ""):
speciality_values.append(value)
speciality_ids = {str(value).strip() for value in speciality_values if str(value).strip()}
mutation_name = str(display.get("mutation_name") or raw.get("mutation_name") or home_pet.get("mutation_name") or "")
variant_text = ""
if "异色" in mutation_name and "炫彩" in mutation_name:
variant_text = "异色炫彩"
elif "异色" in mutation_name:
variant_text = "异色"
elif "炫彩" in mutation_name:
variant_text = "炫彩"
elif "103" in speciality_ids and "502" in speciality_ids:
variant_text = "异色炫彩"
elif "103" in speciality_ids:
variant_text = "异色"
elif "502" in speciality_ids:
variant_text = "炫彩"
is_shiny = variant_text in {"异色", "异色炫彩"}
status = raw.get("status")
is_guard = guard or bool(raw.get("is_guard") or raw.get("guard")) or str(status).lower() in {"2", "guard", "守卫"}
status_text = "守卫中" if is_guard and not has_inspiration else ("灵感已完成" if inspire_ready else ("灵感收集中" if has_inspiration else "未喂食"))
status_class = "guard" if is_guard and not has_inspiration else ("ready" if inspire_ready else ("progress" if has_inspiration else "idle"))
return {
"id": str(pet_id),
"pos": raw.get("pos") or raw.get("position") or index + 1,
"name": str(name),
"level": display.get("level") or raw.get("level") or home_pet.get("level") or "--",
"iconUrl": self._home_pet_icon(pet_id, raw.get("icon_url") or raw.get("pet_img_url") or raw.get("petIcon") or ""),
"badge": "守" if is_guard else "",
"isShiny": is_shiny,
"variantText": variant_text,
"isGuard": is_guard,
"statusText": status_text,
"statusClass": status_class,
"note": self._format_home_remaining(rip_time, now_ts) if has_inspiration else ("家园守卫位" if is_guard else "暂无灵感倒计时"),
"hasEgg": bool(raw.get("have_egg") or home_pet.get("have_egg")),
"eggReady": egg_ready,
"eggTime": egg_time,
"eggText": ("可能已生蛋" if egg_ready else f"预计生蛋 {self._format_home_remaining(egg_time, now_ts)}") if egg_time else "",
"inspireReady": inspire_ready,
"readyAt": rip_time,
"eventId": f"pet:{raw.get('pos') or index + 1}:{pet_id}:{rip_time}",
}
def _home_pet_sources(self, home_info: Dict[str, Any]) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
cell = self._home_cell_info(home_info)
indoor_sources = []
guard_sources = []
if isinstance(home_info.get("home_pets"), list):
indoor_sources.extend(home_info.get("home_pets") or [])
if isinstance(cell.get("home_pets"), list):
for pet in cell.get("home_pets") or []:
home_pet = pet.get("home_pet_info") if isinstance(pet, dict) and isinstance(pet.get("home_pet_info"), dict) else {}
if str(home_pet.get("pet_cfg_id") or "0") == "0" and (home_pet.get("name") or home_pet.get("pet_name")):
guard_sources.append(pet)
else:
indoor_sources.append(pet)
pet_info = cell.get("home_pet_info") if isinstance(cell.get("home_pet_info"), dict) else {}
if isinstance(pet_info.get("home_pet_list"), list):
indoor_sources.extend(pet_info.get("home_pet_list") or [])
for key in ("guard_pets", "home_guard_pets", "guard_pet_list"):
if isinstance(home_info.get(key), list):
guard_sources.extend(home_info.get(key) or [])
if isinstance(cell.get(key), list):
guard_sources.extend(cell.get(key) or [])
for key in ("guard_pet", "home_guard_pet", "guard_pet_info", "home_guard_pet_info", "defend_pet", "defend_pet_info", "protect_pet", "protect_pet_info"):
if isinstance(home_info.get(key), dict):
guard_sources.append(home_info.get(key))
if isinstance(cell.get(key), dict):
guard_sources.append(cell.get(key))
for key in ("guard_pet_info", "home_guard_pet_info"):
info = cell.get(key) if isinstance(cell.get(key), dict) else home_info.get(key)
if isinstance(info, dict):
for list_key in ("guard_pet_list", "home_guard_pet_list", "pet_list"):
if isinstance(info.get(list_key), list):
guard_sources.extend(info.get(list_key) or [])
return indoor_sources, guard_sources
def _load_home_plant_map(self, res_path: str) -> Dict[str, Any]:
path = os.path.join(res_path, "render", "home", "data", "home_item_list.json")
if not os.path.exists(path):
return {}
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception as e:
logger.warning(f"[Rocom] 加载家园作物映射失败: {e}")
return {}
def _home_plant_icon(self, icon_id: Any) -> str:
if not icon_id:
return ""
icon_text = str(icon_id)
if icon_text.startswith(("http://", "https://", "data:")):
return icon_text
return f"img/home_icon/{icon_text}_2.png"
def _extract_home_plants(self, home_info: Dict[str, Any]) -> List[Dict[str, Any]]:
cell = self._home_cell_info(home_info)
plant_sources = []
if isinstance(home_info.get("home_plants"), list):
plant_sources.extend(home_info.get("home_plants") or [])
plant_info = cell.get("home_plant_info") if isinstance(cell.get("home_plant_info"), dict) else {}
land_list = plant_info.get("home_plant_land_list") if isinstance(plant_info.get("home_plant_land_list"), list) else []
for land in land_list:
if not isinstance(land, dict):
continue
for item in land.get("home_plant_list") or []:
if isinstance(item, dict):
copied = dict(item)
copied.setdefault("land_index", land.get("land_index"))
plant_sources.append(copied)
now_ts = int(time.time())
result = []
for index, raw in enumerate(plant_sources):
plant_data = raw.get("plant_info") if isinstance(raw.get("plant_info"), dict) else raw
plant_id = raw.get("plant_seed_id") or raw.get("plant_cfg_id") or raw.get("plant_id") or plant_data.get("id")
if str(plant_id or "0") in {"", "0"}:
continue
mapped_plant = getattr(self, "home_plant_map", {}).get(str(plant_id), {})
icon_id = (
plant_data.get("icon_url")
or plant_data.get("iconUrl")
or raw.get("icon_url")
or raw.get("iconUrl")
or plant_data.get("iconid")
or raw.get("iconid")
or raw.get("icon_id")
or (mapped_plant.get("iconid") if isinstance(mapped_plant, dict) else "")
)
rip_time = self._normalize_epoch_seconds(raw.get("plant_rip_time") or raw.get("rip_time") or raw.get("end_time"))
left_time = int(raw.get("left_time") or 0)
if not rip_time and left_time > 0:
rip_time = now_ts + left_time
ready = bool(rip_time and now_ts >= rip_time) or (raw.get("status") in {2, "ready", "mature"})
total = int(raw.get("time_cost") or raw.get("total_time") or 0)
if not total and raw.get("plant_tab_id"):
try:
total = int(raw.get("plant_tab_id")) * 21600
except (TypeError, ValueError):
total = 0
progress = int(max(0, min(100, ((total - max(0, rip_time - now_ts)) / total) * 100))) if total and rip_time else (100 if ready else 35)
land_index = raw.get("slot_index") or raw.get("land_index") or index + 1
harvest_num = raw.get("plant_harvest_num")
steal_account = raw.get("plant_steal_account")
can_steal_account = raw.get("plant_can_steal_account")
result.append({
"id": str(plant_id),
"landIndex": land_index,
"plantName": plant_data.get("name") or raw.get("name") or (mapped_plant.get("name") if isinstance(mapped_plant, dict) else "") or f"种子 {plant_id}",
"iconUrl": self._home_plant_icon(icon_id),
"stateType": "ready" if ready else "warning",
"statusText": "已成熟" if ready else "成长中",
"leftTimeText": "可收获" if ready else self._format_home_remaining(rip_time, now_ts),
"progress": progress,
"ready": ready,
"readyAt": rip_time,
"harvestText": f"产量 {harvest_num}" if harvest_num not in (None, "") else "",
"stealText": f"可偷 {steal_account}/{can_steal_account}" if steal_account not in (None, "") and can_steal_account not in (None, "") else "",
"eventId": f"plant:{raw.get('slot_index') or raw.get('land_index') or index}:{plant_id}:{rip_time}",
})
return result
def _build_home_render_data(self, res: Dict[str, Any] | None, uid: str) -> Dict[str, Any]:
home_info = self._home_info_payload(res)
brief = self._home_brief_info(home_info)
indoor_sources, guard_sources = self._home_pet_sources(home_info)
indoor_pets = []
guard_pets = []
for index, raw in enumerate(indoor_sources):
item = self._extract_home_pet(raw, index)
if not item:
continue
if item["isGuard"]:
guard_pets.append(item)
else:
indoor_pets.append(item)
for index, raw in enumerate(guard_sources):
item = self._extract_home_pet(raw, index, guard=True)
if item:
guard_pets.append(item)
garden_plots = self._extract_home_plants(home_info)
home_name = brief.get("home_name") or brief.get("name") or f"{uid} 的小屋"
meta = (res or {}).get("meta") or {}
created_at = self._normalize_epoch_seconds(meta.get("created_at"))
updated_at = datetime.fromtimestamp(created_at, tz=self._cn_tz()).strftime("%Y-%m-%d %H:%M:%S") if created_at else datetime.now(self._cn_tz()).strftime("%Y-%m-%d %H:%M:%S")
return {
"title": "洛克家园",
"subtitle": "Home Information",
"homeName": home_name,
"uid": uid,
"summaryCards": [
{"label": "房间等级", "value": brief.get("room_level", "--")},
{"label": "家园等级", "value": brief.get("home_level", "--")},
{"label": "家园经验", "value": brief.get("home_experience", "--")},
{"label": "舒适度", "value": brief.get("home_comfort_level", "--")},
],
"gardenPlots": garden_plots,
"guardPets": guard_pets,
"indoorPets": indoor_pets,
"gardenCount": len(garden_plots),
"guardCount": len(guard_pets),
"indoorCount": len(indoor_pets),
"guardEmptyText": "后端当前返回中没有守卫精灵字段",
"updatedAt": updated_at,
}
def _pet_data_display(self, value: Any, default: str = "--") -> str:
if value is None or value == "":
return default
if isinstance(value, bool):
return "是" if value else "否"
return str(value)
def _pet_data_image_url(self, pet_id: Any, image_type: str = "image") -> str:
try:
asset_id = int(str(pet_id))
except (TypeError, ValueError):
return ""
if asset_id <= 0:
return ""
if asset_id < 3000:
asset_id += 3000
image_type = "icon" if image_type == "icon" else "image"
return f"https://game.gtimg.cn/images/rocom/rocodata/jingling/{asset_id}/{image_type}.png"
def _pet_data_time_text(self, value: Any) -> str:
ts = self._normalize_epoch_seconds(value)
if not ts:
return "--"
return datetime.fromtimestamp(ts, tz=self._cn_tz()).strftime("%Y-%m-%d %H:%M")
def _pet_data_size_text(self, value: Any, unit: str) -> str:
try:
number = float(value)
except (TypeError, ValueError):
return "--"
if unit == "g":
return f"{number / 1000:.2f} kg"
if unit == "cm":
return f"{number:g} cm"
return f"{number:g} {unit}".strip()
def _pet_data_voice_text(self, value: Any) -> str:
if value in (None, ""):
return "--"
try:
number = float(value)
except (TypeError, ValueError):
return self._pet_data_display(value)
if number.is_integer():
return f"{int(number)} dB"
return f"{number:g} dB"
def _pet_data_voice_hint(self, value: Any) -> str:
try:
number = int(float(value))
except (TypeError, ValueError):
return ""
if 96 <= number <= 100:
return "婉转声 96~100"
if -100 <= number <= -96:
return "粗嗓门 -96~-100"
return "婉转声 96~100 / 粗嗓门 -96~-100"
def _pet_data_voice_info(self, value: Any) -> Dict[str, str]:
text = self._pet_data_voice_text(value)
try:
number = int(float(value))
except (TypeError, ValueError):
return {"value": text, "hint": "", "className": ""}
if 96 <= number <= 100:
return {
"value": f"{text} · 婉转声",
"hint": "婉转声 96~100",
"className": "voice-soft",
}
if -100 <= number <= -96:
return {
"value": f"{text} · 粗嗓门",
"hint": "粗嗓门 -96~-100",
"className": "voice-rough",
}
return {
"value": text,
"hint": "婉转声 96~100 / 粗嗓门 -96~-100",
"className": "",
}
def _pet_data_wiki_pet_id(self, value: Any) -> str:
try:
pet_id = int(str(value))
except (TypeError, ValueError):
return ""
if pet_id <= 0:
return ""
if pet_id < 3000:
pet_id += 3000
return str(pet_id)
def _pet_data_kg_compact(self, grams: Any) -> str:
try:
number = float(grams) / 1000
except (TypeError, ValueError):
return "--"
text = f"{number:.2f}".rstrip("0").rstrip(".")
return f"{text}kg"
def _pet_data_weight_size_info(
self,
pet: Dict[str, Any],
wiki_pet: Dict[str, Any] | None,
) -> Dict[str, str]:
body_size = wiki_pet.get("body_size") if isinstance(wiki_pet, dict) else {}
weight_range = body_size.get("weight") if isinstance(body_size, dict) else {}
if not isinstance(weight_range, dict):
return {}
try:
current = float(pet.get("weight"))
low = float(weight_range.get("min_g"))
high = float(weight_range.get("max_g"))
except (TypeError, ValueError):
return {}
if high <= low:
return {}
span = high - low
small_cut = low + span * 0.05
large_cut = high - span * 0.05
range_text = f"{self._pet_data_kg_compact(low)}-{self._pet_data_kg_compact(high)}"
if current <= small_cut:
return {
"label": "小块头",
"className": "size-small",
"hint": f"小块头 · ≤{self._pet_data_kg_compact(small_cut)} · 范围 {range_text}",
}
if current >= large_cut:
return {
"label": "大块头",
"className": "size-large",
"hint": f"大块头 · ≥{self._pet_data_kg_compact(large_cut)} · 范围 {range_text}",
}
return {
"label": "",
"className": "",
"hint": f"范围 {range_text}",
}
def _pet_data_option_maps(self, options: Dict[str, Any] | None) -> Dict[str, Dict[str, str]]:
pet_options = (options or {}).get("pet") if isinstance(options, dict) else {}
if not isinstance(pet_options, dict):
pet_options = {}
def build_map(key: str, prefer_short: bool = False) -> Dict[str, str]:
result: Dict[str, str] = {}
values = pet_options.get(key)
if not isinstance(values, list):
return result
for item in values:
if not isinstance(item, dict):
continue
item_id = item.get("id")
if item_id in (None, ""):
continue
name = item.get("short_name") if prefer_short and item.get("short_name") else item.get("name")