Files
SGU-CredentialProvider/scripts/Set-SguWelcomeWallpaper.ps1
T

446 lines
17 KiB
PowerShell

#Requires -Version 5.1
[CmdletBinding()]
param(
[string]$BaseImagePath = (Join-Path $env:ProgramData 'SGU\Branding\darkblue.jpg'),
[string]$FontsPath = (Join-Path $env:ProgramData 'SGU\Branding\fonts'),
[string]$OutputPath,
[string]$DisplayName,
[string]$ComputerName = $env:COMPUTERNAME,
[string]$Location,
[string]$OrganizationalUnit,
[ValidateRange(640, 16384)]
[int]$CanvasWidth,
[ValidateRange(480, 16384)]
[int]$CanvasHeight,
[switch]$SkipDirectoryLookup,
[switch]$SkipApply
)
$ErrorActionPreference = 'Stop'
$script:LogPath = Join-Path $env:LOCALAPPDATA 'SGU\Logs\welcome-wallpaper.log'
Add-Type -AssemblyName System.Drawing
function Write-WelcomeLog {
param([Parameter(Mandatory)][string]$Message)
try {
$logDirectory = Split-Path $script:LogPath -Parent
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
Add-Content -LiteralPath $script:LogPath `
-Value ('{0:o} {1}' -f (Get-Date), $Message) `
-Encoding UTF8
}
catch {
# The wallpaper must still be generated when logging is unavailable.
}
}
function ConvertTo-LdapFilterValue {
param([Parameter(Mandatory)][string]$Value)
return $Value.Replace('\', '\5c').Replace('*', '\2a').Replace('(', '\28').Replace(')', '\29').Replace(([string][char]0), '\00')
}
function ConvertFrom-LdapRdnValue {
param([Parameter(Mandatory)][string]$Value)
$decoded = [Text.RegularExpressions.Regex]::Replace(
$Value,
'\\([0-9A-Fa-f]{2})',
{ param($match) [char][Convert]::ToByte($match.Groups[1].Value, 16) })
return $decoded.Replace('\,', ',').Replace('\+', '+').Replace('\=', '=').Replace('\\', '\')
}
function Get-ImmediateOrganizationalUnit {
param([string]$DistinguishedName)
if (-not $DistinguishedName) {
return $null
}
$parts = [Text.RegularExpressions.Regex]::Split($DistinguishedName, '(?<!\\),')
foreach ($part in $parts) {
if ($part.StartsWith('OU=', [StringComparison]::OrdinalIgnoreCase)) {
return ConvertFrom-LdapRdnValue -Value $part.Substring(3)
}
}
return $null
}
function Get-DirectoryWelcomeMetadata {
param(
[Parameter(Mandatory)][string]$UserName,
[Parameter(Mandatory)][string]$MachineName
)
Add-Type -AssemblyName System.DirectoryServices
$rootDse = [DirectoryServices.DirectoryEntry]::new('LDAP://RootDSE')
try {
$namingContext = [string]$rootDse.Properties['defaultNamingContext'][0]
}
finally {
$rootDse.Dispose()
}
if (-not $namingContext) {
throw 'Active Directory did not return a default naming context.'
}
$searchRoot = [DirectoryServices.DirectoryEntry]::new("LDAP://$namingContext")
try {
$userSearcher = [DirectoryServices.DirectorySearcher]::new($searchRoot)
try {
$userSearcher.PageSize = 1
$userSearcher.Filter = '(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))' -f `
(ConvertTo-LdapFilterValue -Value $UserName)
[void]$userSearcher.PropertiesToLoad.Add('displayName')
$userResult = $userSearcher.FindOne()
$directoryDisplayName = if ($userResult -and $userResult.Properties['displayname'].Count) {
[string]$userResult.Properties['displayname'][0]
}
else {
$null
}
}
finally {
$userSearcher.Dispose()
}
$computerSearcher = [DirectoryServices.DirectorySearcher]::new($searchRoot)
try {
$computerSearcher.PageSize = 1
$computerSearcher.Filter = '(&(objectCategory=computer)(sAMAccountName={0}))' -f `
(ConvertTo-LdapFilterValue -Value ($MachineName + '$'))
[void]$computerSearcher.PropertiesToLoad.Add('location')
[void]$computerSearcher.PropertiesToLoad.Add('distinguishedName')
$computerResult = $computerSearcher.FindOne()
$directoryLocation = if ($computerResult -and $computerResult.Properties['location'].Count) {
[string]$computerResult.Properties['location'][0]
}
else {
$null
}
$computerDn = if ($computerResult -and $computerResult.Properties['distinguishedname'].Count) {
[string]$computerResult.Properties['distinguishedname'][0]
}
else {
$null
}
}
finally {
$computerSearcher.Dispose()
}
}
finally {
$searchRoot.Dispose()
}
[pscustomobject]@{
DisplayName = $directoryDisplayName
Location = $directoryLocation
OrganizationalUnit = Get-ImmediateOrganizationalUnit -DistinguishedName $computerDn
}
}
function Get-SpanishArticle {
param([Parameter(Mandatory)][string]$Value)
if ($Value -match '^(Sala|Aula|Facultad|Unidad|Biblioteca|Oficina|Coordinaci.n)\b') {
return 'la'
}
if ($Value -match '^(Laboratorio|Centro|Edificio|Campus|Taller|Auditorio)\b') {
return 'el'
}
return $null
}
function Get-WelcomeLocationText {
param(
[string]$Room,
[string]$OuName
)
$located = 'Est{0}s ubicado en' -f [char]0x00E1
$engineeringLab = 'Bienvenido al Laboratorio de C{0}mputo de Ingenier{1}a.' -f [char]0x00F3,[char]0x00ED
$Room = if ($Room) { $Room.Trim() } else { $null }
$OuName = if ($OuName) { $OuName.Trim() } else { $null }
if ($Room -and $OuName) {
$roomArticle = Get-SpanishArticle -Value $Room
$ouArticle = Get-SpanishArticle -Value $OuName
$roomPhrase = if ($roomArticle) { "$roomArticle $Room" } else { $Room }
$ouPhrase = if ($ouArticle -eq 'el') { "del $OuName" } elseif ($ouArticle) { "de $ouArticle $OuName" } else { "de $OuName" }
return "$located $roomPhrase $ouPhrase."
}
if ($Room) {
$article = Get-SpanishArticle -Value $Room
$phrase = if ($article) { "$article $Room" } else { $Room }
return "$located $phrase."
}
if ($OuName) {
$article = Get-SpanishArticle -Value $OuName
$phrase = if ($article) { "$article $OuName" } else { $OuName }
return "$located $phrase."
}
return $engineeringLab
}
function Get-AvailableFontFamily {
param(
[Parameter(Mandatory)][string[]]$Candidates,
[Drawing.FontFamily[]]$PrivateFamilies = @()
)
foreach ($candidate in $Candidates) {
$privateMatch = @($PrivateFamilies | Where-Object Name -eq $candidate | Select-Object -First 1)
if ($privateMatch.Count) {
return $privateMatch[0]
}
if (@([Drawing.FontFamily]::Families | ForEach-Object Name) -contains $candidate) {
return [Drawing.FontFamily]::new($candidate)
}
}
return [Drawing.FontFamily]::GenericSansSerif
}
function New-WelcomeFont {
param(
[Parameter(Mandatory)][Drawing.FontFamily]$Family,
[Parameter(Mandatory)][single]$Size,
[Parameter(Mandatory)][Drawing.FontStyle]$PreferredStyle
)
$style = if ($Family.IsStyleAvailable($PreferredStyle)) { $PreferredStyle } `
elseif ($Family.IsStyleAvailable([Drawing.FontStyle]::Bold)) { [Drawing.FontStyle]::Bold } `
else { [Drawing.FontStyle]::Regular }
return [Drawing.Font]::new($Family, $Size, $style, [Drawing.GraphicsUnit]::Pixel)
}
function Draw-CenteredText {
param(
[Parameter(Mandatory)][Drawing.Graphics]$Graphics,
[Parameter(Mandatory)][string]$Text,
[Parameter(Mandatory)][Drawing.Font]$Font,
[Parameter(Mandatory)][Drawing.Brush]$Brush,
[Parameter(Mandatory)][Drawing.RectangleF]$Bounds,
[Parameter(Mandatory)][Drawing.StringFormat]$Format,
[single]$ShadowOffset = 2
)
$shadowBounds = [Drawing.RectangleF]::new(
$Bounds.X + $ShadowOffset,
$Bounds.Y + $ShadowOffset,
$Bounds.Width,
$Bounds.Height)
$shadow = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(135, 0, 0, 0))
try {
$Graphics.DrawString($Text, $Font, $shadow, $shadowBounds, $Format)
$Graphics.DrawString($Text, $Font, $Brush, $Bounds, $Format)
}
finally {
$shadow.Dispose()
}
}
trap {
Write-WelcomeLog -Message ('ERROR ' + $_.Exception.Message)
throw
}
if (-not (Test-Path -LiteralPath $BaseImagePath -PathType Leaf)) {
throw "The welcome wallpaper base image does not exist: $BaseImagePath"
}
$userName = [Environment]::UserName
$metadata = $null
if (-not $SkipDirectoryLookup) {
try {
$metadata = Get-DirectoryWelcomeMetadata -UserName $userName -MachineName $ComputerName
}
catch {
Write-WelcomeLog -Message ('WARN Active Directory metadata was unavailable: ' + $_.Exception.Message)
}
}
if (-not $PSBoundParameters.ContainsKey('DisplayName')) {
$DisplayName = if ($metadata -and $metadata.DisplayName) { $metadata.DisplayName } else { $userName }
}
if (-not $DisplayName) {
$DisplayName = $userName
}
if (-not $PSBoundParameters.ContainsKey('Location') -and $metadata) {
$Location = $metadata.Location
}
if (-not $PSBoundParameters.ContainsKey('OrganizationalUnit') -and $metadata) {
$OrganizationalUnit = $metadata.OrganizationalUnit
}
$locationText = Get-WelcomeLocationText -Room $Location -OuName $OrganizationalUnit
if (-not $CanvasWidth -or -not $CanvasHeight) {
try {
Add-Type -AssemblyName System.Windows.Forms
$screenBounds = [Windows.Forms.Screen]::PrimaryScreen.Bounds
if (-not $CanvasWidth) { $CanvasWidth = $screenBounds.Width }
if (-not $CanvasHeight) { $CanvasHeight = $screenBounds.Height }
}
catch {
if (-not $CanvasWidth) { $CanvasWidth = 1600 }
if (-not $CanvasHeight) { $CanvasHeight = 1000 }
}
}
if (-not $OutputPath) {
$wallpaperDirectory = Join-Path $env:LOCALAPPDATA 'SGU\Wallpapers'
$safeComputerName = $ComputerName -replace '[^A-Za-z0-9_.-]', '_'
$OutputPath = Join-Path $wallpaperDirectory "welcome-$safeComputerName.jpg"
}
New-Item -ItemType Directory -Path (Split-Path $OutputPath -Parent) -Force | Out-Null
$source = [Drawing.Image]::FromFile($BaseImagePath)
$canvas = [Drawing.Bitmap]::new($CanvasWidth, $CanvasHeight, [Drawing.Imaging.PixelFormat]::Format24bppRgb)
try {
$graphics = [Drawing.Graphics]::FromImage($canvas)
try {
$graphics.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::HighQuality
$graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$graphics.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality
$graphics.TextRenderingHint = [Drawing.Text.TextRenderingHint]::AntiAliasGridFit
$sourceRatio = $source.Width / $source.Height
$targetRatio = $CanvasWidth / $CanvasHeight
if ($sourceRatio -gt $targetRatio) {
$sourceHeight = $source.Height
$sourceWidth = [int]($sourceHeight * $targetRatio)
$sourceX = [int](($source.Width - $sourceWidth) / 2)
$sourceY = 0
}
else {
$sourceWidth = $source.Width
$sourceHeight = [int]($sourceWidth / $targetRatio)
$sourceX = 0
$sourceY = [int](($source.Height - $sourceHeight) / 2)
}
$graphics.DrawImage(
$source,
[Drawing.Rectangle]::new(0, 0, $CanvasWidth, $CanvasHeight),
$sourceX,
$sourceY,
$sourceWidth,
$sourceHeight,
[Drawing.GraphicsUnit]::Pixel)
$scale = [Math]::Min($CanvasWidth / 1600.0, $CanvasHeight / 1000.0)
$panelWidth = [single]($CanvasWidth * 0.76)
$panelHeight = [single](310 * $scale)
$panelX = [single](($CanvasWidth - $panelWidth) / 2)
$panelY = [single]($CanvasHeight * 0.50 - ($panelHeight / 2))
$panelBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(72, 0, 13, 58))
$whiteBrush = [Drawing.SolidBrush]::new([Drawing.Color]::White)
$accentBrush = [Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(255, 211, 226, 255))
$linePen = [Drawing.Pen]::new([Drawing.Color]::FromArgb(155, 211, 226, 255), [single](2 * $scale))
$privateFonts = [Drawing.Text.PrivateFontCollection]::new()
if (Test-Path -LiteralPath $FontsPath -PathType Container) {
foreach ($fontFile in Get-ChildItem -LiteralPath $FontsPath -File |
Where-Object Extension -in '.otf','.ttf') {
try {
$privateFonts.AddFontFile($fontFile.FullName)
}
catch {
Write-WelcomeLog -Message ("WARN Font could not be loaded: {0}" -f $fontFile.Name)
}
}
}
$sansFamily = Get-AvailableFontFamily `
-Candidates @('Indivisa Text Sans', 'Indivisa Text', 'Segoe UI') `
-PrivateFamilies $privateFonts.Families
$serifFamily = Get-AvailableFontFamily `
-Candidates @('Indivisa Text Serif', 'Indivisa Serif', 'Georgia') `
-PrivateFamilies $privateFonts.Families
$welcomeFont = New-WelcomeFont -Family $sansFamily -Size ([single](34 * $scale)) -PreferredStyle ([Drawing.FontStyle]::Bold)
$nameFont = New-WelcomeFont -Family $serifFamily -Size ([single](70 * $scale)) `
-PreferredStyle ([Drawing.FontStyle]::Bold -bor [Drawing.FontStyle]::Italic)
$locationFont = New-WelcomeFont -Family $sansFamily -Size ([single](27 * $scale)) `
-PreferredStyle ([Drawing.FontStyle]::Regular)
$format = [Drawing.StringFormat]::new()
$format.Alignment = [Drawing.StringAlignment]::Center
$format.LineAlignment = [Drawing.StringAlignment]::Center
$format.Trimming = [Drawing.StringTrimming]::EllipsisWord
try {
$graphics.FillRectangle($panelBrush, $panelX, $panelY, $panelWidth, $panelHeight)
Draw-CenteredText -Graphics $graphics -Text 'Bienvenido,' -Font $welcomeFont `
-Brush $accentBrush -Bounds ([Drawing.RectangleF]::new($panelX, $panelY + 24*$scale, $panelWidth, 50*$scale)) -Format $format
Draw-CenteredText -Graphics $graphics -Text $DisplayName -Font $nameFont `
-Brush $whiteBrush -Bounds ([Drawing.RectangleF]::new($panelX + 30*$scale, $panelY + 64*$scale, $panelWidth - 60*$scale, 105*$scale)) -Format $format
$graphics.DrawLine($linePen, $panelX + 150*$scale, $panelY + 180*$scale, $panelX + $panelWidth - 150*$scale, $panelY + 180*$scale)
Draw-CenteredText -Graphics $graphics -Text $locationText -Font $locationFont `
-Brush $accentBrush -Bounds ([Drawing.RectangleF]::new($panelX + 60*$scale, $panelY + 190*$scale, $panelWidth - 120*$scale, 94*$scale)) -Format $format
}
finally {
$format.Dispose()
$locationFont.Dispose()
$nameFont.Dispose()
$welcomeFont.Dispose()
$serifFamily.Dispose()
$sansFamily.Dispose()
$privateFonts.Dispose()
$linePen.Dispose()
$accentBrush.Dispose()
$whiteBrush.Dispose()
$panelBrush.Dispose()
}
}
finally {
$graphics.Dispose()
}
$jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |
Where-Object MimeType -eq 'image/jpeg' |
Select-Object -First 1
$encoderParameters = [Drawing.Imaging.EncoderParameters]::new(1)
$encoderParameters.Param[0] = [Drawing.Imaging.EncoderParameter]::new(
[Drawing.Imaging.Encoder]::Quality,
[long]94)
try {
$canvas.Save($OutputPath, $jpegCodec, $encoderParameters)
}
finally {
$encoderParameters.Dispose()
}
}
finally {
$canvas.Dispose()
$source.Dispose()
}
if (-not $SkipApply) {
$desktopKey = 'HKCU:\Control Panel\Desktop'
Set-ItemProperty -LiteralPath $desktopKey -Name Wallpaper -Value $OutputPath
Set-ItemProperty -LiteralPath $desktopKey -Name WallpaperStyle -Value '10'
Set-ItemProperty -LiteralPath $desktopKey -Name TileWallpaper -Value '0'
if (-not ('Sgu.NativeMethods' -as [type])) {
Add-Type @'
using System;
using System.Runtime.InteropServices;
namespace Sgu {
public static class NativeMethods {
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool SystemParametersInfo(int action, int parameter, string value, int flags);
}
}
'@
}
if (-not [Sgu.NativeMethods]::SystemParametersInfo(20, 0, $OutputPath, 3)) {
throw "Windows could not apply the generated wallpaper. Win32 error: $([Runtime.InteropServices.Marshal]::GetLastWin32Error())"
}
}
Write-WelcomeLog -Message ("OK computer={0}; location={1}; ou={2}; output={3}" -f $ComputerName,[bool]$Location,[bool]$OrganizationalUnit,$OutputPath)
[pscustomobject]@{
DisplayName = $DisplayName
ComputerName = $ComputerName
Location = $Location
OrganizationalUnit = $OrganizationalUnit
LocationText = $locationText
OutputPath = $OutputPath
Applied = -not $SkipApply
}