From 30bae18edf3be15d8d856ae88992cf0692f95efc Mon Sep 17 00:00:00 2001 From: xtaodada Date: Sat, 7 Oct 2023 23:21:45 +0800 Subject: [PATCH] :recycle: Refactor get fight prop rule --- .gitmodules | 3 -- metadata/scripts/metadatas.py | 9 +++++- modules/apihelper/client/components/remote.py | 28 +++++++++++++++---- modules/playercards/helpers.py | 10 ++----- modules/playercards/metadata | 1 - plugins/starrail/player_cards.py | 19 +++++++++++-- 6 files changed, 50 insertions(+), 20 deletions(-) delete mode 160000 modules/playercards/metadata diff --git a/.gitmodules b/.gitmodules index b62574e..b67cba9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,6 +2,3 @@ path = gram_core url = https://github.com/PaiGramTeam/GramCore.git branch = v4 -[submodule "modules/playercards/metadata"] - path = modules/playercards/metadata - url = https://github.com/PaiGramTeam/FightPropRule.git diff --git a/metadata/scripts/metadatas.py b/metadata/scripts/metadatas.py index 8caa615..16efc7c 100644 --- a/metadata/scripts/metadatas.py +++ b/metadata/scripts/metadatas.py @@ -9,12 +9,19 @@ from httpx import URL, AsyncClient, RemoteProtocolError, Response from utils.const import AMBR_HOST, PROJECT_ROOT from utils.log import logger -__all__ = ["update_metadata_from_ambr", "update_metadata_from_github", "make_github_fast", "RESOURCE_DEFAULT_PATH"] +__all__ = [ + "update_metadata_from_ambr", + "update_metadata_from_github", + "make_github_fast", + "RESOURCE_DEFAULT_PATH", + "RESOURCE_FightPropRule_URL", +] GENSHIN_PY_DATA_REPO = parse_token("aHR0cHM6Ly9naXRsYWIuY29tL0RpbWJyZWF0aC9nYW1lZGF0YS8tL3Jhdy9tYXN0ZXIv").decode() RESOURCE_REPO = "PaiGramTeam/PaiGram_Resources" RESOURCE_BRANCH = "remote" RESOURCE_ROOT = "Resources" RESOURCE_DEFAULT_PATH = f"{RESOURCE_REPO}/{RESOURCE_BRANCH}/{RESOURCE_ROOT}/" +RESOURCE_FightPropRule_URL = "https://fightproprule.paimon.vip/" client = AsyncClient() diff --git a/modules/apihelper/client/components/remote.py b/modules/apihelper/client/components/remote.py index c5a103e..2ecb33a 100644 --- a/modules/apihelper/client/components/remote.py +++ b/modules/apihelper/client/components/remote.py @@ -1,8 +1,9 @@ from typing import List, Dict -from httpx import AsyncClient, HTTPError +from httpx import AsyncClient -from metadata.scripts.metadatas import RESOURCE_DEFAULT_PATH +from metadata.scripts.metadatas import RESOURCE_DEFAULT_PATH, RESOURCE_FightPropRule_URL +from utils.log import logger class Remote: @@ -12,6 +13,7 @@ class Remote: CALENDAR = f"{BASE_URL}calendar.json" BIRTHDAY = f"{BASE_URL}birthday.json" MATERIAL = f"{BASE_URL}roles_material.json" + RULE = f"{RESOURCE_FightPropRule_URL}FightPropRule_starrail.json" @staticmethod async def get_remote_calendar() -> Dict[str, Dict]: @@ -22,7 +24,8 @@ class Remote: if req.status_code == 200: return req.json() return {} - except HTTPError: + except Exception as exc: + logger.error("获取云端日历失败: %s", exc_info=exc) return {} @staticmethod @@ -34,7 +37,8 @@ class Remote: if req.status_code == 200: return req.json() return {} - except HTTPError: + except Exception as exc: + logger.error("获取云端生日失败: %s", exc_info=exc) return {} @staticmethod @@ -46,5 +50,19 @@ class Remote: if req.status_code == 200: return req.json() return {} - except HTTPError: + except Exception as exc: + logger.error("获取云端角色材料失败: %s", exc_info=exc) + return {} + + @staticmethod + async def get_fight_prop_rule_data() -> Dict[str, Dict[str, float]]: + """获取云端圣遗物评分规则""" + try: + async with AsyncClient() as client: + req = await client.get(Remote.RULE) + if req.status_code == 200: + return req.json() + return {} + except Exception as exc: + logger.error("获取云端圣遗物评分规则失败: %s", exc_info=exc) return {} diff --git a/modules/playercards/helpers.py b/modules/playercards/helpers.py index 7417094..4937f5b 100644 --- a/modules/playercards/helpers.py +++ b/modules/playercards/helpers.py @@ -1,18 +1,12 @@ import os - -import ujson as json +from typing import Dict from modules.playercards.fight_prop import FightPropScore, EquipmentsStats, nameToFightProp, FightProp from modules.wiki.models.enums import RelicAffix -_project_path = os.path.dirname(__file__) -_fight_prop_rule_file = os.path.join(_project_path, "metadata", "FightPropRule_starrail.json") -with open(_fight_prop_rule_file, "r", encoding="utf-8") as f: - fight_prop_rule_data: dict = json.load(f) - class ArtifactStatsTheory: - def __init__(self, character_name: str): + def __init__(self, character_name: str, fight_prop_rule_data: Dict[str, Dict[str, float]]): self.character_name = character_name self.fight_prop_rules = fight_prop_rule_data.get(self.character_name, {}) fight_prop_rule_list = list(self.fight_prop_rules.keys()) diff --git a/modules/playercards/metadata b/modules/playercards/metadata deleted file mode 160000 index c8e4815..0000000 --- a/modules/playercards/metadata +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c8e481518e29aff43244afdee1048604ab1e8148 diff --git a/plugins/starrail/player_cards.py b/plugins/starrail/player_cards.py index 426ed6a..b3cd740 100644 --- a/plugins/starrail/player_cards.py +++ b/plugins/starrail/player_cards.py @@ -16,6 +16,7 @@ from core.services.template.services import TemplateService from core.services.wiki.services import WikiService from metadata.shortname import roleToName, idToRole from modules.apihelper.client.components.player_cards import PlayerCards as PlayerCardsClient, PlayerInfo, Avatar, Relic +from modules.apihelper.client.components.remote import Remote from modules.playercards.fight_prop import EquipmentsStats from modules.playercards.helpers import ArtifactStatsTheory from utils.log import logger @@ -47,9 +48,14 @@ class PlayerCards(Plugin): self.template_service = template_service self.wiki_service = wiki_service self.kitsune: Optional[str] = None + self.fight_prop_rule: Dict[str, Dict[str, float]] = {} async def initialize(self): await self.client.async_init() + await self._refresh() + + async def _refresh(self): + self.fight_prop_rule = await Remote.get_fight_prop_rule_data() async def _load_history(self, uid) -> Optional[PlayerInfo]: data = await self.client.player_cards_file.load_history_info(uid) @@ -173,6 +179,7 @@ class PlayerCards(Plugin): self.assets_service, self.wiki_service, self.client, + self.fight_prop_rule, ).render() # pylint: disable=W0631 await render_result.reply_photo( message, @@ -293,7 +300,13 @@ class PlayerCards(Plugin): await callback_query.answer(text="正在渲染图片中 请稍等 请不要重复点击按钮", show_alert=False) await message.reply_chat_action(ChatAction.UPLOAD_PHOTO) render_result = await RenderTemplate( - uid, characters, self.template_service, self.assets_service, self.wiki_service, self.client + uid, + characters, + self.template_service, + self.assets_service, + self.wiki_service, + self.client, + self.fight_prop_rule, ).render() # pylint: disable=W0631 render_result.filename = f"player_card_{uid}_{result}.png" await render_result.edit_media(message) @@ -440,6 +453,7 @@ class RenderTemplate: assets_service: AssetsService, wiki_service: WikiService, client: PlayerCardsClient, + fight_prop_rule: Dict[str, Dict[str, float]], ): self.uid = uid self.template_service = template_service @@ -447,6 +461,7 @@ class RenderTemplate: self.assets_service = assets_service self.wiki_service = wiki_service self.client = client + self.fight_prop_rule = fight_prop_rule async def render(self): images = await self.cache_images() @@ -520,7 +535,7 @@ class RenderTemplate: def find_artifacts(self) -> List[Artifact]: """在 equipments 数组中找到圣遗物,并转换成带有分数的 model。equipments 数组包含圣遗物和武器""" - stats = ArtifactStatsTheory(idToRole(self.character.avatarId)) + stats = ArtifactStatsTheory(idToRole(self.character.avatarId), self.fight_prop_rule) def substat_score(s: EquipmentsStats) -> float: return stats.theory(s)