CaiWuXiTong/scripts/hxb-bank/read-dingtalk-otp.ps1

552 lines
16 KiB
PowerShell

[CmdletBinding()]
param(
[string]$ProcessName = 'DingTalk',
[string]$WindowTitle = '钉钉',
[string]$ImagePath,
[string]$OcrText,
[string]$ReadyFile,
[string]$GroupMarker = '华夏',
[switch]$SkipGroupMarker,
[string[]]$IgnoreCode = @(),
[switch]$IncludeExisting,
[ValidateRange(5, 300)]
[int]$TimeoutSeconds = 120,
[ValidateRange(250, 10000)]
[int]$PollMilliseconds = 1000,
[ValidateRange(0.2, 0.8)]
[double]$CropLeft = 0.4,
[ValidateRange(0.0, 0.3)]
[double]$CropTop = 0.04,
[ValidateRange(0.5, 1.0)]
[double]$CropRight = 0.995,
[ValidateRange(0.5, 1.0)]
[double]$CropBottom = 0.92,
[ValidateSet('Auto', 'PrintWindow', 'Foreground')]
[string]$CaptureMode = 'Auto'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Runtime.WindowsRuntime
[void][Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage, ContentType = WindowsRuntime]
[void][Windows.Storage.Streams.DataWriter, Windows.Storage, ContentType = WindowsRuntime]
[void][Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
[void][Windows.Graphics.Imaging.SoftwareBitmap, Windows.Foundation, ContentType = WindowsRuntime]
[void][Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
[void][Windows.Media.Ocr.OcrResult, Windows.Foundation, ContentType = WindowsRuntime]
[void][Windows.Globalization.Language, Windows.Foundation, ContentType = WindowsRuntime]
if (-not ('CaiwuOtpWindowNative' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public static class CaiwuOtpWindowNative
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint flags);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int command);
[DllImport("user32.dll")]
public static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool SetProcessDPIAware();
}
'@
}
[void][CaiwuOtpWindowNative]::SetProcessDPIAware()
$asTaskMethod = [System.WindowsRuntimeSystemExtensions].GetMethods() |
Where-Object {
$_.Name -eq 'AsTask' -and
$_.IsGenericMethod -and
$_.GetParameters().Count -eq 1 -and
$_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1'
} |
Select-Object -First 1
if ($null -eq $asTaskMethod) {
throw '当前系统缺少 Windows 异步操作支持,无法使用 Windows OCR。'
}
function Await-WinRtOperation {
param(
[Parameter(Mandatory = $true)]
$Operation,
[Parameter(Mandatory = $true)]
[Type]$ResultType
)
$task = $asTaskMethod.MakeGenericMethod($ResultType).Invoke($null, @($Operation))
return $task.GetAwaiter().GetResult()
}
function Get-DingTalkWindow {
param(
[Parameter(Mandatory = $true)]
[string]$Name,
[string]$Title
)
$windows = @(
Get-Process -Name $Name -ErrorAction SilentlyContinue |
Where-Object { $_.MainWindowHandle -ne [IntPtr]::Zero }
)
if ($windows.Count -gt 1 -and -not [string]::IsNullOrWhiteSpace($Title)) {
$matching = @($windows | Where-Object { $_.MainWindowTitle -like "*$Title*" })
if ($matching.Count -gt 0) {
$windows = $matching
}
}
if ($windows.Count -eq 0) {
throw "未找到 $Name 的可见主窗口,请先打开钉钉并进入【华夏验证码】群。"
}
if ($windows.Count -gt 1) {
throw "找到多个 $Name 主窗口,无法安全确定要读取哪一个。请只保留一个钉钉主窗口。"
}
return $windows[0]
}
function Get-WindowBitmap {
param(
[Parameter(Mandatory = $true)]
[IntPtr]$Handle,
[Parameter(Mandatory = $true)]
[ValidateSet('Auto', 'PrintWindow', 'Foreground')]
[string]$Mode
)
if ([CaiwuOtpWindowNative]::IsIconic($Handle)) {
[void][CaiwuOtpWindowNative]::ShowWindow($Handle, 9)
}
$rect = New-Object CaiwuOtpWindowNative+RECT
if (-not [CaiwuOtpWindowNative]::GetWindowRect($Handle, [ref]$rect)) {
throw '无法读取钉钉窗口坐标。'
}
$width = $rect.Right - $rect.Left
$height = $rect.Bottom - $rect.Top
if ($width -lt 500 -or $height -lt 400) {
throw "钉钉窗口尺寸异常:${width}x${height}。请恢复最大化或正常尺寸。"
}
$bitmap = New-Object Drawing.Bitmap $width, $height, ([Drawing.Imaging.PixelFormat]::Format32bppArgb)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
$needsScreenCapture = $Mode -eq 'Foreground'
try {
if (-not $needsScreenCapture) {
$hdc = $graphics.GetHdc()
try {
$printed = [CaiwuOtpWindowNative]::PrintWindow($Handle, $hdc, 2)
}
finally {
$graphics.ReleaseHdc($hdc)
}
if (-not $printed) {
if ($Mode -eq 'PrintWindow') {
throw '钉钉窗口后台截图失败。'
}
$needsScreenCapture = $true
}
}
if ($needsScreenCapture) {
[void][CaiwuOtpWindowNative]::ShowWindow($Handle, 9)
[void][CaiwuOtpWindowNative]::SetForegroundWindow($Handle)
Start-Sleep -Milliseconds 250
$graphics.CopyFromScreen(
$rect.Left,
$rect.Top,
0,
0,
(New-Object Drawing.Size $width, $height),
[Drawing.CopyPixelOperation]::SourceCopy
)
}
return $bitmap
}
finally {
$graphics.Dispose()
}
}
function Convert-BitmapToPngBytes {
param(
[Parameter(Mandatory = $true)]
[Drawing.Bitmap]$Bitmap,
[Parameter(Mandatory = $true)]
[double]$Scale,
[Parameter(Mandatory = $true)]
[double]$Left,
[Parameter(Mandatory = $true)]
[double]$Top,
[Parameter(Mandatory = $true)]
[double]$Right,
[Parameter(Mandatory = $true)]
[double]$Bottom
)
$left = [Math]::Max(0, [int][Math]::Floor($Bitmap.Width * $Left))
$top = [Math]::Max(0, [int][Math]::Floor($Bitmap.Height * $Top))
$right = [Math]::Min($Bitmap.Width, [int][Math]::Ceiling($Bitmap.Width * $Right))
$bottom = [Math]::Min($Bitmap.Height, [int][Math]::Ceiling($Bitmap.Height * $Bottom))
if ($right - $left -lt 100 -or $bottom - $top -lt 30) {
throw '钉钉聊天区域太小,无法可靠识别验证码。请放大钉钉窗口。'
}
$crop = $Bitmap.Clone(
(New-Object Drawing.Rectangle $left, $top, ($right - $left), ($bottom - $top)),
$Bitmap.PixelFormat
)
$maxDimension = 5000.0
$effectiveScale = [Math]::Min($Scale, [Math]::Min($maxDimension / $crop.Width, $maxDimension / $crop.Height))
$effectiveScale = [Math]::Max(1.0, $effectiveScale)
$scaled = New-Object Drawing.Bitmap (
[Math]::Max(1, [int][Math]::Round($crop.Width * $effectiveScale)),
[Math]::Max(1, [int][Math]::Round($crop.Height * $effectiveScale))
)
$graphics = [Drawing.Graphics]::FromImage($scaled)
$stream = New-Object IO.MemoryStream
try {
$graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$graphics.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
$graphics.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::HighQuality
$graphics.DrawImage($crop, 0, 0, $scaled.Width, $scaled.Height)
$scaled.Save($stream, [Drawing.Imaging.ImageFormat]::Png)
return $stream.ToArray()
}
finally {
$stream.Dispose()
$graphics.Dispose()
$scaled.Dispose()
$crop.Dispose()
}
}
function Get-OcrLines {
param(
[Parameter(Mandatory = $true)]
[Drawing.Bitmap]$Bitmap,
[Parameter(Mandatory = $true)]
[double]$Scale,
[string]$LanguageTag = 'en-US',
[double]$Left = $CropLeft,
[double]$Top = $CropTop,
[double]$Right = $CropRight,
[double]$Bottom = $CropBottom
)
$bytes = Convert-BitmapToPngBytes `
-Bitmap $Bitmap `
-Scale $Scale `
-Left $Left `
-Top $Top `
-Right $Right `
-Bottom $Bottom
$stream = [Windows.Storage.Streams.InMemoryRandomAccessStream]::new()
$writer = [Windows.Storage.Streams.DataWriter]::new($stream)
try {
$writer.WriteBytes($bytes)
[void](Await-WinRtOperation -Operation $writer.StoreAsync() -ResultType ([uint32]))
$writer.DetachStream()
$stream.Seek(0)
$decoder = Await-WinRtOperation `
-Operation ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) `
-ResultType ([Windows.Graphics.Imaging.BitmapDecoder])
$softwareBitmap = Await-WinRtOperation `
-Operation ($decoder.GetSoftwareBitmapAsync()) `
-ResultType ([Windows.Graphics.Imaging.SoftwareBitmap])
$language = [Windows.Globalization.Language]::new($LanguageTag)
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage($language)
if ($null -eq $engine) {
throw "Windows 未安装 $LanguageTag OCR 语言包。"
}
$result = Await-WinRtOperation `
-Operation ($engine.RecognizeAsync($softwareBitmap)) `
-ResultType ([Windows.Media.Ocr.OcrResult])
return @($result.Lines | ForEach-Object { $_.Text })
}
finally {
if ($stream) {
$stream.Dispose()
}
}
}
function Test-GroupMarker {
param(
[Parameter(Mandatory = $true)]
[Drawing.Bitmap]$Bitmap
)
if ($SkipGroupMarker -or [string]::IsNullOrWhiteSpace($GroupMarker)) {
return $true
}
$lines = @(Get-OcrLines `
-Bitmap $Bitmap `
-Scale 5.0 `
-LanguageTag 'zh-Hans-CN' `
-Left $CropLeft `
-Top 0.0 `
-Right $CropRight `
-Bottom 0.16)
$headerText = ($lines -join '').Replace(' ', '')
return $headerText.Contains($GroupMarker)
}
function Find-OtpCandidates {
param(
[Parameter(Mandatory = $true)]
[string[]]$Lines
)
$candidates = New-Object 'System.Collections.Generic.List[object]'
$seen = New-Object 'System.Collections.Generic.HashSet[string]'
$position = 0
foreach ($line in $Lines) {
foreach ($match in [regex]::Matches([string]$line, '(?<!\d)\d{6}(?!\d)')) {
$code = $match.Value
if ($seen.Add($code)) {
$candidates.Add([pscustomobject]@{
Code = $code
Position = $position
})
}
$position++
}
}
return $candidates
}
function Get-OtpFromBitmap {
param(
[Parameter(Mandatory = $true)]
[Drawing.Bitmap]$Bitmap,
[double[]]$Scales = @(4.0, 5.0, 6.0)
)
$votes = @{}
$positions = @{}
foreach ($scale in $Scales) {
$lines = @(Get-OcrLines -Bitmap $Bitmap -Scale $scale)
foreach ($candidate in @(Find-OtpCandidates -Lines $lines)) {
$code = [string]$candidate.Code
if (-not $votes.ContainsKey($code)) {
$votes[$code] = 0
$positions[$code] = [int]$candidate.Position
}
$votes[$code]++
$positions[$code] = [Math]::Max([int]$positions[$code], [int]$candidate.Position)
}
}
return @(
$votes.GetEnumerator() |
ForEach-Object {
[pscustomobject]@{
Code = [string]$_.Key
Votes = [int]$_.Value
Position = [int]$positions[[string]$_.Key]
}
} |
Sort-Object -Property @{ Expression = 'Votes'; Descending = $true }, @{ Expression = 'Position'; Descending = $true }
)
}
function Get-BaselineCodes {
param(
[Parameter(Mandatory = $true)]
[Drawing.Bitmap]$Bitmap
)
$codes = New-Object 'System.Collections.Generic.HashSet[string]'
foreach ($candidate in @(Get-OtpFromBitmap -Bitmap $Bitmap)) {
[void]$codes.Add([string]$candidate.Code)
}
return $codes
}
function Complete-Result {
param(
[Parameter(Mandatory = $true)]
[string]$Code,
[string]$Window
)
[pscustomobject]@{
ok = $true
code = $Code
window = $Window
observedAt = (Get-Date).ToString('o')
} | ConvertTo-Json -Compress
}
$ignored = New-Object 'System.Collections.Generic.HashSet[string]'
foreach ($code in $IgnoreCode) {
if ($code -match '^\d{6}$') {
[void]$ignored.Add($code)
}
}
if (-not [string]::IsNullOrWhiteSpace($OcrText)) {
$candidates = @(Find-OtpCandidates -Lines ($OcrText -split "\r?\n"))
$allowed = @($candidates | Where-Object { -not $ignored.Contains([string]$_.Code) })
if ($allowed.Count -eq 0) {
throw 'OCR 文本中没有发现未被排除的 6 位验证码。'
}
$picked = $allowed | Sort-Object -Property Position -Descending | Select-Object -First 1
Complete-Result -Code $picked.Code -Window 'ocr-text'
exit 0
}
if (-not [string]::IsNullOrWhiteSpace($ImagePath)) {
if (-not (Test-Path -LiteralPath $ImagePath -PathType Leaf)) {
throw "图片不存在:$ImagePath"
}
$bitmap = [Drawing.Bitmap]::FromFile((Resolve-Path -LiteralPath $ImagePath).Path)
try {
if (-not (Test-GroupMarker -Bitmap $bitmap)) {
throw "图片中没有识别到群名标记:$GroupMarker"
}
$candidates = @(Get-OtpFromBitmap -Bitmap $bitmap)
$allowed = @($candidates | Where-Object { $_.Votes -ge 2 -and -not $ignored.Contains([string]$_.Code) })
if ($allowed.Count -eq 0) {
throw '图片 OCR 没有发现足够可靠的 6 位验证码。'
}
Complete-Result -Code $allowed[0].Code -Window 'image'
exit 0
}
finally {
$bitmap.Dispose()
}
}
$window = Get-DingTalkWindow -Name $ProcessName -Title $WindowTitle
$handle = $window.MainWindowHandle
$windowName = $window.MainWindowTitle
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
$observed = @{}
if (-not $IncludeExisting) {
$baselineBitmap = Get-WindowBitmap -Handle $handle -Mode $CaptureMode
try {
if (-not (Test-GroupMarker -Bitmap $baselineBitmap)) {
throw "钉钉当前窗口没有识别到群名标记:$GroupMarker"
}
foreach ($code in (Get-BaselineCodes -Bitmap $baselineBitmap)) {
[void]$ignored.Add([string]$code)
}
}
finally {
$baselineBitmap.Dispose()
}
}
if (-not [string]::IsNullOrWhiteSpace($ReadyFile)) {
[IO.File]::WriteAllText($ReadyFile, 'ready', [Text.UTF8Encoding]::new($false))
}
while ((Get-Date) -lt $deadline) {
$bitmap = Get-WindowBitmap -Handle $handle -Mode $CaptureMode
try {
if (-not (Test-GroupMarker -Bitmap $bitmap)) {
Start-Sleep -Milliseconds $PollMilliseconds
continue
}
$candidates = @(Get-OtpFromBitmap -Bitmap $bitmap)
}
finally {
$bitmap.Dispose()
}
foreach ($candidate in $candidates) {
$code = [string]$candidate.Code
if ($ignored.Contains($code) -or $candidate.Votes -lt 2) {
continue
}
if (-not $observed.ContainsKey($code)) {
$observed[$code] = 0
}
$observed[$code]++
if ($observed[$code] -ge 2) {
Complete-Result -Code $code -Window $windowName
exit 0
}
}
Start-Sleep -Milliseconds $PollMilliseconds
}
throw "等待 $TimeoutSeconds 秒仍未读到新的 6 位验证码。请确认钉钉停留在【华夏验证码】群,并且新验证码已经出现。"