Celerium.FanartTV.psm1

#Region './Private/ApiCalls/ConvertTo-FanartTVQueryString.ps1' -1

function ConvertTo-FanartTVQueryString {
<#
    .SYNOPSIS
        Converts uri filter parameters into a query string

    .DESCRIPTION
        The ConvertTo-FanartTVQueryString cmdlet converts & formats a hashtable
        of parameters into a url encoded query string that is later appended to
        the resource uri of an API call

        This is an internal helper function that is used by Invoke-FanartTVRequest

        Conversion rules:
            - $null values are skipped
            - Arrays are sent as comma separated lists
            - Dates are converted to UTC and formatted as yyyy-MM-ddTHH:mm:ss.fffZ
            - Booleans are sent as lowercase true\false
            - Hashtables & objects are sent as compressed JSON

    .PARAMETER UriFilter
        Hashtable of query string parameters

    .PARAMETER MultiValueParameter
        Defines the names of the UriFilter keys that must be sent as repeated
        key\value pairs instead of a comma separated list

    .EXAMPLE
        ConvertTo-FanartTVQueryString -UriFilter @{ date = 1771657200; ids = 1,2,3 }

        Returns 'date=1771657200&ids=1,2,3'

    .EXAMPLE
        ConvertTo-FanartTVQueryString -UriFilter @{ states = 'active','expired' } -MultiValueParameter 'states'

        Returns 'states=active&states=expired'

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/ConvertTo-FanartTVQueryString.html
#>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
        [hashtable]$UriFilter,

        [Parameter(Mandatory = $false)]
        [string[]]$MultiValueParameter
    )

    begin {

        function ConvertTo-QueryValue {
            param ($Value)

            if ($Value -is [bool]) { return $Value.ToString().ToLowerInvariant() }

            if ($Value -is [datetime]) {
                return $Value.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ', [System.Globalization.CultureInfo]::InvariantCulture)
            }

            if ($Value -is [System.Collections.IDictionary] -or $Value -is [System.Management.Automation.PSCustomObject]) {
                return (ConvertTo-Json -InputObject $Value -Compress -Depth 10)
            }

            return [System.Convert]::ToString($Value, [System.Globalization.CultureInfo]::InvariantCulture)
        }

    }

    process {

        if (-not $UriFilter -or $UriFilter.Count -eq 0) { return '' }

        $Pairs = foreach ($Key in ($UriFilter.Keys | Sort-Object)) {

            $Value = $UriFilter[$Key]
            if ($null -eq $Value) { continue }

            $EncodedKey = [System.Uri]::EscapeDataString($Key)

            if ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [string] -and $Value -isnot [System.Collections.IDictionary]) {

                $Items = @($Value | Where-Object { $null -ne $_ } | ForEach-Object { [System.Uri]::EscapeDataString( (ConvertTo-QueryValue -Value $_) ) })
                if ($Items.Count -eq 0) { continue }

                if ($MultiValueParameter -contains $Key) { foreach ($Item in $Items) { "$EncodedKey=$Item" } }
                else { "$EncodedKey=$($Items -join ',')" }

            }
            else {
                "$EncodedKey=$([System.Uri]::EscapeDataString( (ConvertTo-QueryValue -Value $Value) ))"
            }

        }

        return ($Pairs -join '&')

    }

    end {}

}
#EndRegion './Private/ApiCalls/ConvertTo-FanartTVQueryString.ps1' 106
#Region './Private/ApiCalls/Invoke-FanartTVRequest.ps1' -1

function Invoke-FanartTVRequest {
<#
    .SYNOPSIS
        Makes an API request to the Fanart.tv API

    .DESCRIPTION
        The Invoke-FanartTVRequest cmdlet invokes an API request to the Fanart.tv API

        This is an internal function that is used by all public functions

        The Fanart.tv API is read-only, only GET requests are supported. Requests that fail
        because of rate limiting or a temporary server error are retried

        The project key is sent in the api-key header & the personal key is sent in the
        client-key header, the keys are never added to the url

    .PARAMETER Method
        Defines the type of API method to use

        Allowed values:
        'GET'

    .PARAMETER ResourceURI
        Defines the resource uri (url) path to use when creating the API call

        The path is appended to the base URI defined by Add-FanartTVBaseURI

    .PARAMETER UriFilter
        Hashtable of query string parameters to append to the resource uri

        Arrays are sent as comma separated lists, dates are converted to UTC,
        and booleans are sent as lowercase true\false values

    .PARAMETER Headers
        Hashtable of additional request headers

        The api-key & client-key headers cannot be overwritten

    .EXAMPLE
        Invoke-FanartTVRequest -Method GET -ResourceURI '/movies/550'

        Invoke a rest method against the defined resource

    .EXAMPLE
        Invoke-FanartTVRequest -ResourceURI '/movies/latest' -UriFilter @{ date = 1771657200 }

        Invoke a rest method against the defined resource using the provided query parameters

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Invoke-FanartTVRequest.html
#>


    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateSet('GET')]
        [string]$Method = 'GET',

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ResourceURI,

        [Parameter()]
        [hashtable]$UriFilter,

        [Parameter()]
        [hashtable]$Headers
    )

    begin {

        $FunctionName   = $MyInvocation.InvocationName
        $ParameterName  = $FunctionName + '_Parameters' -replace '-','_'

        $BaseUri = Get-FanartTVBaseURI -WarningAction SilentlyContinue
        $ApiKeys = Get-FanartTVAPIKey -AsPlainText -WarningAction SilentlyContinue
        if (-not $BaseUri -or -not $ApiKeys -or (-not $ApiKeys.ProjectKey -and -not $ApiKeys.PersonalKey)) {
            throw "No authentication method or base uri found, please run Add-FanartTVAPIKey & Add-FanartTVBaseURI to continue"
        }

        # Windows PowerShell does not always negotiate TLS 1.2 by default
        if ($PSEdition -eq 'Desktop') {
            [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
        }

        $RequestHeaders = @{}
        foreach ($Key in $Headers.Keys) {
            if ($Key -notin 'api-key', 'client-key') { $RequestHeaders[$Key] = $Headers[$Key] }
        }
        $RequestHeaders['Accept'] = 'application/json'

        # The project key is sent as the api-key & the personal key is sent as the client-key
        if ($ApiKeys.ProjectKey)    { $RequestHeaders['api-key']    = $ApiKeys.ProjectKey }
        if ($ApiKeys.PersonalKey)   { $RequestHeaders['client-key'] = $ApiKeys.PersonalKey }
        $ApiKeys = $null

        $ResourceURI = '/' + $ResourceURI.TrimStart('/')

    }

    process {

        Write-Verbose "[ $FunctionName ] - Running the [ $($PSCmdlet.ParameterSetName) ] parameterSet"

        $QueryString    = ConvertTo-FanartTVQueryString -UriFilter $UriFilter
        $TargetUri      = $BaseUri + $ResourceURI
        if ($QueryString) { $TargetUri = $TargetUri + '?' + $QueryString }

        $InvokeParams = @{
            Method          = $Method
            Uri             = $TargetUri
            Headers         = $RequestHeaders
            UserAgent       = $FanartTVModuleUserAgent
            UseBasicParsing = $true
            ErrorAction     = 'Stop'
        }

        # Keeps the API keys out of the debug variable
        $DebugParams = @{} + $InvokeParams
        $DebugParams.Headers = @{} + $RequestHeaders
        foreach ($KeyHeader in 'api-key', 'client-key') {
            if ($DebugParams.Headers.ContainsKey($KeyHeader)) { $DebugParams.Headers[$KeyHeader] = '*******' }
        }
        Set-Variable -Name $ParameterName -Value $DebugParams -Scope Global -Force -Confirm:$false

        $RetryCount = 0
        $RetryMax   = 3
        $Response   = $null

        while ($null -eq $Response) {

            try {
                $WebResponse    = Invoke-WebRequest @InvokeParams
                $Bytes          = $WebResponse.RawContentStream.ToArray()
                $ContentType    = "$($WebResponse.Headers['Content-Type'])"

                # Windows PowerShell decodes responses without a charset as ISO-8859-1
                $Content = [System.Text.Encoding]::UTF8.GetString($Bytes)

                if ($ContentType -match 'json' -or $Content.TrimStart() -match '^[\{\[]') {
                    if ($Content.Trim()) { $Response = $Content | ConvertFrom-Json }

                    # An array with zero or one item is not returned as an array when it is converted from JSON
                    if ($Content.TrimStart().StartsWith('[')) { $Response = @($Response | Where-Object { $null -ne $_ }) }
                }
                else { $Response = $Content }

                if ($null -eq $Response -or ($Response -is [string] -and -not $Response.Trim())) { $Response = [PSCustomObject]@{} }
            }
            catch {

                $ErrorRecord    = $_
                $StatusCode     = $null
                $RetryAfter     = $null

                if ($ErrorRecord.Exception.Response) {
                    $StatusCode = [int]$ErrorRecord.Exception.Response.StatusCode
                    try {
                        $ResponseHeaders = $ErrorRecord.Exception.Response.Headers
                        if ($ResponseHeaders.GetType().Name -eq 'HttpResponseHeaders') {
                            if ($ResponseHeaders.RetryAfter.Delta) { $RetryAfter = [int]$ResponseHeaders.RetryAfter.Delta.TotalSeconds }
                        }
                        elseif ($ResponseHeaders['Retry-After']) { $RetryAfter = [int]$ResponseHeaders['Retry-After'] }
                    }
                    catch { Write-Verbose "[ $FunctionName ] - Unable to read the Retry-After header" }
                }

                # Prefer the error detail returned by the API, such as {"error": "Movie not found"}
                $Detail = $ErrorRecord.Exception.Message
                if ($ErrorRecord.ErrorDetails.Message) {
                    try {
                        $ApiError = $ErrorRecord.ErrorDetails.Message | ConvertFrom-Json -ErrorAction Stop
                        if ($ApiError.error)                    { $Detail = "$($ApiError.error)" }
                        elseif ($ApiError.'error message')      { $Detail = "$($ApiError.'error message')" }
                        elseif ($ApiError.message)              { $Detail = "$($ApiError.message)" }
                        else                                    { $Detail = $ErrorRecord.ErrorDetails.Message }
                    }
                    catch { $Detail = $ErrorRecord.ErrorDetails.Message }
                }

                $Retryable = ( $null -eq $StatusCode ) -or ( $StatusCode -in 429, 502, 503, 504 )

                if (-not $Retryable) {
                    Write-Warning 'The [ Invoke_FanartTVRequest_Parameters & CmdletName_Parameters ] variables can provide extra details'
                    switch ($StatusCode) {
                        401     { throw "Invoke-FanartTVRequest : [ 401 ] Unauthorized, verify the API keys - [ $ResourceURI ]" }
                        403     { throw "Invoke-FanartTVRequest : [ 403 ] Forbidden, the API keys are not allowed to access this resource - [ $ResourceURI ]" }
                        404     { throw "Invoke-FanartTVRequest : [ 404 ] $Detail - [ $ResourceURI ]" }
                        default { throw "Invoke-FanartTVRequest : [ $StatusCode ] $Detail - [ $ResourceURI ]" }
                    }
                }

                $RetryCount++
                if ($RetryCount -ge $RetryMax) {
                    throw "Invoke-FanartTVRequest : Maximum retry attempts reached [ $RetryCount/$RetryMax ] - [ $StatusCode ] $Detail - [ $ResourceURI ]"
                }

                $WaitTime = [Math]::Min( [Math]::Pow(2, $RetryCount) + (Get-Random -Minimum 0 -Maximum 5), 60 )
                if ($RetryAfter) { $WaitTime = [Math]::Min($RetryAfter, 120) }

                Write-Warning "Invoke-FanartTVRequest : [ $StatusCode ] Retrying request [ $ResourceURI ] in [ $WaitTime ] seconds - Attempt [ $RetryCount/$RetryMax ]"
                Start-Sleep -Seconds $WaitTime

            }

        }

        return $Response

    }

    end {}

}
#EndRegion './Private/ApiCalls/Invoke-FanartTVRequest.ps1' 218
#Region './Private/ApiKeys/Add-FanartTVAPIKey.ps1' -1

function Add-FanartTVAPIKey {
<#
    .SYNOPSIS
        Sets the API keys used to authenticate all API calls

    .DESCRIPTION
        The Add-FanartTVAPIKey cmdlet sets the personal and\or project API keys which
        are used to authenticate all API calls made to the Fanart.tv API

        The keys are stored in memory as a SecureString. At least one key is required,
        a key that is not defined is removed so the keys of an earlier call are never mixed

        Fanart.tv API keys are created at https://fanart.tv/get-an-api-key/

            Project key - Sent as the api-key, identifies the project or application
            Personal key - Sent as the client-key, identifies the user

        When both keys are provided, the personal key determines the access tier
        (2-day delay instead of 7-day)

    .PARAMETER PersonalKey
        Defines your personal API key (client key) as plain text

        If no key is defined the cmdlet will prompt you to enter the personal key
        which will be stored as a SecureString

    .PARAMETER ProjectKey
        Defines your project API key (api key) as plain text

    .PARAMETER PersonalKeySecureString
        Input a SecureString object containing the personal API key

    .PARAMETER ProjectKeySecureString
        Input a SecureString object containing the project API key

    .EXAMPLE
        Add-FanartTVAPIKey

        Prompts to enter in the personal API key which will be
        stored as a SecureString

    .EXAMPLE
        Add-FanartTVAPIKey -ProjectKey 8765309

        Adds the project key which will be stored as a SecureString

    .EXAMPLE
        Add-FanartTVAPIKey -PersonalKey 123456 -ProjectKey 8765309

        Adds both project & personal keys which will be
        stored as a SecureString

    .EXAMPLE
        Add-FanartTVAPIKey -ProjectKeySecureString (Read-Host -AsSecureString)

        Stores an existing SecureString object as the project key

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Add-FanartTVAPIKey.html
#>


    [CmdletBinding(DefaultParameterSetName = 'AsPlainText')]
    [Alias('Set-FanartTVAPIKey')]
    Param (
        [Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'AsPlainText')]
        [Alias('ClientKey')]
        [AllowEmptyString()]
        [string]$PersonalKey,

        [Parameter(Mandatory = $false, Position = 1, ValueFromPipeline = $true, ParameterSetName = 'AsPlainText')]
        [Alias('ApiKey')]
        [AllowEmptyString()]
        [string]$ProjectKey,

        [Parameter(Mandatory = $false, ParameterSetName = 'AsSecureString')]
        [securestring]$PersonalKeySecureString,

        [Parameter(Mandatory = $false, ParameterSetName = 'AsSecureString')]
        [securestring]$ProjectKeySecureString
    )

    begin {}

    process {

        switch ($PSCmdlet.ParameterSetName) {

            'AsPlainText'       {
                $PersonalSecureString   = if ($PersonalKey) { ConvertTo-SecureString $PersonalKey -AsPlainText -Force } else { $null }
                $ProjectSecureString    = if ($ProjectKey)  { ConvertTo-SecureString $ProjectKey -AsPlainText -Force }  else { $null }

                if (-not $PersonalSecureString -and -not $ProjectSecureString) {
                    $PersonalSecureString = Read-Host -Prompt 'Please enter your personal API key' -AsSecureString
                }
            }

            'AsSecureString'    {
                $PersonalSecureString   = $PersonalKeySecureString
                $ProjectSecureString    = $ProjectKeySecureString
            }

        }

        if ( (-not $PersonalSecureString -or $PersonalSecureString.Length -eq 0) -and (-not $ProjectSecureString -or $ProjectSecureString.Length -eq 0) ) {
            throw 'No API key was provided, define a personal and\or project key'
        }

        foreach ($Name in 'FanartTVModulePersonalApiKey', 'FanartTVModuleProjectApiKey') {
            Remove-Variable -Name $Name -Scope Global -Force -ErrorAction SilentlyContinue
        }

        if ($PersonalSecureString -and $PersonalSecureString.Length -gt 0) {
            Set-Variable -Name 'FanartTVModulePersonalApiKey' -Value $PersonalSecureString -Option ReadOnly -Scope Global -Force
        }

        if ($ProjectSecureString -and $ProjectSecureString.Length -gt 0) {
            Set-Variable -Name 'FanartTVModuleProjectApiKey' -Value $ProjectSecureString -Option ReadOnly -Scope Global -Force
        }

    }

    end {}

}
#EndRegion './Private/ApiKeys/Add-FanartTVAPIKey.ps1' 128
#Region './Private/ApiKeys/Get-FanartTVAPIKey.ps1' -1

function Get-FanartTVAPIKey {
<#
    .SYNOPSIS
        Gets the Fanart.tv API keys

    .DESCRIPTION
        The Get-FanartTVAPIKey cmdlet gets the Fanart.tv personal & project API keys
        from the global variables and returns them as an object

        By default the keys are returned as a SecureString, a key that is not set is $null

    .PARAMETER AsPlainText
        Decrypt and return the API keys in plain text

    .EXAMPLE
        Get-FanartTVAPIKey

        Gets the API keys and returns them as an object with the
        keys as a SecureString

    .EXAMPLE
        Get-FanartTVAPIKey -AsPlainText

        Gets and decrypts the API keys from the global variables and
        returns them as an object with the keys as plain text

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Get-FanartTVAPIKey.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Index')]
    Param (
        [Parameter(Mandatory = $false)]
        [switch]$AsPlainText
    )

    begin {}

    process {

        try {

            if ($FanartTVModulePersonalApiKey -or $FanartTVModuleProjectApiKey) {

                if ($AsPlainText) {

                    if ($FanartTVModulePersonalApiKey) {
                        $PersonalBSTR       = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($FanartTVModulePersonalApiKey)
                        $DecryptedPersonal  = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($PersonalBSTR)
                    }

                    if ($FanartTVModuleProjectApiKey) {
                        $ProjectBSTR        = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($FanartTVModuleProjectApiKey)
                        $DecryptedProject   = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ProjectBSTR)
                    }

                    [PSCustomObject]@{
                        PersonalKey = $DecryptedPersonal
                        ProjectKey  = $DecryptedProject
                    }

                }
                else {
                    [PSCustomObject]@{
                        PersonalKey = $FanartTVModulePersonalApiKey
                        ProjectKey  = $FanartTVModuleProjectApiKey
                    }
                }

            }
            else { Write-Warning "The Fanart.tv API keys are not set. Run Add-FanartTVAPIKey to set the API keys" }

        }
        catch {
            Write-Error $_
        }
        finally {
            if ($PersonalBSTR)  { [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($PersonalBSTR) }
            if ($ProjectBSTR)   { [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ProjectBSTR) }
        }

    }

    end {}

}
#EndRegion './Private/ApiKeys/Get-FanartTVAPIKey.ps1' 90
#Region './Private/ApiKeys/Remove-FanartTVAPIKey.ps1' -1

function Remove-FanartTVAPIKey {
<#
    .SYNOPSIS
        Removes the Fanart.tv API keys

    .DESCRIPTION
        The Remove-FanartTVAPIKey cmdlet removes the Fanart.tv personal & project
        API keys from the global variables

    .EXAMPLE
        Remove-FanartTVAPIKey

        Removes the Fanart.tv API key global variables

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Remove-FanartTVAPIKey.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Destroy', SupportsShouldProcess, ConfirmImpact = 'None')]
    Param ()

    begin {}

    process {

        if ([bool]$FanartTVModulePersonalApiKey -or [bool]$FanartTVModuleProjectApiKey) {
            if ($PSCmdlet.ShouldProcess('FanartTVModulePersonalApiKey, FanartTVModuleProjectApiKey')) {
                Remove-Variable -Name 'FanartTVModulePersonalApiKey' -Scope Global -Force -ErrorAction SilentlyContinue
                Remove-Variable -Name 'FanartTVModuleProjectApiKey' -Scope Global -Force -ErrorAction SilentlyContinue
            }
        }
        else { Write-Warning "The Fanart.tv API keys are not set. Nothing to remove" }

    }

    end {}

}
#EndRegion './Private/ApiKeys/Remove-FanartTVAPIKey.ps1' 42
#Region './Private/ApiKeys/Test-FanartTVAPIKey.ps1' -1

function Test-FanartTVAPIKey {
<#
    .SYNOPSIS
        Test the Fanart.tv API keys

    .DESCRIPTION
        The Test-FanartTVAPIKey cmdlet tests the base URI & API keys that
        are defined by the Add-FanartTVBaseURI & Add-FanartTVAPIKey cmdlets

        Helpful when needing to validate general functionality or when using
        RMM deployment tools

        The test makes a single GET request for the images of one movie
        (TMDB ID 550, Fight Club)

        A 200 status code means the base URI & API keys are valid. A 401 status code means
        the API keys were not accepted

    .PARAMETER BaseURI
        Define the base URI for the Fanart.tv API connection
        using Fanart.tv's URI or a custom URI

        By default the value used is the one defined by the
        Add-FanartTVBaseURI function

    .EXAMPLE
        Test-FanartTVAPIKey

        Tests the base URI & API keys that are defined by the
        Add-FanartTVBaseURI & Add-FanartTVAPIKey cmdlets

    .EXAMPLE
        Test-FanartTVAPIKey -BaseURI https://myapi.gateway.celerium.org/v3.2

        Tests the defined base URI & the API keys that were defined by
        the Add-FanartTVAPIKey cmdlet

        The full test uri in this example is:
            https://myapi.gateway.celerium.org/v3.2/movies/550

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Test-FanartTVAPIKey.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Test')]
    Param (
        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$BaseURI = $FanartTVModuleBaseURI
    )

    begin { $ResourceUri = '/movies/550' }

    process {

        $ApiKeys = Get-FanartTVAPIKey -AsPlainText -WarningAction SilentlyContinue

        if ([bool]$BaseURI -eq $false -or [bool]$ApiKeys -eq $false) {
            Write-Error "The BaseURI and or API keys are not set. Please run the Add-FanartTVAPIKey & Add-FanartTVBaseURI cmdlets before running this function"
            return
        }

        $TargetUri = $BaseURI.TrimEnd('/') + $ResourceUri
        Write-Verbose "Testing API keys against [ $TargetUri ]"

        # Windows PowerShell does not always negotiate TLS 1.2 by default
        if ($PSEdition -eq 'Desktop') {
            [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
        }

        try {

            $Headers = @{ 'Accept' = 'application/json' }
            if ($ApiKeys.ProjectKey)    { $Headers['api-key']       = $ApiKeys.ProjectKey }
            if ($ApiKeys.PersonalKey)   { $Headers['client-key']    = $ApiKeys.PersonalKey }

            $Parameters = @{
                'Method'            = 'GET'
                'Uri'               = $TargetUri
                'Headers'           = $Headers
                'UserAgent'         = $FanartTVModuleUserAgent
                'UseBasicParsing'   = $true
            }

            $RestOutput = Invoke-WebRequest @Parameters -ErrorAction Stop

        }
        catch {

            # Windows PowerShell exposes StatusDescription, PowerShell Core exposes ReasonPhrase
            $Description = if ($PSEdition -eq 'Desktop') { $_.Exception.Response.StatusDescription } else { $_.Exception.Response.ReasonPhrase }

            [PSCustomObject]@{
                Method              = 'GET'
                StatusCode          = [int]$_.Exception.Response.StatusCode
                StatusDescription   = $Description
                Message             = $_.Exception.Message
                URI                 = $TargetUri
            }

        }
        finally {
            $Headers    = $null
            $ApiKeys    = $null
        }

        if ($RestOutput) {

            [PSCustomObject]@{
                StatusCode          = [int]$RestOutput.StatusCode
                StatusDescription   = $RestOutput.StatusDescription
                URI                 = $TargetUri
            }

        }

    }

    end {}

}
#EndRegion './Private/ApiKeys/Test-FanartTVAPIKey.ps1' 125
#Region './Private/BaseUri/Add-FanartTVBaseURI.ps1' -1

function Add-FanartTVBaseURI {
<#
    .SYNOPSIS
        Sets the base URI for the Fanart.tv API connection

    .DESCRIPTION
        The Add-FanartTVBaseURI cmdlet sets the base URI which is used
        to construct the full URI for all API calls

        The API version is appended to the base URI. When the base URI already ends
        with an API version such as /v3.2, the version is not appended again

    .PARAMETER BaseURI
        Sets the base URI for the Fanart.tv API connection. Helpful
        if using a custom API gateway

        The URL must use https

        The default value is 'https://webservice.fanart.tv'

    .PARAMETER Version
        Sets the API version to use

        Note: Module was built and tested on v3.2 only

        The default value is 'v3.2'

    .EXAMPLE
        Add-FanartTVBaseURI

        The base URI will use https://webservice.fanart.tv/v3.2

    .EXAMPLE
        Add-FanartTVBaseURI -BaseURI 'https://gateway.celerium.org'

        The base URI will use https://gateway.celerium.org/v3.2

    .EXAMPLE
        'https://webservice.fanart.tv/v3.2' | Add-FanartTVBaseURI

        The base URI is passed in from the pipeline and will use https://webservice.fanart.tv/v3.2

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Add-FanartTVBaseURI.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Set')]
    [Alias('Set-FanartTVBaseURI')]
    Param (
        [Parameter(Mandatory = $false, ValueFromPipeline = $true, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$BaseURI = 'https://webservice.fanart.tv',

        [Parameter(Mandatory = $false, Position = 1)]
        [AllowNull()]
        [AllowEmptyString()]
        [string]$Version = 'v3.2'
    )

    begin {}

    process {

        $ParsedUri = $null
        if (-not [System.Uri]::TryCreate($BaseURI.Trim(), [System.UriKind]::Absolute, [ref]$ParsedUri) -or $ParsedUri.Scheme -ne 'https') {
            throw "The base URI [ $BaseURI ] is not valid, it must be an absolute https url such as https://webservice.fanart.tv"
        }

        # The query string & fragment are not part of the base URI
        $NormalizedUri = ($ParsedUri.GetLeftPart([System.UriPartial]::Path)).TrimEnd('/')

        $Version = "$Version".Trim().Trim('/')

        if ($Version -and $NormalizedUri -notmatch '/v\d+(\.\d+)*$') {
            $NormalizedUri = "$NormalizedUri/$Version"
        }

        Write-Verbose "Using URI: [ $NormalizedUri ]"
        Set-Variable -Name 'FanartTVModuleBaseURI' -Value $NormalizedUri -Option ReadOnly -Scope Global -Force

    }

    end {}

}
#EndRegion './Private/BaseUri/Add-FanartTVBaseURI.ps1' 89
#Region './Private/BaseUri/Get-FanartTVBaseURI.ps1' -1

function Get-FanartTVBaseURI {
<#
    .SYNOPSIS
        Shows the FanartTV base URI

    .DESCRIPTION
        The Get-FanartTVBaseURI cmdlet shows the FanartTV
        base URI from the global variable

    .EXAMPLE
        Get-FanartTVBaseURI

        Shows the FanartTV base URI value defined in the global variable

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Get-FanartTVBaseURI.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Index')]
    Param ()

    begin {}

    process {

        switch ([bool]$FanartTVModuleBaseURI) {
            $true   { $FanartTVModuleBaseURI }
            $false  { Write-Warning "The FanartTV base URI is not set. Run Add-FanartTVBaseURI to set the base URI." }
        }

    }

    end {}

}
#EndRegion './Private/BaseUri/Get-FanartTVBaseURI.ps1' 39
#Region './Private/BaseUri/Remove-FanartTVBaseURI.ps1' -1

function Remove-FanartTVBaseURI {
<#
    .SYNOPSIS
        Removes the FanartTV base URI global variable

    .DESCRIPTION
        The Remove-FanartTVBaseURI cmdlet removes the FanartTV
        base URI from the global variable

    .EXAMPLE
        Remove-FanartTVBaseURI

        Removes the FanartTV base URI value from the global variable

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Remove-FanartTVBaseURI.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Destroy', SupportsShouldProcess, ConfirmImpact = 'None')]
    Param ()

    begin {}

    process {

        switch ([bool]$FanartTVModuleBaseURI) {

            $true   {
                if ($PSCmdlet.ShouldProcess('FanartTVModuleBaseURI')) {
                    Remove-Variable -Name "FanartTVModuleBaseURI" -Scope Global -Force
                }
            }
            $false  { Write-Warning "The FanartTV base URI variable is not set. Nothing to remove" }

        }

    }

    end {}

}
#EndRegion './Private/BaseUri/Remove-FanartTVBaseURI.ps1' 45
#Region './Private/ModuleSettings/Export-FanartTVModuleSettings.ps1' -1

function Export-FanartTVModuleSettings {
<#
    .SYNOPSIS
        Exports the Fanart.tv BaseURI, API, & JSON configuration information to file

    .DESCRIPTION
        The Export-FanartTVModuleSettings cmdlet exports the Fanart.tv BaseURI, API, & JSON configuration information to file

        Making use of PowerShell's System.Security.SecureString type, exporting module settings encrypts your API keys in a format
        that can only be unencrypted with the your Windows account as this encryption is tied to your user principal
        This means that you cannot copy your configuration file to another computer or user account and expect it to work

        On Linux & macOS the SecureString is NOT encrypted, it is recommended to use the FANARTTV_BASE_URI,
        FANARTTV_PROJECT_KEY, & FANARTTV_PERSONAL_KEY environment variables or a secret store instead

    .PARAMETER FanartTVConfigPath
        Define the location to store the Fanart.tv configuration file

        By default the configuration file is stored in the following location:
            $env:USERPROFILE\Celerium.FanartTV

    .PARAMETER FanartTVConfigFile
        Define the name of the Fanart.tv configuration file

        By default the configuration file is named:
            config.psd1

    .EXAMPLE
        Export-FanartTVModuleSettings

        Validates that the BaseURI, API keys, and JSON depth are set then exports their values
        to the current user's Fanart.tv configuration file located at:
            $env:USERPROFILE\Celerium.FanartTV\config.psd1

    .EXAMPLE
        Export-FanartTVModuleSettings -FanartTVConfigPath C:\Celerium.FanartTV -FanartTVConfigFile MyConfig.psd1

        Validates that the BaseURI, API keys, and JSON depth are set then exports their values
        to the current user's Fanart.tv configuration file located at:
            C:\Celerium.FanartTV\MyConfig.psd1

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Export-FanartTVModuleSettings.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Set')]
    Param (
        [Parameter()]
        [Alias('FanartTVConfPath')]
        [string]$FanartTVConfigPath = $(Join-Path -Path $home -ChildPath $(if ($IsWindows -or $PSEdition -eq 'Desktop') {"Celerium.FanartTV"}else{".Celerium.FanartTV"}) ),

        [Parameter()]
        [Alias('FanartTVConfFile')]
        [string]$FanartTVConfigFile = 'config.psd1'
    )

    begin {}

    process {

        if ($IsWindows -or $PSEdition -eq 'Desktop') {
            Write-Verbose "Secrets are stored using the Windows Data Protection API (DPAPI)"
        }
        else {
            Write-Warning "DPAPI provides user context encryption in Windows but NOT in other operating systems like Linux or UNIX. It is recommended to use the FANARTTV_BASE_URI, FANARTTV_PROJECT_KEY, & FANARTTV_PERSONAL_KEY environment variables or a more secure & cross-platform storage method"
        }

        $FanartTVConfig = Join-Path -Path $FanartTVConfigPath -ChildPath $FanartTVConfigFile

        $MissingVariables = foreach ($GlobalVariable in 'FanartTVModuleBaseURI', 'FanartTVModuleJSONConversionDepth') {
            if (-not (Get-Variable -Name $GlobalVariable -ErrorAction SilentlyContinue)) { $GlobalVariable }
        }
        if (-not $FanartTVModulePersonalApiKey -and -not $FanartTVModuleProjectApiKey) {
            $MissingVariables = @($MissingVariables) + 'FanartTVModulePersonalApiKey or FanartTVModuleProjectApiKey'
        }

        if ($MissingVariables) {
            throw "Failed to export Fanart.tv Module settings, the required module variables [ $($MissingVariables -join ', ') ] are not set"
        }

        $SecurePersonalString   = if ($FanartTVModulePersonalApiKey) { $FanartTVModulePersonalApiKey | ConvertFrom-SecureString } else { '' }
        $SecureProjectString    = if ($FanartTVModuleProjectApiKey)  { $FanartTVModuleProjectApiKey | ConvertFrom-SecureString }  else { '' }

        if ($IsWindows -or $PSEdition -eq 'Desktop') {
            New-Item -Path $FanartTVConfigPath -ItemType Directory -Force | ForEach-Object { $_.Attributes = $_.Attributes -bor "Hidden" }
        }
        else {
            New-Item -Path $FanartTVConfigPath -ItemType Directory -Force > $null
        }

@"
@{
    FanartTVModuleBaseURI = '$($FanartTVModuleBaseURI -replace "'","''")'
    FanartTVModulePersonalApiKey = '$SecurePersonalString'
    FanartTVModuleProjectApiKey = '$SecureProjectString'
    FanartTVModuleJSONConversionDepth = '$FanartTVModuleJSONConversionDepth'
}
"@
 | Out-File -FilePath $FanartTVConfig -Force

    }

    end {}

}
#EndRegion './Private/ModuleSettings/Export-FanartTVModuleSettings.ps1' 108
#Region './Private/ModuleSettings/Get-FanartTVModuleSettings.ps1' -1

function Get-FanartTVModuleSettings {
<#
    .SYNOPSIS
        Gets the saved FanartTV configuration settings

    .DESCRIPTION
        The Get-FanartTVModuleSettings cmdlet gets the saved FanartTV configuration settings
        from the local system

        By default the configuration file is stored in the following location:
            $env:USERPROFILE\Celerium.FanartTV

    .PARAMETER FanartTVConfigPath
        Define the location to store the FanartTV configuration file

        By default the configuration file is stored in the following location:
            $env:USERPROFILE\Celerium.FanartTV

    .PARAMETER FanartTVConfigFile
        Define the name of the FanartTV configuration file

        By default the configuration file is named:
            config.psd1

    .PARAMETER OpenConfigFile
        Opens the FanartTV configuration file

    .EXAMPLE
        Get-FanartTVModuleSettings

        Gets the contents of the configuration file that was created with the
        Export-FanartTVModuleSettings

        The default location of the FanartTV configuration file is:
            $env:USERPROFILE\Celerium.FanartTV\config.psd1

    .EXAMPLE
        Get-FanartTVModuleSettings -FanartTVConfigPath C:\Celerium.FanartTV -FanartTVConfigFile MyConfig.psd1 -OpenConfigFile

        Opens the configuration file from the defined location in the default editor

        The location of the FanartTV configuration file in this example is:
            C:\Celerium.FanartTV\MyConfig.psd1

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Get-FanartTVModuleSettings.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Index')]
    Param (
        [Parameter()]
        [Alias('FanartTVConfPath')]
        [string]$FanartTVConfigPath = $(Join-Path -Path $home -ChildPath $(if ($IsWindows -or $PSEdition -eq 'Desktop') {"Celerium.FanartTV"}else{".Celerium.FanartTV"}) ),

        [Parameter()]
        [Alias('FanartTVConfFile')]
        [string]$FanartTVConfigFile = 'config.psd1',

        [Parameter()]
        [Alias('OpenConfFile')]
        [switch]$OpenConfigFile
    )

    begin {
        $FanartTVConfig = Join-Path -Path $FanartTVConfigPath -ChildPath $FanartTVConfigFile
    }

    process {

        if (Test-Path -Path $FanartTVConfig) {

            if($OpenConfigFile) {
                Invoke-Item -Path $FanartTVConfig
            }
            else{
                Import-LocalizedData -BaseDirectory $FanartTVConfigPath -FileName $FanartTVConfigFile
            }

        }
        else{
            Write-Verbose "No configuration file found at [ $FanartTVConfig ]"
        }

    }

    end {}

}
#EndRegion './Private/ModuleSettings/Get-FanartTVModuleSettings.ps1' 92
#Region './Private/ModuleSettings/Import-FanartTVModuleSettings.ps1' -1

function Import-FanartTVModuleSettings {
<#
    .SYNOPSIS
        Imports the Fanart.tv BaseURI, API, & JSON configuration information to the current session

    .DESCRIPTION
        The Import-FanartTVModuleSettings cmdlet imports the Fanart.tv BaseURI, API, & JSON configuration
        information stored in the Fanart.tv configuration file to the users current session

        By default the configuration file is stored in the following location:
            $env:USERPROFILE\Celerium.FanartTV

        When no configuration file exists the default base URI (https://webservice.fanart.tv/v3.2) is used

        The FANARTTV_BASE_URI, FANARTTV_PROJECT_KEY, & FANARTTV_PERSONAL_KEY environment variables
        are also supported and take precedence over the values stored in the configuration file

    .PARAMETER FanartTVConfigPath
        Define the location to store the Fanart.tv configuration file

        By default the configuration file is stored in the following location:
            $env:USERPROFILE\Celerium.FanartTV

    .PARAMETER FanartTVConfigFile
        Define the name of the Fanart.tv configuration file

        By default the configuration file is named:
            config.psd1

    .EXAMPLE
        Import-FanartTVModuleSettings

        Validates that the configuration file created with the Export-FanartTVModuleSettings cmdlet exists
        then imports the stored data into the current users session

        The default location of the Fanart.tv configuration file is:
            $env:USERPROFILE\Celerium.FanartTV\config.psd1

    .EXAMPLE
        Import-FanartTVModuleSettings -FanartTVConfigPath C:\Celerium.FanartTV -FanartTVConfigFile MyConfig.psd1

        Validates that the configuration file created with the Export-FanartTVModuleSettings cmdlet exists
        then imports the stored data into the current users session

        The location of the Fanart.tv configuration file in this example is:
            C:\Celerium.FanartTV\MyConfig.psd1

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Import-FanartTVModuleSettings.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Set')]
    Param (
        [Parameter()]
        [Alias('FanartTVConfPath')]
        [string]$FanartTVConfigPath = $(Join-Path -Path $home -ChildPath $(if ($IsWindows -or $PSEdition -eq 'Desktop') {"Celerium.FanartTV"}else{".Celerium.FanartTV"}) ),

        [Parameter()]
        [Alias('FanartTVConfFile')]
        [string]$FanartTVConfigFile = 'config.psd1'
    )

    begin {

        $FanartTVConfig = Join-Path -Path $FanartTVConfigPath -ChildPath $FanartTVConfigFile

        $ModuleVersion = if ($MyInvocation.MyCommand.Version) { $MyInvocation.MyCommand.Version.ToString() } else { '2.0.0' }

        switch ($PSVersionTable.PSEdition){
            'Core'      { $UserAgent = "Celerium.FanartTV/$ModuleVersion - PowerShell/$($PSVersionTable.PSVersion) ($($PSVersionTable.Platform) $($PSVersionTable.OS))" }
            'Desktop'   { $UserAgent = "Celerium.FanartTV/$ModuleVersion - WindowsPowerShell/$($PSVersionTable.PSVersion) ($($PSVersionTable.BuildVersion))" }
            default     { $UserAgent = "Celerium.FanartTV/$ModuleVersion - PowerShell/$($PSVersionTable.PSVersion)" }
        }

    }

    process {

        Set-Variable -Name "FanartTVModuleUserAgent"            -Value $UserAgent -Scope Global -Force
        Set-Variable -Name "FanartTVModuleJSONConversionDepth"  -Value 100 -Scope Global -Force

        if (Test-Path -Path $FanartTVConfig) {

            try {
                $TempConfig = Import-PowerShellDataFile -Path $FanartTVConfig -ErrorAction Stop

                # The base URI is sent to the function to validate it & to strip a superfluous slash (/)
                try {
                    if ($TempConfig.FanartTVModuleBaseURI) { Add-FanartTVBaseURI -BaseURI $TempConfig.FanartTVModuleBaseURI }
                    else { Add-FanartTVBaseURI }
                }
                catch {
                    Write-Warning "The stored base URI is not valid, the default base URI is used - $($_.Exception.Message)"
                    Add-FanartTVBaseURI
                }

                if ($TempConfig.FanartTVModuleJSONConversionDepth) {
                    Set-Variable -Name "FanartTVModuleJSONConversionDepth" -Value ([int]$TempConfig.FanartTVModuleJSONConversionDepth) -Scope Global -Force
                }

                foreach ($Name in 'FanartTVModulePersonalApiKey', 'FanartTVModuleProjectApiKey') {
                    Remove-Variable -Name $Name -Scope Global -Force -ErrorAction SilentlyContinue
                    if ($TempConfig.$Name) {
                        $SecureKey = ConvertTo-SecureString $TempConfig.$Name
                        Set-Variable -Name $Name -Value $SecureKey -Option ReadOnly -Scope Global -Force
                    }
                }

                Write-Verbose "Celerium.FanartTV Module configuration loaded successfully from [ $FanartTVConfig ]"
            }
            catch {
                Write-Warning "The Celerium.FanartTV Module configuration at [ $FanartTVConfig ] could not be loaded - $($_.Exception.Message)"
            }
            finally {
                Remove-Variable -Name "TempConfig" -ErrorAction SilentlyContinue
            }

        }
        else {
            Write-Verbose "No configuration file found at [ $FanartTVConfig ] run Add-FanartTVAPIKey to get started"
            Add-FanartTVBaseURI
        }

        # Environment variables take precedence & are the recommended method for CI\CD, Linux, & macOS
        if ($env:FANARTTV_BASE_URI) {
            try { Add-FanartTVBaseURI -BaseURI $env:FANARTTV_BASE_URI }
            catch { Write-Warning "The FANARTTV_BASE_URI environment variable is not valid - $($_.Exception.Message)" }
        }

        if ($env:FANARTTV_PROJECT_KEY -or $env:FANARTTV_PERSONAL_KEY) {
            Add-FanartTVAPIKey -PersonalKey $env:FANARTTV_PERSONAL_KEY -ProjectKey $env:FANARTTV_PROJECT_KEY
        }

    }

    end {}

}
#EndRegion './Private/ModuleSettings/Import-FanartTVModuleSettings.ps1' 142
#Region './Private/ModuleSettings/Initialize-FanartTVModuleSettings.ps1' -1

#Used to auto load either baseline settings or saved configurations when the module is imported
Import-FanartTVModuleSettings -Verbose:$false
#EndRegion './Private/ModuleSettings/Initialize-FanartTVModuleSettings.ps1' 3
#Region './Private/ModuleSettings/Remove-FanartTVModuleSettings.ps1' -1

function Remove-FanartTVModuleSettings {
<#
    .SYNOPSIS
        Removes the stored FanartTV configuration folder

    .DESCRIPTION
        The Remove-FanartTVModuleSettings cmdlet removes the FanartTV folder and its files
        This cmdlet also has the option to remove sensitive FanartTV variables as well

        By default configuration files are stored in the following location and will be removed:
            $env:USERPROFILE\Celerium.FanartTV

    .PARAMETER FanartTVConfigPath
        Define the location of the FanartTV configuration folder

        By default the configuration folder is located at:
            $env:USERPROFILE\Celerium.FanartTV

    .PARAMETER AndVariables
        Define if sensitive FanartTV variables should be removed as well

        By default the variables are not removed

    .EXAMPLE
        Remove-FanartTVModuleSettings

        Checks to see if the default configuration folder exists and removes it if it does

        The default location of the FanartTV configuration folder is:
            $env:USERPROFILE\Celerium.FanartTV

    .EXAMPLE
        Remove-FanartTVModuleSettings -FanartTVConfigPath C:\Celerium.FanartTV -AndVariables

        Checks to see if the defined configuration folder exists and removes it if it does
        If sensitive FanartTV variables exist then they are removed as well

        The location of the FanartTV configuration folder in this example is:
            C:\Celerium.FanartTV

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Internal/Remove-FanartTVModuleSettings.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Destroy',SupportsShouldProcess, ConfirmImpact = 'None')]
    Param (
        [Parameter()]
        [Alias('FanartTVConfPath')]
        [string]$FanartTVConfigPath = $(Join-Path -Path $home -ChildPath $(if ($IsWindows -or $PSEdition -eq 'Desktop') {"Celerium.FanartTV"}else{".Celerium.FanartTV"}) ),

        [Parameter()]
        [switch]$AndVariables
    )

    begin {}

    process {

        if(Test-Path $FanartTVConfigPath)  {

            Remove-Item -Path $FanartTVConfigPath -Recurse -Force -WhatIf:$WhatIfPreference

            If ($AndVariables) {
                Remove-FanartTVAPIKey
                Remove-FanartTVBaseURI
            }

            if ($WhatIfPreference -eq $false) {

                if (!(Test-Path $FanartTVConfigPath)) {
                    Write-Output "The Celerium.FanartTV configuration folder has been removed successfully from [ $FanartTVConfigPath ]"
                }
                else {
                    Write-Error "The Celerium.FanartTV configuration folder could not be removed from [ $FanartTVConfigPath ]"
                }

            }

        }
        else {
            Write-Warning "No configuration folder found at [ $FanartTVConfigPath ]"
        }

    }

    end {}

}
#EndRegion './Private/ModuleSettings/Remove-FanartTVModuleSettings.ps1' 92
#Region './Public/Latest/Get-FanartTVLatest.ps1' -1

function Get-FanartTVLatest {
<#
    .SYNOPSIS
        Retrieve the latest fanart images for a specific resource type

    .DESCRIPTION
        The Get-FanartTVLatest cmdlet retrieves the latest fanart
        images for a specific resource type

        Resource types are Movies, TV Shows, & Music

    .PARAMETER ResourceType
        What type of latest resource to retrieve

        Allowed values:
            'Movies','TV Shows','Music'

    .PARAMETER Date
        Date to return items updated after

        By default, the API returns items updated in the last 2 days

        The date is converted to a Unix timestamp (seconds)

        Example:
            2026-02-21 = 1771632000 (UTC)

    .EXAMPLE
        Get-FanartTVLatest -ResourceType Movies

        Retrieve all available fanart images for movies updated in the
        past 2 days

    .EXAMPLE
        Get-FanartTVLatest -ResourceType Movies -Date '2026-02-01'

        Retrieve all available fanart images for movies updated since
        the defined date

    .EXAMPLE
        Get-FanartTVLatest -ResourceType 'TV Shows' -Date (Get-Date).AddHours(-12)

        Retrieve all available fanart images for TV shows updated in the
        past 12 hours

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Latest/Get-FanartTVLatest.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Index')]
    Param (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Movies','TV Shows','Music')]
        [string]$ResourceType,

        [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
        [ValidateNotNull()]
        [datetime]$Date
    )

    begin {

        $FunctionName       = $MyInvocation.InvocationName
        $ParameterName      = $FunctionName + '_Parameters' -replace '-','_'

    }

    process {

        Write-Verbose "[ $FunctionName ] - Running the [ $($PSCmdlet.ParameterSetName) ] parameterSet"

        switch ($ResourceType){
            'Movies'    { $ResourceUri = "/movies/latest" }
            'TV Shows'  { $ResourceUri = "/tv/latest" }
            'Music'     { $ResourceUri = "/music/latest" }
        }

        $UriParameters = @{}
        if ($PSBoundParameters.ContainsKey('Date')) { $UriParameters['date'] = ([DateTimeOffset]$Date).ToUnixTimeSeconds() }

        Set-Variable -Name $ParameterName -Value $PSBoundParameters -Scope Global -Force -Confirm:$false

        return Invoke-FanartTVRequest -Method GET -ResourceURI $ResourceUri -UriFilter $UriParameters

    }

    end {}

}
#EndRegion './Public/Latest/Get-FanartTVLatest.ps1' 93
#Region './Public/Movies/Get-FanartTVMovie.ps1' -1

function Get-FanartTVMovie {
<#
    .SYNOPSIS
        Retrieve all available fanart images for a specific movie

    .DESCRIPTION
        The Get-FanartTVMovie cmdlet retrieves all available
        fanart images for a specific movie

    .PARAMETER ID
        Movie identifier (TMDB ID or IMDB ID with 'tt' prefix)

        Examples:
            550 - TMDB ID (Fight Club)
            tt0137523 - IMDB ID (Fight Club)

    .EXAMPLE
        Get-FanartTVMovie -ID 550

        Retrieve all available fanart images for a specific movie

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Movies/Get-FanartTVMovie.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Index')]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ID
    )

    begin {

        $FunctionName       = $MyInvocation.InvocationName
        $ParameterName      = $FunctionName + '_Parameters' -replace '-','_'

    }

    process {

        Write-Verbose "[ $FunctionName ] - Running the [ $($PSCmdlet.ParameterSetName) ] parameterSet"

        $ResourceUri = "/movies/$([System.Uri]::EscapeDataString($ID))"

        Set-Variable -Name $ParameterName -Value $PSBoundParameters -Scope Global -Force -Confirm:$false

        return Invoke-FanartTVRequest -Method GET -ResourceURI $ResourceUri

    }

    end {}

}
#EndRegion './Public/Movies/Get-FanartTVMovie.ps1' 58
#Region './Public/Music/Get-FanartTVMusic.ps1' -1

function Get-FanartTVMusic {
<#
    .SYNOPSIS
        Retrieve all available music artist and album images

    .DESCRIPTION
        The Get-FanartTVMusic cmdlet retrieves all available
        music artist and album images

    .PARAMETER ImageType
        What type of image to retrieve

        Allowed values:
            'Artist','Album','Label'

    .PARAMETER ID
        MusicBrainz Artist ID (MBID)
        MusicBrainz Release Group ID
        MusicBrainz Label ID

        Examples:
            Artist - 20244d07-534f-4eff-b4d4-930878889970 - MusicBrainz ID (Taylor Swift)
            Album - 70816f08-b7d1-4e77-817e-8c1426751de0 - MusicBrainz Release Group ID (Taylor Swift)
            Label - be994c3e-0527-404f-b8f9-455e217e83d2 - MusicBrainz Label ID (Profile Records)

    .EXAMPLE
        Get-FanartTVMusic -ImageType Artist -ID 20244d07-534f-4eff-b4d4-930878889970

        Retrieve all available fanart artist images for a specific music artist

    .EXAMPLE
        Get-FanartTVMusic -ImageType Album -ID 70816f08-b7d1-4e77-817e-8c1426751de0

        Retrieve all available fanart album images for a specific music album

    .EXAMPLE
        Get-FanartTVMusic -ImageType Label -ID be994c3e-0527-404f-b8f9-455e217e83d2

        Retrieve all available fanart label images for a specific music label

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/Music/Get-FanartTVMusic.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Index')]
    Param (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Artist','Album','Label')]
        [string]$ImageType,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ID
    )

    begin {

        $FunctionName       = $MyInvocation.InvocationName
        $ParameterName      = $FunctionName + '_Parameters' -replace '-','_'

    }

    process {

        Write-Verbose "[ $FunctionName ] - Running the [ $($PSCmdlet.ParameterSetName) ] parameterSet"

        switch ($ImageType) {
            'Artist'{ $ResourceUri = "/music/$([System.Uri]::EscapeDataString($ID))" }
            'Album' { $ResourceUri = "/music/albums/$([System.Uri]::EscapeDataString($ID))" }
            'Label' { $ResourceUri = "/music/labels/$([System.Uri]::EscapeDataString($ID))" }
        }

        Set-Variable -Name $ParameterName -Value $PSBoundParameters -Scope Global -Force -Confirm:$false

        return Invoke-FanartTVRequest -Method GET -ResourceURI $ResourceUri

    }

    end {}

}
#EndRegion './Public/Music/Get-FanartTVMusic.ps1' 85
#Region './Public/TVShows/Get-FanartTVShow.ps1' -1

function Get-FanartTVShow {
<#
    .SYNOPSIS
        Retrieve all available fanart images for a specific TV Show

    .DESCRIPTION
        The Get-FanartTVShow cmdlet retrieves all available
        fanart images for a specific TV Show

    .PARAMETER ID
        TV Show identifier (TVDB ID)

        Examples:
            76703 - TVDB ID (Pokemon)

    .EXAMPLE
        Get-FanartTVShow -ID 76703

        Retrieve all available fanart images for a specific TV Show

    .NOTES
        N/A

    .LINK
        https://celerium.github.io/Celerium.FanartTV/site/TVShows/Get-FanartTVShow.html
#>


    [CmdletBinding(DefaultParameterSetName = 'Index')]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ID
    )

    begin {

        $FunctionName       = $MyInvocation.InvocationName
        $ParameterName      = $FunctionName + '_Parameters' -replace '-','_'

    }

    process {

        Write-Verbose "[ $FunctionName ] - Running the [ $($PSCmdlet.ParameterSetName) ] parameterSet"

        $ResourceUri = "/tv/$([System.Uri]::EscapeDataString($ID))"

        Set-Variable -Name $ParameterName -Value $PSBoundParameters -Scope Global -Force -Confirm:$false

        return Invoke-FanartTVRequest -Method GET -ResourceURI $ResourceUri

    }

    end {}

}
#EndRegion './Public/TVShows/Get-FanartTVShow.ps1' 57