Files
SceneMarshal/scripts/explorer-media-rename.ps1
T
ali 18a7dee439 fix(menu): 队列积压时重复右键不再无窗口
- check 只读动作免二次确认
- worker 汇总按目录计数并显示批次
- 重复入队但队列有积压时也拉起 worker 清积压
2026-11-28 13:53:19 +08:00

523 lines
22 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#Requires -Version 7.0
<#
.SYNOPSIS
资源管理器右键菜单的入口,支持「多选排队、单窗口顺序处理」。
.DESCRIPTION
三种运行方式:
1) 入队(菜单用):-Enqueue -Action <动作> -Paths <路径>
把任务写进队列后立即退出,由 worker 统一处理。多次点击只会拉起一个窗口。
2) 队列 worker(内部使用):-Worker
串行消费队列;队列处理完即退出(不等新任务)。
同一时刻只允许一个 worker(靠 worker.lock 独占锁保证)。
3) 直接执行(调试/手动):-Action <动作> -Paths <路径>
不进队列,立即处理当前窗口里的这一项。
.PARAMETER Action
rename(默认)/ archive / variety / extract-subs / check。
.PARAMETER DryRun
只打印将要执行的远端命令,不真正执行。
.PARAMETER Pause
执行结束后停住窗口(直接执行模式用);worker 结束时也会停一下。
.PARAMETER Paths
资源管理器传入的选中项(可多选)。每一项都会先回溯到剧集根目录再入队。
#>
[CmdletBinding()]
param(
[ValidateSet('rename', 'archive', 'variety', 'extract-subs', 'check')]
[string]$Action = 'rename',
[switch]$Pause,
[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'
$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 = @{
# 所有动作都走同一个 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') }
# 兼容性校验是纯只读(只出 preflight_report),不值得为它挡一次确认
'check' = @{ Runner = 'scene-marshal.ps1'; Extra = @('check', '--pass') }
'rename' = @{ Runner = 'scene-marshal.ps1'; Extra = @() }
}
function Write-WorkerLog([string]$message) {
try {
$line = '{0} {1}' -f (Get-Date).ToString('yyyy-MM-dd HH:mm:ss'), $message
Add-Content -LiteralPath $WorkerLog -Value $line -Encoding utf8
}
catch { }
}
function Enter-FileLock([string]$path, [int]$timeoutMs = 3000) {
$deadline = (Get-Date).AddMilliseconds($timeoutMs)
while ((Get-Date) -lt $deadline) {
try { return [IO.File]::Open($path, 'OpenOrCreate', 'ReadWrite', 'None') }
catch { Start-Sleep -Milliseconds 50 }
}
return $null
}
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 {
$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([string]$onlyAction) {
<#
取出一条(若给了 onlyAction,则取第一条同 action 的,其余原样留在队列里)。
用于「多选 N 个文件夹 → 合成一个批次」。
#>
New-Item -ItemType Directory -Force -Path $QueueDir | Out-Null
$lock = Enter-FileLock $QueueLock
if ($null -eq $lock) { return $null }
try {
if (-not (Test-Path -LiteralPath $QueueFile)) { return $null }
$lines = @(Get-Content -LiteralPath $QueueFile -Encoding utf8 | Where-Object { $_.Trim() })
if ($lines.Count -eq 0) {
Remove-Item -LiteralPath $QueueFile -Force -ErrorAction SilentlyContinue
return $null
}
$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 ($picked | ConvertFrom-Json)
}
finally { $lock.Close() }
}
function Test-WorkerAlive {
$lock = Enter-FileLock $WorkerLock 200
if ($null -eq $lock) { return $true }
$lock.Close()
return $false
}
function Get-PendingQueueCount {
if (-not (Test-Path -LiteralPath $QueueFile)) { return 0 }
try {
return @(Get-Content -LiteralPath $QueueFile -Encoding utf8 |
Where-Object { $_.Trim() }).Count
}
catch { return 0 }
}
function Start-Worker {
Start-Process -FilePath $PwshPath `
-ArgumentList @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-File', $PSCommandPath, '-Worker') `
-WindowStyle Normal | Out-Null
# 等它真正拿到锁再返回,避免同一批多选时重复拉起 worker
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Milliseconds 50
if (Test-WorkerAlive) { return }
}
}
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 $resolved.ToArray()
}
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
# 模式放在最前,路径一律显式 -p:多选时裸路径会被当成第二个 mode / 位置参数
$tokens = @($plan.Extra)
foreach ($t in $targets) { $tokens += @('-p', $t) }
# 关键:用独立子进程「继承当前控制台」来跑,而不是在进程内 + 管道。
# 管道会让远端 ssh -t 的交互提示与本地输入回显错位(提示行会消失)。
$quotedTokens = ($tokens | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ','
$quotedRunner = "'" + ($runnerPath -replace "'", "''") + "'"
$extra = ''
if ($DryRun) { $extra = ' -DryRun' }
# 末尾必须显式 exit:脚本里的 exit 只结束脚本体,-Command 宿主会按
# 「最后一条命令是否成功」给退出码,取消(code 2)会被错报成 1。
$command = "& $quotedRunner -Tokens @($quotedTokens)$extra; exit " + '$LASTEXITCODE'
$proc = Start-Process -FilePath $PwshPath `
-ArgumentList @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-Command', ('"' + $command + '"')) `
-NoNewWindow -Wait -PassThru
if ($null -eq $proc) { return 1 }
return [int]$proc.ExitCode
}
# ---------------------------------------------------------------- worker 模式
function Invoke-Worker {
Write-WorkerLog 'worker 进程启动(抢锁中)'
$workerLock = Enter-FileLock $WorkerLock 200
if ($null -eq $workerLock) {
Write-WorkerLog '已有 worker 在运行,本次进程直接退出'
Write-Host '已有 worker 在运行,退出。' -ForegroundColor DarkGray
return 0
}
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
Write-Host ''
$batches = 0 # 实际跑了几批(一次右键多选合批后算 1 批)
$okDirs = 0 # 下面三个按「目录」累加:一批 10 个目录成功就是 10
$cancelDirs = 0
$failDirs = 0
$summaryShown = $false
$closeDeadline = $null
while ($true) {
$item = Take-QueueItem
if ($null -ne $item) {
$summaryShown = $false
$closeDeadline = $null
# 合批: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 {
@{ 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
$batches++
if ($code -eq 0) {
$okDirs += $targets.Count
Write-Host (" ✅ 完成,用时 {0}s" -f $cost) -ForegroundColor Green
Write-WorkerLog ("完成 {0}({1}s)" -f ($targets -join '; '), $cost)
}
elseif ($code -eq 2) {
# 退出码 2 约定为「用户主动取消」,不算失败
$cancelDirs += $targets.Count
Write-Host (" ⏭ 已取消(未改动任何文件),用时 {0}s" -f $cost) -ForegroundColor DarkYellow
Write-WorkerLog ("已取消 {0}" -f ($targets -join '; '))
}
else {
$failDirs += $targets.Count
Write-Host (" ⚠️ 失败(退出码 {0}),用时 {1}s" -f $code, $cost) -ForegroundColor Red
Write-WorkerLog ("失败 {0}(code={1}, {2}s)" -f ($targets -join '; '), $code, $cost)
}
Write-Host ''
continue
}
# 队列已空:只显示一次汇总,然后等 Esc / Enter 关窗
if (-not $summaryShown) {
$dirTotal = $okDirs + $cancelDirs + $failDirs
$batchNote = if ($batches -gt 1) { "($batches 批)" } else { '' }
Write-Host ('📊 本次共处理 {0} 个目录{1}:成功 {2},取消 {3},失败 {4}' -f `
$dirTotal, $batchNote, $okDirs, $cancelDirs, $failDirs) -ForegroundColor Cyan
Write-Host ' 按 Esc / Enter 关闭窗口;期间有新任务会接着处理(2 分钟无操作自动关闭)' -ForegroundColor DarkGray
Write-WorkerLog ("队列处理完毕:成功 {0} 个目录,取消 {1},失败 {2}({3} 批)" -f `
$okDirs, $cancelDirs, $failDirs, $batches)
$summaryShown = $true
$closeDeadline = (Get-Date).AddSeconds(120)
}
# 只认 Esc / Enter 关窗:其它键(含误触的字母键)一律忽略,避免窗口被顺手按掉
$closeRequested = $false
try {
if ($Host.UI.RawUI.KeyAvailable) {
$key = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
# KeyInfo 没有 ConsoleKey 属性,只能比 VirtualKeyCode(Esc=27 / Enter=13)
$closeRequested = $key.VirtualKeyCode -in @([int][ConsoleKey]::Escape, [int][ConsoleKey]::Enter)
}
}
catch { }
if ($closeRequested) { break }
if ($null -ne $closeDeadline -and (Get-Date) -ge $closeDeadline) { break }
Start-Sleep -Milliseconds 150
}
Write-WorkerLog 'worker 退出'
$workerLock.Close()
return 0
}
# ---------------------------------------------------------------- 主流程
if ($Worker) {
exit (Invoke-Worker)
}
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 ($targets.Count -eq 0) { exit 0 } # 没拿到有效路径就静默退出,不弹窗
if ($DryRun) {
$targets | ForEach-Object { Write-Host "[DryRun] 解析结果: $_" -ForegroundColor Yellow }
exit 0
}
$queued = Add-QueueItem $Action $targets
$pendingCount = Get-PendingQueueCount
# 即使本次全是重复项,只要队列里还有积压且没有 worker,也要拉起 worker 清积压。
# 否则 worker 在关窗/退出瞬间留下的条目会让后续同路径点击永远静默、连窗口都不开。
if (-not (Test-WorkerAlive) -and ($queued -or $pendingCount -gt 0)) {
if (-not $queued -and $pendingCount -gt 0) {
Write-WorkerLog ("重复入队,但队列有 {0} 条积压;拉起 worker 清积压" -f $pendingCount)
}
# 多选时 Explorer 会同时发起 N 个入队调用,这里必须串行化,
# 否则每个调用都会在 worker 抢到锁之前各拉起一个窗口。
$spawnLock = Enter-FileLock $SpawnLock 8000
try {
if ($null -ne $spawnLock -and -not (Test-WorkerAlive)) { Start-Worker }
}
finally {
if ($null -ne $spawnLock) { $spawnLock.Close() }
}
}
exit 0
}
# 直接执行模式
if ($targets.Count -eq 0) {
Write-Host '❌ 没有收到要处理的路径' -ForegroundColor Red
if ($Pause) { Write-Host ''; Read-Host '按 Enter 关闭' | Out-Null }
exit 1
}
foreach ($t in $targets) { Write-Host "📁 目标: $t" -ForegroundColor DarkGray }
Write-Host ("▶ 动作: {0}" -f $Action) -ForegroundColor DarkGray
$exitCode = Invoke-Action $Action $targets
if ($Pause) {
Write-Host ''
Read-Host '按 Enter 关闭窗口' | Out-Null
}
exit $exitCode