NN.HpWarranty.psm1

#Region './Private/Get-HpwAccessToken.ps1' 0
function Get-HpwAccessToken {
    [CmdletBinding()]
    param (
        $accessTokenPath = "$env:USERPROFILE\.creds\HP\hpWarrantyAccessToken.xml"
    )
    
    process {
        #Conditions to refresh access token
        if (Test-Path $accessTokenPath) {
            [datetime]$accessTokenExpiryDate = (Import-Clixml $accessTokenPath | ConvertFrom-SecureString -AsPlainText | ConvertFrom-Json).expiry_date

            #Refresh access token if there's less than 5 minutes till token expiry
            if (($accessTokenExpiryDate.AddMinutes(-5)) -lt (Get-Date)) {
                New-HpwAccessToken
            }
        } else {
            New-HpwAccessToken
        }

        #Import the existing access token
        (Import-Clixml $accessTokenPath | ConvertFrom-SecureString -AsPlainText | ConvertFrom-Json).access_token
    }
}
#EndRegion './Private/Get-HpwAccessToken.ps1' 24
#Region './Public/Get-HpwJob.ps1' 0
function Get-HpwJob {
    [CmdletBinding()]
    param (
        $id
    )

    process {
        $splat = @{
            "Uri" = "https://warranty.api.hp.com/productwarranty/v2/jobs/$id"
            "Method" = "GET"
            "Headers" = @{
                "accept" = "application/json"
                "Content-Type" = "application/json"
                "Authorization" = "Bearer $(Get-HpwAccessToken)"
            }
        }
        Invoke-RestMethod @splat
    }
}
#EndRegion './Public/Get-HpwJob.ps1' 20
#Region './Public/Get-HpwJobResult.ps1' 0
function Get-HpwJobResult {
    [CmdletBinding()]
    param (
        $id
    )

    process {
        $splat = @{
            "Uri" = "https://warranty.api.hp.com/productwarranty/v2/jobs/$id/results"
            "Method" = "GET"
            "Headers" = @{
                "accept" = "application/json"
                "Content-Type" = "application/json"
                "Authorization" = "Bearer $(Get-HpwAccessToken)"
            }
        }
        Invoke-RestMethod @splat
    }
}
#EndRegion './Public/Get-HpwJobResult.ps1' 20
#Region './Public/New-HpwAccessToken.ps1' 0
function New-HpwAccessToken {
    [CmdletBinding()]
    param (
        [string]$credsPath = "$env:USERPROFILE\.creds\HP\hpWarrantyCreds.xml",
        [string]$accessTokenPath = "$env:USERPROFILE\.creds\HP\hpWarrantyAccessToken.xml",
        [switch]$RefreshCreds
    )
    
    process {
        #Create parent folders of the access token file
        $accessTokenDir = $accessTokenPath.Substring(0, $accessTokenPath.lastIndexOf('\'))
        if (!(Test-Path $accessTokenDir)) {
            $null = New-Item -ItemType Directory $accessTokenDir
        }

        #Create creds file
        if (!(Test-Path $credsPath) -or $RefreshCreds) {
            while (!$clientId) {
                $clientId = Read-Host "Enter HP client_id"
            }
            while (!$clientSecret) {
                $clientSecret = Read-Host "Enter HP client_secret"
            }
            
            @{
                "client_id" = $clientId
                "client_secret" = $clientSecret
            } | ConvertTo-Json | ConvertTo-SecureString -AsPlainText | Export-Clixml $credsPath
        }

        $creds = Import-Clixml $credsPath | ConvertFrom-SecureString -AsPlainText | ConvertFrom-Json
        $b64EncodedCred  = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($creds.client_id):$($creds.client_secret)"))

        $splat = @{
            "Method" = "POST"
            "Uri" = "https://warranty.api.hp.com/oauth/v1/token"
            "Headers" = @{
                "accept" = "application/json"
                "authorization" = "Basic $b64EncodedCred"
                "content-type" = "application/x-www-form-urlencoded"
            }
            "Body" = @{
                "grant_type" = "client_credentials"
            }
        }
        $result = Invoke-RestMethod @splat

        #Adds access token and expiry date to access token file
        [PSCustomObject]@{
            access_token = $result.access_token
            expiry_date = (Get-Date).AddSeconds($result.expires_in)
        } | ConvertTo-Json | ConvertTo-SecureString -AsPlainText | Export-Clixml -Path $accessTokenPath
    }
}
#EndRegion './Public/New-HpwAccessToken.ps1' 55
#Region './Public/New-HpwJob.ps1' 0
function New-HpwJob {
    <#
    .EXAMPLE
        @("5CD2022DDS","5CD2022D9Q") | New-HpwJob

        Get an array of serialnumbers without productnumber.
        Note that this could result in a not found message when retrieving the results.
    .EXAMPLE
        @("5CD2022DDS","5CD2022D9Q") | New-HpwJob -pn "2U740AV"

        Get an array of serialnumbers using the same productnumber.
    .EXAMPLE
        @(
        @{
            "sn" = "5CD2022DDS"
            "pn" = "2U740AV"
        },
        @{
            "sn" = "5CD2022D9Q"
            "pn" = "2U740AV"
        }
        ) | New-HpwJob -HashtableInput

        You can pipe an array of hashtables into the function with the use of the "-Hashtable" switch
        in order to set multiple inputs independent of eachother e.g. separate PN for each SN.
    #>

    [CmdletBinding(DefaultParameterSetName="Normal inputs")]
    param (
        [Parameter(ParameterSetName="Normal inputs",Mandatory,ValueFromPipeline,Position=0)]$sn,
        [Parameter(ParameterSetName="Normal inputs")][string]$pn,
        [Parameter(ParameterSetName="Normal inputs")][string]$cc,
        [Parameter(ParameterSetName="Hashtable input",Mandatory,ValueFromPipeline,Position=0)][hashtable]$InputObject,
        [Parameter(ParameterSetName="Hashtable input")][switch]$HashtableInput
    )

    begin {
        $queryBody = New-Object -TypeName System.Collections.ArrayList
    }

    process {
        switch ($PsCmdlet.ParameterSetName) {
            "Normal inputs" {
                $ParamHashtable = $PSBoundParameters
            }
            "Hashtable input" {
                $ParamHashtable = $InputObject
            }
        }

        $CurrentQueryBody = $null

        #Build request Uri
        $ParamHashtable.Keys.ForEach({
            [string]$Key = $_
            [string]$Value = $ParamHashtable.$key
        
            $CurrentQueryBody = $CurrentQueryBody + @{
                "$Key" = "$Value"
            }
        })

        $null = $queryBody.Add($CurrentQueryBody)
    }

    end {
        $splat = @{
            "Uri" = "https://warranty.api.hp.com/productwarranty/v2/jobs"
            "Method" = "POST"
            "Headers" = @{
                "accept" = "application/json"
                "Content-Type" = "application/json"
                "Authorization" = "Bearer $(Get-HpwAccessToken)"
            }
            "Body" = ConvertTo-Json @($queryBody)
        }
        Invoke-RestMethod @splat
    }
}
#EndRegion './Public/New-HpwJob.ps1' 79