Update-MediaInfo.ps1

#requires -Version 5.1
param(
    [guid]$OperationId = [guid]::NewGuid(),
    [uri]$SourceUrl,
    [ValidatePattern('\A[a-fA-F0-9]{64}\z')][string]$ArchiveSha256
)
$ErrorActionPreference = 'Stop'

$principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    throw 'Run the MediaInfo updater as a standard user.'
}
if ($SourceUrl -and (!$SourceUrl.IsAbsoluteUri -or $SourceUrl.Scheme -ne 'https' -or $SourceUrl.UserInfo -or $SourceUrl.Fragment)) {
    throw 'Specify an absolute HTTPS archive URL without credentials or a fragment.'
}
$root = [IO.Directory]::CreateDirectory((Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'Hacksoft\VideoTools\MediaInfo'))
$stage = $root.CreateSubdirectory('download-' + $OperationId.ToString('N'))
try {
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    $officialPath = '/download/binary/libmediainfo0/(\d+\.\d+(?:\.\d+)?)/MediaInfo_DLL_\1_Windows_x64_WithoutInstaller\.zip'
    $version = $null
    if ($SourceUrl) {
        $uri = $SourceUrl
        if ($uri.Authority -eq 'mediaarea.net' -and $uri.AbsolutePath -cmatch ('\A' + $officialPath + '\z')) {
            $version = [version]$Matches[1]
        }
        elseif (!$ArchiveSha256) { throw 'An alternate MediaInfo archive requires a trusted SHA-256.' }
    }
    else {
        $page = Invoke-WebRequest -UseBasicParsing -Uri 'https://mediaarea.net/en/MediaInfo/Download/Windows' -TimeoutSec 20
        $packages = [regex]::Matches($page.Content, '(?:https://mediaarea\.net)?' + $officialPath)
        $package = $packages | Sort-Object { [version]$_.Groups[1].Value } -Descending | Select-Object -First 1
        if (!$package) { throw 'MediaArea did not list an Intel x64 DLL ZIP.' }
        $version = [version]$package.Groups[1].Value
        $uri = [uri]::new([uri]'https://mediaarea.net/', $package.Value)
    }
    $archive = Join-Path $stage.FullName 'MediaInfo.zip'
    Invoke-WebRequest -UseBasicParsing -Uri $uri -OutFile $archive -TimeoutSec 60
    if ((Get-Item -LiteralPath $archive).Length -gt 32MB) { throw 'The MediaInfo ZIP exceeded the expected package size.' }
    $packageDigest = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash
    if ($ArchiveSha256 -and $packageDigest -ne $ArchiveSha256) { throw 'The MediaInfo ZIP did not match the expected SHA-256.' }
    $knownArchive = $packageDigest -eq '4EFE172DF014693732E8B64A004CF382B8599EAF86BE26A9B38C0D2993E60E1D'

    $payload = $stage.CreateSubdirectory('payload')
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $zip = [IO.Compression.ZipFile]::OpenRead($archive)
    try {
        foreach ($name in 'MediaInfo.dll','Developers/License.html') {
            $entry = @($zip.Entries | Where-Object FullName -ceq $name)
            if ($entry.Count -ne 1 -or $entry[0].Length -le 0 -or $entry[0].Length -gt 32MB) {
                throw "Invalid MediaInfo archive entry: $name"
            }
            [IO.Compression.ZipFileExtensions]::ExtractToFile($entry[0], (Join-Path $payload.FullName ([IO.Path]::GetFileName($name))), $false)
        }
    }
    finally { $zip.Dispose() }

    $library = Get-Item -LiteralPath (Join-Path $payload.FullName 'MediaInfo.dll')
    $libraryVersion = [version]$library.VersionInfo.FileVersion
    if ($library.VersionInfo.ProductName -ne 'MediaInfo' -or
        ($version -and $libraryVersion.ToString($version.ToString().Split('.').Length) -ne $version.ToString())) {
        throw 'The DLL version does not match the advertised package.'
    }
    if (!$knownArchive) {
        $signature = Get-AuthenticodeSignature -FilePath $library.FullName
        if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.GetNameInfo('SimpleName', $false) -ine 'MEDIAAREA.NET') {
            throw 'The MediaInfo DLL does not have a trusted MediaArea signature.'
        }
    }
    $dest = Join-Path $root.FullName $libraryVersion.ToString()
    if ([IO.Directory]::Exists($dest)) {
        foreach ($file in 'MediaInfo.dll','License.html') {
            if ((Get-FileHash -LiteralPath (Join-Path $dest $file)).Hash -ne (Get-FileHash -LiteralPath (Join-Path $payload.FullName $file)).Hash) {
                throw 'The installed files differ from the official package for this version.'
            }
        }
    }
    else { [IO.Directory]::Move($payload.FullName, $dest) }
    [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
    [Console]::WriteLine((@{ Path = (Join-Path $dest 'MediaInfo.dll'); Version = $libraryVersion.ToString(); Source = $uri.GetLeftPart([UriPartial]::Path) } | ConvertTo-Json -Compress))
}
finally {
    if ($stage.Parent.FullName -eq $root.FullName -and $stage.Name -match '^download-[a-f0-9]{32}$') {
        Remove-Item -LiteralPath $stage.FullName -Recurse -Force
    }
}