Private/Get-GhostPostImage.ps1

function Get-GhostPostImage {
    <#
    .SYNOPSIS
        Finds the image files that a post file refers to, and their address on the site when they are there.

    .DESCRIPTION
        A post file can point to an image file next to it instead of to an address: in its Markdown, and in the
        front matter as feature_image, og_image or twitter_image. Sync-GhostPost uploads those files. This
        function returns one object for every such reference.

        A reference is a file when it is a relative path. The path is relative to the folder of the post file.
        An address (https://...), a path from the root of the site (/content/...) and a path with a drive are
        left alone. A relative path to a file that does not exist is an error, so that a typo does not go
        unnoticed.

        The name to upload a file under is the name of the file followed by the start of the hash of its
        content, such as diagram-0f3a9c2b7d415e68.png. Ghost keeps that name in the address. That is how an
        image is recognized the next time: when the post on the site already has an address with that name, the
        file was uploaded before and has not changed, and the object carries that address in Url. Without it,
        the file has to be uploaded.

    .EXAMPLE
        Get-GhostPostImage -Source (Read-GhostPostFile -Path $path -Fields $fields) -Post $post

        Returns the references to image files in the post file, with the address of those the post already has.
    #>

    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        # The post file, as Read-GhostPostFile returned it.
        [Parameter(Mandatory)]
        [object] $Source,

        # The post on the site as Get-GhostPost returned it, when there is one.
        [AllowNull()]
        [object] $Post
    )

    # The fields of a post that hold an image: parameter name = name of the field in the Ghost API.
    $imageFields = @{
        FeatureImage = 'feature_image'
        OgImage      = 'og_image'
        TwitterImage = 'twitter_image'
    }

    $references = @(
        foreach ($name in $imageFields.Keys | Sort-Object) {
            if ($Source.Parameters.Keys -contains $name -and $Source.Parameters[$name] -is [string]) {
                [pscustomobject]@{ Field = $name; Destination = $Source.Parameters[$name]; Index = 0; Length = 0 }
            }
        }
        foreach ($image in Get-MarkdownImage -Markdown $Source.Markdown) {
            [pscustomobject]@{
                Field       = 'Markdown'
                Destination = $image.Destination
                Index       = $image.Index
                Length      = $image.Length
            }
        }
    )

    # Everything on the post that can hold the address of an image.
    $stored = @()
    if ($Post) {
        foreach ($name in @($imageFields.Values) + 'lexical') {
            $property = $Post.PSObject.Properties[$name]
            if ($property -and $property.Value) {
                $stored += [string] $property.Value
            }
        }
    }
    $stored = $stored -join "`n"

    $directory = [System.IO.Path]::GetDirectoryName($Source.Path)
    $names = @{}

    foreach ($reference in $references) {
        $destination = $reference.Destination

        # An address, a path from the root of the site or a path with a drive: not a file next to the post.
        $notRelative = '^(?:[a-z][a-z0-9+.-]*:|[/\\#?]|__GHOST_URL__)'
        if ([string]::IsNullOrWhiteSpace($destination) -or $destination -match $notRelative) {
            continue
        }

        # As it is written and, for a path such as my%20image.png, decoded.
        $file = $null
        foreach ($candidate in @($destination, [uri]::UnescapeDataString($destination))) {
            try {
                $fullPath = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($directory, $candidate))
            }
            catch {
                Write-Debug -Message "'$candidate' cannot be a path: $($_.Exception.Message)"
                continue
            }
            if ([System.IO.File]::Exists($fullPath)) {
                $file = $fullPath
                break
            }
        }
        if (-not $file) {
            $advice = 'The path of an image is relative to the folder of the file.'
            throw "The image '$destination' that $($Source.Path) refers to does not exist. $advice"
        }

        if (-not $names.ContainsKey($file)) {
            $algorithm = [System.Security.Cryptography.SHA256]::Create()
            try {
                $hash = $algorithm.ComputeHash([System.IO.File]::ReadAllBytes($file))
            }
            finally {
                $algorithm.Dispose()
            }
            $hash = ($hash[0..7] | ForEach-Object { $_.ToString('x2') }) -join ''

            # Only characters that Ghost keeps as they are, so that the name can be found in the address.
            $stem = [System.IO.Path]::GetFileNameWithoutExtension($file).ToLowerInvariant()
            $stem = ($stem -replace '[^a-z0-9]+', '-').Trim('-')
            if ($stem.Length -gt 60) {
                $stem = $stem.Substring(0, 60).Trim('-')
            }
            if (-not $stem) {
                $stem = 'image'
            }
            $names[$file] = '{0}-{1}{2}' -f $stem, $hash, [System.IO.Path]::GetExtension($file).ToLowerInvariant()
        }
        $name = $names[$file]

        # An address ends where the Markdown, the HTML or the JSON around it goes on. Ghost may add something
        # to the name, after the hash, when it stores the file.
        $key = [regex]::Escape([System.IO.Path]::GetFileNameWithoutExtension($name))
        $address = [regex]::Match($stored, ('[^\s"''()<>\\]*/{0}[^/\s"''()<>\\]*' -f $key), 'IgnoreCase')
        $url = $null
        if ($address.Success) {
            $url = $address.Value
        }

        [pscustomobject]@{
            Field       = $reference.Field
            Destination = $destination
            Index       = $reference.Index
            Length      = $reference.Length
            Path        = $file
            Name        = $name
            Url         = $url
        }
    }
}