diff --git a/app/core/config.py b/app/core/config.py index 7516600..ed5bce7 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -31,7 +31,7 @@ import json import sys import shutil import re -from datetime import datetime, timedelta +from datetime import datetime from collections import defaultdict from pathlib import Path from qfluentwidgets import ( @@ -45,7 +45,7 @@ from qfluentwidgets import ( OptionsValidator, qconfig, ) -from typing import Union, Dict, List +from typing import Union, Dict, List, Tuple class AppConfig: @@ -469,8 +469,6 @@ class AppConfig: def save_maa_log(self, log_path: Path, logs: list, maa_result: str) -> None: """保存MAA日志""" - log_path.parent.mkdir(parents=True, exist_ok=True) - data: Dict[str, Union[str, Dict[str, Union[int, dict]]]] = { "recruit_statistics": defaultdict(int), "drop_statistics": defaultdict(dict), @@ -545,6 +543,7 @@ class AppConfig: data["drop_statistics"][current_stage] = stage_drops # 保存日志 + log_path.parent.mkdir(parents=True, exist_ok=True) with log_path.open("w", encoding="utf-8") as f: f.writelines(logs) with log_path.with_suffix(".json").open("w", encoding="utf-8") as f: @@ -552,10 +551,10 @@ class AppConfig: logger.info(f"处理完成:{log_path}") - self.merge_maa_logs(log_path.parent) + self.merge_maa_logs("所有项", log_path.parent) - def merge_maa_logs(self, logs_path: Path) -> None: - """合并所有 .log 文件""" + def merge_maa_logs(self, mode: str, logs_path: Union[Path, List[Path]]) -> dict: + """合并指定数据统计信息文件""" data = { "recruit_statistics": defaultdict(int), @@ -563,7 +562,12 @@ class AppConfig: "maa_result": defaultdict(str), } - for json_file in logs_path.glob("*.json"): + if mode == "所有项": + logs_path_list = list(logs_path.glob("*.json")) + elif mode == "指定项": + logs_path_list = logs_path + + for json_file in logs_path_list: with json_file.open("r", encoding="utf-8") as f: single_data: Dict[str, Union[str, Dict[str, Union[int, dict]]]] = ( @@ -592,10 +596,14 @@ class AppConfig: ] = single_data["maa_result"] # 生成汇总 JSON 文件 - with logs_path.with_suffix(".json").open("w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=4) + if mode == "所有项": - logger.info(f"统计完成:{logs_path.with_suffix(".json")}") + with logs_path.with_suffix(".json").open("w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=4) + + logger.info(f"统计完成:{logs_path.with_suffix(".json")}") + + return data def load_maa_logs( self, mode: str, json_path: Path @@ -779,11 +787,14 @@ class GlobalConfig(QConfig): ui_location = ConfigItem("UI", "location", "100x100") ui_maximized = ConfigItem("UI", "maximized", False, BoolValidator()) - notify_IfPushPlyer = ConfigItem("Notify", "IfPushPlyer", False, BoolValidator()) - notify_IfSendMail = ConfigItem("Notify", "IfSendMail", False, BoolValidator()) notify_IfSendErrorOnly = ConfigItem( "Notify", "IfSendErrorOnly", False, BoolValidator() ) + notify_IfSendStatistic = ConfigItem( + "Notify", "IfSendStatistic", False, BoolValidator() + ) + notify_IfPushPlyer = ConfigItem("Notify", "IfPushPlyer", False, BoolValidator()) + notify_IfSendMail = ConfigItem("Notify", "IfSendMail", False, BoolValidator()) notify_SMTPServerAddress = ConfigItem("Notify", "SMTPServerAddress", "") notify_AuthorizationCode = ConfigItem("Notify", "AuthorizationCode", "") notify_FromAddress = ConfigItem("Notify", "FromAddress", "") diff --git a/app/models/MAA.py b/app/models/MAA.py index f95ea2c..8ff7b90 100644 --- a/app/models/MAA.py +++ b/app/models/MAA.py @@ -34,7 +34,7 @@ import subprocess import shutil import time from pathlib import Path -from typing import List +from typing import Union, List from app.core import Config from app.services import Notify, System @@ -176,6 +176,9 @@ class MaaManager(QObject): [True, "routine", "日常"], ] + user_logs_list = [] + user_start_time = datetime.now() + # 尝试次数循环 for i in range(self.set["RunSet"]["RunTimesLimit"]): @@ -273,7 +276,7 @@ class MaaManager(QObject): System.kill_process(self.maa_exe_path) self.if_open_emulator = True # 推送异常通知 - Notify.push_notification( + Notify.push_plyer( "用户自动代理出现异常!", f"用户 {user[0].replace("_", " 今天的")}的{mode_book[j][5:7]}部分出现一次异常", f"{user[0].replace("_", " ")}的{mode_book[j][5:7]}出现异常", @@ -287,13 +290,17 @@ class MaaManager(QObject): # 移除静默进程标记 Config.silence_list.remove(self.emulator_path) - # 保存运行日志 + # 保存运行日志以及统计信息 Config.save_maa_log( Config.app_path / f"history/{curdate}/{self.data[user[2]][0]}/{start_time.strftime("%H-%M-%S")}.log", self.check_maa_log(start_time, mode_book[j]), self.maa_result, ) + user_logs_list.append( + Config.app_path + / f"history/{curdate}/{self.data[user[2]][0]}/{start_time.strftime("%H-%M-%S")}.json", + ) # 成功完成代理的用户修改相关参数 if run_book[0] and run_book[1]: @@ -301,7 +308,7 @@ class MaaManager(QObject): self.data[user[2]][3] -= 1 self.data[user[2]][14] += 1 user[1] = "完成" - Notify.push_notification( + Notify.push_plyer( "成功完成一个自动代理任务!", f"已完成用户 {user[0].replace("_", " 今天的")}任务", f"已完成 {user[0].replace("_", " 的")}", @@ -309,6 +316,26 @@ class MaaManager(QObject): ) break + if Config.global_config.get( + Config.global_config.notify_IfSendStatistic + ): + + statistics = Config.merge_maa_logs("指定项", user_logs_list) + statistics["start_time"] = user_start_time.strftime( + "%Y-%m-%d %H:%M:%S" + ) + statistics["end_time"] = datetime.now().strftime( + "%Y-%m-%d %H:%M:%S" + ) + statistics["maa_result"] = ( + "代理任务全部完成" + if (run_book[0] and run_book[1]) + else "代理任务未全部完成" + ) + self.push_notification( + "统计信息", f"用户 {user[0]} 的自动代理统计报告", statistics + ) + # 录入代理失败的用户 if not (run_book[0] and run_book[1]): user[1] = "异常" @@ -487,7 +514,7 @@ class MaaManager(QObject): else f"{self.mode[:4]}任务报告" ) # 推送代理结果通知 - Notify.push_notification( + Notify.push_plyer( title.replace("报告", "已完成!"), f"已完成用户数:{len(over_index)},未完成用户数:{len(error_index) + len(wait_index)}", f"已完成用户数:{len(over_index)},未完成用户数:{len(error_index) + len(wait_index)}", @@ -499,12 +526,7 @@ class MaaManager(QObject): Config.global_config.get(Config.global_config.notify_IfSendErrorOnly) and len(error_index) + len(wait_index) != 0 ): - Notify.send_mail( - title, - f"{end_log}\n\nAUTO_MAA 敬上\n\n我们根据您在 AUTO_MAA 中的设置发送了这封电子邮件,本邮件无需回复\n", - ) - Notify.ServerChanPush(title, f"{end_log}\n\nAUTO_MAA 敬上") - Notify.CompanyWebHookBotPush(title, f"{end_log}AUTO_MAA 敬上") + self.push_notification("代理结果", title, end_log) self.agree_bilibili(False) self.log_monitor.deleteLater() @@ -1130,3 +1152,165 @@ class MaaManager(QObject): if dt.time() < datetime.min.time().replace(hour=4): dt = dt - timedelta(days=1) return dt.strftime("%Y-%m-%d") + + def push_notification( + self, mode: str, title: str, message: Union[str, dict] + ) -> None: + """通过所有渠道推送通知""" + + if mode == "代理结果": + + Notify.send_mail( + "文本", + title, + f"{message}\n\nAUTO_MAA 敬上\n\n我们根据您在 AUTO_MAA 中的设置发送了这封电子邮件,本邮件无需回复\n", + ) + Notify.ServerChanPush(title, f"{message}\n\nAUTO_MAA 敬上") + Notify.CompanyWebHookBotPush(title, f"{message}AUTO_MAA 敬上") + + elif mode == "统计信息": + + # HTML模板 + html_template = """ + + +
+ +开始时间: {start_time}
+结束时间: {end_time}
+MAA执行结果: {maa_result}
+ +| 星级 | +数量 | +
|---|
| 物品 | +数量 | +
|---|
主题图像信息未知
" + + self.banner_text.setHtml(re.sub(r"