171 lines
8.3 KiB
PowerShell
171 lines
8.3 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' }
|
|
# The password is asked interactively. For an unattended run on a LOCAL host only (a test or CI job), the environment
|
|
# variable SEED_HERO_PASSWORD is used instead when it is set; it is never printed.
|
|
if ($env:SEED_HERO_PASSWORD) {
|
|
$plain = $env:SEED_HERO_PASSWORD
|
|
try {
|
|
$body = @{ email = $Email; password = $plain } | ConvertTo-Json -Compress
|
|
$login = Invoke-RestMethod -Method Post -Uri "$api/auth/login" -ContentType 'application/json' -Body $body
|
|
}
|
|
finally { $plain = $null; $body = $null }
|
|
}
|
|
else {
|
|
$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() }
|
|
}
|
|
|
|
# First every photo is uploaded (the same photo again is the same image, so a second run duplicates nothing). The focus
|
|
# point of a photo is not a call of its own: a changed focus takes effect when the hero is saved, so it travels in the
|
|
# same request as the hero (imageFocus).
|
|
$requestSlides = @()
|
|
$imageFocus = @()
|
|
foreach ($s in $slides) {
|
|
$image = Send-Photo (Join-Path $ImagesDirectory $s.file)
|
|
Write-Host "upload $($s.file) -> image $($image.id)"
|
|
if ($s.focus -and -not ($imageFocus | Where-Object { $_.imageId -eq $image.id })) {
|
|
$imageFocus += [ordered]@{
|
|
imageId = $image.id
|
|
focus = [ordered]@{ x = [double]$s.focus.x; y = [double]$s.focus.y; zoom = 1.0 }
|
|
wide = $null
|
|
tall = $null
|
|
}
|
|
Write-Host "focus $($s.file) at $($s.focus.x), $($s.focus.y) (saved with the hero)"
|
|
}
|
|
$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 } })
|
|
slides = $requestSlides
|
|
imageFocus = $imageFocus
|
|
} | 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)"
|
|
# The variants of the photos are cut in the background (about half a minute per photo on a Raspberry Pi); a photo goes
|
|
# live as soon as its set is ready. Wait for them so the script ends when the site shows everything (at most 15 minutes).
|
|
$deadline = (Get-Date).AddMinutes(15)
|
|
do {
|
|
$state = Invoke-RestMethod -Method Get -Uri "$api/hero/all" -Headers $headers
|
|
$waiting = @($state.slides | Where-Object { $_.image.processing }).Count
|
|
if ($waiting -eq 0) { break }
|
|
Write-Host "wait $waiting photo(s) are still being prepared in the background"
|
|
Start-Sleep -Seconds 15
|
|
} while ((Get-Date) -lt $deadline)
|
|
if ($waiting -eq 0) { Write-Host "ready all photos are prepared" } else { Write-Warning "$waiting photo(s) are still being prepared; they appear on the site by themselves." }
|
|
}
|
|
catch {
|
|
Write-Error "Saving the hero failed: $($_.Exception.Message) $($_.ErrorDetails.Message)"
|
|
}
|