Add simplified processing of cookies

This commit is contained in:
洛水居室 2022-11-27 18:42:49 +08:00 committed by GitHub
parent 15532234b6
commit c090dd97ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,6 +1,6 @@
import contextlib import contextlib
from http.cookies import SimpleCookie, CookieError from http.cookies import SimpleCookie, CookieError
from typing import Optional from typing import Optional, Dict
import genshin import genshin
from genshin import InvalidCookies, GenshinException, DataNotPublic from genshin import InvalidCookies, GenshinException, DataNotPublic
@ -48,6 +48,43 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
self.cookies_service = cookies_service self.cookies_service = cookies_service
self.user_service = user_service self.user_service = user_service
@staticmethod
def de_cookie(cookie: SimpleCookie) -> Dict[str, str]:
cookies = {}
ltoken = cookie.get("ltoken")
if ltoken:
cookies["ltoken"] = ltoken.value
ltuid = cookie.get("ltuid")
login_uid = cookie.get("login_uid")
if ltuid:
cookies["ltuid"] = ltuid.value
cookies["account_id"] = ltuid.value
if login_uid:
cookies["ltuid"] = login_uid.value
cookies["account_id"] = ltuid.value
cookie_token = cookie.get("cookie_token")
cookie_token_v2 = cookie.get("cookie_token_v2")
if cookie_token:
cookies["cookie_token"] = cookie_token.value
if cookie_token_v2:
cookies["cookie_token"] = cookie_token_v2.value
account_mid_v2 = cookie.get("account_mid_v2")
if account_mid_v2:
cookies["account_mid_v2"] = account_mid_v2.value
cookie_token_v2 = cookie.get("cookie_token_v2")
if cookie_token_v2:
cookies["cookie_token_v2"] = cookie_token_v2.value
ltoken_v2 = cookie.get("ltoken_v2")
if ltoken_v2:
cookies["ltoken_v2"] = ltoken_v2.value
ltmid_v2 = cookie.get("ltmid_v2")
if ltmid_v2:
cookies["ltmid_v2"] = ltmid_v2.value
login_ticket = cookie.get("login_ticket")
if login_ticket:
cookies["login_ticket"] = login_ticket.value
return cookies
@conversation.entry_point @conversation.entry_point
@handler.command(command="setcookie", filters=filters.ChatType.PRIVATE, block=True) @handler.command(command="setcookie", filters=filters.ChatType.PRIVATE, block=True)
@restricts() @restricts()
@ -237,6 +274,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
@error_callable @error_callable
async def input_cookies(self, update: Update, context: CallbackContext) -> int: async def input_cookies(self, update: Update, context: CallbackContext) -> int:
message = update.effective_message message = update.effective_message
user = update.effective_user
add_user_command_data: AddUserCommandData = context.chat_data.get("add_user_command_data") add_user_command_data: AddUserCommandData = context.chat_data.get("add_user_command_data")
if message.text == "退出": if message.text == "退出":
await message.reply_text("退出任务", reply_markup=ReplyKeyboardRemove()) await message.reply_text("退出任务", reply_markup=ReplyKeyboardRemove())
@ -246,13 +284,22 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
try: try:
cookie.load(str_cookies) cookie.load(str_cookies)
except CookieError: except CookieError:
logger.info("用户 %s[%s] Cookies格式有误", user.full_name, user.id)
await message.reply_text("Cookies格式有误请检查", reply_markup=ReplyKeyboardRemove()) await message.reply_text("Cookies格式有误请检查", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
if len(cookie) == 0: if len(cookie) == 0:
logger.info("用户 %s[%s] Cookies格式有误", user.full_name, user.id)
await message.reply_text("Cookies格式有误请检查", reply_markup=ReplyKeyboardRemove()) await message.reply_text("Cookies格式有误请检查", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
cookies = {key: morsel.value for key, morsel in cookie.items()} try:
cookies = self.de_cookie(cookie)
except (AttributeError, ValueError) as exc:
logger.info("用户 %s[%s] Cookies解析出现错误", user.full_name, user.id)
logger.debug("解析Cookies出现错误", exc_info=exc)
await message.reply_text("解析Cookies出现错误请检查是否正确", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
if not cookies: if not cookies:
logger.info("用户 %s[%s] Cookies格式有误", user.full_name, user.id)
await message.reply_text("Cookies格式有误请检查", reply_markup=ReplyKeyboardRemove()) await message.reply_text("Cookies格式有误请检查", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
add_user_command_data.cookies = cookies add_user_command_data.cookies = cookies
@ -269,6 +316,7 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
elif add_user_command_data.region == RegionEnum.HOYOLAB: elif add_user_command_data.region == RegionEnum.HOYOLAB:
client = genshin.GenshinClient(cookies=cookies) client = genshin.GenshinClient(cookies=cookies)
else: else:
logger.error("用户 %s[%s] region 异常", user.full_name, user.id)
await message.reply_text("数据错误", reply_markup=ReplyKeyboardRemove()) await message.reply_text("数据错误", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
try: try:
@ -281,27 +329,34 @@ class SetUserCookies(Plugin.Conversation, BasePlugin.Conversation):
add_user_command_data.cookies["account_id"] = account_id add_user_command_data.cookies["account_id"] = account_id
genshin_accounts = await client.genshin_accounts() genshin_accounts = await client.genshin_accounts()
except DataNotPublic: except DataNotPublic:
logger.info("用户 %s[%s] 账号疑似被注销", user.full_name, user.id)
await message.reply_text("账号疑似被注销,请检查账号状态", reply_markup=ReplyKeyboardRemove()) await message.reply_text("账号疑似被注销,请检查账号状态", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
except InvalidCookies: except InvalidCookies:
logger.info("用户 %s[%s] Cookies已经过期", user.full_name, user.id)
await message.reply_text("Cookies已经过期请检查是否正确", reply_markup=ReplyKeyboardRemove()) await message.reply_text("Cookies已经过期请检查是否正确", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
except GenshinException as exc: except GenshinException as exc:
logger.info("用户 %s[%s] 获取账号信息发生错误 [%s]%s", user.full_name, user.id, exc.retcode, exc.original)
await message.reply_text( await message.reply_text(
f"获取账号信息发生错误,错误信息为 {str(exc)}请检查Cookie或者账号是否正常", reply_markup=ReplyKeyboardRemove() f"获取账号信息发生错误,错误信息为 {exc.original}请检查Cookie或者账号是否正常", reply_markup=ReplyKeyboardRemove()
) )
return ConversationHandler.END return ConversationHandler.END
except GetAccountIdException: except GetAccountIdException:
logger.info("用户 %s[%s] 获取账号ID发生错误", user.full_name, user.id)
await message.reply_text("获取账号ID发生错误请检查Cookie或者账号是否正常", reply_markup=ReplyKeyboardRemove()) await message.reply_text("获取账号ID发生错误请检查Cookie或者账号是否正常", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
except (AttributeError, ValueError): except (AttributeError, ValueError) as exc:
logger.warning("用户 %s[%s] Cookies错误", user.full_name, user.id)
logger.debug("Cookies错误", exc_info=exc)
await message.reply_text("Cookies错误请检查是否正确", reply_markup=ReplyKeyboardRemove()) await message.reply_text("Cookies错误请检查是否正确", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
with contextlib.suppress(Exception): with contextlib.suppress(Exception):
sign_in_client = SignIn(cookie=add_user_command_data.cookies) if cookies.get("login_ticket"):
await sign_in_client.get_s_token() sign_in_client = SignIn(cookie=add_user_command_data.cookies)
add_user_command_data.cookies = sign_in_client.cookie await sign_in_client.get_s_token()
logger.info(f"用户 {user.full_name}[{user.id}] 绑定时获取 stoken 成功") add_user_command_data.cookies = sign_in_client.cookie
logger.info("用户 %s[%s] 绑定时获取 stoken 成功", user.full_name, user.id)
user_info: Optional[GenshinAccount] = None user_info: Optional[GenshinAccount] = None
level: int = 0 level: int = 0
# todo : 多账号绑定 # todo : 多账号绑定