Files
SceneMarshal/scripts/explorer-media-rename.ps1
T
ali 0e82f054ad fix(menu): 串行化 worker 拉起,消除多选时闪出多个窗口
- Explorer 对多选是并发发起 N 个入队调用,此前每个调用都在 worker 抢到锁
  之前判断「没有 worker」,于是各拉起一个窗口,抢不到锁的随即退出
- 改为入队后先拿 spawn.lock 再复查并拉起,其他并发调用排队后看到已有
  worker 就直接跳过
- worker 启动时先写一行「进程启动(抢锁中)」日志,便于核对是否只拉起一次
- 实测:4 次快速入队 → 只拉起 1 个 worker,顺序处理完 4 项
2026-11-19 18:25:43 +08:00

273 lines
9.6 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
# 注意:必须 Out-Host 把子脚本的输出导到控制台,
# 否则它会混进本函数的返回值,调用方拿到的就不是退出码了。
if ($DryRun) { & $runnerPath -Tokens $tokens -DryRun | Out-Host }
else { & $runnerPath -Tokens $tokens | Out-Host }
$code = $LASTEXITCODE
if ($null -eq $code -or $code -is [array]) { return 0 }
return [int]$code
}
# ---------------------------------------------------------------- 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 启动'
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