Files
slp-modular-cms/scripts/Seed-Hero.ps1
T

142 lines
6.6 KiB
PowerShell

<#
.SYNOPSIS
Puts the hero of a site into a CMS through the admin API: uploads the photos, sets their focus points and saves the
hero. Test hosts only unless you deliberately point it somewhere else. Skips a CMS that already has a hero.
.DESCRIPTION
Logs in with an admin account (the password is asked interactively, as a secure string; it is never written to disk,
to the console or to a log). Then, from -SeedFile: uploads every slide photo from -ImagesDirectory (the same photo
again is the same image, so a second run does not duplicate anything), sets the focus point of each photo, and saves
the hero (texts, buttons, display and the slides with their alt texts) in one go.
.PARAMETER BaseUrl
Root of the host, e.g. https://test.andreaslop.nl (no trailing /api).
.PARAMETER SeedFile
JSON: title (new lines as \n), tagline, lead, display (single or slideshow), buttons [{label, target}],
slides [{file, alt, decorative, focus {x, y}}]. Default: hero-asf.json next to this script. hero-sls.json is the
text-only hero of SLP Software (no slides).
.PARAMETER ImagesDirectory
The folder that holds the files named in the slides (required when the seed has slides). For ASF these are the
existing exports hero-1.jpg to hero-8.jpg of the website repository (web/src/assets).
.PARAMETER Email
Admin e-mail address. Asked when omitted.
.PARAMETER Force
Replace an existing hero as well (the photos stay; the slide list is replaced).
.PARAMETER WhatIf
Shows what would be done without logging in or writing anything.
.EXAMPLE
./scripts/Seed-Hero.ps1 -BaseUrl https://test.andreaslop.nl -ImagesDirectory K:\Development\SlpSoftware\Projects\AndreaSlopFotografie\web\src\assets
.EXAMPLE
./scripts/Seed-Hero.ps1 -BaseUrl https://test.slpsoftware.nl -SeedFile ./scripts/hero-sls.json
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)] [string] $BaseUrl,
[string] $SeedFile,
[string] $ImagesDirectory,
[string] $Email,
[switch] $Force
)
$ErrorActionPreference = 'Stop'
# $PSScriptRoot is empty in a param default under Windows PowerShell 5.1, so it is read here.
$here = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
if (-not $SeedFile) { $SeedFile = Join-Path $here 'hero-asf.json' }
$BaseUrl = $BaseUrl.TrimEnd('/')
$api = "$BaseUrl/api/v1"
$seed = Get-Content -LiteralPath $SeedFile -Raw -Encoding UTF8 | ConvertFrom-Json
if ([string]::IsNullOrWhiteSpace($seed.title) -or $seed.title -like 'TODO*') { throw "The seed has no title (or it is still TODO)." }
$slides = @($seed.slides | Where-Object { $_ })
if ($slides.Count -gt 0) {
if (-not $ImagesDirectory) { throw 'The seed has slides: give -ImagesDirectory (the folder with the photos).' }
foreach ($s in $slides) {
$path = Join-Path $ImagesDirectory $s.file
if (-not (Test-Path -LiteralPath $path)) { throw "Photo not found: $path" }
if ([string]::IsNullOrWhiteSpace($s.alt) -and -not $s.decorative) { throw "Slide '$($s.file)' has no alt text and is not decorative." }
}
}
if ($WhatIfPreference) {
Write-Host "Would save the hero '$($seed.title -replace "`n", ' / ')' on $BaseUrl with $($slides.Count) slide(s):"
$slides | ForEach-Object { Write-Host " $($_.file) focus $($_.focus.x),$($_.focus.y) alt: $($_.alt)" }
return
}
if (-not $Email) { $Email = Read-Host 'Admin e-mail' }
$secure = Read-Host "Password for $Email" -AsSecureString
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
try {
$plain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
$body = @{ email = $Email; password = $plain } | ConvertTo-Json -Compress
$login = Invoke-RestMethod -Method Post -Uri "$api/auth/login" -ContentType 'application/json' -Body $body
}
finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
$plain = $null; $body = $null
}
$token = $login.accessToken
$headers = @{ Authorization = "Bearer $token" }
$current = Invoke-RestMethod -Method Get -Uri "$api/hero/all" -Headers $headers
if ($current.id -and -not $Force) {
Write-Host "skip a hero already exists on $BaseUrl (use -Force to replace it)"
return
}
Add-Type -AssemblyName System.Net.Http
function Send-Photo([string] $path) {
$client = [System.Net.Http.HttpClient]::new()
try {
$client.DefaultRequestHeaders.Authorization = [System.Net.Http.Headers.AuthenticationHeaderValue]::new('Bearer', $token)
$form = [System.Net.Http.MultipartFormDataContent]::new()
$bytes = [System.IO.File]::ReadAllBytes($path)
$content = [System.Net.Http.ByteArrayContent]::new($bytes)
$form.Add($content, 'file', [System.IO.Path]::GetFileName($path))
$response = $client.PostAsync("$api/hero/images", $form).GetAwaiter().GetResult()
$text = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
if (-not $response.IsSuccessStatusCode) { throw "Upload of '$path' failed ($([int]$response.StatusCode)): $text" }
return ($text | ConvertFrom-Json)
}
finally { $client.Dispose() }
}
$requestSlides = @()
foreach ($s in $slides) {
$image = Send-Photo (Join-Path $ImagesDirectory $s.file)
Write-Host "upload $($s.file) -> image $($image.id)"
if ($s.focus) {
$focus = @{ focus = @{ x = [double]$s.focus.x; y = [double]$s.focus.y; zoom = 1.0 }; wide = $null; tall = $null } | ConvertTo-Json -Depth 5
$null = Invoke-RestMethod -Method Put -Uri "$api/hero/images/$($image.id)/focus" -Headers $headers -ContentType 'application/json' -Body $focus
Write-Host "focus $($s.file) at $($s.focus.x), $($s.focus.y)"
}
$requestSlides += [ordered]@{ imageId = $image.id; alt = $(if ($s.decorative) { $null } else { $s.alt }); decorative = [bool]$s.decorative; isActive = $true }
}
$payload = [ordered]@{
title = $seed.title
tagline = $(if ($seed.tagline) { $seed.tagline } else { $null })
lead = $(if ($seed.lead) { $seed.lead } else { $null })
display = $(if ($seed.display) { $seed.display } else { 'single' })
buttons = @($seed.buttons | Where-Object { $_ } | ForEach-Object { [ordered]@{ label = $_.label; target = $_.target } })
isActive = $true
startsAt = $null
endsAt = $null
slides = $requestSlides
} | ConvertTo-Json -Depth 6
try {
$saved = Invoke-RestMethod -Method Put -Uri "$api/hero" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($payload))
Write-Host "saved hero $($saved.id) with $($saved.slides.Count) slide(s); live: $($saved.isLive)"
}
catch {
Write-Error "Saving the hero failed: $($_.Exception.Message) $($_.ErrorDetails.Message)"
}