Prechádzať zdrojové kódy

Merge remote-tracking branch 'origin/dev' into dev

neptine 2 mesiacov pred
rodič
commit
5e474af03d

+ 13 - 1
assets/i18n/zh-CN.json

@@ -57,5 +57,17 @@
   "enable_switch_daily_training": "日常训练开启切换御魂",
   "enable_switch_cultivation_drills": "修行合训开启切换御魂",
   "demon_battle_config": "逢魔战斗内切换阵容",
-  "best_demon_battle_config": "极逢魔战斗内切换阵容"
+  "best_demon_battle_config": "极逢魔战斗内切换阵容",
+  "anti_ban": "防风控作息",
+  "antiban_enable_help": "开启后启用作息约束(睡眠时间窗、累计活跃上限、强制休息),用于避免24小时不间断/深夜连续运行这类服务端可见的异常行为特征。\n注意:点击/滑动的拟人化(真实按压时长、坐标高斯化、微动、压力抖动)始终生效,不受此开关控制。",
+  "sleep_start": "睡眠开始时间",
+  "sleep_start_help": "进入睡眠时间窗的时刻。此区间内停止一切操作,并按“任务队列清空后”的空闲策略关闭游戏/模拟器,到点自动唤醒。支持跨午夜(如 23:00 到次日 06:00)。",
+  "sleep_end": "睡眠结束时间",
+  "sleep_end_help": "退出睡眠时间窗、恢复运行的时刻。",
+  "daily_active_limit": "累计活跃上限",
+  "daily_active_limit_help": "累计活跃时长达到此值后强制长休息一段(休息结束重新计)。设为 0 表示不限制。用于打破长时间不间断在线。格式:天 时:分:秒。",
+  "long_rest_duration": "强制休息时长",
+  "long_rest_duration_help": "触发累计活跃上限后的强制休息时长。格式:天 时:分:秒。",
+  "min_run_interval": "最小再运行间隔",
+  "min_run_interval_help": "防风控:两次蹭卡运行之间的最小间隔,避免蹭卡过于频繁被服务端标记。设为 0(默认)保持原逻辑(按结界卡剩余时间安排下次)。格式:天 时:分:秒。"
 }

+ 5 - 4
module/atom/click.py

@@ -4,6 +4,7 @@
 import numpy as np
 
 from module.base.decorator import cached_property
+from module.base.utils.utils import random_normal_distribution_int
 from module.logger import logger
 
 class RuleClick:
@@ -27,8 +28,8 @@ class RuleClick:
         :return:
         """
         x, y, w, h = self.roi_front
-        x = np.random.randint(x, x + w)
-        y = np.random.randint(y, y + h)
+        x = random_normal_distribution_int(x, x + w)
+        y = random_normal_distribution_int(y, y + h)
         return x, y
 
     def coord_more(self) -> tuple:
@@ -37,8 +38,8 @@ class RuleClick:
         :return:
         """
         x, y, w, h = self.roi_back
-        x = np.random.randint(x, x + w)
-        y = np.random.randint(y, y + h)
+        x = random_normal_distribution_int(x, x + w)
+        y = random_normal_distribution_int(y, y + h)
         return x, y
 
     @property

+ 3 - 2
module/atom/image.py

@@ -11,6 +11,7 @@ from module.atom.RuleImageMallResourceMixin import RuleImageMallResourceMixin
 from module.base.decorator import cached_property
 from module.logger import logger
 from module.base.utils import is_approx_rectangle
+from module.base.utils.utils import random_normal_distribution_int
 
 
 class RuleImage(RuleImageMallResourceMixin):
@@ -307,7 +308,7 @@ class RuleImage(RuleImageMallResourceMixin):
         :return:
         """
         x, y, w, h = self.roi_front
-        return x + np.random.randint(0, w), y + np.random.randint(0, h)
+        return x + random_normal_distribution_int(0, w), y + random_normal_distribution_int(0, h)
 
     def coord_more(self) -> tuple:
         """
@@ -315,7 +316,7 @@ class RuleImage(RuleImageMallResourceMixin):
         :return:
         """
         x, y, w, h = self.roi_back
-        return x + np.random.randint(0, w), y + np.random.randint(0, h)
+        return x + random_normal_distribution_int(0, w), y + random_normal_distribution_int(0, h)
 
     def front_center(self) -> tuple:
         """

+ 3 - 2
module/atom/ocr.py

@@ -7,6 +7,7 @@ import cv2
 
 from module.ocr.base_ocr import BaseCor, OcrMode, OcrMethod
 from module.ocr.sub_ocr import Full, Single, Digit, DigitCounter, Duration, Quantity
+from module.base.utils.utils import random_normal_distribution_int
 from module.logger import logger
 
 
@@ -54,8 +55,8 @@ class RuleOcr(Digit, DigitCounter, Duration, Single, Full, Quantity):
 		# OCR识别到并点击,在SINGLE模式下,识别到挑战,点击区域应该为ROI,而不是AREA
 		# 该地方应该是误写为self.area,本地变量area没有起作用,如果是self.area,上面几句话就白写了,没起作用
         x, y, w, h = area
-        x = np.random.randint(x, x + w)
-        y = np.random.randint(y, y + h)
+        x = random_normal_distribution_int(x, x + w)
+        y = random_normal_distribution_int(y, y + h)
         return x, y
 
 if __name__ == "__main__":

+ 5 - 4
module/atom/swipe.py

@@ -8,6 +8,7 @@ from math import dist
 
 from module.base.decorator import cached_property
 from module.atom.cBezier import BezierTrajectory
+from module.base.utils.utils import random_normal_distribution_int
 from module.logger import logger
 
 
@@ -52,11 +53,11 @@ class RuleSwipe:
         :return: 两个坐标的tuple
         """
         x, y, w, h = self.roi_front
-        x = np.random.randint(x, x + w)
-        y = np.random.randint(y, y + h)
+        x = random_normal_distribution_int(x, x + w)
+        y = random_normal_distribution_int(y, y + h)
         x2, y2, w2, h2 = self.roi_back
-        x2 = np.random.randint(x2, x2 + w2)
-        y2 = np.random.randint(y2, y2 + h2)
+        x2 = random_normal_distribution_int(x2, x2 + w2)
+        y2 = random_normal_distribution_int(y2, y2 + h2)
         return x, y, x2, y2
 
     def trace(self) -> list:

+ 20 - 5
module/device/method/minitouch.py

@@ -1,5 +1,6 @@
 import asyncio
 import json
+import random
 import re
 import socket
 import time
@@ -406,6 +407,14 @@ class Minitouch(Connection):
     _minitouch_ws: websockets.WebSocketClientProtocol
     max_x: int
     max_y: int
+    max_pressure: int = 100
+
+    def _humanized_pressure(self) -> int:
+        top = getattr(self, 'max_pressure', 100) or 100
+        return random.randint(max(20, top // 2), top)
+
+    def _humanized_dwell(self) -> int:
+        return int(random.triangular(45, 130, 65))
 
     @cached_property
     def minitouch_builder(self):
@@ -468,7 +477,10 @@ class Minitouch(Connection):
         # self.max_contacts = max_contacts
         self.max_x = int(max_x)
         self.max_y = int(max_y)
-        # self.max_pressure = max_pressure
+        try:
+            self.max_pressure = int(max_pressure)
+        except (ValueError, TypeError):
+            self.max_pressure = 100
 
         # $ <pid>
         out = socket_out.readline().replace("\n", "").replace("\r", "")
@@ -569,7 +581,10 @@ class Minitouch(Connection):
     @retry
     def click_minitouch(self, x, y):
         builder = self.minitouch_builder
-        builder.down(x, y).commit()
+        pressure = self._humanized_pressure()
+        builder.down(x, y, pressure=pressure).commit().wait(self._humanized_dwell())
+        mx, my = x + random.randint(-2, 2), y + random.randint(-2, 2)
+        builder.move(mx, my, pressure=pressure).commit().wait(random.randint(8, 20))
         builder.up().commit()
         self.minitouch_send()
 
@@ -577,7 +592,7 @@ class Minitouch(Connection):
     def long_click_minitouch(self, x, y, duration=1.0):
         duration = int(duration * 1000)
         builder = self.minitouch_builder
-        builder.down(x, y).commit().wait(duration)
+        builder.down(x, y, pressure=self._humanized_pressure()).commit().wait(duration)
         builder.up().commit()
         self.minitouch_send()
 
@@ -590,7 +605,7 @@ class Minitouch(Connection):
         self.minitouch_send()
 
         for point in points[1:]:
-            builder.move(*point).commit().wait(10)
+            builder.move(*point).commit().wait(random.randint(6, 15))
         self.minitouch_send()
 
         builder.up().commit()
@@ -607,7 +622,7 @@ class Minitouch(Connection):
         self.minitouch_send()
 
         for point in points[1:]:
-            builder.move(*point).commit().wait(10)
+            builder.move(*point).commit().wait(random.randint(6, 15))
         self.minitouch_send()
 
         builder.move(*p2).commit().wait(140)

+ 6 - 4
module/device/method/nemu_ipc.py

@@ -1,6 +1,7 @@
 import asyncio
 import ctypes
 import os
+import random
 import sys
 from functools import partial, wraps
 from pathlib import Path
@@ -513,11 +514,12 @@ class NemuIpc():
         return image
 
     def click_nemu_ipc(self, x, y):
-        down = ensure_time((0.010, 0.020))
         self.nemu_ipc.down(x, y)
-        self.sleep(down)
+        self.sleep(ensure_time((0.050, 0.110)))
+        self.nemu_ipc.down(x + random.randint(-2, 2), y + random.randint(-2, 2))
+        self.sleep(ensure_time((0.008, 0.020)))
         self.nemu_ipc.up()
-        self.sleep(0.050 - down)
+        self.sleep(ensure_time((0.020, 0.045)))
 
     def long_click_nemu_ipc(self, x, y, duration=1.0):
         self.nemu_ipc.down(x, y)
@@ -530,7 +532,7 @@ class NemuIpc():
 
         for point in points:
             self.nemu_ipc.down(*point)
-            self.sleep(0.010)
+            self.sleep(ensure_time((0.006, 0.015)))
 
         self.nemu_ipc.up()
         self.sleep(0.050)

+ 6 - 2
module/device/method/scrcpy/scrcpy.py

@@ -1,3 +1,4 @@
+import random
 import time
 from functools import wraps
 
@@ -97,7 +98,10 @@ class Scrcpy(ScrcpyCore, Uiautomator2):
 
         with self._scrcpy_control_socket_lock:
             self._scrcpy_control.touch(x, y, const.ACTION_DOWN)
-            self._scrcpy_control.touch(x, y, const.ACTION_UP)
+            self.sleep(random.uniform(0.045, 0.13))
+            mx, my = x + random.randint(-2, 2), y + random.randint(-2, 2)
+            self._scrcpy_control.touch(mx, my, const.ACTION_MOVE)
+            self._scrcpy_control.touch(mx, my, const.ACTION_UP)
             self.sleep(0.05)
 
     @retry
@@ -122,7 +126,7 @@ class Scrcpy(ScrcpyCore, Uiautomator2):
 
             for point in points[1:-1]:
                 self._scrcpy_control.touch(*point, const.ACTION_MOVE)
-                self.sleep(0.002)
+                self.sleep(random.uniform(0.001, 0.004))
 
             self._scrcpy_control.touch(*p2, const.ACTION_MOVE)
             self._scrcpy_control.touch(*p2, const.ACTION_UP)

+ 136 - 0
module/server/diagnostic.py

@@ -0,0 +1,136 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+"""导出脱敏后的配置摘要与最近日志为 zip,用于风控对照分析。不导出账号/token/密码。"""
+import json
+import platform
+import re
+import sys
+import zipfile
+from datetime import datetime
+from pathlib import Path
+
+from module.config.utils import read_file, deep_get
+from module.server.config_manager import ConfigManager
+from module.logger import logger
+
+PROJECT_ROOT = Path.cwd().resolve()
+LOG_DIR = PROJECT_ROOT / 'log'
+OUT_DIR = LOG_DIR / 'diagnostic'
+
+_RECENT_INSTANCE_LOGS = 4
+_RECENT_SHARED_LOGS = 3
+_RECENT_ERROR_LOGS = 10
+
+# 白名单:只导出这些字段,不带出 URS 凭据
+_DEVICE_FIELDS = [
+    'control_method', 'screenshot_method', 'serial', 'package_name',
+    'emulatorinfo_type', 'emulatorinfo_name',
+]
+
+# 值匹配到分隔符为止(涵盖 base64 的 +/= 等), 避免只按 \w 截断导致凭据残留
+_V = r'[^\s"\',:;&?{}\[\]]'
+_SCRUB_PATTERNS = [
+    (re.compile(r'(账号[::]\s*)(' + _V + r'{3,})'), r'\1***'),
+    (re.compile(r'(account["\'\s::=]+)(' + _V + r'{3,})', re.I), r'\1***'),
+    (re.compile(r'(token["\'\s::=]+)(' + _V + r'{6,})', re.I), r'\1***'),
+    (re.compile(r'(urs[\w]*["\'\s::=]+)(' + _V + r'{6,})', re.I), r'\1***'),
+    (re.compile(r'(password["\'\s::=]+)(' + _V + r'+)', re.I), r'\1***'),
+    (re.compile(r'\b(1[3-9]\d)\d{4}(\d{4})\b'), r'\1****\2'),
+]
+
+
+def _scrub(text: str) -> str:
+    for pat, repl in _SCRUB_PATTERNS:
+        text = pat.sub(repl, text)
+    return text
+
+
+def _config_summary(name: str) -> dict:
+    data = read_file(str(PROJECT_ROOT / 'config' / f'{name}.json'))
+    if not isinstance(data, dict):
+        return {'instance': name, 'error': 'config unreadable'}
+    device = {k: deep_get(data, f'script.device.{k}') for k in _DEVICE_FIELDS}
+    optimization = data.get('script', {}).get('optimization', {})
+    anti_ban = data.get('script', {}).get('anti_ban', {})
+    enabled = []
+    for task, cfg in data.items():
+        if isinstance(cfg, dict) and deep_get(cfg, 'scheduler.enable') is True:
+            enabled.append(task)
+    return {
+        'instance': name,
+        'device': device,
+        'optimization': optimization,
+        'anti_ban': anti_ban,
+        'enabled_tasks': sorted(enabled),
+    }
+
+
+def _recent_files(pattern: str, limit: int) -> list:
+    try:
+        candidates = [p for p in LOG_DIR.glob(pattern) if p.is_file()]
+    except OSError:
+        return []
+    recent = []
+    for p in candidates:
+        try:
+            recent.append((p.stat().st_mtime, p))
+        except OSError:
+            continue
+    recent.sort(key=lambda item: item[0], reverse=True)
+    return [p for _, p in recent[:limit]]
+
+
+def build_diagnostic_zip(config_name: str = '') -> Path:
+    """config_name 为空或 'Home' 时导出全部实例。"""
+    # 只接受已存在的实例名, 防止 config_name 带 ../ 造成路径穿越
+    valid = ConfigManager.all_script_files()
+    if config_name and config_name in valid:
+        instances = [config_name]
+        tag = config_name
+    else:
+        instances = valid
+        tag = 'all'
+
+    summary = {
+        'generated_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
+        'platform': platform.platform(),
+        'python': sys.version.split()[0],
+        'instances': [_config_summary(n) for n in instances],
+    }
+
+    OUT_DIR.mkdir(parents=True, exist_ok=True)
+    stamp = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
+    zip_path = OUT_DIR / f'oas_diag_{tag}_{stamp}.zip'
+
+    log_files = []
+    for name in instances:
+        log_files += _recent_files(f'*_{name}.txt', _RECENT_INSTANCE_LOGS)
+    log_files += _recent_files('*_api.txt', _RECENT_SHARED_LOGS)
+    log_files += _recent_files('*_server.txt', _RECENT_SHARED_LOGS)
+
+    error_logs = []
+    error_root = LOG_DIR / 'error'
+    if error_root.exists():
+        try:
+            err = [p for p in error_root.glob('*/log.txt') if p.is_file()]
+            err.sort(key=lambda p: p.stat().st_mtime, reverse=True)
+            error_logs = err[:_RECENT_ERROR_LOGS]
+        except OSError:
+            error_logs = []
+
+    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
+        zf.writestr('summary.json', json.dumps(summary, ensure_ascii=False, indent=2))
+        for f in dict.fromkeys(log_files):
+            try:
+                zf.writestr(f'log/{f.name}', _scrub(f.read_text(encoding='utf-8', errors='replace')))
+            except OSError as e:
+                logger.warning(f'diagnostic: skip {f}: {e}')
+        for f in error_logs:
+            try:
+                zf.writestr(f'error/{f.parent.name}/log.txt',
+                            _scrub(f.read_text(encoding='utf-8', errors='replace')))
+            except OSError as e:
+                logger.warning(f'diagnostic: skip {f}: {e}')
+
+    logger.info(f'诊断日志已导出: {zip_path}')
+    return zip_path

+ 11 - 0
module/server/home_router.py

@@ -96,3 +96,14 @@ async def additional_translate() -> dict:
     except Exception as e:
         logger.error(e)
     return {}
+
+
+@home_app.get('/export_diagnostic')
+async def export_diagnostic(config_name: str = ''):
+    from module.server.diagnostic import build_diagnostic_zip
+    try:
+        zip_path = build_diagnostic_zip(config_name)
+        return {'success': True, 'path': str(zip_path)}
+    except Exception as e:
+        logger.exception(e)
+        return {'success': False, 'path': '', 'error': str(e)}

+ 47 - 0
script.py

@@ -318,6 +318,42 @@ class Script:
             if self.config.should_reload():
                 return False
 
+    @staticmethod
+    def _in_sleep_window(t, start, end) -> bool:
+        if start == end:
+            return False
+        if start < end:
+            return start <= t < end
+        return t >= start or t < end
+
+    @staticmethod
+    def _next_time_point(now: datetime, end) -> datetime:
+        candidate = now.replace(hour=end.hour, minute=end.minute, second=end.second, microsecond=0)
+        if candidate <= now:
+            candidate += timedelta(days=1)
+        return candidate
+
+    def _antiban_wake_time(self, now: datetime):
+        ab = self.config.script.anti_ban
+        if not ab.enable:
+            return None
+        wake = None
+        if self._in_sleep_window(now.time(), ab.sleep_start, ab.sleep_end):
+            wake = self._next_time_point(now, ab.sleep_end)
+        limit = ab.daily_active_limit.total_seconds()
+        if limit > 0:
+            if getattr(self, '_active_date', None) != now.date():
+                self._active_date = now.date()
+                self._active_seconds_today = 0
+            rest_until = getattr(self, '_rest_until', None)
+            if rest_until and now < rest_until:
+                wake = max(wake, rest_until) if wake else rest_until
+            elif getattr(self, '_active_seconds_today', 0) >= limit:
+                self._rest_until = now + ab.long_rest_duration
+                self._active_seconds_today = 0
+                wake = max(wake, self._rest_until) if wake else self._rest_until
+        return wake
+
     def get_next_task(self) -> str:
         """
         获取下一个任务的名字, 大驼峰。
@@ -329,6 +365,9 @@ class Script:
             if self.state_queue:
                 self.state_queue.put({"schedule": self.config.get_schedule_data()})
             now = datetime.now()
+            antiban_wake = self._antiban_wake_time(now)
+            if antiban_wake is not None:
+                task.next_run = max(task.next_run, antiban_wake)
             if not self._try_acquire_queue_token():
                 del_cached_property(self, "config")
                 continue
@@ -625,6 +664,9 @@ class Script:
         start_day = date.today()
         logger.info(f'Start scheduler loop: {self.config_name}')
         self.config.model.running_task = ''
+        self._active_seconds_today = 0
+        self._active_date = date.today()
+        self._rest_until = None
 
         # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
         if not self.config.script.device.run_background_only and IS_WINDOWS:
@@ -680,10 +722,15 @@ class Script:
             self.device.click_record_clear()
             logger.hr(task, level=0)
             self.config.model.running_task = task
+            _task_start = datetime.now()
             success = self.run(inflection.camelize(task))
             self.config.model.running_task = ''
             logger.info(f'Scheduler: End task `{task}`')
             self.is_first_task = False
+            if self._active_date != date.today():
+                self._active_date = date.today()
+                self._active_seconds_today = 0
+            self._active_seconds_today += (datetime.now() - _task_start).total_seconds()
 
             # Check failures
             # failed = deep_get(self.failure_record, keys=task, default=0)

+ 2 - 1
tasks/KekkaiUtilize/config.py

@@ -3,7 +3,7 @@
 # github https://github.com/runhey
 from pydantic import BaseModel, Field
 from enum import Enum
-from datetime import datetime, time
+from datetime import datetime, time, timedelta
 
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_base import ConfigBase, TimeDelta
@@ -31,6 +31,7 @@ class UtilizeConfig(BaseModel):
     select_friend_list: SelectFriendList = Field(default=SelectFriendList.SAME_SERVER, description='select_friend_list_help')
     shikigami_class: ShikigamiClass = Field(default=ShikigamiClass.N, description='shikigami_class_help')
     shikigami_order: int = Field(default=4, description='shikigami_order_help')
+    min_run_interval: TimeDelta = Field(default=timedelta(0), description='min_run_interval_help')
     harvest_guild_max_times: int = Field(default=3, description='收取寮资金或体力失败的最大尝试次数')
     utilize_enable: bool = Field(default=True, description='是否蹭卡,小号可以选择不蹭卡')
     guild_ap_enable: bool = Field(default=True, description='guild_ap_enable_help')

+ 3 - 0
tasks/KekkaiUtilize/script_task.py

@@ -92,6 +92,9 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
                 # 已经蹭上卡了,设置下次蹭卡时间  # 减少30秒
                 # remaining_time = remaining_time - timedelta(seconds=30)
                 next_time = datetime.now() + remaining_time
+                min_interval = con.min_run_interval
+                if min_interval and min_interval.total_seconds() > 0:
+                    next_time = max(next_time, datetime.now() + min_interval)
                 self.set_next_run(task='KekkaiUtilize', target=next_time)
                 return
             if not self.grown_goto_utilize():

+ 3 - 1
tasks/Script/config.py

@@ -6,9 +6,11 @@ from pydantic import BaseModel, Field
 from tasks.Script.config_device import Device
 from tasks.Script.config_error import Error
 from tasks.Script.config_optimization import Optimization
+from tasks.Script.config_antiban import AntiBan
 
 
 class Script(BaseModel):
     device: Device = Field(default_factory=Device)
     error: Error = Field(default_factory=Error)
-    optimization: Optimization = Field(default_factory=Optimization)
+    optimization: Optimization = Field(default_factory=Optimization)
+    anti_ban: AntiBan = Field(default_factory=AntiBan)

+ 18 - 0
tasks/Script/config_antiban.py

@@ -0,0 +1,18 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+from datetime import timedelta
+from pydantic import BaseModel, Field
+
+from tasks.Component.config_base import Time, TimeDelta
+
+
+class AntiBan(BaseModel):
+    enable: bool = Field(default=False, description='antiban_enable_help')
+    sleep_start: Time = Field(default=Time(hour=2, minute=0, second=0),
+                              description='sleep_start_help')
+    sleep_end: Time = Field(default=Time(hour=8, minute=0, second=0),
+                            description='sleep_end_help')
+    daily_active_limit: TimeDelta = Field(default=timedelta(hours=0),
+                                          description='daily_active_limit_help')
+    long_rest_duration: TimeDelta = Field(default=timedelta(hours=2),
+                                          description='long_rest_duration_help')