Files
SceneMarshal/scripts/explorer-media-rename.ps1
T
ali eb1aa5600f fix(menu): 队列内改用独立子进程执行,修复交互提示不可见
- 进程内调用 + '| Out-Host' 会让远端 ssh -t 的输出按行缓冲,'请选择分类'
  这类不带换行的提示不会渲染,用户只能盲输(实测被误按 q 取消,归档全被取消)
- 改为 Start-Process -NoNewWindow -Wait,子进程直接继承控制台,提示与
  输入回显恢复正常;退出码取自子进程 ExitCode
- media-archive 取消时返回 2 而不是 0,避免上层把「取消」记成「成功」
- worker 启动日志补充 stdin/stdout 是否被重定向,便于排查同类问题
2026-11-19 18:30:27 +08:00

281 lines
10 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
串行消费队列;队列空且空闲超过 $WorkerIdleSeconds 秒后自行退出。
同一时刻只允许一个 worker(靠 worker.lock 独占锁保证)。
3) 直接执行(调试/手动):-Action <动作> -Paths <路径>
不进队列,立即处理当前窗口里的这一项。
.PARAMETER Action
rename(默认)/ archive / extract-subs / check。
.PARAMETER DryRun
只打印将要执行的远端命令,不真正执行。
.PARAMETER Pause
执行结束后停住窗口(直接执行模式用);worker 结束时也会停一下。
.PARAMETER Paths
资源管理器传入的选中项。
#>
[CmdletBinding()]
param(
[ValidateSet('rename', 'archive', 'extract-subs', 'check')]
[string]$Action = 'rename',
[switch]$Pause,
[switch]$DryRun,
[switch]$Enqueue,
[switch]$Worker,
[Parameter(ValueFromRemainingArguments = $true)][string[]]$Paths = @()
)
$ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { }
# ---------------------------------------------------------------- 公共定义
$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'
$WorkerLog = Join-Path $QueueDir 'worker.log'
$WorkerIdleSeconds = 20
$PwshPath = (Get-Process -Id $PID).Path
$ActionPlan = @{
'archive' = @{ Runner = 'media-archive.ps1'; Extra = @() }
'extract-subs' = @{ Runner = 'media-rename.ps1'; Extra = @('extract-subs') }
'check' = @{ Runner = 'media-rename.ps1'; Extra = @('check') }
'rename' = @{ Runner = 'media-rename.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 Add-QueueItem([string]$action, [string]$target) {
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') }
Add-Content -LiteralPath $QueueFile -Value ($item | ConvertTo-Json -Compress) -Encoding utf8
}
finally { $lock.Close() }
}
function Take-QueueItem {
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
}
$first = $lines[0]
$rest = @($lines | Select-Object -Skip 1)
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)
}
finally { $lock.Close() }
}
function Test-WorkerAlive {
$lock = Enter-FileLock $WorkerLock 200
if ($null -eq $lock) { return $true }
$lock.Close()
return $false
}
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-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)
}
return $target
}
function Invoke-Action([string]$itemAction, [string]$target) {
$plan = $ActionPlan[$itemAction]
if (-not $plan) {
Write-Host "❌ 未知动作: $itemAction" -ForegroundColor Red
return 1
}
$runnerPath = Join-Path $PSScriptRoot $plan.Runner
$tokens = @($target) + $plan.Extra
# 关键:用独立子进程「继承当前控制台」来跑,而不是在进程内 + 管道。
# 管道会让远端 ssh -t 的交互提示与本地输入回显错位(提示行会消失)。
$quotedTokens = ($tokens | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ','
$quotedRunner = "'" + ($runnerPath -replace "'", "''") + "'"
$extra = ''
if ($DryRun) { $extra = ' -DryRun' }
$command = "& $quotedRunner -Tokens @($quotedTokens)$extra"
$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 { }
Write-WorkerLog ("worker 启动(stdin重定向={0} stdout重定向={1})" -f `
[Console]::IsInputRedirected, [Console]::IsOutputRedirected)
Write-Host '📋 SceneMarshal 队列已启动(空闲 20 秒后自动关闭)' -ForegroundColor Cyan
Write-Host ''
$done = 0
$failed = 0
$idle = 0
$summarized = $false
while ($true) {
$item = Take-QueueItem
if ($null -eq $item) {
# 队列刚空时就报一次汇总,用户在窗口自动关闭前也能看到
if (($done + $failed) -gt 0 -and -not $summarized) {
Write-Host ('📊 已处理 {0} 项:成功 {1},失败 {2};{3} 秒内无新任务将自动关闭' -f `
($done + $failed), $done, $failed, $WorkerIdleSeconds) -ForegroundColor Cyan
$summarized = $true
}
if ($idle -ge $WorkerIdleSeconds) { break }
$idle += 2
Start-Sleep -Seconds 2
continue
}
$idle = 0
$summarized = $false
$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)
$started = Get-Date
try {
$code = Invoke-Action $item.action $item.path
}
catch {
Write-Host (" ❌ 异常: {0}" -f $_.Exception.Message) -ForegroundColor Red
$code = 1
}
$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)
}
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-Host ''
}
Write-Host ('📊 本次共处理 {0} 项:成功 {1},失败 {2}' -f ($done + $failed), $done, $failed) -ForegroundColor Cyan
Write-Host (' 队列已空,{0} 秒内无新任务将自动关闭(详细记录见 worker.log)' -f $WorkerIdleSeconds) -ForegroundColor DarkGray
Write-WorkerLog ("worker 退出:成功 {0},失败 {1}" -f $done, $failed)
$workerLock.Close()
return 0
}
# ---------------------------------------------------------------- 主流程
if ($Worker) {
exit (Invoke-Worker)
}
$target = Resolve-Target $Paths
if ($Enqueue) {
if (-not $target) { exit 0 } # 没拿到路径就静默退出,不弹窗
Add-QueueItem $Action $target
if (-not (Test-WorkerAlive)) {
# 多选时 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 (-not $target) {
Write-Host '❌ 没有收到要处理的路径' -ForegroundColor Red
if ($Pause) { Write-Host ''; Read-Host '按 Enter 关闭' | Out-Null }
exit 1
}
Write-Host "📁 目标: $target" -ForegroundColor DarkGray
Write-Host ("▶ 动作: {0}" -f $Action) -ForegroundColor DarkGray
$exitCode = Invoke-Action $Action $target
if ($Pause) {
Write-Host ''
Read-Host '按 Enter 关闭窗口' | Out-Null
}
exit $exitCode