Browse Source

Merge nearaura invitation, mail timeout and console logging fixes

Review nearaura/dev 5ae88f00..48a5978b after runhey returned Repository not found.
Integrate PR #42 using its resolved first-parent delta (f5856bbe, e5269aa8,
540129ad) and replay 4b1a06d1, ab16df35, 12afdc07 and 48a5978b with source
IDs. The reviewed source tree matches upstream outside the previously
deferred AutoCheckinBigGod change b2f02602.

Use the upstream invitation-confirmation PNG verbatim and align its rule
and JSON to 132x60 at (517,553). Keep the search region covering both dialog
positions. Match tab colors from the supplied templates in their exact
foreground regions in both auto and recent-friend mode. Retain optional ROI
overrides and clear the cached template color on refresh. Stop inviting
when a three-person room fills and use the available first slot when needed.

Skip mail harvesting if opening the mailbox times out after 15 seconds.
Keep local claim-before-read ordering, popup recovery and reward timeout.
Keep the actual 173x121 Six Realms failure portrait and 173x122 search area,
updating the description from the resolved upstream merge. Adopt console
failure isolation, the EternitySea direct-run entry and .workbuddy ignore.

605 tests passed (tests/ and both FrogBoss suites), six deprecation warnings.
Verified changed Python syntax and imports, four upstream PNGs byte-for-byte,
rule and JSON dimensions, both invitation positions, refreshed template colors,
broken stdout/stderr logging and git diff --check. No emulator run.
unknown 6 hours ago
parent
commit
05e3709043

+ 2 - 0
.gitignore

@@ -277,3 +277,5 @@ oas.bat
 
 # Per-instance FrogBoss prediction and result history
 data/frog_oas/
+
+.workbuddy

+ 7 - 3
module/atom/image.py

@@ -236,7 +236,7 @@ class RuleImage(RuleImageMallResourceMixin):
         self._match_init = False
         self.last_score = -1.0
         self.last_scale = None
-        for cached_name in ('name', 'kp', 'des', 'is_template_match', 'is_sift_flann',
+        for cached_name in ('name', 'mean_color', 'kp', 'des', 'is_template_match', 'is_sift_flann',
                             'is_masked_template_match', 'is_multi_scale_template_match'):
             del_cached_property(self, cached_name)
 
@@ -567,6 +567,10 @@ class RuleImage(RuleImageMallResourceMixin):
             cv2.destroyAllWindows()
         return result
 
+    @cached_property
+    def mean_color(self) -> tuple:
+        return tuple(cv2.mean(self.image)[:3])
+
     def match_mean_color(self, image, color: tuple, bias=10, roi=None) -> bool:
         """
 
@@ -575,10 +579,10 @@ class RuleImage(RuleImageMallResourceMixin):
         :param bias:
         :return:
         """
-        image = self.corp(image, roi)
+        image = self.corp(image, self.roi_front if roi is None else roi)
         average_color = cv2.mean(image)
         if self.debug_mode:
-            logger.info(f'{self.name} average_color: {average_color}')
+            logger.info(f'{self.name} average_color: {average_color}, template: {color}, bias: {bias}')
         for i in range(3):
             if abs(average_color[i] - color[i]) > bias:
                 return False

+ 13 - 5
module/logger.py

@@ -114,6 +114,8 @@ console_hdlr = RichHandler(
     tracebacks_width=160
 )
 console_hdlr.setFormatter(console_formatter)
+# 控制台写失败时 logging 会往 stderr 打 traceback,stderr 同样失效就是二次抛错
+console_hdlr.handleError = empty_function
 logger.addHandler(console_hdlr)
 
 
@@ -264,11 +266,17 @@ def _get_renderables(
 
 def print(*objects: ConsoleRenderable, **kwargs):
     for hdlr in logger.handlers:
-        if isinstance(hdlr, FlutterHandler):
-            for renderable in _get_renderables(hdlr.console, *objects, **kwargs):
-                hdlr.console.file._func(str(renderable))
-        elif isinstance(hdlr, RichHandler):
-            hdlr.console.print(*objects)
+        try:
+            if isinstance(hdlr, FlutterHandler):
+                for renderable in _get_renderables(hdlr.console, *objects, **kwargs):
+                    hdlr.console.file._func(str(renderable))
+            elif isinstance(hdlr, RichHandler):
+                hdlr.console.print(*objects)
+        except Exception as e:
+            # 控制台写失败不能中断业务,只提示一次
+            if not getattr(logger, 'console_error', False):
+                logger.console_error = True
+                logger.warning(f'Console output is unavailable: {e!r}')
 
 
 class GuiRule(Rule):

+ 1 - 1
tasks/Component/GeneralInvite/assets.py

@@ -46,7 +46,7 @@ class GeneralInviteAssets:
 	# 左上角退出 
 	I_BACK_YELLOW = RuleImage(roi_front=(19,13,58,55), roi_back=(19,13,58,55), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_back_yellow.png")
 	# 点击邀请 
-	I_INVITE_ENSURE = RuleImage(roi_front=(549,567,68,32), roi_back=(473,505,409,121), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_invite_ensure.png")
+	I_INVITE_ENSURE = RuleImage(roi_front=(517,553,132,60), roi_back=(473,505,409,121), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_invite_ensure.png")
 	# 判断是否点中好友了 
 	I_SELECTED = RuleImage(roi_front=(895,373,33,32), roi_back=(895,373,33,32), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_selected.png")
 	# 用来判断当前的列表是哪儿的 

+ 9 - 5
tasks/Component/GeneralInvite/general_invite.py

@@ -348,6 +348,12 @@ class GeneralInvite(BaseTask, GeneralInviteAssets):
                 break
             if self.appear_then_click(self.I_ADD_2, interval=1):
                 continue
+            if self.is_in_room(False) and self.room_type == RoomType.NORMAL_3:
+                if not self.appear(self.I_ADD_1) and not self.appear(self.I_ADD_2):
+                    logger.info('Room filled while preparing another invitation')
+                    return True
+                if self.appear_then_click(self.I_ADD_1, interval=1):
+                    continue
             if self.appear_then_click(self.I_ADD_5_4, interval=1):
                 continue
             if self.appear_then_click(self.I_ADD_SEA, interval=1):
@@ -392,7 +398,7 @@ class GeneralInvite(BaseTask, GeneralInviteAssets):
             recent_index = friend_class.index('最近')
             while recent_index == 1:
                 self.screenshot()
-                if self.appear(self.I_FLAG_2_ON):
+                if self.I_FLAG_2_ON.match_mean_color(self.device.image, self.I_FLAG_2_ON.mean_color, 10):
                     break
                 if self.appear_then_click(self.I_FLAG_2_OFF, interval=1):
                     continue
@@ -417,15 +423,13 @@ class GeneralInvite(BaseTask, GeneralInviteAssets):
             # 首先切换到不同的好友列表
             while index == 0:
                 self.screenshot()
-                # Sample only the badge, excluding the desktop template search padding.
-                flag = self.I_FLAG_1_ON
-                if flag.match_mean_color(self.device.image, (227, 193, 153), roi=flag.roi_back):
+                if self.I_FLAG_1_ON.match_mean_color(self.device.image, self.I_FLAG_1_ON.mean_color, 10):
                     break
                 if self.click(self.I_FLAG_1_OFF, interval=1):
                     continue
             while index == 1:
                 self.screenshot()
-                if self.appear(self.I_FLAG_2_ON):
+                if self.I_FLAG_2_ON.match_mean_color(self.device.image, self.I_FLAG_2_ON.mean_color, 10):
                     break
                 if self.appear_then_click(self.I_FLAG_2_OFF, interval=1):
                     continue

BIN
tasks/Component/GeneralInvite/gi/gi_invite_ensure.png


+ 1 - 1
tasks/Component/GeneralInvite/gi/image.json

@@ -155,7 +155,7 @@
   {
     "itemName": "invite_ensure",
     "imageName": "gi_invite_ensure.png",
-    "roiFront": "549,567,68,32",
+    "roiFront": "517,553,132,60",
     "roiBack": "473,505,409,121",
     "method": "Template matching",
     "threshold": 0.8,

+ 1 - 1
tasks/EternitySea/script_task.py

@@ -333,4 +333,4 @@ if __name__ == "__main__":
     c = Config("oas1")
     d = Device(c)
     t = ScriptTask(c, d)
-    t.screenshot()
+    t.run()

+ 4 - 3
tasks/Restart/login.py

@@ -344,13 +344,14 @@ class LoginHandler(BaseTask, RestartAssets, GameUiAssets, GeneralBuffAssets):
                 not self.appear(self.I_HARVEST_MAIL_COPY):
             return False
         logger.info('Harvest mail')
-        open_timer = Timer(10).start()
+        open_mail_timer = Timer(15).start()
         while 1:
             self.screenshot()
             if any(self.appear(asset) for asset in mail_screens):
                 break
-            if open_timer.reached():
-                raise GameStuckError('Open mail timeout')
+            if open_mail_timer.reached():
+                logger.warning('Harvest mail page did not open within 15 seconds, skip mail harvest')
+                return False
             if self.appear_then_click_multi_scale(self.I_HARVEST_MAIL, interval=1.5, scale_range=(0.8, 1.1)):
                 continue
             if self.appear_then_click(self.I_HARVEST_MAIL_COPY, interval=1.5):

+ 1 - 1
tasks/SixRealms/assets.py

@@ -34,7 +34,7 @@ class SixRealmsAssets:
 	I_BOSS_SHARE = RuleImage(roi_front=(1090,604,70,74), roi_back=(1074,587,100,100), threshold=0.8, method="Template matching", file="./tasks/SixRealms/gate1/gate1_boss_share.png")
 	# 结算的椒图 
 	I_BOSS_SHUTU = RuleImage(roi_front=(108,141,173,122), roi_back=(108,141,173,122), threshold=0.8, method="Template matching", file="./tasks/SixRealms/gate1/gate1_boss_shutu.png")
-	# description
+	# 失败的结算的椒图
 	I_BOSS_SHUTU2 = RuleImage(roi_front=(108,141,173,121), roi_back=(108,141,173,122), threshold=0.8, method="Template matching", file="./tasks/SixRealms/gate1/gate1_boss_shutu2.png")
 	# description
 	I_BOSS_BATTLE_AGAIN = RuleImage(roi_front=(435,403,173,64), roi_back=(409,390,212,100), threshold=0.8, method="Template matching", file="./tasks/SixRealms/gate1/gate1_boss_battle_again.png")

+ 1 - 1
tasks/SixRealms/gate1/boss.json

@@ -78,7 +78,7 @@
     "roiBack": "108,141,173,122",
     "method": "Template matching",
     "threshold": 0.8,
-    "description": "description"
+    "description": "失败的结算的椒图"
   },
   {
     "itemName": "boss_battle_again",

+ 42 - 1
tests/tasks/Component/GeneralInvite/test_friend_tab.py

@@ -4,7 +4,8 @@ import numpy as np
 import pytest
 
 from module.atom import image
-from tasks.Component.GeneralInvite.general_invite import GeneralInvite
+from tasks.Component.GeneralInvite.config_invite import FindMode
+from tasks.Component.GeneralInvite.general_invite import GeneralInvite, RoomType
 
 
 @pytest.mark.parametrize('padding', [0, 2])
@@ -39,3 +40,43 @@ def test_first_friend_tab_ignores_surrounding_colors(monkeypatch, padding):
     monkeypatch.setattr('tasks.Component.GeneralInvite.general_invite.sleep', lambda _: None)
     assert task.invite_friend('friend')
     assert clicks == [task.I_FLAG_1_OFF]
+
+
+@pytest.mark.parametrize('mode', [FindMode.AUTO_FIND, FindMode.RECENT_FRIEND])
+def test_second_tab_uses_selected_template_inside_wider_search_area(monkeypatch, mode):
+    task = object.__new__(GeneralInvite)
+    frame = np.zeros((720, 1280, 3), dtype=np.uint8)
+    task.device = SimpleNamespace(image=frame)
+    for index, label in enumerate(('好友', '最近', '', ''), start=1):
+        setattr(task, f'O_F_LIST_{index}', SimpleNamespace(ocr=lambda _, label=label: label))
+
+    def show_selected(rule):
+        x, y, w, h = rule.roi_front
+        frame[y:y+h, x:x+w] = rule.image
+
+    show_selected(task.I_FLAG_1_ON)
+    clicks = []
+
+    def click(rule, interval):
+        assert rule is task.I_FLAG_2_OFF and not clicks
+        clicks.append(rule)
+        show_selected(task.I_FLAG_2_ON)
+        return True
+
+    task.appear = lambda rule: rule is task.I_LOAD_FRIEND
+    task.appear_then_click = click
+    task.screenshot = lambda: None
+    task.detect_select = lambda name: bool(clicks)
+    monkeypatch.setattr('tasks.Component.GeneralInvite.general_invite.sleep', lambda _: None)
+    assert task.invite_friend('friend', mode)
+    assert clicks == [task.I_FLAG_2_OFF]
+
+
+def test_full_three_player_room_finishes_before_opening_another_invitation():
+    task = object.__new__(GeneralInvite)
+    task.room_type = RoomType.NORMAL_3
+    task.appear = lambda rule: rule is task.I_GI_EMOJI_1
+    frames = iter([None])
+    task.screenshot = lambda: next(frames)
+    task.appear_then_click = lambda rule, interval: False
+    assert task.invite_friend('friend')

+ 3 - 3
tests/tasks/Component/GeneralInvite/test_invite_asset.py

@@ -11,8 +11,8 @@ from tasks.Component.GeneralInvite.assets import GeneralInviteAssets
 
 
 @pytest.mark.parametrize('pad', [0, 2])
-@pytest.mark.parametrize('position,expected', [((742, 558), True), ((549, 567), True), ((100, 100), False)])
-def test_cropped_invitation_template_covers_both_dialog_positions(monkeypatch, pad, position, expected):
+@pytest.mark.parametrize('position,expected', [((710, 544), True), ((517, 553), True), ((100, 100), False)])
+def test_invitation_template_covers_both_dialog_positions(monkeypatch, pad, position, expected):
     monkeypatch.setattr(image_module, 'ROI_MATCH_PAD', pad)
     rule = deepcopy(GeneralInviteAssets.I_INVITE_ENSURE)
     template = rule.image
@@ -30,7 +30,7 @@ def test_invitation_metadata_keeps_crop_and_search_region_consistent():
     rows = json.loads(Path('tasks/Component/GeneralInvite/gi/image.json').read_text(encoding='utf-8'))
     row, = [entry for entry in rows if entry['itemName'] == 'invite_ensure']
     with Image.open(rule.file) as template:
-        assert template.size == (68, 32) == tuple(rule.roi_front[2:])
+        assert template.size == (132, 60) == tuple(rule.roi_front[2:])
         template.verify()
     assert tuple(map(int, row['roiFront'].split(','))) == tuple(rule.roi_front)
     assert tuple(map(int, row['roiBack'].split(','))) == tuple(rule.roi_back)

+ 10 - 0
tests/tasks/Restart/test_mail.py

@@ -147,3 +147,13 @@ def test_no_mail_does_not_click(monkeypatch, mail_screens):
 
     assert task.harvest_mail() is False
     assert task.clicks == []
+
+
+def test_unopened_mailbox_skips_harvest_after_fifteen_seconds(monkeypatch, mail_screens):
+    task = MailReplay(monkeypatch, mail_screens, screen='closed', frame_seconds=1)
+    task.appear_multi_scale = lambda *args, **kwargs: True
+    task.appear_then_click_multi_scale = lambda *args, **kwargs: True
+    start = task.now
+    assert task.harvest_mail() is False
+    assert 15 <= task.now - start <= 16
+    assert task.clicks == []