PushoverForPS.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
#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 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 (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