PushoverForPS.psm1

#For help Get-Help PushoverForPS

#The Pushover API limits the same request to once every five seconds.
#The following variable and function are used to hold the last request,
#and then check that the same request doesn't occurr within five seconds.

#Variable to hold the sounds from Pushover
$Global:PushoverSounds = @()

#Variable to hold the last few requests made and their times.
$Global:LastPushoverRequests = New-Object System.Collections.ArrayList

#Function to compare the previous and current requests
Function Compare-PushoverRequest {
    [CmdletBinding()]
    Param([hashtable]$CurrentRequest)
    
    #Get current requests values for comparison
    $arrCurr = $CurrentRequest.Values.GetEnumerator()
    
    Write-Verbose "Testing that the current request has not been sent within the last 5 seconds"
    #Iterate through clone to add or remove objects from the base array
    foreach ($request in $Global:LastPushoverRequests.Clone()) {
        #Remove any request older than 5 seconds.
        if (((Get-Date) - $request.Timestamp).TotalSeconds -gt 5) {
            $Global:LastPushoverRequests.Remove($request) | Out-Null
        }
        #Test that it is not the same as the current request
        else {
            $arrLast = $request.Request.Values.GetEnumerator()
            if (-not (Compare-Object -ReferenceObject $arrCurr -DifferenceObject $arrLast)) {
                Write-Warning "The Pushover API does not allow the same request to be sent more than once every 5 seconds. This request will be sent once five seconds have elapsed since it was last sent."
                
                #Wait until five seconds has passed, update every 100 milliseconds
                while (((Get-Date) - $request.Timestamp).TotalSeconds -lt 5) {
                    Start-Sleep -Milliseconds 100
                }
            }
        }
    }       
}

#Function to add the latest request to the history for rate limiting checks
Function Add-PushoverRequest {
    [CmdletBinding()]
    Param( [hashtable]$Request )
    
    Write-Verbose "Adding the request to the history array for rate limiting checks."
    $element = @{Request=$Request; Timestamp=(Get-Date)}
    $Global:LastPushoverRequests.Add($element) | Out-Null
}

#Create Enum for priority
Add-Type -TypeDefinition @'
using System;
 
namespace Pushover
{
    public enum Priority
    {
        None = -2,
        Quiet = -1,
        Normal = 0,
        High = 1,
        Emergency = 2
    };
};
'@


#Export function definitions
Function Send-Pushover {
    <#
    .SYNOPSIS
    Sends data to the Pushover API
 
    .DESCRIPTION
    This command sends data to the Pushover API to generate notifications on Android, iOS, and desktops through Chrome, Mozilla, and Safari.
 
    The UserKey (alias GroupKey) is the key given to a user when they sign up for an account, or the group key given when a group is created.
 
    The AppToken is the token given to an application when it is created.
 
    The Message is the text that will be displayed in the notification.
 
    AppToken, UserKey, and Message parameters are all required.
    .PARAMETER AppToken
    The token of the application to use when generating notifications. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .PARAMETER UserKey
    The key of the user or group to send the notifications to. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .PARAMETER Message
    The text that will form the body of the notification.
 
    .PARAMETER Device
    An array of device names that can accept Pushover notifications. These are up to 25 characters long and made up of upper and lowercase letters, numbers, hyphens, and underscores. No spaces are allowed.
 
    If this is left blank, the notification is sent to all devices in the user account.
 
    .PARAMETER Title
    The title to be used for the notification. If this is blank the name of the application is used.
 
    .PARAMETER Url
    A supplemental URL to be included in the notification that the user can interact with.
 
    .PARAMETER UrlTitle
    If this is supplied the URL in the Url parameter will be displayed with this text instead of the actual URL address.
 
    .PARAMETER Priority
    The priority of the message. None generates no notification. Quiet does not produce sound or vibration. Normal generates a notification with sound and/or vibration except during quiet hours. High will not obey quiet hours. Emergency will not obey quiet hours, and will repeat until acknowledged by the user.
 
    .PARAMETER Retry
    Specifies how often in seconds Pushover will send an Emergency priority notification to the user. The value must be at least 30 seconds. The default is 5 minutes (300 seconds).
 
    .PARAMETER Expire
    Specifies how long in seconds an Emergency priority notification will be retried for acknowledgement. After it expires it will stop being resent to the user. The value must be less than 24 hours (86,400 seconds). The default is 8 hours (28,800 seconds).
 
    .PARAMETER Callback
    Specifies a publicly accessible URL that Pushover can a request to when the user has acknowledged the Emergency priority notification.
 
    .PARAMETER Timestamp
    The time to be shown in the notification. If blank the server time from Pushover is used.
 
    .PARAMETER Sound
    The notification sound to use. When not used the user's default tone is played.
 
    .PARAMETER UseHtml
    This tells Pushover that the message contains HTML.
 
    Note: The HTML version is only visible in the device client. It is not shown in the notification on mobile devices.
 
    .INPUTS
    System.Management.Automation.PSCustomObject
 
 
    You can pipe PSCustomObjects to Send-Pushover that have properties matching the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Send-Pushover returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Send-Pushover -AppToken <token string> -UserKey <key string> -Message 'Test notification.'
 
    This command will generate a notification on all devices of the user specified by the UserKey using the app specified by the AppToken with the content of 'Test Notification'.
    .EXAMPLE
    PS C:\> Send-Pushover -AppToken <token string> -UserKey <key string> -Message 'Test notification.' -Device my-device_name -Title Test -Priority High
 
    This command will generate a notification on the device named 'my-device_name of the user specified by the UserKey using the app specified by the AppToken with the content of 'Test Notification', a title of 'Test', and will have a high priority that will not obey quiet hours.
    .EXAMPLE
    PS C:\> Send-Pushover -AppToken <token string> -UserKey <key string> -Message "Emergency Notification!" -Priority Emergency -Retry 60 -Expire 3600
 
    This command will send an Emergency priority notification that will be resent to the user every minute for an hour, or until they acknowledge the notification.
    .NOTES
    This command will test that all supplied data conforms to the Pushover API.
    .LINK
    https://pushover.net/api
    #>


    #Requires -Version 3.0
    [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')]

    Param(
        [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$AppToken,

        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
        [Alias("GroupKey")]
            [String]$UserKey,

        [Parameter(Position=2,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$Message,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [String[]]$Device,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [String]$Title,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [Uri]$Url,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [String]$UrlTitle,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [Pushover.Priority]$Priority=[Pushover.Priority]::Normal,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [Int]$Retry=300,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [Int]$Expire=28800,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [Uri]$Callback,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [DateTime]$Timestamp,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [String]$Sound,

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [Switch]$UseHtml
    )
    
    Process {
        #Test that user or group key, and the app token match the Pushover API specification.
        if (($AppToken,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The user key, group key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters."
            return
        }
        else { Write-Verbose "The user key and app token are formatted correctly." }

        if ($Device) {
            #Create array to hold valid device names
            $devices = @()
            foreach ($d in $Device) {
                #Check that each device name matches the PushoverAPI specification
                if ($d -notmatch '^[-\w]{1,25}$') {
                    Write-Error "The device name $d does not meet the required criteria. It should be up to 25 characters long and made up of only upper and lowercase letters, numbers, hyphens, or underscores, no spaces or special characters."
                }
                else {
                    Write-Verbose "The device name $d is formatted correctly."
                    #Add the validated string to the devices array
                    $devices += $d
                }
            }
            #Check that any device names were accepted then join together with commas or set $Device to null if no names were
            if ($devices) {
                $Device = $devices -join ','
            }
            else { 
                Write-Error "None of the submitted device names matched the Pushover API specification."
                return
            }
        }

        #Retrieve the available sounds from the Pushover API if they haven't been stored already,
        #and check that the sound, if supplied, is one of them
        if ($Sound) {
            if (-not $Global:PushoverSounds) {
                Write-Verbose "Receiveing the available sounds from Pushover"
                $Global:PushoverSounds = Receive-PushoverSound -AppToken $AppToken -ea Stop | Get-Member |
                                    Where-Object MemberType -EQ NoteProperty | ForEach-Object { $_.Name }
                if ($?) {
                    Write-Verbose "The list of available sounds was successfully received from Pushover."
                    if ($Sound -notin $Global:PushoverSounds) {
                        Write-Error "The sound $Sound provided is not one of the official Pushover sounds. Please choose from one of the following: $($Global:PushoverSounds -join ',')."
                        return
                    }
                }
                else {
                    Write-Error "There was an error retrieving the sounds list from Pushover. Each device will use their default sound."
                    $Sound = $null
                }
            }
            else {
                if ($Sound -notin $Global:PushoverSounds) {
                    Write-Error "The sound $Sound provided is not one of the official Pushover sounds. Please choose from one of the following: $($Global:PushoverSounds -join ', ')."
                    return
                }
            }
        }

        #If the Priority is set to Emergency, test that the Retry, Expire, and Callback parameters conform to the Pushover API specification.
        #Otherwise, set to $null
        if ($Priority -eq "Emergency") {
            if ($Retry -lt 30) { Write-Error "The Retry parameter must have a value of greater than 30 seconds."; return }
            if ($Expire -gt 86400) { Write-Error "The Expire parameter must have a value less than 24 hours (86400 seconds)."; return }

            #If provided check that Callback URL is an absolute path, eg http://, https:// and convert to a string if it is
            if ($Callback) {
                if (-not $Callback.IsAbsoluteUri) { Write-Error "The Callback URL is not a valid absolute path."; return }
                else {$Callback = $Callback.OriginalString}
            }
        }
        else { $Retry, $Expire, $Callback = $null } 

        #Convert Priority to [int]
        [int]$Priority = $Priority

        if ($Timestamp) {
            Write-Verbose "Converting Timestamp to Unix time"
            #Convert DateTime to UnixTime
            $epoch = Get-Date '1/1/1970'
            $Timestamp = $Timestamp.ToUniversalTime()
            #If the timestamp is not within Unix time, set to null to use Pushover's server's time.
            if (-not ($Timestamp -ge $epoch -or $Timestamp -le [Int32]::MaxValue)) {
                Write-Error "The timestamp given is not within the bounds of Unix time from 1/1/1970 12:00 a.m. to 1/19/2038 3:14 a.m."
                $Timestamp = $null
            }
            else {
                Write-Verbose "Timestamp converted to Unix time"
                [int]$Timestamp = (New-TimeSpan -Start $epoch -End $Timestamp).TotalSeconds
            }
        }

        #Test Url for an absolute path and convert to string if it is
        if ($Url) {
            if (-not $Url.IsAbsoluteUri) { Write-Error "The URL is not a valid absolute path."; return }
            else {$Url = $Url.OriginalString}
        }

        #Test the message, the title, the supplemental URL, and the URL title for conformity to the Pushover API limitations
        if ($Message.Length -gt 1024) { Write-Error "The message cannot exceed 1024 characters."; return }
        if ($Title.Length -gt 250) { Write-Error "The title cannot exceed 250 characters."; return }
        if ($Url.Length -gt 512) { Write-Error "The URL cannot exceed 512 characters."; return }
        if ($UrlTitle.Length -gt 100) { Write-Error "The URL title cannot exceed 100 characters."; return }

        #Convert AppToken, UserKey, and UrlTitle value to token, user, and url_title per API specification
        if ($UrlTitle) { $url_title = $UrlTitle }
        $token = $AppToken
        $user = $UserKey

        #Test if html will be used in the message and set the appropriate parameter to send to Pushover
        if ($UseHtml) { $html = 1 }

        #Hashtable to send to Pushover
        $PushoverHash = @{}

        #Create hashtable from parameters that have value to send to Pushover
        Write-Verbose "Creating data collection to send to Pushover"
        switch ('token', 'user', 'message', 'device', 'title', 'url', 'url_title','priority', 'retry', 'expire', 'callback', 'timestamp', 'sound', 'html') {
            {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly}
        }

        #Send to comparison function to determine if rate limiting needs to apply
        Compare-PushoverRequest -CurrentRequest $PushoverHash

        Write-Verbose "Sending data to Pushover"
        try {
            #Send to Pushover and return the response if successful
            $response = Invoke-RestMethod -Body $PushoverHash -Uri https://api.pushover.net/1/messages.json -Method Post -ea Stop

            if ($response.status -eq 1) {
                Write-Verbose "Data sent through Pushover successfully"
            }
            $response
        }
        catch { 
            #Generate error, but also build response so that error details from Pushover are exposed
            if (-not $_.Exception.Response) {
                Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)"
            }
            else {
                $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream())
                $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json
                foreach ($err in $response.errors) {
                    Write-Error "An error occurred while sending data to Pushover: $err"
                }
            }
        }
        finally { Add-PushoverRequest -Request $PushoverHash }
    }
}

Function Receive-PushoverSound {
    <#
    .SYNOPSIS
    Receives Pushover available notification sounds.
 
    .DESCRIPTION
    Receive-PushoverSound receives the current list of available sounds from the Pushover API
    .PARAMETER AppToken
    The token of the application to use when requesting a cancel. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .INPUTS
    System.Object or System.String
 
 
    You can pipe Objects to Test-PushoverKey with properties that match the desired parameters, or a string containing a valid Pushover application token.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Receive-PushoverSound returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Receive-PushoverSound -AppToken <token string>
 
    This command will retrieve the sounds available from Pushover using the application specified in AppToken.
    .NOTES
    This command will test that all supplied data conforms to the Pushover API.
 
    Due to the fact that Pushover generates rich JSON responses that are converted into PowerShell objects, this command always returns Pushover's response,if one exists, even in the case of an error.
    .LINK
    https://pushover.net/api
    #>


    #Requires -Version 3.0
    [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')]

    Param(
        [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$AppToken
    )

    Process {
        foreach ($Token in $AppToken) {
            #Test that the app token matches the Pushover API specification
            if ($Token -notmatch '^[a-zA-Z\d]{30}$') {
                Write-Error "The app token given does not meet the required criteria. It should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters."
                return
            }
            else { Write-Verbose "The app token is formatted correctly." }

            #Send to comparison function to determine if rate limiting needs to apply
            Compare-PushoverRequest -CurrentRequest @{URL="https://api.pushover.net/1/sounds.json"}

            Write-Verbose "Sending data to Pushover"
            try {
                #Send to Pushover and return the response if successful
                $response = Invoke-RestMethod -Uri "https://api.pushover.net/1/sounds.json?token=$Token" -Method Get -ea Stop
        
                if ($response.sounds) {
                    Write-Verbose "Data sent to Pushover successfully"
                    #Store the contents in the global PushoverSounds variable
                    $Global:PushoverSounds = $response.sounds | Get-Member | 
                        Where-Object MemberType -EQ NoteProperty | ForEach-Object { $_.Name }

                    $response.sounds
                }
                else { $response }
            }
            catch { 
                #Generate error, but also build response so that error details from Pushover are exposed
                if (-not $_.Exception.Response) {
                    Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)"
                }
                else {
                    $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream())
                    $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json
                    foreach ($err in $response.errors) {
                        Write-Error "An error occurred while sending data to Pushover: $err"
                    }
                }
            }
            finally { Add-PushoverRequest -Request @{URL="https://api.pushover.net/1/sounds.json"} }
        }
    }
}

Function Test-PushoverKey {
    <#
    .SYNOPSIS
    Validates a Pushover user or group key
 
    .DESCRIPTION
    Test-PushoverKey receives a response from Pushover validating a user or group key, and optionally a device belonging to that user. Provide the app token to the AppToken parameter, and the user/group key to the UserKey (alias GroupKey) parameter.
 
    If a device supplied, the verification will apply to that user and device. If the Device parameter is blank, a user will be validated if there is at least one active device on the account.
 
    The user is valid if the status in the response is 1, and will contain a devices array of the user's active devices. If the user and/or device is not valid, the status will be set to 0, along with the errors in an errors array.
    .PARAMETER AppToken
    The token of the application to use when validating users, group, or devices. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .PARAMETER UserKey
    The key of the user or group to validate. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .PARAMETER Device
    The name of a device to validate. If left blank, the user is valid as long as there is one active device on the account. These are up to 25 characters long and made up of upper and lowercase letters, numbers, hyphens, and underscores. No spaces are allowed.
 
    .INPUTS
    System.Object
 
 
    You can pipe objects to Test-PushoverKey that have properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Test-PushoverKey returns a PSCustomObject with Pushover's response to validation.
 
    .EXAMPLE
    PS C:\> Test-PushoverKey -AppToken <token string> -UserKey <key string>
 
    This command will receive validation of the specified user key using the specified app token to ensure the user is valid and has one active device on the account.
    .EXAMPLE
    PS C:\> Test-PushoverKey -AppToken <token string> -UserKey <key string>-Device my-device_name
 
    This command will receive validation of the specified user key using the specified app token to ensure the user is valid and has a device named 'my-device_name on the account.
    .NOTES
    This command will test that all supplied data conforms to the Pushover API.
 
    Due to the fact that Pushover generates rich JSON responses that are converted into PowerShell objects, this command always returns Pushover's response,if one exists, even in the case of an error.
    .LINK
    https://pushover.net/api
    #>


    #Requires -Version 3.0
    [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')]

    Param(
        [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$AppToken,

        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [Alias("GroupKey")]
            [String]$UserKey,

        [Parameter(Position=2,ValueFromPipelineByPropertyName=$true)]
            [String]$Device
    )

    Process {
        #Test that user or group key, and the app token match the Pushover API specification
        if (($AppToken,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The user key, group key, or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters."
            exit
        }
        else { Write-Verbose "The user key and app token are formatted correctly." }

        #Check that the device name matches the PushoverAPI specification
        if ($Device) {
            if ($Device -notmatch '^[-\w]{1,25}$') {
                Write-Error "The device name $Device does not meet the required criteria. It should be up to 25 characters long and made up of only upper and lowercase letters, numbers, hyphens, or underscores, no spaces or special characters."
                exit
            }
            else {
                Write-Verbose "The device name $Device is formatted correctly."
        
            }
        }

        #Convert AppToken and UserKey values to token and user per API specification
        $token = $AppToken
        $user = $UserKey

        #Hashtable to send to Pushover
        $PushoverHash = @{}

        #Create hashtable from parameters that have value to send to Pushover
        Write-Verbose "Creating data collection to send to Pushover"
        switch ('token', 'user', 'device') {
            {Get-Variable -Name $_ -ValueOnly -ea SilentlyContinue} {$PushoverHash.$_ = Get-Variable -Name $_ -ValueOnly}
        }

        #Send to comparison function to determine if rate limiting needs to apply
        Compare-PushoverRequest -CurrentRequest $PushoverHash

        Write-Verbose "Sending data to Pushover"
        try {
            #Send to Pushover and return the response if successful
            $response = Invoke-RestMethod -Body $PushoverHash -Uri https://api.pushover.net/1/users/validate.json -Method Post -ea Stop

            if ($response.status -eq 1) {
                Write-Verbose "User/group and/or device successfully validated."

                $response.group = $response.group -eq 1
            } 

            $response
        }
        catch { 
            #Generate error, but also build response so that error details from Pushover are exposed
            if (-not $_.Exception.Response) {
                Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)"
            }
            else {
                $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream())
                $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json
                foreach ($err in $response.errors) {
                    Write-Error "An error occurred while sending data to Pushover: $err"
                }
            }
        }
        finally { Add-PushoverRequest -Request $PushoverHash }
    }
}

Function Receive-PushoverReceipt {
    <#
    .SYNOPSIS
    Receives Pushover receipts from Emergency priority notifications.
 
    .DESCRIPTION
    Receive-PushoverReceipt receives a receipt response from Pushover regarding the status of Emergency priority notifications, up to 1 week after notifications are received.
 
    When an Emergency priority notification is sent, a receipt parameter is given in the response from Pushover. This can be supplied to the Receipt parameter along with the app token to receive the status of the notification.
 
    The information in the response from Pushover will include whether the user has acknowledged the notification, when it was acknowledged and from what device, whether it has expired and when, when it was last delivered, and more.
    .PARAMETER AppToken
    The token of the application to use when retrieving receipts. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .PARAMETER Receipt
    The receipt returned by Pushover when an Emergency priority notification is sent. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .INPUTS
    System.Object
 
 
    You can pipe objects to Test-PushoverKey that have properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Receive-PushoverReceipt returns a PSCustomObject with Pushover's details about the Emergency notification.
 
    .EXAMPLE
    PS C:\> Test-PushoverKey -AppToken <token string> -Recipt <key string>
 
    This command will receive the information about the Emergency priority notification that is identified by the data supplied to the Receipt parameter using the application specified by the AppToken.
    .NOTES
    This command will test that all supplied data conforms to the Pushover API.
 
    Due to the fact that Pushover generates rich JSON responses that are converted into PowerShell objects, this command always returns Pushover's response,if one exists, even in the case of an error.
    .LINK
    https://pushover.net/api
    #>


    #Requires -Version 3.0
    [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')]

    Param(
        [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$AppToken,

        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$Receipt
    )
    
    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$Receipt -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The receipt or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters."
            exit
        }
        else { Write-Verbose "The receipt and app token are formatted correctly." }

        #Send to comparison function to determine if rate limiting needs to apply
        Compare-PushoverRequest -CurrentRequest @{URL="https://api.pushover.net/1/receipts/$Receipt.json";token=$AppToken}

        Write-Verbose "Sending data to Pushover"
        try {
            #Send to Pushover and return the response if successful
            $response = Invoke-RestMethod -Uri "https://api.pushover.net/1/receipts/$Receipt.json?token=$AppToken" -Method Get -ea Stop

            #If the response is successful, convert unix time to datetimes and flags to boolean
            if ($response.status -eq 1) {
                Write-Verbose "User/group and/or device successfully validated."
        
                $ResponseHash = @{}
                $Epoch = Get-Date 1/1/1970

                $ResponseHash.Status = $response.status
                $ResponseHash.Acknowledged = $response.acknowledged -eq 1
                $ResponseHash.Acknowledged_By = $response.acknowledged_by
                $ResponseHash.Acknowledged_By_Device = $response.acknowledged_by_device
                $ResponseHash.Expired = $response.expired -eq 1
                $ResponseHash.Called_Back = $response.called_back -eq 1

                switch ('Acknowledged_At','Last_Delivered_At','Expires_At','Called_Back_At') {
                    { $response.$_ } { $ResponseHash.$_ = ($Epoch.AddSeconds($response.$_)).ToLocalTime() }
                    default { $ResponseHash.$_ = $null }
                }

                $response = New-Object PSObject -Property $ResponseHash
            }

            $response
        }
        catch { 
            #Generate error, but also build response so that error details from Pushover are exposed
            if (-not $_.Exception.Response) {
                Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)"
            }
            else {
                $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream())
                $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json
                foreach ($err in $response.errors) {
                    Write-Error "An error occurred while sending data to Pushover: $err"
                }
            }
        }
        finally { Add-PushoverRequest -Request @{URL="https://api.pushover.net/1/receipts/$Receipt.json";token=$AppToken} }
    }
}

Function Stop-PushoverRetry {
    <#
    .SYNOPSIS
    Sends request to cancel Pushover Emergency priority retries.
 
    .DESCRIPTION
    Stop-PushoverRetry sends a request to cancel retries of an Emergency priority notification.
 
    Emergency priority notifications are retried at a set interval for a set duration or until the user acknowledges the notification or Stop-PushoverRetry is used
    .PARAMETER AppToken
    The token of the application to use when requesting a cancel. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .PARAMETER Receipt
    The receipt to request a cancel on that is returned by Pushover when an Emergency priority notification is sent. This is a 30 character string made up of upper and lowercase letters and numbers.
 
    .INPUTS
    System.Object
 
 
    You can pipe objects to Test-PushoverKey that have properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Stop-PushoverRetry returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Stop-PushoverRetry -AppToken <token string> -Recipt <key string>
 
    This command will cancel the Emergency priority of the notification that is represented by the receipt returned by Pushover at its creation.
    .NOTES
    This command will test that all supplied data conforms to the Pushover API.
 
    Due to the fact that Pushover generates rich JSON responses that are converted into PowerShell objects, this command always returns Pushover's response,if one exists, even in the case of an error.
    .LINK
    https://pushover.net/api
    #>


    #Requires -Version 3.0
    [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/Send-Notifications-to-aec9763a')]

    Param(
        [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$AppToken,

        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
            [String]$Receipt
    )
    
    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$Receipt -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The receipt or app token given do not meet the required criteria. Both should be 30 characters long and made up of only upper and lowercase letters or numbers, no spaces or special characters."
            exit
        }
        else { Write-Verbose "The receipt and app token are formatted correctly." }

        #Hashtable to send to Pushover
        $PushoverHash = @{token=$AppToken}

        #Send to comparison function to determine if rate limiting needs to apply
        Compare-PushoverRequest -CurrentRequest @{URL="https://api.pushover.net/1/receipts/$Receipt/cancel.json";token=$AppToken}

        Write-Verbose "Sending data to Pushover"
        try {
            #Send to Pushover and return the response if successful
            $response = Invoke-RestMethod -Body $PushoverHash -Uri https://api.pushover.net/1/receipts/$Receipt/cancel.json -Method Post -ea Stop

            if ($response.status -eq 1) {
                Write-Verbose "Data sent to Pushover successfully"
            }

            $response
        }
        catch { 
            #Generate error, but also build response so that error details from Pushover are exposed
            if (-not $_.Exception.Response) {
                Write-Error "An error occurred while sending data to Pushover: $($_.Exception.Message)"
            }
            else {
                $StreamReader = New-Object System.IO.StreamReader -Args ($_.Exception.Response.GetResponseStream())
                $response = ($StreamReader.ReadToEnd()) | ConvertFrom-Json
                foreach ($err in $response.errors) {
                    Write-Error "An error occurred while sending data to Pushover: $err"
                }
            }
        }
        finally { Add-PushoverRequest -Request @{URL="https://api.pushover.net/1/receipts/$Receipt/cancel.json";token=$AppToken} }
    }
}

New-Alias -Name snpo -Value Send-Pushover
New-Alias -Name rcpr -Value Receive-PushoverReceipt
New-Alias -Name tspk -Value Test-PushoverKey
New-Alias -Name sppr -Value Stop-PushoverRetry
New-Alias -Name rcps -Value Receive-PushoverSound