diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 4d73f77..477e202 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -303,6 +303,17 @@ class underlying_operations: # 注释掉全局日志禁用,以便查看详细的计时日志 # logging.disable(logging.DEBUG) # logging.disable(logging.WARNING) + # 用于短期内记录 get_screenshot 调用来源(用于精确定位高频调用) + try: + import collections + + self._screenshot_call_cache = collections.deque(maxlen=1000) + except Exception: + self._screenshot_call_cache = [] + # 日志文件路径(JSON Lines 格式) + self._screenshot_log_path = os.path.join( + os.path.dirname(__file__), "logs", "screenshot_calls.jsonl" + ) @staticmethod def _adb() -> str: @@ -498,6 +509,48 @@ class underlying_operations: 是否成功获取截图 """ start_ts = time_module.time() + # Diagnostic: record pre-call info including caller stack (top frames) + try: + import inspect, json, threading + + frames = [] + for fr in inspect.stack()[1:9]: + frame_info = { + "file": os.path.relpath(fr.filename, os.path.dirname(__file__)), + "line": fr.lineno, + "function": fr.function, + } + frames.append(frame_info) + + pre_record = { + "ts": datetime.now().isoformat(), + "device_id": device_id, + "use_service": bool(use_service), + "path": path, + "phase": "start", + "thread": threading.get_ident(), + "stack": frames, + } + # cache in memory + try: + if hasattr(self, "_screenshot_call_cache"): + try: + self._screenshot_call_cache.append(pre_record) + except Exception: + pass + except Exception: + pass + + # append JSON line to log file + try: + log_dir = os.path.join(os.path.dirname(__file__), "logs") + os.makedirs(log_dir, exist_ok=True) + with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: + _lf.write(json.dumps(pre_record, ensure_ascii=False) + "\n") + except Exception: + pass + except Exception: + pass # 如果启用服务模式,使用后台截图服务;若服务不可用或返回 False,则回退到直接截图 if use_service: try: @@ -527,7 +580,34 @@ class underlying_operations: logging.info( "[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id ) - return True + # 写结束记录 + try: + import json, threading + + end_record = { + "ts": datetime.now().isoformat(), + "device_id": device_id, + "use_service": True, + "path": path, + "phase": "end", + "result": True, + "duration_ms": dur, + "thread": threading.get_ident(), + } + try: + if hasattr(self, "_screenshot_call_cache"): + self._screenshot_call_cache.append(end_record) + except Exception: + pass + try: + with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: + _lf.write(json.dumps(end_record, ensure_ascii=False) + "\n") + except Exception: + pass + except Exception: + pass + # do not return here; let final return at function end + result = True else: timetag = datetime.now().strftime("%H:%M:%S") logging.info( @@ -542,6 +622,8 @@ class underlying_operations: timetag, e, ) + # ensure result exists + result = False except ImportError as e: timetag = datetime.now().strftime("%H:%M:%S") logging.warning( @@ -549,23 +631,62 @@ class underlying_operations: timetag, e, ) + result = False except Exception as e: timetag = datetime.now().strftime("%H:%M:%S") logging.warning( "[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e ) + result = False # 原有的直接截图逻辑(保持向后兼容),测量其耗时 - result = self._get_screenshot_direct(device_id, path) + try: + # If result already set by service branch, skip direct call + if "result" in locals() and locals()["result"] is True: + # already successful via service + final_result = True + else: + final_result = self._get_screenshot_direct(device_id, path) + except Exception: + final_result = False + dur = (time_module.time() - start_ts) * 1000.0 logging.info( "[截图] 总耗时(ms)=%.1f device=%s use_service=%s result=%s", dur, device_id, bool(use_service), - result, + final_result, ) - return result + + # 写结束记录(包含持续时长与结果) + try: + import json, threading + + end_record = { + "ts": datetime.now().isoformat(), + "device_id": device_id, + "use_service": bool(use_service), + "path": path, + "phase": "end", + "result": bool(final_result), + "duration_ms": dur, + "thread": threading.get_ident(), + } + try: + if hasattr(self, "_screenshot_call_cache"): + self._screenshot_call_cache.append(end_record) + except Exception: + pass + try: + with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf: + _lf.write(json.dumps(end_record, ensure_ascii=False) + "\n") + except Exception: + pass + except Exception: + pass + + return bool(final_result) def _get_screenshot_direct(self, device_id, path="pic"): """直接截图(不使用服务模式)""" diff --git a/config/config.json b/config/config.json index 35b649d..6b3bbfc 100644 --- a/config/config.json +++ b/config/config.json @@ -7,7 +7,8 @@ "max_participants": 0, "skip_if_countdown_gt_seconds": 180, "reset_after_swipes_enabled": true, - "reset_after_swipes": 30, + "reset_after_swipes": 10, + "reset_after_swipes_action": "back", "auto_join_fansclub": true, "fansclub_fail_action": "switch", "high_value_fudai_enabled": true, @@ -29,8 +30,8 @@ "yanghao_fallback_enter_live_y": 1200, "fudai_find_max_attempts": 99999, "fudai_icon_retry_delay_seconds": 0.1, - "fudai_icon_max_wait_seconds": 8.0, - "fudai_click_wait_seconds": 1.7, + "fudai_icon_max_wait_seconds": 6.5, + "fudai_click_wait_seconds": 1.0, "fudai_detail_initial_wait_seconds": 0.8, "fudai_detail_verified_wait_seconds": 0.2, "fudai_detail_retry_delay_seconds": 0.5, @@ -185,8 +186,8 @@ }, "debug_captures": { "enabled": false, - "keep_days": 3, - "max_files": 2000, + "keep_days": 1, + "max_files": 100, "auto_cleanup": true, "async_save": false, "log_on_complete": false diff --git a/douyin/core/douyin_flow_control.py b/douyin/core/douyin_flow_control.py index cb65931..7caebfd 100644 --- a/douyin/core/douyin_flow_control.py +++ b/douyin/core/douyin_flow_control.py @@ -199,20 +199,40 @@ def find_and_open_fudai_detail( enabled = True if enabled: + # 若最近已有由滑动重置触发的回退,且在短时间内,跳过本次返回键调用以避免重复 try: - analyser.operation.click_back(analyser.device_id) + import time as _time + + recent_ts = getattr(analyser, "_recent_reset_ts", 0) + if recent_ts and (_time.time() - float(recent_ts) < 5.0): + try: + analyser._log_kv( + "流程", + "检测到近期已由滑动重置触发回退,跳过重复按返回键", + ) + except Exception: + pass + else: + try: + analyser.operation.click_back(analyser.device_id) + except Exception: + try: + # 兜底:使用通用 click 返回坐标 + rx = int( + getattr(analyser, "resolution_ratio_x", 1080) or 1080 + ) + ry = int( + getattr(analyser, "resolution_ratio_y", 2400) or 2400 + ) + back_x = int(50 * rx / 1080) + back_y = int(50 * ry / 2400) + analyser.operation.click(analyser.device_id, back_x, back_y) + except Exception: + pass except Exception: + # 在异常情况下保守地尝试按返回键 try: - # 兜底:使用通用 click 返回坐标 - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - back_x = int(50 * rx / 1080) - back_y = int(50 * ry / 2400) - analyser.operation.click(analyser.device_id, back_x, back_y) + analyser.operation.click_back(analyser.device_id) except Exception: pass else: diff --git a/douyin/handlers/douyin_swipe_handler.py b/douyin/handlers/douyin_swipe_handler.py index a2ea1c2..17828cd 100644 --- a/douyin/handlers/douyin_swipe_handler.py +++ b/douyin/handlers/douyin_swipe_handler.py @@ -206,8 +206,23 @@ class SwipeHandler: if mode not in ("swipe", "back"): mode = "swipe" + # 如果显式启用了达到未找到福袋阈值时按返回键回退(GUI 勾选),优先使用返回键回退 + try: + if bool(getattr(analyser, "enable_back_on_misses", False)): + mode = "back" + except Exception: + pass + if mode == "back": # 使用返回键回退(兼容性更好,适用于无法通过滑动稳定回退的设备) + # 标记:开始通过滑动重置/回退流程,防止其他路径重复触发返回键 + try: + import time as _time + + setattr(analyser, "_recent_reset_ts", _time.time()) + setattr(analyser, "_recent_reset_by", "swipe_reset") + except Exception: + pass for i in range(back_times): try: analyser.operation.click_back(analyser.device_id) @@ -278,12 +293,16 @@ class SwipeHandler: analyser.operation.delay(2) except Exception: pass - # 回到第一个后,计数归零 analyser.operation.delay(3) try: analyser._swipe_times = 0 analyser.room_pos = 0 + # 清除连续未找到福袋计数,避免与其他回退逻辑重复 + try: + setattr(analyser, "_consecutive_no_fudai_count", 0) + except Exception: + pass except Exception: pass return 0 diff --git a/douyin/utils/douyin_config.py b/douyin/utils/douyin_config.py index 901da28..9e77834 100644 --- a/douyin/utils/douyin_config.py +++ b/douyin/utils/douyin_config.py @@ -244,6 +244,24 @@ class ConfigManager: if "reset_after_swipes" in config: analyser.reset_after_swipes = int(config["reset_after_swipes"] or 10) + # 回退方式配置:'swipe'(默认)或 'back' + if "reset_after_swipes_action" in config: + try: + analyser.reset_after_swipes_action = str( + config["reset_after_swipes_action"] or "swipe" + ).lower() + except Exception: + analyser.reset_after_swipes_action = "swipe" + if analyser.reset_after_swipes_action not in ("swipe", "back"): + analyser.reset_after_swipes_action = "swipe" + + # 启用/禁用:达到连续未找到福袋阈值时按返回键回退 + if "enable_back_on_misses" in config: + try: + analyser.enable_back_on_misses = bool(config["enable_back_on_misses"]) + except Exception: + analyser.enable_back_on_misses = True + # 新增:下滑达到阈值后按返回并重新进入直播间的配置 if "swipe_down_back_enabled" in config: analyser.swipe_down_back_enabled = bool(config["swipe_down_back_enabled"]) diff --git a/gui/gui_app.py b/gui/gui_app.py index 9c8df98..7b32e71 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -317,7 +317,7 @@ def main(): side=LEFT, padx=(0, 12) ) # 连续无福袋退出阈值变量(提前声明,实际声明在下方唯一位置以便与配置同步) - #(变量将在后面统一声明,避免重复创建 IntVar 导致绑定不一致) + # (变量将在后面统一声明,避免重复创建 IntVar 导致绑定不一致) # 启用返回键回退开关变量(提前声明) enable_back_on_misses_var = tk.BooleanVar( value=bool(cfg.get("enable_back_on_misses", True)) @@ -1860,6 +1860,12 @@ def main(): ) cfg2["fudai_exit_after_misses"] = int(fudai_exit_after_misses_var.get() or 30) cfg2["enable_back_on_misses"] = bool(enable_back_on_misses_var.get()) + # 如果勾选了启用返回键回退,同时将滑动重置的回退方式设置为按返回键,保持与 UI 预期一致 + if bool(enable_back_on_misses_var.get()): + cfg2["reset_after_swipes_action"] = "back" + else: + # 保留已有配置,若不存在则设为默认的滑动回退 + cfg2.setdefault("reset_after_swipes_action", "swipe") cfg2["fudai_disable_content_recognition"] = bool( fudai_disable_content_recognition_var.get() ) @@ -2606,6 +2612,13 @@ def main(): log_search_frame = ttk.Frame(log_box) log_search_frame.pack(fill=X, padx=10, pady=(10, 5)) + # 关键字筛选(与行为日志一致) + log_filter_var = tk.StringVar(value="") + ttk.Label(log_search_frame, text="筛选:").pack(side=LEFT) + ttk.Entry(log_search_frame, textvariable=log_filter_var, width=16).pack( + side=LEFT, padx=(0, 8) + ) + log_search_var = tk.StringVar(value="") log_search_entry = ttk.Entry( log_search_frame, textvariable=log_search_var, width=20 @@ -3090,6 +3103,13 @@ def main(): while True: line = q.get_nowait() + # 运行日志关键字筛选(与行为日志一致) + try: + kw = log_filter_var.get().strip() + if kw and kw not in line: + continue + except Exception: + pass try: # 插入日志行并应用颜色标签 start_pos = log_text.index("end-1c") diff --git a/gui/gui_core.py b/gui/gui_core.py index 9dbb5e0..78cf85c 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -985,6 +985,12 @@ class Runner: cmd.append("--enable-back-on-misses") else: cmd.append("--disable-back-on-misses") + # 确保从 GUI 启动时传递回退方式(若启用返回键回退,则将 reset action 设为 back) + try: + if getattr(params, "enable_back_on_misses", False): + cmd += ["--reset-after-swipes-action", "back"] + except Exception: + pass # 只养号模式:如果启用则传递到 run_cli.py try: diff --git a/run_cli.py b/run_cli.py index d77b292..902920d 100644 --- a/run_cli.py +++ b/run_cli.py @@ -571,6 +571,18 @@ def main(argv: list[str]) -> int: except Exception: pass + # CLI 覆盖:启用/禁用 达到连续未找到福袋阈值时按返回键回退 + if getattr(args, "enable_back_on_misses", False): + try: + analyser.enable_back_on_misses = True + except Exception: + pass + if getattr(args, "disable_back_on_misses", False): + try: + analyser.enable_back_on_misses = False + except Exception: + pass + device_id = args.device_id.strip() if args.device_id else "" if not device_id: device_id = analyser.operation.select_device() diff --git a/test_screencap.png b/test_screencap.png new file mode 100644 index 0000000..c9e057e Binary files /dev/null and b/test_screencap.png differ diff --git a/tools/diagnose_runtime_flags.py b/tools/diagnose_runtime_flags.py new file mode 100644 index 0000000..c64695f --- /dev/null +++ b/tools/diagnose_runtime_flags.py @@ -0,0 +1,19 @@ +from douyin.core.douyin_fudai import fudai_analyse +from douyin.utils import douyin_config + + +def main(): + a = fudai_analyse() + print('Before load:') + print(' enable_back_on_misses attr ->', getattr(a, 'enable_back_on_misses', None)) + print(' reset_after_swipes_action attr ->', getattr(a, 'reset_after_swipes_action', None)) + print(' fudai_exit_after_misses attr ->', getattr(a, 'fudai_exit_after_misses', None)) + # load from config + douyin_config.ConfigManager.load_config_from_file(a) + print('\nAfter load_config_from_file:') + print(' enable_back_on_misses ->', getattr(a, 'enable_back_on_misses', None)) + print(' reset_after_swipes_action ->', getattr(a, 'reset_after_swipes_action', None)) + print(' fudai_exit_after_misses ->', getattr(a, 'fudai_exit_after_misses', None)) + +if __name__ == '__main__': + main() diff --git a/tools/dism_restorehealth_from_iso.ps1 b/tools/dism_restorehealth_from_iso.ps1 new file mode 100644 index 0000000..a271ed3 --- /dev/null +++ b/tools/dism_restorehealth_from_iso.ps1 @@ -0,0 +1,87 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)] + [string]$IsoPath, + + [int]$Index = 0, + + [switch]$NoUnmount +) + +$ErrorActionPreference = 'Stop' + +function Write-Section([string]$title) { + Write-Host "" + Write-Host "=== $title ===" +} + +function Test-IsAdmin { + $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +if (!(Test-IsAdmin)) { + throw 'Please run this script as Administrator.' +} + +$isoFull = (Resolve-Path $IsoPath).Path +if (!(Test-Path -LiteralPath $isoFull)) { + throw "ISO not found: $isoFull" +} + +Write-Section 'Mount ISO' +Write-Host "ISO: $isoFull" + +$disk = Mount-DiskImage -ImagePath $isoFull -PassThru +Start-Sleep -Seconds 1 +$vol = ($disk | Get-Volume | Select-Object -First 1) +if ($null -eq $vol -or [string]::IsNullOrWhiteSpace($vol.DriveLetter)) { + throw 'Failed to get mounted ISO drive letter.' +} +$drive = ($vol.DriveLetter + ':') +Write-Host "Mounted drive: $drive" + +try { + Write-Section 'Locate install.wim/install.esd' + $wim = Join-Path $drive 'sources\install.wim' + $esd = Join-Path $drive 'sources\install.esd' + + $imagePath = $null + if (Test-Path -LiteralPath $wim) { $imagePath = $wim } + elseif (Test-Path -LiteralPath $esd) { $imagePath = $esd } + else { throw 'install.wim/install.esd not found under sources\\' } + + Write-Host "Image: $imagePath" + + Write-Section 'Show available indexes' + dism /English /Get-WimInfo /WimFile:"$imagePath" + + if ($Index -le 0) { + Write-Host "\nIndex is 0: please re-run with -Index matching your edition (e.g. Pro/Home)." + return + } + + Write-Section 'DISM RestoreHealth (from ISO source)' + Write-Host "Using Index: $Index" + + $sourceArg = if ($imagePath.ToLowerInvariant().EndsWith('.wim')) { + "wim:$imagePath:$Index" + } else { + "esd:$imagePath:$Index" + } + + dism /Online /Cleanup-Image /RestoreHealth /Source:$sourceArg /LimitAccess + + Write-Section 'SFC Scannow' + sfc /scannow + + Write-Host '\nDone. Reboot recommended.' +} +finally { + if (-not $NoUnmount) { + Write-Section 'Unmount ISO' + Dismount-DiskImage -ImagePath $isoFull -ErrorAction SilentlyContinue + } else { + Write-Host 'NoUnmount set; ISO left mounted.' + } +} diff --git a/tools/fix_start_menu_win11.ps1 b/tools/fix_start_menu_win11.ps1 new file mode 100644 index 0000000..fbe17d7 --- /dev/null +++ b/tools/fix_start_menu_win11.ps1 @@ -0,0 +1,226 @@ +[CmdletBinding()] +param( + [ValidateSet('Auto','Diagnose','FixShortcuts','RestartShell','ReregisterAppx')] + [string]$Mode = 'Auto' +) + +$ErrorActionPreference = 'Stop' + +function Write-Section([string]$title) { + Write-Host "" + Write-Host "=== $title ===" +} + +function Test-IsAdmin { + $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +function Get-UserSid { + return ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value +} + +function Get-ProfileImagePathFromRegistry([string]$sid) { + $key = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid" + if (Test-Path $key) { + return (Get-ItemProperty $key).ProfileImagePath + } + return $null +} + +function Get-LnkCount([string]$path) { + if (!(Test-Path $path)) { return -1 } + return (Get-ChildItem -LiteralPath $path -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | Measure-Object).Count +} + +function Ensure-Directory([string]$path) { + if (!(Test-Path $path)) { + New-Item -ItemType Directory -Path $path -Force | Out-Null + } +} + +function Get-StartMenuPaths { + $programsUser = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs' + $programsCommon = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs' + + return [pscustomobject]@{ + ProgramsUser = $programsUser + ProgramsCommon = $programsCommon + } +} + +function Find-CandidateProgramsUserPaths([string]$currentProgramsUser) { + $candidates = @() + + $user = [Environment]::UserName + + $roots = @('C:\Users', 'D:\Users', 'E:\Users', 'C:\Windows.old\Users') + foreach ($root in $roots) { + if (!(Test-Path $root)) { continue } + + Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue | ForEach-Object { + $candidate = Join-Path $_.FullName 'AppData\Roaming\Microsoft\Windows\Start Menu\Programs' + if ($candidate -ine $currentProgramsUser -and (Test-Path -LiteralPath $candidate -ErrorAction SilentlyContinue)) { + $count = Get-LnkCount $candidate + $candidates += [pscustomobject]@{ Path = $candidate; LnkCount = $count } + } + } + } + + $candidates | Sort-Object LnkCount -Descending | Select-Object -First 10 +} + +function Backup-Folder([string]$sourcePath, [string]$backupRoot) { + if (!(Test-Path $sourcePath)) { return $null } + + Ensure-Directory $backupRoot + + $leaf = Split-Path $sourcePath -Leaf + $backupPath = Join-Path $backupRoot $leaf + Ensure-Directory $backupPath + + Copy-Item -LiteralPath $sourcePath -Destination $backupPath -Recurse -Force -ErrorAction SilentlyContinue + return $backupPath +} + +function Copy-Shortcuts([string]$fromPath, [string]$toPath) { + Ensure-Directory $toPath + + $items = Get-ChildItem -LiteralPath $fromPath -Force -ErrorAction SilentlyContinue + foreach ($item in $items) { + if ($item.Name -ieq 'desktop.ini') { continue } + Copy-Item -LiteralPath $item.FullName -Destination $toPath -Recurse -Force -ErrorAction SilentlyContinue + } +} + +function Restart-Shell { + Write-Section 'Restart Shell/Start Menu' + + $procs = @('StartMenuExperienceHost','ShellExperienceHost') + foreach ($p in $procs) { + Get-Process -Name $p -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue + } + + Get-Process -Name explorer -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue + Start-Sleep -Milliseconds 600 + Start-Process explorer.exe + + Write-Host 'Explorer restarted.' +} + +function Reregister-AppxCurrentUser { + Write-Section 'Re-register AppX (Current User)' + Get-AppxPackage | ForEach-Object { + $manifest = Join-Path $_.InstallLocation 'AppxManifest.xml' + if (Test-Path $manifest) { + try { + Add-AppxPackage -DisableDevelopmentMode -Register $manifest -ErrorAction Stop | Out-Null + } catch { + # Keep going; many packages will throw benign errors + } + } + } + Write-Host 'AppX re-register done (current user).' +} + +function Diagnose { + $sid = Get-UserSid + $profileImagePath = Get-ProfileImagePathFromRegistry $sid + $paths = Get-StartMenuPaths + + Write-Section 'Diagnose' + Write-Host "Admin: $(Test-IsAdmin)" + Write-Host "User: $([Environment]::UserName)" + Write-Host "SID: $sid" + Write-Host "ProfileImagePath(HKLM): $profileImagePath" + Write-Host "USERPROFILE: $env:USERPROFILE" + Write-Host "APPDATA: $env:APPDATA" + Write-Host "ProgramData: $env:ProgramData" + Write-Host "ProgramsUser: $($paths.ProgramsUser)" + Write-Host "ProgramsCommon: $($paths.ProgramsCommon)" + + $userExists = Test-Path $paths.ProgramsUser + $commonExists = Test-Path $paths.ProgramsCommon + + Write-Host "User.Exists=$userExists LnkCount=$(Get-LnkCount $paths.ProgramsUser)" + Write-Host "Common.Exists=$commonExists LnkCount=$(Get-LnkCount $paths.ProgramsCommon)" + + Write-Section 'Top-level items (first 20)' + if ($userExists) { + Write-Host "[User] $($paths.ProgramsUser)" + Get-ChildItem -LiteralPath $paths.ProgramsUser -Force -ErrorAction SilentlyContinue | Select-Object -First 20 Name | ForEach-Object { $_.Name } + } else { + Write-Host "[User] (missing)" + } + + if ($commonExists) { + Write-Host "[Common] $($paths.ProgramsCommon)" + Get-ChildItem -LiteralPath $paths.ProgramsCommon -Force -ErrorAction SilentlyContinue | Select-Object -First 20 Name | ForEach-Object { $_.Name } + } else { + Write-Host "[Common] (missing)" + } + + return [pscustomobject]@{ + Sid = $sid + ProfileImagePath = $profileImagePath + ProgramsUser = $paths.ProgramsUser + ProgramsCommon = $paths.ProgramsCommon + UserLnkCount = Get-LnkCount $paths.ProgramsUser + CommonLnkCount = Get-LnkCount $paths.ProgramsCommon + } +} + +function Fix-Shortcuts { + Write-Section 'Fix Start Menu Shortcuts' + + $diag = Diagnose + Ensure-Directory $diag.ProgramsUser + Ensure-Directory $diag.ProgramsCommon + + $now = Get-Date -Format 'yyyyMMdd_HHmmss' + $desktop = [Environment]::GetFolderPath('Desktop') + $backupRoot = Join-Path $desktop "StartMenuBackup_$now" + + Write-Host "BackupRoot: $backupRoot" + + $backupUser = Backup-Folder $diag.ProgramsUser $backupRoot + $backupCommon = Backup-Folder $diag.ProgramsCommon $backupRoot + Write-Host "BackupUser: $backupUser" + Write-Host "BackupCommon: $backupCommon" + + $candidates = Find-CandidateProgramsUserPaths $diag.ProgramsUser + if (!$candidates -or $candidates.Count -eq 0) { + Write-Host 'No candidate old Programs paths found under C:\Users/D:\Users/E:\Users.' + return + } + + Write-Section 'Candidate old ProgramsUser paths' + $candidates | Select-Object -First 5 | Format-Table -AutoSize + + $best = $candidates | Select-Object -First 1 + if ($best.LnkCount -le $diag.UserLnkCount) { + Write-Host "Current ProgramsUser already has >= shortcuts than best candidate. (Current=$($diag.UserLnkCount), Best=$($best.LnkCount))" + return + } + + Write-Host "Copying shortcuts from: $($best.Path)" + Write-Host "To (current user programs): $($diag.ProgramsUser)" + Copy-Shortcuts $best.Path $diag.ProgramsUser + + Write-Host "AfterCopy User LnkCount=$(Get-LnkCount $diag.ProgramsUser)" +} + +switch ($Mode) { + 'Diagnose' { Diagnose | Out-Null; break } + 'FixShortcuts' { Fix-Shortcuts; break } + 'RestartShell' { Restart-Shell; break } + 'ReregisterAppx' { Reregister-AppxCurrentUser; break } + 'Auto' { + $diag = Diagnose + Fix-Shortcuts + Restart-Shell + # If Start Menu is still missing many Store apps, user can run this explicitly. + Write-Host "\nTip: If Store apps are still missing, run: .\\tools\\fix_start_menu_win11.ps1 -Mode ReregisterAppx" + break + } +} diff --git a/tools/fix_start_menu_win11_admin.ps1 b/tools/fix_start_menu_win11_admin.ps1 new file mode 100644 index 0000000..a1b5e5f --- /dev/null +++ b/tools/fix_start_menu_win11_admin.ps1 @@ -0,0 +1,81 @@ +[CmdletBinding()] +param( + [switch]$SkipDism, + [switch]$SkipSfc, + [switch]$SkipAppx +) + +$ErrorActionPreference = 'Stop' + +function Write-Section([string]$title) { + Write-Host "" + Write-Host "=== $title ===" +} + +function Test-IsAdmin { + $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +$now = Get-Date -Format 'yyyyMMdd_HHmmss' +$logPath = Join-Path ([Environment]::GetFolderPath('Desktop')) "StartMenuFix_Admin_$now.log" + +"StartMenuFix Admin started: $(Get-Date)" | Out-File -FilePath $logPath -Encoding UTF8 +"Running as admin: $(Test-IsAdmin)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + +if (!(Test-IsAdmin)) { + "ERROR: This script must be run as Administrator." | Out-File -FilePath $logPath -Append -Encoding UTF8 + throw 'This script must be run as Administrator.' +} + +Write-Host "Log: $logPath" + +try { + if (-not $SkipDism) { + Write-Section 'DISM RestoreHealth' + "DISM start: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + DISM /Online /Cleanup-Image /RestoreHealth | Out-File -FilePath $logPath -Append -Encoding UTF8 + "DISM end: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + } + + if (-not $SkipSfc) { + Write-Section 'SFC Scannow' + "SFC start: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + sfc /scannow | Out-File -FilePath $logPath -Append -Encoding UTF8 + "SFC end: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + } + + if (-not $SkipAppx) { + Write-Section 'Re-register AppX (All Users)' + "AppX re-register start: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + + Get-AppxPackage -AllUsers | ForEach-Object { + $manifest = Join-Path $_.InstallLocation 'AppxManifest.xml' + if (Test-Path $manifest) { + try { + Add-AppxPackage -DisableDevelopmentMode -Register $manifest -ErrorAction Stop | Out-Null + } catch { + # Keep going; capture error into log for diagnostics + "WARN: $($_.Name) - $($_.Exception.Message)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + } + } + } + + "AppX re-register end: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + } + + Write-Section 'Restart Explorer' + "Restart explorer: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + Get-Process -Name StartMenuExperienceHost -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue + Get-Process -Name ShellExperienceHost -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue + Get-Process -Name explorer -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue + Start-Sleep -Milliseconds 600 + Start-Process explorer.exe + + "DONE: $(Get-Date)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + Write-Host 'Done. Explorer restarted.' + Write-Host "Log saved: $logPath" +} catch { + "FATAL: $($_.Exception.Message)" | Out-File -FilePath $logPath -Append -Encoding UTF8 + throw +} diff --git a/tools/restore_start_menu_from_recyclebin.ps1 b/tools/restore_start_menu_from_recyclebin.ps1 new file mode 100644 index 0000000..2ce6c0d --- /dev/null +++ b/tools/restore_start_menu_from_recyclebin.ps1 @@ -0,0 +1,107 @@ +[CmdletBinding()] +param( + [switch]$WhatIf +) + +$ErrorActionPreference = 'Stop' + +function Write-Section([string]$title) { + Write-Host "" + Write-Host "=== $title ===" +} + +$programsUser = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs' +$programsCommon = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs' + +Write-Section 'Targets' +Write-Host "ProgramsUser: $programsUser" +Write-Host "ProgramsCommon: $programsCommon" +Write-Host "WhatIf: $WhatIf" + +Write-Section 'Enumerate Recycle Bin' +$shell = New-Object -ComObject Shell.Application +$recycle = $shell.Namespace(0xA) +if ($null -eq $recycle) { + throw 'Failed to open Recycle Bin namespace.' +} + +$items = @($recycle.Items()) +Write-Host "RecycleBin items: $($items.Count)" + +function Get-DeletedFrom($item) { + try { return $item.ExtendedProperty('System.Recycle.DeletedFrom') } catch { return $null } +} + +function Get-OriginalName($item) { + try { return $item.Name } catch { return $null } +} + +function Find-RestoreVerb($item) { + try { + $verbs = @($item.Verbs()) + foreach ($v in $verbs) { + $name = ($v.Name -as [string]) + if ([string]::IsNullOrWhiteSpace($name)) { continue } + $n = $name.Replace('&','').Trim() + if ($n -match '(?i)restore' -or $n -match '还原') { + return $n + } + } + } catch { } + return $null +} + +$matches = @() +foreach ($it in $items) { + $deletedFrom = Get-DeletedFrom $it + $name = Get-OriginalName $it + if ([string]::IsNullOrWhiteSpace($name)) { continue } + + $isLnk = $name.ToLowerInvariant().EndsWith('.lnk') + if (!$isLnk) { continue } + + if ($deletedFrom -and ( + $deletedFrom -like "$programsUser*" -or + $deletedFrom -like "$programsCommon*" -or + $deletedFrom -like '*\\Microsoft\\Windows\\Start Menu\\Programs*' + )) { + $matches += [pscustomobject]@{ Name = $name; DeletedFrom = $deletedFrom; Item = $it } + } +} + +Write-Section 'Matches' +Write-Host "Matching .lnk from Start Menu Programs: $($matches.Count)" +$matches | Select-Object -First 50 Name,DeletedFrom | Format-List + +if ($matches.Count -eq 0) { + Write-Host 'No matching shortcuts found in Recycle Bin.' + exit 0 +} + +if ($WhatIf) { + Write-Host 'WhatIf set; not restoring.' + exit 0 +} + +Write-Section 'Restore' +$restored = 0 +$skipped = 0 +foreach ($m in $matches) { + $it = $m.Item + $verb = Find-RestoreVerb $it + if ([string]::IsNullOrWhiteSpace($verb)) { + $skipped++ + continue + } + + try { + $it.InvokeVerb($verb) + $restored++ + } catch { + $skipped++ + } +} + +Write-Host "Restored: $restored" +Write-Host "Skipped: $skipped" +Write-Host 'Tip: If restore succeeded, restart Explorer / Start menu.' diff --git a/tools/run_screenshot_diagnostics.py b/tools/run_screenshot_diagnostics.py new file mode 100644 index 0000000..20d14f8 --- /dev/null +++ b/tools/run_screenshot_diagnostics.py @@ -0,0 +1,19 @@ +from Underlying_Operations import underlying_operations +import time + +op = underlying_operations() +# try to trigger several screenshots +for i in range(8): + print(f"Triggering screenshot #{i+1}") + ok = op.get_screenshot(device_id="DUMMY_DEVICE", path="pic", use_service=False) + print("result:", ok) + time.sleep(0.6) + +print('\n--- Log snippet ---') +try: + with open('logs/screenshot_calls.log', 'r', encoding='utf-8') as f: + lines = f.read().splitlines() + for ln in lines[-120:]: + print(ln) +except Exception as e: + print('Could not read log:', e) diff --git a/tools/simulate_swipe_trigger.py b/tools/simulate_swipe_trigger.py new file mode 100644 index 0000000..476f997 --- /dev/null +++ b/tools/simulate_swipe_trigger.py @@ -0,0 +1,41 @@ +from douyin.core.douyin_fudai import fudai_analyse +from douyin.handlers import douyin_swipe_ops + +class DummyOp: + def swipe(self, device_id, sx, sy, ex, ey, duration_ms): + # minimal output + print(f"swipe: device={device_id} from=({sx},{sy}) to=({ex},{ey}) dur={duration_ms}") + def click_back(self, device_id=None): + print(f"click_back called, device={device_id}") + + +def main(): + a = fudai_analyse() + a.operation = DummyOp() + a.device_id = "DUMMY" + # use config default of 10 to simulate ten swipes + a.fudai_exit_after_misses = int(getattr(a, 'fudai_exit_after_misses', 10) or 10) + print('fudai_exit_after_misses =', a.fudai_exit_after_misses) + # ensure counter starts at 0 + a._consecutive_no_fudai_count = 0 + + for i in range(1, 11): + print(f"\n-- swipe #{i} --") + douyin_swipe_ops.swipe_up_switch_live(a) + # simulate not finding fudai -> increment counter + a._consecutive_no_fudai_count = int(getattr(a, '_consecutive_no_fudai_count', 0)) + 1 + print('consecutive_no_fudai_count =', a._consecutive_no_fudai_count) + if a._consecutive_no_fudai_count >= a.fudai_exit_after_misses: + print('threshold reached, invoking back') + try: + a.operation.click_back(a.device_id) + except Exception: + print('click_back failed') + # reset counter as real logic would + a._consecutive_no_fudai_count = 0 + break + else: + print('\nNo back triggered after 10 swipes') + +if __name__ == '__main__': + main() diff --git a/tools/test_back_on_misses.py b/tools/test_back_on_misses.py new file mode 100644 index 0000000..efb6fc4 --- /dev/null +++ b/tools/test_back_on_misses.py @@ -0,0 +1,69 @@ +from douyin.core.douyin_fudai import fudai_analyse +from douyin.utils import douyin_config + +class DummyOp: + def __init__(self): + self.clicked_back = False + self.clicked_coord = None + def click_back(self, device_id=None): + print("DummyOp.click_back called, device_id=", device_id) + self.clicked_back = True + def click(self, device_id, x, y): + print(f"DummyOp.click called at ({x},{y}), device_id={device_id}") + self.clicked_coord = (x,y) + + +def simulate(): + a = fudai_analyse() + # use dummy op to avoid real adb + a.operation = DummyOp() + # ensure config loads (reads config/config.json) + a.load_config() + print("config enable_back_on_misses ->", getattr(a, "enable_back_on_misses", None)) + + # 快速验证:强制设置阈值为 1(触发返回键) + a.fudai_exit_after_misses = 1 + print("(test override) fudai_exit_after_misses ->", a.fudai_exit_after_misses) + + # simulate "not found" path logic + cur = int(getattr(a, "_consecutive_no_fudai_count", 0) or 0) + print("initial consecutive count ->", cur) + cur += 1 + setattr(a, "_consecutive_no_fudai_count", cur) + print("after increment ->", cur) + + threshold = int(getattr(a, "fudai_exit_after_misses", 0) or 0) or None + if threshold is None or threshold <= 0: + threshold = 30 + if threshold and cur >= threshold: + print("threshold reached: cur=", cur, "threshold=", threshold) + enabled = getattr(a, "enable_back_on_misses", None) + print("enable_back_on_misses attribute ->", enabled) + if enabled is None: + # try load from file + try: + douyin_config.ConfigManager.load_config_from_file(a) + enabled = bool(getattr(a, "enable_back_on_misses", True)) + except Exception: + enabled = True + print("final enabled ->", enabled) + if enabled: + try: + a.operation.click_back(a.device_id) + except Exception: + try: + # fallback coord click + rx = int(getattr(a, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(a, "resolution_ratio_y", 2400) or 2400) + back_x = int(50 * rx / 1080) + back_y = int(50 * ry / 2400) + a.operation.click(a.device_id, back_x, back_y) + except Exception: + print("both click_back and click fallback failed") + else: + print("enabled is False; skipping back click") + else: + print("threshold not reached: cur=", cur, "threshold=", threshold) + +if __name__ == '__main__': + simulate() diff --git a/tools/test_reset_action.py b/tools/test_reset_action.py new file mode 100644 index 0000000..e38cf5c --- /dev/null +++ b/tools/test_reset_action.py @@ -0,0 +1,25 @@ +from douyin.handlers.douyin_swipe_handler import SwipeHandler + +class DummyOp: + def click_back(self, device_id=None): + print('DummyOp.click_back called, device_id=', device_id) + def delay(self, s): + pass + +class DummyAnalyser: + def __init__(self): + self.operation = DummyOp() + self.device_id = 'DUMMY' + self._swipe_times = 5 + self.reset_after_swipes_enabled = True + self.reset_after_swipes = 5 + self.reset_after_swipes_action = 'back' + self.resolution_ratio_x = 1080 + self.resolution_ratio_y = 2400 + self.room_pos = 3 + +if __name__ == '__main__': + a = DummyAnalyser() + print('Before maybe_reset, _swipe_times=', a._swipe_times, 'action=', a.reset_after_swipes_action) + SwipeHandler.maybe_reset_after_swipes(a) + print('After maybe_reset, _swipe_times=', getattr(a, '_swipe_times', None), 'room_pos=', getattr(a, 'room_pos', None)) diff --git a/tools/test_swipe_switch.py b/tools/test_swipe_switch.py new file mode 100644 index 0000000..3cf1d61 --- /dev/null +++ b/tools/test_swipe_switch.py @@ -0,0 +1,23 @@ +from douyin.handlers import douyin_swipe_ops +from douyin.core.douyin_fudai import fudai_analyse + +class DummyOp: + def _adb(self): + # Return path to non-existing adb to force fallback + return "adb" + def swipe(self, device_id, sx, sy, ex, ey, duration_ms): + print(f"DummyOp.swipe called device={device_id} from ({sx},{sy}) to ({ex},{ey}) duration={duration_ms}") + + +def simulate_once(i:int): + a = fudai_analyse() + a.operation = DummyOp() + a.device_id = f"DUMMY{i}" + a.resolution_ratio_x = 1080 + a.resolution_ratio_y = 2400 + print(f"--- simulate swipe #{i} ---") + douyin_swipe_ops.swipe_up_switch_live(a) + +if __name__ == '__main__': + for i in range(1, 11): + simulate_once(i)