PushoverForPS.psm1

#For help Get-Help PushoverForPS

#region Utility Functions and variables

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

#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 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 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
    };
};
'@

#endregion

#region Messages API

Function Send-Pushover {
    <#
    .SYNOPSIS
    Sends data to the Pushover API
 
    .DESCRIPTION
    Send-Pushover 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 Receive-PushoverSound 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.
 
    .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.
 
    .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."
            return
        }
        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."
                return
            }
            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.
 
    .PARAMETER Poll
    Specifies that the commmand should poll the Pushover API at the interval specified in the Interval parameter until the Emergency notification has been acknowledged. This is a blocking procedure by itself. To create a background job, use the AsJob parameter in conjunction with Poll to return immediate control to the console.
 
    .PARAMETER Interval
    Specifies how often the Pushover API should be polled (in seconds) until the Emergency notification is acknowledged. The minimum value and default is 5 seconds. This is in accordance with the Pushover API which does not allow identical requests within 5 seconds of each other.
 
    .PARAMETER JobName
    The name to give to the background job when the AsJob parameter is used.
 
    .PARAMETER AsJob
    Specifies that the command should be run as a background job. Use this in conjunction with the Poll parameter to poll the Pushover API without blocking the console. Use Receive-Job to get the results of the command when it has completed.
 
    .INPUTS
    System.Object
 
 
    You can pipe objects to Receive-PushoverReceipt that have properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject or System.Management.Automation.PSRemotingJob
 
 
    When you use the AsJob parameter Receive-PushoverReceipt returns a job object. Otherwise, Receive-PushoverReceipt returns a PSCustomObject with Pushover's details about the Emergency notification.
 
    .EXAMPLE
    PS C:\> Receive-PushoverReceipt -AppToken <token string> -Receipt <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.
    .EXAMPLE
    PS C:\> $obj = New-Object psobject -Args @{AppToken=<token string>; Receipt=<key string>}
    PS C:\> $response = $obj | Receive-PushoverReceipt
 
    The first command creates a custom object that has the properties needed by Receive-PushoverReceipt.
    The second command pipes the custom object to Receive-PushoverReceipt and stores the result.
    .EXAMPLE
    PS C:\> $obj = New-Object psobject -Args @{AppToken=<token string>; Receipt=<key string>}
    PS C:\> $job = $obj | Receive-PushoverReceipt -Poll -AsJob
    PS C:\> Receive-Job $job
 
    The first command creates a custom object that has the properties needed by Receive-PushoverReceipt.
    The second command pipes the custom object to Receive-PushoverReceipt and specifies that it should poll the Pushover API every five seconds (the minimum allowed and the default value) as a background job and stores the returned job object.
    The third command retrieves the Pushover API data from the job once it has completed. It has completed when the Emergency notification is acknowledged by the user.
    .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',
        DefaultParameterSetName="Normal"
    )]

    Param(
        [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Normal")]
        [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Poll")]
            [String]$AppToken,
        
        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Normal")]
        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="Poll")]
            [String]$Receipt,

        [Parameter(Mandatory=$true,ParameterSetName="Poll")]
            [Switch]$Poll,

        [Parameter(ParameterSetName="Poll")]
            [Int]$Interval=5,

        [Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName="Poll")]
            [String]$JobName,

        [Parameter(ParameterSetName="Poll")]
            [Switch]$AsJob
    )
    
    Begin {
        if ($Interval -lt 5) {
            Write-Error "The Pushover API does not allow identical calls to be within 5 seconds of each other. Please set the Interval to 5 or greater."
            return
        }
    }

    Process {
        if ($AsJob) {
            if ($JobName) {
                
                #Check that a job with JobName doesn't already exist. Encourage use of JobName property on passed objects to avoid the issue
                if (Get-Job -Name $JobName -ea SilentlyContinue) {
                    Write-Error "There is already a job with that name. If objects are being passed on the pipeline and the JobName parameter is being used, the passed objects should include a unique JobName property."
                    return
                }
                #JobName doesn't exist, start a new job using the command
                else { 
                    Write-Verbose "Starting background job"
                    Start-Job -InitializationScript $initialize -ScriptBlock {
                            Param($AppToken, $Receipt, $Interval, $ModuleRoot)
                            #The module has to be imported in the job's scope
                            #First attempt to import as if it is installed
                            #If that fails import using the script root path
                            if (Import-Module PushoverForPS -PassThru -ea SilentlyContinue) {
                                Write-Verbose "Importing Module in job successful."
                            }
                            else {
                                Import-Module $ModuleRoot
                            }
                            Receive-PushoverReceipt -AppToken $AppToken -Receipt $Receipt -Poll -Interval $Interval
                        } -ArgumentList $AppToken, $Receipt, $Interval, $PSScriptRoot -Name $JobName
                }
            }
            #JobName not used, just return job object with default assigned name
            else {
                Write-Verbose "Starting background job"
                Start-Job -InitializationScript $initialize -ScriptBlock {
                        Param($AppToken, $Receipt, $Interval, $ModuleRoot)
                        #The module has to be imported in the job's scope
                        #First attempt to import as if it is installed
                        #If that fails import using the script root path
                        if (Import-Module PushoverForPS -PassThru -ea SilentlyContinue) {
                            Write-Verbose "Importing Module in job successful."
                        }
                        else {
                            Import-Module $ModuleRoot
                        }
                        Receive-PushoverReceipt -AppToken $AppToken -Receipt $Receipt -Poll -Interval $Interval
                    } -ArgumentList $AppToken, $Receipt, $Interval, $PSScriptRoot
            }
        }
        #No job desired, run the command as normal
        else {
            #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."
                return
            }
            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
                }

                #If polling is desired call the function again recursively, but do not use the Poll or AsJob parameters.
                #Polling interval has already been checked in Begin block.
                if ($Poll) {
                    #Create object to pipe to recursive command
                    $obj = New-Object psobject -Property @{AppToken=$AppToken; Receipt=$Receipt}
                    #Use do..while so that the polling interval is used on the first polling cycle for Pushover API conformity
                    do {
                        Start-Sleep -Seconds $Interval
                        $pollResponse = $obj | Receive-PushoverReceipt
                        if (-not $?) { break }
                    } while (-not $pollResponse.Acknowledged)

                    #When finally acknowledged, output acknowledged response
                    $pollResponse
                }
                else {
                    #Placing the output here will stop the poll from outputting on every polling cycle
                    $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 {
                #Skip adding to history when recursion ends. This has already been done in the last recursive call
                if ($pollResponse -eq $null) {
                    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 Stop-PushoverRetry 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.
    .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."
            return
        }
        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} }
    }
}

#endregion

#region Groups API

Function Receive-PushoverGroup {
    <#
    .SYNOPSIS
    Receives information about Pushover groups.
 
    .DESCRIPTION
    Receive-PushoverGroup receives information about the group specified to the GroupKey parameter using the application specified by the AppToken parameter. Each response will contain an object that has a Users property containing an array with each user as an object containing user, device, memo, and disabled properties.
 
    Delivery groups are used by Pushover to send notifications to multiple users at once that are attached to the group and enabled. For example, when using Send-Pushover, a group key can be used in place of the user key, and the message will be sent to all members of the group.
 
    The group key and application token used must be a part of the same account in order to use the Pushover Groups API.
    .PARAMETER AppToken
    The token of the application to use to send the request to Pushover.
     
    .PARAMETER GroupKey
    The key of the Pushover group to receive information about.
 
    .INPUTS
    System.Object
 
 
    You can pipe Objects to Receive-PushoverGroup with properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Receive-PushoverGroup returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Receive-PushoverGroup -AppToken <token string> -GroupKey <key string>
 
    This command will retrieve the information of the group specifed by the unique group key string using the application specifed by the unique app token string.
    .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)]
            [String]$GroupKey
    )

    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$GroupKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The 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 group key and app token are formatted correctly." }

        #Request to send to Pushover
        $RequestURL = "https://api.pushover.net/1/groups/$GroupKey.json"
        #Hash to compare to previous requests and store in the history
        $HistoryEntry = @{URL=$RequestURL;token=$AppToken}

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

        Write-Verbose "Sending data to Pushover"
        try {
            #Send to Pushover and return the response if successful
            $response = Invoke-RestMethod -Uri "$($RequestURL)?token=$AppToken" -Method Get -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 $HistoryEntry }
    }
}

Function Add-PushoverUserToGroup {
    <#
    .SYNOPSIS
    Adds users to Pushover groups.
 
    .DESCRIPTION
    Add-PushoverUserToGroup adds pushover users specified by their user key to delivery groups specified by their group key using the application given as its app token. There is an optional Device parameter to restrict delivery to just the device specified, and you can also use the Memo parameter to associate any other data desired with the user: name, email, etc. Memo is limited to 200 characters.
 
    Delivery groups are used by Pushover to send notifications to multiple users at once that are attached to the group and enabled. For example, when using Send-Pushover, a group key can be used in place of the user key, and the message will be sent to all members of the group.
 
    The group key and application token used must be a part of the same account in order to use the Pushover Groups API.
    .PARAMETER AppToken
    The token of the application to use to send the request to Pushover.
     
    .PARAMETER GroupKey
    The key of the Pushover group to add the user to.
 
    .PARAMETER UserKey
    The key of the Pushover user to add to the group.
 
    .PARAMETER Device
    The name of the device to restrict delivery to. Leaving this blank will send to all of a user's active devices.
 
    .PARAMETER Memo
    A place to put associated data about the user. Name, email, or any other data desired. Limited to 200 characters.
 
    .INPUTS
    System.Object
 
 
    You can pipe Objects to Add-PushoverUserToGroup with properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Add-PushoverUserToGroup returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Add-PushoverUserToGroup -AppToken <token string> -GroupKey <key string> -UserKey <key string> -Device "my-device" Memo "John Doe"
 
    This command will add the user associated with the user key to the group specifed by the unique group key string using the application specifed by the unique app token string. Any messages sent to the user through the group will only be received on the device 'my-device', and the data 'John Doe' will also be stored with the user's entry.
    .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)]
            [String]$GroupKey,

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

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

        [Parameter(ValueFromPipelineByPropertyName=$true)]
            [String]$Memo
    )

    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The group key, user 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 group key, 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."
                return
            }
            else {
                Write-Verbose "The device name $Device is formatted correctly."
        
            }
        }

        #Test properties that have character limitations
        if ($Memo.Length -gt 200) { Write-Error "The Memo property is limited to 200 characters."; return }

        #Convert AppToken and UserKey value to token and userAPI specification
        $token = $AppToken
        $user = $UserKey

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

        #Request URL
        $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/add_user.json"

        #Create hashtable from parameters that have value to send to Pushover
        Write-Verbose "Creating data collection to send to Pushover"
        switch ('token', 'user', 'device', 'memo') {
            {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 $PushoverHash.request -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 $PushoverHash }
    }
}

Function Remove-PushoverUserFromGroup {
    <#
    .SYNOPSIS
    Removes users from Pushover groups.
 
    .DESCRIPTION
    Remove-PushoverUserFromGroup removes pushover users specified by their user key from delivery groups specified by their group key using the application given as its app token.
 
    The group key and application token used must be a part of the same account in order to use the Pushover Groups API.
    .PARAMETER AppToken
    The token of the application to use to send the request to Pushover.
     
    .PARAMETER GroupKey
    The key of the Pushover group to remove the user from.
 
    .PARAMETER UserKey
    The key of the Pushover user to remove from the group.
 
    .INPUTS
    System.Object
 
 
    You can pipe Objects to Remove-PushoverUserFromGroup with properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Remove-PushoverUserFromGroup returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Remove-PushoverUserFromGroup -AppToken <token string> -GroupKey <key string> -UserKey <key string>
 
    This command will remove the user associated with the user key from the group specifed by the unique group key string using the application specifed by the unique app token string.
    .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)]
            [String]$GroupKey,

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

    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The group key, user 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 group key, user key, and app token are formatted correctly." }

        #Convert AppToken and UserKey value to token and userAPI specification
        $token = $AppToken
        $user = $UserKey

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

        #Request URL
        $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/delete_user.json"

        #Create hashtable from parameters that have value to send to Pushover
        Write-Verbose "Creating data collection to send to Pushover"
        switch ('token', 'user') {
            {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 $PushoverHash.request -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 $PushoverHash }
    }
}

Function Disable-PushoverUser {
    <#
    .SYNOPSIS
    Disables users in Pushover groups.
 
    .DESCRIPTION
    Disable-PushoverUser disables pushover users specified by their user key in delivery groups specified by their group key using the application given as its app token.
 
    The group key and application token used must be a part of the same account in order to use the Pushover Groups API.
    .PARAMETER AppToken
    The token of the application to use to send the request to Pushover.
     
    .PARAMETER GroupKey
    The key of the Pushover group to disable the user in.
 
    .PARAMETER UserKey
    The key of the Pushover user to disable in the group.
 
    .INPUTS
    System.Object
 
 
    You can pipe Objects to Disable-PushoverUser with properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Disable-PushoverUser returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Disable-PushoverUser -AppToken <token string> -GroupKey <key string> -UserKey <key string>
 
    This command will disable the user associated with the user key in the group specifed by the unique group key string using the application specifed by the unique app token string.
    .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)]
            [String]$GroupKey,

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

    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The group key, user 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 group key, user key, and app token are formatted correctly." }

        #Convert AppToken and UserKey value to token and userAPI specification
        $token = $AppToken
        $user = $UserKey

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

        #Request URL
        $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/disable_user.json"

        #Create hashtable from parameters that have value to send to Pushover
        Write-Verbose "Creating data collection to send to Pushover"
        switch ('token', 'user') {
            {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 $PushoverHash.request -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 $PushoverHash }
    }
}

Function Enable-PushoverUser {
    <#
    .SYNOPSIS
    Enables users in Pushover groups.
 
    .DESCRIPTION
    Enable-PushoverUser enables pushover users specified by their user key in delivery groups specified by their group key using the application given as its app token.
 
    The group key and application token used must be a part of the same account in order to use the Pushover Groups API.
    .PARAMETER AppToken
    The token of the application to use to send the request to Pushover.
     
    .PARAMETER GroupKey
    The key of the Pushover group to enable the user in.
 
    .PARAMETER UserKey
    The key of the Pushover user to enable in the group.
 
    .INPUTS
    System.Object
 
 
    You can pipe Objects to Enable-PushoverUser with properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Enable-PushoverUser returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Enable-PushoverUser -AppToken <token string> -GroupKey <key string> -UserKey <key string>
 
    This command will enable the user associated with the user key in the group specifed by the unique group key string using the application specifed by the unique app token string.
    .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)]
            [String]$GroupKey,

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

    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$GroupKey,$UserKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The group key, user 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 group key, user key, and app token are formatted correctly." }

        #Convert AppToken and UserKey value to token and userAPI specification
        $token = $AppToken
        $user = $UserKey

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

        #Request URL
        $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/enable_user.json"

        #Create hashtable from parameters that have value to send to Pushover
        Write-Verbose "Creating data collection to send to Pushover"
        switch ('token', 'user') {
            {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 $PushoverHash.request -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 $PushoverHash }
    }
}

Function Rename-PushoverGroup {
    <#
    .SYNOPSIS
    Renames Pushover groups.
 
    .DESCRIPTION
    Rename-PushoverGroup renames delivery groups specified by their group key to the name in the NewName parameter using the application given as its app token.
 
    Note that only one group with a particular name may exist on an account.
 
    The group key and application token used must be a part of the same account in order to use the Pushover Groups API.
    .PARAMETER AppToken
    The token of the application to use to send the request to Pushover.
     
    .PARAMETER GroupKey
    The key of the Pushover group to rename.
 
    .PARAMETER NewName
    The new name for the group.
 
    .INPUTS
    System.Object
 
 
    You can pipe Objects to Rename-PushoverGroup with properties that match the desired parameters.
 
    .OUTPUTS
    System.Management.Automation.PSCustomObject
 
 
    Rename-PushoverGroup returns a PSCustomObject with Pushover's response.
 
    .EXAMPLE
    PS C:\> Rename-PushoverGroup -AppToken <token string> -GroupKey <key string> -NewName "My New Group Name"
 
    This command will rename the group specifed by the unique group key string to the name "My New Group Name" using the application specifed by the unique app token string.
    .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)]
            [String]$GroupKey,

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

    Process {
        #Test that the receipt, and the app token match the Pushover API specification
        if (($AppToken,$GroupKey -notmatch '^[a-zA-Z\d]{30}$').Count -gt 0) {
            Write-Error "The 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 group key and app token are formatted correctly." }

        #Convert AppToken and NewName value to token and name per API specification
        $token = $AppToken
        $name = $NewName

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

        #Request URL
        $PushoverHash.request = "https://api.pushover.net/1/groups/$GroupKey/rename.json"

        #Create hashtable from parameters that have value to send to Pushover
        Write-Verbose "Creating data collection to send to Pushover"
        switch ('token', 'name') {
            {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 $PushoverHash.request -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 $PushoverHash }
    }
}

#endregion

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
New-Alias -Name rcpg -Value Receive-PushoverGroup
New-Alias -Name apug -Value Add-PushoverUserToGroup
New-Alias -Name rpug -Value Remove-PushoverUserFromGroup
New-Alias -Name dbpu -Value Disable-PushoverUser
New-Alias -Name enpu -Value Enable-PushoverUser
New-Alias -Name rnpg -Value Rename-PushoverGroup