/
poclient.go
288 lines (228 loc) · 6.79 KB
/
poclient.go
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
package poclient
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
)
const LIBRARY_NAME string = "go-poclient"
const LIBRARY_VERSION string = "1.2.0"
// Client represents the main Pushover Client.
// The Messages channel works in conjunction with ListenForNotifications,
// which pushes incoming Messages into this channel.
type Client struct {
loggedIn bool
registered bool
user user
device device
wsConn *websocket.Conn
Messages chan Message
appName string
appVersion string
}
// New creates a new POClient with default values
func New() *Client {
return &Client{
loggedIn: false,
registered: false,
user: user{},
device: device{},
wsConn: nil,
Messages: make(chan Message, 32),
appName: "DefaultApp",
appVersion: "NoVersionString",
}
}
// User returns user id and user secret
func (p Client) User() (userID string, secret string) {
return p.user.ID, p.user.Secret
}
// Device returns the device ID
func (p Client) Device() string {
return p.device.ID
}
// RestoreLogin sets user ID and secret to access the API from a previous login
func (p *Client) RestoreLogin(secret string, userid string) {
p.user.Secret = secret
p.user.ID = userid
p.loggedIn = true
}
// RestoreDevice sets device ID from a previous device registration
func (p *Client) RestoreDevice(devid string) {
p.device.ID = devid
p.registered = true
}
// GetStatus returns the login and registration status
func (p *Client) GetStatus() (bool, bool) {
return p.loggedIn, p.registered
}
// SetAppInfo sets information about the calling app, which is sent with every request
// so that pushover can identify the applications using their API
func (p *Client) SetAppInfo(appName string, appVersion string) {
p.appName = appName
p.appVersion = appVersion
}
// RegisterDevice registers a new device after logging in.
// The name parameter is a human readable short name (up to 25 characters long) for the device.
// After successfully registering the device you should retrieve the device_id by calling Device()
// and store it in a safe place.
func (p *Client) RegisterDevice(name string) error {
if !p.loggedIn {
return errors.New("Not logged in")
}
if p.registered {
return errors.New("Already registered")
}
if len(name) > 25 {
return errors.New("Name is too long")
}
resp, err := p.SendRequest("https://api.pushover.net/1/devices.json", url.Values{"secret": {p.user.Secret}, "name": {name}, "os": {"O"}})
if err != nil {
return err
}
defer resp.Body.Close()
reply := devicesReply{}
err = json.NewDecoder(resp.Body).Decode(&reply)
if err != nil {
return err
}
if reply.Status == 0 {
errorMessage := ""
for errorType, messages := range reply.Errors {
for _, errMsg := range messages {
errorMessage += fmt.Sprintf("%s %s, ", errorType, errMsg)
}
}
return errors.New(errorMessage)
}
p.device.ID = reply.Deviceid
p.registered = true
return nil
}
// Login retrieves user id and user secret.
// After successfully logging, you should retrieve the user id and secret by calling User() and store
// them somewhere safe.
func (p *Client) Login(email string, password string) error {
if p.loggedIn {
return errors.New("Already logged in")
}
resp, err := p.SendRequest("https://api.pushover.net/1/users/login.json", url.Values{"email": {email}, "password": {password}})
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == 412 {
return &Missing2FAError{}
}
reply := loginReply{}
err = json.NewDecoder(resp.Body).Decode(&reply)
if err != nil {
return err
}
if reply.Status == 0 {
return errors.New(reply.Errors[0])
}
p.user.Secret = reply.Secret
p.user.ID = reply.Userid
p.loggedIn = true
p.registered = false
return nil
}
func (p *Client) Login2FA(email string, password string, twofacode string) error {
if p.loggedIn {
return errors.New("Already logged in")
}
resp, err := p.SendRequest("https://api.pushover.net/1/users/login.json", url.Values{"email": {email}, "password": {password}, "twofa": {twofacode}})
if err != nil {
return err
}
defer resp.Body.Close()
reply := loginReply{}
err = json.NewDecoder(resp.Body).Decode(&reply)
if err != nil {
return err
}
if reply.Status == 0 {
return errors.New(reply.Errors[0])
}
p.user.Secret = reply.Secret
p.user.ID = reply.Userid
p.loggedIn = true
p.registered = false
return nil
}
// GetMessages retrieves all new messages from the API.
// Usually you call DeleteOldMessages right afterwards to clear all pending notifications
func (p Client) GetMessages() ([]Message, error) {
if !p.loggedIn {
return nil, errors.New("Not logged in")
}
if !p.registered {
return nil, errors.New("Device not registered")
}
resp, err := http.Get(fmt.Sprintf("https://api.pushover.net/1/messages.json?secret=%s&device_id=%s", p.user.Secret, p.device.ID))
if err != nil {
return nil, err
}
defer resp.Body.Close()
reply := messagesReply{}
err = json.NewDecoder(resp.Body).Decode(&reply)
if err != nil {
return nil, err
}
if reply.Status != 1 {
return reply.Messages, errors.New("Getting messages led to a status != 1")
}
// parse all timestamps into time.Time
for i, msg := range reply.Messages {
reply.Messages[i].Date = time.Unix(msg.Timestamp, 0)
}
return reply.Messages, nil
}
// DeleteMessagesByID marks all messages below the given relative ID as
// read which means they will not be transmitted again by the API
// https://pushover.net/api/client#delete
func (p Client) DeleteMessagesByID(highestID int) error {
resp, err := p.SendRequest(
fmt.Sprintf("https://api.pushover.net/1/devices/%s/update_highest_message.json", p.device.ID),
url.Values{"secret": {p.user.Secret}, "message": {strconv.Itoa(highestID)}},
)
if err != nil {
return err
}
defer resp.Body.Close()
reply := deleteOldMessagesReply{}
err = json.NewDecoder(resp.Body).Decode(&reply)
if err != nil {
return err
}
if reply.Status == 0 {
return errors.New(reply.Errors[0])
}
return nil
}
// DeleteOldMessages finds the hightest relative ID and calls DeleteMessagesByID
// This action is permanent, so you need to save the messages if you want to keep them
func (p Client) DeleteOldMessages(messages []Message) error {
highestID := 0
for _, msg := range messages {
if msg.RelativeID > highestID {
highestID = msg.RelativeID
}
}
return p.DeleteMessagesByID(highestID)
}
func (p Client) SendRequest(endpoint string, data url.Values) (*http.Response, error) {
req, err := http.NewRequest("POST", endpoint, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", fmt.Sprintf("%s v%s (%s v%s)", p.appName, p.appVersion, LIBRARY_NAME, LIBRARY_VERSION))
return http.DefaultClient.Do(req)
}