From 2da1e643afe758ee891266be95dab99644296380 Mon Sep 17 00:00:00 2001 From: ali Date: Sat, 21 Nov 2026 21:09:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(menu):=20=E5=8F=B3=E9=94=AE=E8=8F=9C?= =?UTF-8?q?=E5=8D=95=E6=94=B6=E6=95=9B=E4=B8=BA=E4=BA=94=E9=A1=B9=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=A4=9A=E9=80=89=E4=B8=80=E6=AC=A1=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4=E4=B8=8E=E6=96=87=E4=BB=B6=E5=9B=9E=E6=BA=AF=E5=89=A7?= =?UTF-8?q?=E9=9B=86=E6=A0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/explorer-media-rename.ps1 | 270 ++++++++++++++++++++++++++---- scripts/install-explorer-menu.ps1 | 106 ++++++++++-- scripts/remote-common.ps1 | 52 +++++- 3 files changed, 378 insertions(+), 50 deletions(-) diff --git a/scripts/explorer-media-rename.ps1 b/scripts/explorer-media-rename.ps1 index c005d5e..f2228b6 100644 --- a/scripts/explorer-media-rename.ps1 +++ b/scripts/explorer-media-rename.ps1 @@ -17,7 +17,7 @@ 不进队列,立即处理当前窗口里的这一项。 .PARAMETER Action - rename(默认)/ archive / extract-subs / check。 + rename(默认)/ archive / variety / extract-subs / check。 .PARAMETER DryRun 只打印将要执行的远端命令,不真正执行。 @@ -26,7 +26,7 @@ 执行结束后停住窗口(直接执行模式用);worker 结束时也会停一下。 .PARAMETER Paths - 资源管理器传入的选中项。 + 资源管理器传入的选中项(可多选)。每一项都会先回溯到剧集根目录再入队。 #> [CmdletBinding()] param( @@ -36,12 +36,16 @@ param( [switch]$DryRun, [switch]$Enqueue, [switch]$Worker, + [switch]$Status, [Parameter(ValueFromRemainingArguments = $true)][string[]]$Paths = @() ) $ErrorActionPreference = 'Stop' try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { } +# 路径规则(剧集根回溯 / 下载根守卫)与 SSH 工具共用一份 +. (Join-Path $PSScriptRoot 'remote-common.ps1') + # ---------------------------------------------------------------- 公共定义 $QueueDir = Join-Path $env:LOCALAPPDATA 'SceneMarshal' @@ -49,15 +53,17 @@ $QueueFile = Join-Path $QueueDir 'queue.jsonl' $QueueLock = Join-Path $QueueDir 'queue.lock' $WorkerLock = Join-Path $QueueDir 'worker.lock' $SpawnLock = Join-Path $QueueDir 'spawn.lock' +$CurrentFile = Join-Path $QueueDir 'current.json' $WorkerLog = Join-Path $QueueDir 'worker.log' $PwshPath = (Get-Process -Id $PID).Path $ActionPlan = @{ - 'archive' = @{ Runner = 'media-archive.ps1'; Extra = @() } - 'variety' = @{ Runner = 'media-rename.ps1'; Extra = @('variety') } - 'extract-subs' = @{ Runner = 'media-rename.ps1'; Extra = @('extract-subs') } - 'check' = @{ Runner = 'media-rename.ps1'; Extra = @('check') } - 'rename' = @{ Runner = 'media-rename.ps1'; Extra = @() } + # 所有动作都走同一个 scene-marshal.ps1,差异只有模式(rename = 不指定,用服务端默认 auto) + 'archive' = @{ Runner = 'scene-marshal.ps1'; Extra = @('archive') } + 'variety' = @{ Runner = 'scene-marshal.ps1'; Extra = @('variety') } + 'extract-subs' = @{ Runner = 'scene-marshal.ps1'; Extra = @('extract-subs') } + 'check' = @{ Runner = 'scene-marshal.ps1'; Extra = @('check') } + 'rename' = @{ Runner = 'scene-marshal.ps1'; Extra = @() } } function Write-WorkerLog([string]$message) { @@ -77,18 +83,95 @@ function Enter-FileLock([string]$path, [int]$timeoutMs = 3000) { return $null } -function Add-QueueItem([string]$action, [string]$target) { +function Get-ItemPaths($item) { + if ($null -eq $item) { return @() } + if ($item.PSObject.Properties.Name -contains 'paths' -and $item.paths) { + return @($item.paths | Where-Object { $_ }) + } + if ($item.PSObject.Properties.Name -contains 'path' -and $item.path) { + return @($item.path) # 兼容旧队列格式 {action, path} + } + return @() +} + +function Get-PathKey([string]$path) { + # 归一化:大小写 / 结尾反斜杠 / Y: 与 UNC 视为同一条 + if (-not $path) { return '' } + $p = ($path.Trim() -replace '/', '\').TrimEnd('\') + if ($p -match '^[Yy]:(\\.*)?$') { return ('hdd\sda1' + $Matches[1]).ToLowerInvariant() } + if ($p -match '^\\\\10\.10\.1\.202\\n100-sda1(\\.*)?$') { return ('hdd\sda1' + $Matches[1]).ToLowerInvariant() } + return $p.ToLowerInvariant() +} + +function Get-PendingKeys([string]$action) { + <# + 同 action 的「队列中 + 正在执行」路径集合。 + current.json 是必需的:worker 出队后队列里已经没有这条了,只比队列必然重复执行。 + 残留保护:超过 30 分钟的 current.json 视为陈旧(worker 崩溃)。 + #> + $keys = @{} + if (Test-Path -LiteralPath $QueueFile) { + foreach ($line in @(Get-Content -LiteralPath $QueueFile -Encoding utf8)) { + if (-not $line.Trim()) { continue } + try { $o = $line | ConvertFrom-Json } catch { continue } + if ($o.action -ne $action) { continue } + foreach ($p in (Get-ItemPaths $o)) { $keys[(Get-PathKey $p)] = $true } + } + } + if (Test-Path -LiteralPath $CurrentFile) { + # current.json 只在 worker 持有 worker.lock 期间存在: + # 锁空闲 => 没有 worker 在跑 => 这份必然是上次 Ctrl+C / 关窗 / 强杀留下的残留。 + # 若仍当成「正在执行」,同路径同动作会在 30 分钟内全部被静默丢弃(表现为「点了没反应」)。 + if (-not (Test-WorkerAlive)) { + Write-WorkerLog '清理残留 current.json(无 worker 存活)' + Remove-Item -LiteralPath $CurrentFile -Force -ErrorAction SilentlyContinue + } + else { + try { + $o = Get-Content -LiteralPath $CurrentFile -Raw -Encoding utf8 | ConvertFrom-Json + $age = if ($o.ts) { ((Get-Date) - [datetime]$o.ts).TotalMinutes } else { 999 } + if ($o.action -eq $action -and $age -lt 30) { + foreach ($p in (Get-ItemPaths $o)) { $keys[(Get-PathKey $p)] = $true } + } + } + catch { } + } + } + return $keys +} + +function Add-QueueItem([string]$action, [string[]]$targets) { New-Item -ItemType Directory -Force -Path $QueueDir | Out-Null $lock = Enter-FileLock $QueueLock if ($null -eq $lock) { throw '队列被占用,请稍后重试' } try { - $item = [ordered]@{ action = $action; path = $target; ts = (Get-Date).ToString('o') } + $pending = Get-PendingKeys $action + $fresh = New-Object System.Collections.Generic.List[string] + foreach ($t in $targets) { + $k = Get-PathKey $t + if (-not $k -or $pending.ContainsKey($k)) { continue } + $pending[$k] = $true + $fresh.Add($t) + } + if ($fresh.Count -eq 0) { + Write-WorkerLog ("跳过重复入队 {0} :: {1}" -f $action, ($targets -join '; ')) + return $false + } + if ($fresh.Count -lt $targets.Count) { + Write-WorkerLog ("去重后入队 {0}/{1} 项({2})" -f $fresh.Count, $targets.Count, $action) + } + $item = [ordered]@{ action = $action; paths = @($fresh.ToArray()); ts = (Get-Date).ToString('o') } Add-Content -LiteralPath $QueueFile -Value ($item | ConvertTo-Json -Compress) -Encoding utf8 + return $true } finally { $lock.Close() } } -function Take-QueueItem { +function Take-QueueItem([string]$onlyAction) { + <# + 取出一条(若给了 onlyAction,则取第一条同 action 的,其余原样留在队列里)。 + 用于「多选 N 个文件夹 → 合成一个批次」。 + #> New-Item -ItemType Directory -Force -Path $QueueDir | Out-Null $lock = Enter-FileLock $QueueLock if ($null -eq $lock) { return $null } @@ -99,15 +182,29 @@ function Take-QueueItem { Remove-Item -LiteralPath $QueueFile -Force -ErrorAction SilentlyContinue return $null } - $first = $lines[0] - $rest = @($lines | Select-Object -Skip 1) + + $index = 0 + if ($onlyAction) { + $index = -1 + for ($i = 0; $i -lt $lines.Count; $i++) { + try { $o = $lines[$i] | ConvertFrom-Json } catch { continue } + if ($o.action -eq $onlyAction) { $index = $i; break } + } + if ($index -lt 0) { return $null } + } + + $picked = $lines[$index] + $rest = @() + for ($i = 0; $i -lt $lines.Count; $i++) { + if ($i -ne $index) { $rest += $lines[$i] } + } if ($rest.Count -eq 0) { Remove-Item -LiteralPath $QueueFile -Force -ErrorAction SilentlyContinue } else { Set-Content -LiteralPath $QueueFile -Value $rest -Encoding utf8 } - return ($first | ConvertFrom-Json) + return ($picked | ConvertFrom-Json) } finally { $lock.Close() } } @@ -131,23 +228,43 @@ function Start-Worker { } } -function Resolve-Target([string[]]$rawPaths) { - $target = $rawPaths | Where-Object { $_ } | Select-Object -First 1 - if (-not $target) { return $null } - if (Test-Path -LiteralPath $target -PathType Leaf) { - return (Split-Path -Parent $target) +function Resolve-Targets([string[]]$rawPaths) { + <# + 多选 N 项 → 回溯到各自剧集根目录 → 去重。 + 文件右键(E01.mkv / extras\花絮.mkv)回溯后若落在下载根,视为误触,丢弃该条。 + #> + $items = @($rawPaths | Where-Object { $_ }) + if ($items.Count -eq 0) { return @() } + + $resolved = New-Object System.Collections.Generic.List[string] + $seen = @{} + foreach ($raw in $items) { + $isLeaf = Test-Path -LiteralPath $raw -PathType Leaf + $root = Resolve-SeriesRoot $raw + if (-not $root) { continue } + if ($isLeaf -and (Test-DownloadRootPath $root)) { + Write-Warning "「$raw」所在目录是下载根,请在具体剧集文件夹上右键" + Write-WorkerLog "拒绝入队(落在下载根): $raw" + continue + } + $key = Get-PathKey $root + if ($seen.ContainsKey($key)) { continue } + $seen[$key] = $true + $resolved.Add($root) } - return $target + return $resolved.ToArray() } -function Invoke-Action([string]$itemAction, [string]$target) { +function Invoke-Action([string]$itemAction, [string[]]$targets) { $plan = $ActionPlan[$itemAction] if (-not $plan) { Write-Host "❌ 未知动作: $itemAction" -ForegroundColor Red return 1 } $runnerPath = Join-Path $PSScriptRoot $plan.Runner - $tokens = @($target) + $plan.Extra + # 模式放在最前,路径一律显式 -p:多选时裸路径会被当成第二个 mode / 位置参数 + $tokens = @($plan.Extra) + foreach ($t in $targets) { $tokens += @('-p', $t) } # 关键:用独立子进程「继承当前控制台」来跑,而不是在进程内 + 管道。 # 管道会让远端 ssh -t 的交互提示与本地输入回显错位(提示行会消失)。 @@ -180,6 +297,14 @@ function Invoke-Worker { } try { $Host.UI.RawUI.WindowTitle = 'SceneMarshal 队列' } catch { } + + # 抢到锁 = 没有别的 worker 在跑 => 残留的 current.json 一定是上次被强杀的痕迹, + # 留着会让同路径同动作在 30 分钟内全被当成「正在执行」而丢弃。 + if (Test-Path -LiteralPath $CurrentFile) { + Write-WorkerLog 'worker 启动:清理残留 current.json' + Remove-Item -LiteralPath $CurrentFile -Force -ErrorAction SilentlyContinue + } + Write-WorkerLog ("worker 启动(stdin重定向={0} stdout重定向={1})" -f ` [Console]::IsInputRedirected, [Console]::IsOutputRedirected) Write-Host '📋 SceneMarshal 队列已启动' -ForegroundColor Cyan @@ -197,33 +322,82 @@ function Invoke-Worker { if ($null -ne $item) { $summaryShown = $false $closeDeadline = $null - $name = Split-Path -Leaf $item.path - Write-Host ('─── [{0}] {1}' -f $item.action, $name) -ForegroundColor Yellow - Write-WorkerLog ("开始处理 {0} :: {1}" -f $item.action, $item.path) + + # 合批:Explorer 多选会对每个选中项各起一个入队进程(几百毫秒一个), + # 所以先等一小段"安静期"把同 action 的项收齐,再合成一批—— + # 于是「选了 5 个文件夹」只问一次、只跑一个进程。 + $batch = New-Object System.Collections.Generic.List[string] + $seen = @{} + foreach ($p in (Get-ItemPaths $item)) { + $k = Get-PathKey $p + if (-not $k -or $seen.ContainsKey($k)) { continue } + $seen[$k] = $true + $batch.Add($p) + } + $lastSeen = Get-Date + $hardStop = $lastSeen.AddSeconds(6) + while ($true) { + $next = Take-QueueItem $item.action + if ($null -ne $next) { + foreach ($p in (Get-ItemPaths $next)) { + $k = Get-PathKey $p + if (-not $k -or $seen.ContainsKey($k)) { continue } + $seen[$k] = $true + $batch.Add($p) + } + $lastSeen = Get-Date + continue + } + if (((Get-Date) - $lastSeen).TotalMilliseconds -ge 900 -or (Get-Date) -ge $hardStop) { + break + } + Start-Sleep -Milliseconds 120 + } + $targets = $batch.ToArray() + + if ($targets.Count -eq 0) { + Write-WorkerLog '空批次(无有效路径),跳过' + continue + } + + $label = if ($targets.Count -eq 1) { Split-Path -Leaf $targets[0] } else { "$($targets.Count) 个目录" } + Write-Host ('─── [{0}] {1}' -f $item.action, $label) -ForegroundColor Yellow + if ($targets.Count -gt 1) { + foreach ($t in $targets) { Write-Host (" · {0}" -f (Split-Path -Leaf $t)) -ForegroundColor DarkGray } + } + Write-WorkerLog ("开始处理 {0} :: {1}" -f $item.action, ($targets -join '; ')) $started = Get-Date try { - $code = Invoke-Action $item.action $item.path + @{ action = $item.action; paths = @($targets); ts = (Get-Date).ToString('o'); pid = $PID } | + ConvertTo-Json -Compress | Set-Content -LiteralPath $CurrentFile -Encoding utf8 + } + catch { } + try { + $code = Invoke-Action $item.action $targets } catch { Write-Host (" ❌ 异常: {0}" -f $_.Exception.Message) -ForegroundColor Red $code = 1 } + finally { + Remove-Item -LiteralPath $CurrentFile -Force -ErrorAction SilentlyContinue + } $cost = [int]((Get-Date) - $started).TotalSeconds if ($code -eq 0) { $done++ Write-Host (" ✅ 完成,用时 {0}s" -f $cost) -ForegroundColor Green - Write-WorkerLog ("完成 {0}({1}s)" -f $item.path, $cost) + Write-WorkerLog ("完成 {0}({1}s)" -f ($targets -join '; '), $cost) } elseif ($code -eq 2) { # 退出码 2 约定为「用户主动取消」,不算失败 $cancelled++ Write-Host (" ⏭ 已取消(未改动任何文件),用时 {0}s" -f $cost) -ForegroundColor DarkYellow - Write-WorkerLog ("已取消 {0}" -f $item.path) + Write-WorkerLog ("已取消 {0}" -f ($targets -join '; ')) } else { $failed++ Write-Host (" ⚠️ 失败(退出码 {0}),用时 {1}s" -f $code, $cost) -ForegroundColor Red - Write-WorkerLog ("失败 {0}(code={1}, {2}s)" -f $item.path, $code, $cost) + Write-WorkerLog ("失败 {0}(code={1}, {2}s)" -f ($targets -join '; '), $code, $cost) } Write-Host '' continue @@ -265,12 +439,38 @@ if ($Worker) { exit (Invoke-Worker) } -$target = Resolve-Target $Paths +if ($Status) { + # 右键是隐藏窗口,出问题时什么都看不到;这个开关把队列/锁/残留状态一次打出来 + Write-Host "队列目录: $QueueDir" -ForegroundColor Cyan + $alive = Test-WorkerAlive + Write-Host ("worker 存活: {0}" -f $alive) -ForegroundColor Cyan + if (Test-Path -LiteralPath $QueueFile) { + $lines = @(Get-Content -LiteralPath $QueueFile -Encoding utf8 | Where-Object { $_.Trim() }) + Write-Host ("队列: {0} 条" -f $lines.Count) -ForegroundColor Cyan + foreach ($l in $lines) { Write-Host (" {0}" -f $l) -ForegroundColor DarkGray } + } + else { Write-Host '队列: 空' -ForegroundColor Cyan } + if (Test-Path -LiteralPath $CurrentFile) { + $txt = Get-Content -LiteralPath $CurrentFile -Raw -Encoding utf8 + if ($alive) { Write-Host "正在执行: $txt" -ForegroundColor Yellow } + else { Write-Host "残留 current.json(会阻塞同路径入队): $txt" -ForegroundColor Red } + } + Write-Host '' ; Write-Host '--- worker.log 尾部 10 行 ---' -ForegroundColor Cyan + if (Test-Path -LiteralPath $WorkerLog) { Get-Content -LiteralPath $WorkerLog -Tail 10 -Encoding utf8 } + exit 0 +} + +$targets = @(Resolve-Targets $Paths) if ($Enqueue) { - if (-not $target) { exit 0 } # 没拿到路径就静默退出,不弹窗 - Add-QueueItem $Action $target - if (-not (Test-WorkerAlive)) { + if ($targets.Count -eq 0) { exit 0 } # 没拿到有效路径就静默退出,不弹窗 + if ($DryRun) { + $targets | ForEach-Object { Write-Host "[DryRun] 解析结果: $_" -ForegroundColor Yellow } + exit 0 + } + $queued = Add-QueueItem $Action $targets + # 只有真的入队了才需要 worker;全部是重复项时不要白拉一个窗口 + if ($queued -and -not (Test-WorkerAlive)) { # 多选时 Explorer 会同时发起 N 个入队调用,这里必须串行化, # 否则每个调用都会在 worker 抢到锁之前各拉起一个窗口。 $spawnLock = Enter-FileLock $SpawnLock 8000 @@ -285,16 +485,16 @@ if ($Enqueue) { } # 直接执行模式 -if (-not $target) { +if ($targets.Count -eq 0) { Write-Host '❌ 没有收到要处理的路径' -ForegroundColor Red if ($Pause) { Write-Host ''; Read-Host '按 Enter 关闭' | Out-Null } exit 1 } -Write-Host "📁 目标: $target" -ForegroundColor DarkGray +foreach ($t in $targets) { Write-Host "📁 目标: $t" -ForegroundColor DarkGray } Write-Host ("▶ 动作: {0}" -f $Action) -ForegroundColor DarkGray -$exitCode = Invoke-Action $Action $target +$exitCode = Invoke-Action $Action $targets if ($Pause) { Write-Host '' Read-Host '按 Enter 关闭窗口' | Out-Null diff --git a/scripts/install-explorer-menu.ps1 b/scripts/install-explorer-menu.ps1 index 0044cba..baad9f9 100644 --- a/scripts/install-explorer-menu.ps1 +++ b/scripts/install-explorer-menu.ps1 @@ -5,10 +5,11 @@ .DESCRIPTION 默认注册成「SceneMarshal ▸」级联子菜单,子项: - 1. 重命名(自动) → auto - 2. 归档… → media-archive(交互选分类) - 3. 补外挂字幕(转码片源) → extract-subs - 4. 入库前体检(只读) → check + 1. 整理入库 → auto(预览确认 → 整理 → 单目录自动归档) + 2. 归档入库 → archive(交互选分类) + 3. 综艺整理 → variety(排集 → 特典放置) + 4. 补外挂字幕 → extract-subs + 5. 兼容性校验 → check(只读,出报告) 级联写法与 Windows 自带项(UpdateEncryptionSettingsWork)一致: 父键上写 ExtendedSubCommandsKey = 该键自身的 HKCR 相对路径,子项放在父键的 Shell\ 下。 @@ -17,10 +18,17 @@ HKCU\Software\Classes\Directory\shell\SceneMarshal (文件夹右键) HKCU\Software\Classes\Directory\Background\shell\SceneMarshal (文件夹空白处右键) HKCU\Software\Classes\SystemFileAssociations\.mkv\shell\SceneMarshal - ... 同上 .mp4 / .avi(文件右键,取其所在目录) + ... 同上 .mp4 / .avi(文件右键,自动回溯到剧集根目录) .PARAMETER Flat - 兜底模式:不级联,直接注册 4 个平级菜单项(名称带「SceneMarshal ▸ 」前缀)。 + 兜底模式:不级联,直接注册 5 个平级菜单项(名称带「SceneMarshal ▸ 」前缀)。 + +.PARAMETER Verify + 只读自检:校验 5 处父键、自引用、子项文案、图标、命令里的 wscript/vbs/pwsh 是否存在。 + 不写注册表;退出码 0 全绿,1 有问题。 + +.PARAMETER Repair + 等价于重新安装(先清理再注册)。 .EXAMPLE .\install-explorer-menu.ps1 @@ -29,7 +37,9 @@ #> [CmdletBinding()] param( - [switch]$Flat + [switch]$Flat, + [switch]$Verify, + [switch]$Repair ) $ErrorActionPreference = 'Stop' @@ -63,12 +73,13 @@ function Get-ItemIcon([string]$name) { } # 级联子项:ExtendedSubCommandsKey 模式下 Explorer 取 MUIVerb 作为显示名 +# Key 决定菜单排序(字典序),改文案不影响顺序;插新项才需要重排 01…NN $items = @( - @{ Key = '01-rename'; Text = '媒体整理'; Action = 'rename'; Icon = (Get-ItemIcon 'rename.ico') }, - @{ Key = '02-archive'; Text = '媒体归档'; Action = 'archive'; Icon = (Get-ItemIcon 'archive.ico') }, + @{ Key = '01-rename'; Text = '整理入库'; Action = 'rename'; Icon = (Get-ItemIcon 'rename.ico') }, + @{ Key = '02-archive'; Text = '归档入库'; Action = 'archive'; Icon = (Get-ItemIcon 'archive.ico') }, @{ Key = '03-variety'; Text = '综艺整理'; Action = 'variety'; Icon = (Get-ItemIcon 'variety.ico') }, @{ Key = '04-extract-subs'; Text = '补外挂字幕'; Action = 'extract-subs'; Icon = (Get-ItemIcon 'subtitle.ico') }, - @{ Key = '05-check'; Text = '入库校验'; Action = 'check'; Icon = (Get-ItemIcon 'check.ico') } + @{ Key = '05-check'; Text = '兼容性校验'; Action = 'check'; Icon = (Get-ItemIcon 'check.ico') } ) # Relative = ExtendedSubCommandsKey 的值(相对 HKEY_CLASSES_ROOT),同时用于定位注册表路径 @@ -80,18 +91,85 @@ $locations = @( @{ Relative = 'SystemFileAssociations\.avi\shell\SceneMarshal'; Token = '%1' } ) +$vbsPath = $enqueueVbs +$wscriptPath = Join-Path $env:SystemRoot 'System32\wscript.exe' + function New-MenuCommand([string]$Action, [string]$Token) { # 经 wscript 调 VBS:无控制台窗口,只把任务写进队列, # 由唯一的 worker 窗口按顺序处理(多选时不会弹多个终端) - $vbs = Join-Path $PSScriptRoot 'scenemarshal-enqueue.vbs' - $wscript = Join-Path $env:SystemRoot 'System32\wscript.exe' - '"' + $wscript + '" //nologo "' + $vbs + '" ' + $Action + ' "' + $pwsh + '" "' + $Token + '"' + '"' + $wscriptPath + '" //nologo "' + $vbsPath + '" ' + $Action + ' "' + $pwsh + '" "' + $Token + '"' } function Get-RegPath([string]$relative) { return "HKCU:\Software\Classes\$relative" } +# ---------------------------------------------------------------- 自检(只读) + +if ($Verify) { + $problems = New-Object System.Collections.Generic.List[string] + if (-not (Test-Path -LiteralPath $wscriptPath)) { $problems.Add("wscript 不存在: $wscriptPath") } + if (-not (Test-Path -LiteralPath $vbsPath)) { $problems.Add("入队 VBS 不存在: $vbsPath") } + if (-not (Test-Path -LiteralPath $pwsh)) { $problems.Add("pwsh 不存在: $pwsh") } + + foreach ($loc in $locations) { + $parent = Get-RegPath $loc.Relative + if (-not (Test-Path -LiteralPath $parent)) { + $problems.Add("缺少父键: HKCU\Software\Classes\$($loc.Relative)") + continue + } + $props = Get-ItemProperty -LiteralPath $parent + if ($props.MUIVerb -ne $menuName) { + $problems.Add("$($loc.Relative): MUIVerb 应为「$menuName」,实际「$($props.MUIVerb)」") + } + if ($props.ExtendedSubCommandsKey -ne $loc.Relative) { + $problems.Add("$($loc.Relative): ExtendedSubCommandsKey 不是自引用($($props.ExtendedSubCommandsKey))") + } + if ($props.Icon -and -not (Test-Path -LiteralPath $props.Icon)) { + $problems.Add("$($loc.Relative): 父菜单图标不存在 $($props.Icon)") + } + foreach ($item in $items) { + $child = Join-Path (Join-Path $parent 'Shell') $item.Key + if (-not (Test-Path -LiteralPath $child)) { + $problems.Add("$($loc.Relative): 缺少子项 $($item.Key)") + continue + } + $cp = Get-ItemProperty -LiteralPath $child + if ($cp.MUIVerb -ne $item.Text) { + $problems.Add("$($loc.Relative)\$($item.Key): 文案应为「$($item.Text)」,实际「$($cp.MUIVerb)」") + } + if ($cp.Icon -and -not (Test-Path -LiteralPath $cp.Icon)) { + $problems.Add("$($loc.Relative)\$($item.Key): 图标不存在 $($cp.Icon)") + } + $cmd = (Get-ItemProperty -LiteralPath (Join-Path $child 'command')).'(default)' + if (-not $cmd) { + $problems.Add("$($loc.Relative)\$($item.Key): command 为空") + continue + } + # 仓库移盘 / 换 pwsh 安装后,写死的绝对路径会失效 + foreach ($needle in @($wscriptPath, $vbsPath, $pwsh)) { + if ($cmd -notlike "*$needle*") { + $problems.Add("$($loc.Relative)\$($item.Key): command 未包含 $needle") + } + } + if ($cmd -notmatch ('\s' + [regex]::Escape($item.Action) + '\s')) { + $problems.Add("$($loc.Relative)\$($item.Key): command 里的动作不是 $($item.Action)") + } + } + } + + if ($problems.Count) { + Write-Host ("✘ 菜单自检发现 {0} 个问题:" -f $problems.Count) -ForegroundColor Red + $problems | ForEach-Object { Write-Host " - $_" -ForegroundColor Red } + Write-Host '修复:.\install-explorer-menu.ps1 -Repair' -ForegroundColor Yellow + exit 1 + } + Write-Host '✔ 菜单自检通过:5 处父键 / 自引用 / 子项文案与图标 / 命令路径均正常' -ForegroundColor Green + exit 0 +} + +if ($Repair) { Write-Host '▶ 重新安装(-Repair)' -ForegroundColor Cyan } + # ---------------------------------------------------------------- 清理旧结构 foreach ($loc in $locations) { foreach ($name in @($menuName, 'SceneMarshalArchive')) { @@ -116,7 +194,7 @@ foreach ($loc in $locations) { if (-not (Test-Path -LiteralPath $parent)) { New-Item -Path $parent -Force | Out-Null } if ($Flat) { - # 兜底:每个位置注册 4 个平级项 + # 兜底:每个位置注册 5 个平级项 foreach ($item in $items) { $key = Join-Path $parent ("SceneMarshal-{0}" -f $item.Action) $commandKey = Join-Path $key 'command' diff --git a/scripts/remote-common.ps1 b/scripts/remote-common.ps1 index d555fc2..d73177d 100644 --- a/scripts/remote-common.ps1 +++ b/scripts/remote-common.ps1 @@ -1,7 +1,7 @@ #Requires -Version 7.0 <# .SYNOPSIS - media-rename / media-archive 共用的 SSH 与路径翻译工具(由调用方 dot-source 引入)。 + scene-marshal 与右键菜单共用的 SSH 与路径翻译工具(由调用方 dot-source 引入)。 #> $script:Remote = 'ali@10.10.1.202' @@ -87,3 +87,53 @@ function Resolve-TargetToken([string]$Token) { } return Resolve-RemoteTarget $Token } + +# ---------------------------------------------------------------- 剧集根回溯(壳层路径规则,不做媒体识别) + +# 容器目录段:Season 1 / S01 / 第2季 / Specials / extras +$script:ContainerDirPattern = '^(?i)(season\s*0*\d{1,2}|s\s*0*\d{1,2}|第\s*[0-9一二三四五六七八九十两]+\s*季|specials?|extras|花絮)$' + +function Test-ContainerDirName([string]$Name) { + if (-not $Name) { return $false } + return ($Name.Trim() -match $script:ContainerDirPattern) +} + +function Resolve-SeriesRoot([string]$Path) { + <# + 把「任意选中项」归一到一个确定的剧集/电影根目录: + 文件(Season 1\E01.mkv / extras\花絮.mkv)→ 父目录 → 反复剥容器段(最多 3 层) + 目录(Season 1 / 第2季)→ 同样剥容器段 + 纯路径规则,不依赖 TMDB/文件名识别。 + #> + if (-not $Path) { return $null } + $p = $Path.Trim().TrimEnd('\', '/') + if (-not $p) { return $null } + if (Test-Path -LiteralPath $p -PathType Leaf) { + $p = Split-Path -Parent $p + } + if (-not $p) { return $null } + + for ($i = 0; $i -lt 3; $i++) { + $leaf = Split-Path -Leaf $p + if (-not (Test-ContainerDirName $leaf)) { break } + $parent = (Split-Path -Parent $p) + if (-not $parent -or $parent -eq $p) { break } + $p = $parent.TrimEnd('\', '/') + if (-not $p) { break } + } + return $p +} + +function Test-DownloadRootPath([string]$Path) { + <# + 下载根/盘符根的粗判定:只能拿到这种结果时不入队(等于要么整盘扫、要么把一部剧的 + 上级目录当成一部剧处理)。目录/空白处右键不设此守卫。 + #> + if (-not $Path) { return $true } + $p = $Path.TrimEnd('\', '/') + if ($p -match '^[A-Za-z]:$') { return $true } # Y: + if ($p -match '^\\\\[^\\]+\\[^\\]+$') { return $true } # \\host\share + if ($p -match '^/$') { return $true } + $leaf = Split-Path -Leaf $p + return ($leaf -in @('Quark-Down', 'Finish', 'media', 'n100-sda1')) +}