-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPushBulletWebSocket.ps1
More file actions
93 lines (63 loc) · 2.88 KB
/
PushBulletWebSocket.ps1
File metadata and controls
93 lines (63 loc) · 2.88 KB
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
#Set here you access token from Pushbullet https://www.pushbullet.com/#settings "Create access token"
$token = "YOUR_TOKEN_HERE"
#Set this to "Continue" to get more verbose logs
$verbosepreference = "Continue"
Function WaitFor-SocketMessages {
#Web API call starts the session and gets a websocket URL to use.
$url = "wss://stream.pushbullet.com/websocket/$token"
Try{
Do{
$WS = New-Object System.Net.WebSockets.ClientWebSocket
$CT = New-Object System.Threading.CancellationToken
$Conn = $WS.ConnectAsync($url, $CT)
While (!$Conn.IsCompleted) {
Start-Sleep -Milliseconds 100
}
write-Host "Connected to Pushbullet, waiting for stream events..."
$Size = 1024
$Array = [byte[]] @(,0) * $Size
$Recv = New-Object System.ArraySegment[byte] -ArgumentList @(,$Array)
While ($WS.State -eq 'Open') {
$RTM = ""
Do {
$Conn = $WS.ReceiveAsync($Recv, $CT)
While (!$Conn.IsCompleted) {
Start-Sleep -Milliseconds 100 }
$Recv.Array[0..($Conn.Result.Count - 1)] | ForEach-Object { $RTM = $RTM + [char]$_ }
} Until ($Conn.Result.Count -lt $Size)
write-verbose "Response: $RTM"
If ($RTM){
try {
handleMessage (ConvertFrom-Json $RTM)
} catch {
write-error "Unable to handle message $_"
}
}
}
} Until (!$Conn)
}Finally{
If ($WS) {
Write-Verbose "Closing websocket"
$WS.Dispose()
}
}
}
function HandleMessage ($msg) {
switch ($msg) {
{ $_.type -eq "nop"} {write-verbose "ping-pong"}
{ $_.type -eq "tickle" -and $_.subtype -eq "push"} {
$lastPushes = ""
$lastPushes = ((Invoke-WebRequest -Uri "https://api.pushbullet.com/v2/pushes?active=true" -Headers @{'Access-Token' = $token} -Method Get).Content | ConvertFrom-Json).pushes
foreach ($lastPush in $lastPushes) {
if ($lastPush.title -eq "PSScript") {
$lastPushID = $lastPush.iden
$command = $lastPush.body
$deleteresp = Invoke-WebRequest -Uri "https://api.pushbullet.com/v2/pushes/$lastPushID" -Headers @{'Access-Token' = $token} -Method Delete
Write-Host "Executing: $command"
Invoke-Expression $command
}
}
}
}
}
WaitFor-SocketMessages