Skip to content

Commit

Permalink
chore: 添加签到重试,仅每日签到获取token (#229)
Browse files Browse the repository at this point in the history
* fix: 修复无法构建docker镜像的问题

* Update Dockerfile

* 🔧 自动更新requirements

* chore: 添加自动每日运行时间提示

* chore: 将时间类型从str改成int

* Add files via upload

* chore: 更新日志收集方法

* chore: 遵守代码规范

* chore: update issue templates

* chore: 删除测试代码

* chore: 更改日志输出样式

* chore: docker生成配置时随机生成自动运行时间

* chore: trailing-whitespace

* chore: 日志添加换行

* chore: 未配置验证码解决方案时直接跳过

* chore: 使用遍历方法找到键值,提升泛用性

* chore: 使用cron执行自动任务

* chore: snake_case

* chore: 修改运行时间

* Update config.py

* chore: 添加签到重试,仅每日签到获取token

* 🔧 自动更新requirements

* chore: 更新版本号

* Update config.py

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
Night-stars-1 and github-actions[bot] authored Dec 4, 2023
1 parent 6f5bc44 commit f85232e
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 74 deletions.
6 changes: 3 additions & 3 deletions miuitask.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
'''
Date: 2023-11-13 20:29:19
LastEditors: Night-stars-1 [email protected]
LastEditTime: 2023-11-24 16:23:43
LastEditTime: 2023-12-03 01:53:48
'''
# new Env("MIUI-Auto-Task") # pylint: disable=missing-module-docstring
# cron 30 8 * * * miuitask.py

import asyncio

from utils.api.login import Login
from utils.api.sign import BaseSign
from utils.api.sign import BaseSign, CheckIn
from utils.config import ConfigManager
from utils.logger import InterceptHandler, log
from utils.request import notify_me
Expand All @@ -25,7 +25,6 @@ async def main():
for account in _conf.accounts:
login_obj = Login(account)
if cookies := await login_obj.login():
token = await get_token(cookies["cUserId"])
sign_obj = BaseSign(cookies)
daily_tasks = await sign_obj.check_daily_tasks()
sign_task_obj = sign_obj.AVAILABLE_SIGNS # 签到任务对象合集
Expand All @@ -34,6 +33,7 @@ async def main():
log.info(f"开始执行{task.name}任务")
if task_obj := sign_task_obj.get(task.name): # 签到任务对象
if getattr(account, task_obj.__name__):
token = await get_token(cookies["cUserId"]) if task_obj == CheckIn else None
await task_obj(cookies, token).sign()
else:
log.info(f"任务{task.name}被禁用")
Expand Down
10 changes: 5 additions & 5 deletions pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ version = ""
description = ""
authors = []
dependencies = [
"onepush",
"orjson>=3.9.10",
"loguru>=0.7.2",
"pydantic>=2.4.2",
Expand All @@ -13,6 +12,7 @@ dependencies = [
"pyyaml>=6.0.1",
"tenacity>=8.2.3",
"tzdata>=2023.3",
"onepush @ git+https://github.com/y1ndan/onepush.git@main",
]
requires-python = ">=3.11"
license = {text = "MIT"}
Expand Down
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
cryptography==41.0.6
httpx==0.25.1
cryptography==41.0.7
httpx==0.25.2
loguru==0.7.2
onepush==1.3.0
orjson==3.9.10
Expand Down
114 changes: 62 additions & 52 deletions utils/api/sign.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import time

from typing import Dict, List, Optional, Type, Union, Any
from tenacity import RetryError, Retrying, stop_after_attempt

from ..data_model import ApiResultHandler, DailyTasksResult, SignResultHandler
from ..request import get, post
from ..logger import log
from ..utils import is_incorrect_return


class BaseSign:
Expand Down Expand Up @@ -37,28 +39,32 @@ def __init__(self, cookie: Dict, token: Optional[str] = None):
async def check_daily_tasks(self, nolog: bool = False) -> Union[List[DailyTasksResult], List[None]]:
"""获取每日任务状态"""
try:
response = await get('https://api.vip.miui.com/mtop/planet/vip/member/getCheckinPageCakeList',
cookies=self.cookie)
log.debug(response.text)
result = response.json()
api_data = ApiResultHandler(result)
if api_data.success:
task_status = []
tasks: List[Dict[str, List[Dict[str, Any]]]] = list(filter(
lambda x: x['head']['title'] in ["每日任务", "其他任务"], api_data.data))
for task in tasks:
for daily_task in task['data']:
task_name = daily_task['title']
task_desc = daily_task.get('desc', '')
show_type = True if daily_task['showType'] == 0 else False # pylint: disable=simplifiable-if-expression
task_status.append(DailyTasksResult(name=task_name, showType=show_type, desc=task_desc))
return task_status
for attempt in Retrying(stop=stop_after_attempt(3)):
with attempt:
response = await get('https://api.vip.miui.com/mtop/planet/vip/member/getCheckinPageCakeList',
cookies=self.cookie)
log.debug(response.text)
result = response.json()
api_data = ApiResultHandler(result)
if api_data.success:
task_status = []
tasks: List[Dict[str, List[Dict[str, Any]]]] = list(filter(
lambda x: x['head']['title'] in ["每日任务", "其他任务"], api_data.data))
for task in tasks:
for daily_task in task['data']:
task_name = daily_task['title']
task_desc = daily_task.get('desc', '')
show_type = True if daily_task['showType'] == 0 else False # pylint: disable=simplifiable-if-expression
task_status.append(DailyTasksResult(name=task_name, showType=show_type, desc=task_desc))
return task_status
else:
if not nolog:
log.error(f"获取每日任务状态失败:{api_data.message}")
return []
except RetryError as error:
if is_incorrect_return(error):
log.exception(f"每日任务 - 服务器没有正确返回 {response.text}")
else:
if not nolog:
log.error(f"获取每日任务状态失败:{api_data.message}")
return []
except Exception: # pylint: disable=broad-exception-caught
if not nolog:
log.exception("获取每日任务异常")
return []

Expand All @@ -67,40 +73,44 @@ async def sign(self) -> bool:
每日任务处理器
"""
try:
params = self.PARAMS.copy()
params['miui_vip_ph'] = self.cookie['miui_vip_ph'] if 'miui_vip_ph' in self.cookie else params
params['token'] = self.token if 'token' in params else params
data = self.DATA.copy()
data['miui_vip_ph'] = self.cookie['miui_vip_ph'] if 'miui_vip_ph' in self.cookie else data
if 'token' in data:
if self.token:
data['token'] = self.token
else:
log.info(f"未获取到token, 跳过{self.NAME}")
return False
response = await post(self.URL_SIGN,
params=params, data=data,
cookies=self.cookie, headers=self.headers)
log.debug(response.text)
result = response.json()
api_data = SignResultHandler(result)
if api_data:
if api_data.growth:
log.success(f"{self.NAME}结果: 成长值+{api_data.growth}")
else:
log.success(f"{self.NAME}结果: {api_data.message}")
return True
elif api_data.ck_invalid:
log.error(f"{self.NAME}失败: Cookie无效")
return False
for attempt in Retrying(stop=stop_after_attempt(3)):
with attempt:
params = self.PARAMS.copy()
params['miui_vip_ph'] = self.cookie['miui_vip_ph'] if 'miui_vip_ph' in self.cookie else params
params['token'] = self.token if 'token' in params else params
data = self.DATA.copy()
data['miui_vip_ph'] = self.cookie['miui_vip_ph'] if 'miui_vip_ph' in self.cookie else data
if 'token' in data:
if self.token:
data['token'] = self.token
else:
log.info(f"未获取到token, 跳过{self.NAME}")
return False
response = await post(self.URL_SIGN,
params=params, data=data,
cookies=self.cookie, headers=self.headers)
log.debug(response.text)
result = response.json()
api_data = SignResultHandler(result)
if api_data:
if api_data.growth:
log.success(f"{self.NAME}结果: 成长值+{api_data.growth}")
else:
log.success(f"{self.NAME}结果: {api_data.message}")
return True
elif api_data.ck_invalid:
log.error(f"{self.NAME}失败: Cookie无效")
return False
else:
log.error(f"{self.NAME}失败:{api_data.message}")
return False
except RetryError as error:
if is_incorrect_return(error):
log.exception(f"{self.NAME} - 服务器没有正确返回 {response.text}")
else:
log.error(f"{self.NAME}失败:{api_data.message}")
return False
except Exception: # pylint: disable=broad-exception-caught
log.exception(f"{self.NAME}出错")
log.exception("{self.NAME}出错")
return False


class CheckIn(BaseSign):
"""
每日签到
Expand Down
30 changes: 20 additions & 10 deletions utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from pathlib import Path
from typing import Dict, List, Optional, Union

import yaml
from pydantic import BaseModel
from pydantic import ValidationError, field_validator
import orjson
import yaml # pylint: disable=wrong-import-order
from pydantic import BaseModel, ValidationError, field_validator

from .logger import log

Expand All @@ -17,7 +17,10 @@
DATA_PATH = ROOT_PATH / "data"
"""数据保存目录"""

CONFIG_PATH = DATA_PATH / "config.yaml" if os.getenv("MIUITASK_CONFIG_PATH") is None else Path(os.getenv("MIUITASK_CONFIG_PATH"))
CONFIG_TYPE = "json" if os.path.isfile(DATA_PATH / "config.json") else "yaml"
"""数据文件类型"""

CONFIG_PATH = DATA_PATH / f"config.{CONFIG_TYPE}" if os.getenv("MIUITASK_CONFIG_PATH") is None else Path(os.getenv("MIUITASK_CONFIG_PATH"))
"""数据文件默认路径"""

os.makedirs(DATA_PATH, exist_ok=True)
Expand Down Expand Up @@ -128,14 +131,18 @@ def write_plugin_data(data: Config = None):
if data is None:
data = ConfigManager.data_obj
try:
# str_data = orjson.dumps(data.dict(), option=orjson.OPT_PASSTHROUGH_DATETIME | orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_INDENT_2)
str_data = yaml.dump(data.model_dump(), indent=4, allow_unicode=True, sort_keys=False)
if CONFIG_TYPE == "json":
str_data = orjson.dumps(data.model_dump(), option=orjson.OPT_PASSTHROUGH_DATETIME | orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_INDENT_2)
with open(CONFIG_PATH, "wb") as file:
file.write(str_data)
else:
str_data = yaml.dump(data.model_dump(), indent=4, allow_unicode=True, sort_keys=False)
with open(CONFIG_PATH, "w", encoding="utf-8") as file:
file.write(str_data)
return True
except (AttributeError, TypeError, ValueError):
log.exception("数据对象序列化失败,可能是数据类型错误")
return False
with open(CONFIG_PATH, "w", encoding="utf-8") as file:
file.write(str_data)
return True
except OSError:
return False

Expand All @@ -155,7 +162,10 @@ def load_config(cls):
if os.path.exists(DATA_PATH) and os.path.isfile(CONFIG_PATH):
try:
with open(CONFIG_PATH, 'r', encoding="utf-8") as file:
data = yaml.safe_load(file)
if CONFIG_TYPE == "json":
data = orjson.loads(file.read())
else:
data = yaml.safe_load(file)
new_model = Config.model_validate(data)
for attr in new_model.model_fields:
# ConfigManager.data_obj.__setattr__(attr, new_model.__getattribute__(attr))
Expand Down
2 changes: 1 addition & 1 deletion utils/system_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

def print_info():
"""打印系统信息"""
log.info("MIUI-AUTO-TASK v1.7.2")
log.info("MIUI-AUTO-TASK v1.7.3")
log.info('---------- 系统信息 -------------')
system_info()
log.info('---------- 项目信息 -------------')
Expand Down

0 comments on commit f85232e

Please sign in to comment.