Public/Import-GhostContent.ps1

function Import-GhostContent {
    <#
    .SYNOPSIS
        Adds the content of an export to the Ghost site.

    .DESCRIPTION
        Imports a JSON file that Export-GhostContent or Ghost Admin wrote: posts, pages, tags and the settings of
        the site. It is how a site on your own machine is given the content of a live site, to write and to work
        on a theme with the real thing in front of you.

        Ghost adds what is in the file to what the site has. A post that is there already is added again under
        another address, so importing the same file twice gives everything twice. With -Replace every post, page
        and tag of the site is deleted first, and the site ends up with what the file holds.

        Because this changes a whole site at once, and -Replace cannot be undone, it only works on a site on
        this machine, such as the one of Start-GhostLocalSite, and asks for confirmation. -Force lets it work on
        any site, and -Confirm:$false skips the question.

        An integration may not import: connect with a staff access token of an owner or an administrator.
        Start-GhostLocalSite returns the one of a local site in StaffAccessToken, and connects with it with
        -Connect -AsOwner.

        Ghost 6 imports in the background: it answers before the content is there. The command therefore waits
        until the site shows more posts and pages than before, for as long as -TimeoutSec allows, so that what
        follows works with the imported content. Ghost has no request that tells how an import went. It sends
        that to the owner of the site by email, and writes it in the log of the site. An older Ghost imports
        while the command waits and answers with the problems it had, which are returned in Problems.

    .EXAMPLE
        Import-GhostContent -Path ./live.json -Replace -Confirm:$false

        Replaces the posts, pages and tags of the local site that is connected with the content of the file.

    .EXAMPLE
        Import-GhostContent -Path ./posts.json

        Adds the content of the file to the local site, after confirmation.

    .LINK
        https://docs.ghost.org/admin-api
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    [OutputType('Ghost.ContentImport')]
    param(
        # The JSON file to import.
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string] $Path,

        # Delete every post, page and tag of the site before the import.
        [switch] $Replace,

        # How many seconds to wait for the posts and pages of the file to show on the site.
        [ValidateRange(1, 86400)]
        [int] $TimeoutSec = 300,

        # Import into a site that is not on this machine.
        [switch] $Force
    )

    begin {
        Test-GhostConnection
        $resources = Get-GhostAPIData -Endpoint $MyInvocation.MyCommand.Name
    }

    process {
        try {
            if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
                throw "The file '$Path' does not exist."
            }
            $file = (Resolve-Path -LiteralPath $Path).ProviderPath

            $uri = New-URIString -Endpoint $resources.URI
            $site = $uri -replace '/ghost/api/admin/.*$'
            if (-not ([uri] $site).IsLoopback -and -not $Force) {
                $what = if ($Replace) { 'replace' } else { 'add to' }
                $advice = 'Pass -Force when that is what you want.'
                throw "This would $what the content of $site, which is not a site on this machine. $advice"
            }

            $bytes = [System.IO.File]::ReadAllBytes($file)
            $form = @{
                FieldName       = 'importfile'
                FileName        = [System.IO.Path]::GetFileName($file)
                FileContent     = $bytes
                FileContentType = 'application/json'
            }
            $form = ConvertTo-MultipartContent @form

            # Whether the file has a post or a page, which is what shows that an import has arrived. Looked up
            # in the text: Windows PowerShell cannot read a JSON file of more than a few megabytes.
            $hasPosts = [System.Text.Encoding]::UTF8.GetString($bytes) -match '"posts"\s*:\s*\[\s*\{'

            $action = $resources.Description
            if ($Replace) {
                $action = 'Delete every post, page and tag, and import the content of a file'
            }

            if ($PSCmdlet.ShouldProcess($site, $action)) {
                try {
                    if ($Replace) {
                        # One by one: Ghost lets nobody but a person who is signed in delete everything at once.
                        foreach ($kind in 'posts', 'pages', 'tags') {
                            $browse = '{0}?fields=id' -f (New-URIString -Endpoint "/$kind/")
                            $ids = @(
                                Submit-Request -Uri $browse -Method 'Get' -Paginate |
                                    ForEach-Object { $_.$kind } |
                                    ForEach-Object { $_.id }
                            )
                            foreach ($id in $ids) {
                                $item = New-URIString -Endpoint "/$kind/{id}/" -Parameters @{ id = $id }
                                $null = Submit-Request -Uri $item -Method 'Delete' -Success 204
                            }
                        }
                    }

                    $before = if ($hasPosts) { Get-GhostContentCount } else { 0 }

                    $request = @{
                        Uri         = $uri
                        Method      = $resources.Method
                        Content     = $form.Content
                        ContentType = $form.ContentType
                        Success     = $resources.Success
                    }
                    $result = Submit-Request @request

                    # Ghost imports everything in one transaction, so the first change is the whole import.
                    if ($hasPosts) {
                        $deadline = [datetime]::UtcNow.AddSeconds($TimeoutSec)
                        while ((Get-GhostContentCount) -eq $before) {
                            if ([datetime]::UtcNow -ge $deadline) {
                                $waited = "$site does not show the posts of the file after $TimeoutSec seconds."
                                $cause = 'Ghost imports in the background and tells how it went only by email'
                                throw "$waited $cause to the owner of the site, and in the log of the site."
                            }
                            Start-Sleep -Milliseconds 500
                        }
                    }
                }
                catch {
                    if ($_.FullyQualifiedErrorId -like 'NoPermissionError*') {
                        $advice = 'Connect with a staff access token of an owner or an administrator instead.'
                        throw "An integration may not import content. $advice"
                    }
                    throw
                }

                # A Ghost that imports while the request waits answers with what it could not import as it was.
                $problems = @()
                $reported = if ($result) { $result.PSObject.Properties['problems'] }
                if ($reported -and $reported.Value) {
                    $problems = @($reported.Value)
                }

                [pscustomobject]@{
                    PSTypeName = 'Ghost.ContentImport'
                    Site       = $site
                    Path       = $file
                    Replaced   = [bool] $Replace
                    Problems   = $problems
                }
            }
        }
        catch {
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}