-
Notifications
You must be signed in to change notification settings - Fork 0
/
unifi.go
396 lines (326 loc) · 9.98 KB
/
unifi.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
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
package unifi
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
)
const (
defaultSite = "default"
)
var (
debugMode = false
rawURLs = map[string]string{
"login": "/api/login",
"logout": "/api/logout",
"stamgr": "/api/s/$site/cmd/stamgr",
}
)
// Unifi provides functions to call Unifi APIs.
type Unifi struct {
userName string
password string
baseURL *url.URL
urls map[string]*url.URL
jar *cookiejar.Jar
}
// SetDebugMode sets debug mode for package unifi.
func SetDebugMode(f bool) {
debugMode = f
}
// IsDebugMode returns if it's in debug mode or not.
func IsDebugMode() bool {
return debugMode
}
// logFnResult outputs the result of the function.
//
// params:
// funcName: function name.
// err: result of function.
func logFnResult(funcName string, err error) {
if !debugMode {
return
}
if err != nil {
log.Printf("%v() error: %v", funcName, err)
return
}
log.Printf("%v() ok", funcName)
}
// New creates a new Unifi.
//
// Params:
// unifiURL: Unifi Controller's URL. E.g. https://10.0.1.100:8443
// userName: User name of Unifi Controller.
// password: Password of Unifi Controller.
func New(unifiURL, userName, password string) (*Unifi, error) {
var err error
defer logFnResult("New", err)
u := &Unifi{}
if u.baseURL, err = url.Parse(unifiURL); err != nil {
err = fmt.Errorf("Parse Unifi URL error: %v", err)
return u, err
}
u.urls = map[string]*url.URL{}
for k, v := range rawURLs {
refURL, _ := url.Parse(v)
u.urls[k] = u.baseURL.ResolveReference(refURL)
}
u.userName = userName
u.password = password
if u.jar, err = cookiejar.New(nil); err != nil {
err = fmt.Errorf("cookiejar.New() error: %v", err)
return u, err
}
return u, err
}
// ParseJSON parses the JSON returned by Unifi APIs.
//
// Params:
// b: Bytes returned by Unifi APIs which contains JSON string.
// Return:
// map[string]interface{} as parsed JSON object.
// true or false if "rc" is "ok".
func ParseJSON(b []byte) (map[string]interface{}, bool, error) {
var err error
m := map[string]interface{}{}
defer logFnResult("ParseJSON", err)
if err = json.Unmarshal(b, &m); err != nil {
err = fmt.Errorf("json.Unmarshal() error: %v", err)
return m, false, err
}
if _, ok := m["meta"]; !ok {
err = fmt.Errorf("'meta' does not exist in returned JSON.")
return m, false, err
}
meta, ok := m["meta"].(map[string]interface{})
if !ok {
err = fmt.Errorf("meta type: %T, can't convert meta to map[string]interface{}", m["meta"])
return m, false, err
}
rc, ok := meta["rc"].(string)
if !ok {
err = fmt.Errorf("rc type: %T, can't convert rc to string", meta["rc"])
return m, false, err
}
return m, rc == "ok", err
}
// Do does the HTTP request for Unifi API.
//
// Params:
// r: *http.Request.
// readRespBody: if read response body or not.
// it will return the response body if it's true or return nil if it's false.
// Return:
// response body if readRespBody is true.
func (u *Unifi) Do(r *http.Request, readRespBody bool) ([]byte, error) {
var err error
var b []byte
tr := &http.Transport{
// Skip cert verify.
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr, Jar: u.jar}
resp, err := client.Do(r)
if err != nil {
err = fmt.Errorf("client.Do() error: %v", err)
return b, err
}
defer resp.Body.Close()
if readRespBody {
if b, err = ioutil.ReadAll(resp.Body); err != nil {
err = fmt.Errorf("ReadAll() error: %v", err)
return b, err
}
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("response status code: %v", resp.StatusCode)
return b, err
}
respCookies := resp.Cookies()
// Set cookie for cookiejar manually.
u.jar.SetCookies(u.baseURL, respCookies)
return b, err
}
// Login logins Unifi Controller.
//
// Params:
// ctx: Parent context. You may use context.Background() to create an empty context.
// See http://godoc.org/context for more info.
func (u *Unifi) Login(ctx context.Context) error {
var err error
defer logFnResult("Login", err)
// POST data is in JSON format.
args := struct {
Username string `json:"username"`
Password string `json:"password"`
}{
u.userName,
u.password,
}
b, err := json.Marshal(args)
if err != nil {
err = fmt.Errorf("json.Marshal() error: %v", err)
return err
}
buf := bytes.NewBuffer(b)
// Login.
r, err := http.NewRequest("POST", u.urls["login"].String(), buf)
if err != nil {
err = fmt.Errorf("NewRequest error: %v", err)
return err
}
// Get a copy of req with its context changed to ctx.
r = r.WithContext(ctx)
r.Header.Set("Accept", "*/*")
r.Header.Set("Content-Type", "application/json")
_, err = u.Do(r, false)
return err
}
// Logout logouts Unifi Controller.
//
// Params:
// ctx: Parent context. You may use context.Background() to create an empty context.
// See http://godoc.org/context for more info.
func (u *Unifi) Logout(ctx context.Context) error {
var err error
defer logFnResult("Logout", err)
// Logout.
// Method: POST.
r, err := http.NewRequest("POST", u.urls["logout"].String(), nil)
if err != nil {
err = fmt.Errorf("NewRequest error: %v", err)
return err
}
// Get a copy of req with its context changed to ctx.
r = r.WithContext(ctx)
r.Header.Set("Accept", "*/*")
_, err = u.Do(r, false)
return err
}
// AuthorizeGuestWithQos authorizes guest by MAC, time and set qos.
//
// Params:
// ctx: Parent context. You may use context.Background() to create an empty context.
// See http://godoc.org/context for more info.
// site: Site name. It's **NOT** the "Site Name"(just description) in Unifi GUI.
// If you only have 1 site. Just use "default" or leave it empty.
// If you've created new sites, follow this to get the site name:
// https://github.com/northbright/Notes/blob/master/Software/unifi/use-compass-to-explore-mongodb-of-unifi/use-compass-to-explore-mongodb-of-unifi.md
// mac: MAC address of guest to be authorized. It's in "aa:bb:cc:dd:ee:ff" format.
// min: Timeout in minutes.
// down: Max download speed in KB.
// up: Max upload speed in KB.
// quota: Quota in MB.
func (u *Unifi) AuthorizeGuestWithQos(ctx context.Context, site, mac string, min, down, up, quota int) error {
var err error
defer logFnResult("AuthorizeGuestWithQos", err)
if site == "" {
site = "default"
}
args := map[string]string{}
args["cmd"] = "authorize-guest"
args["mac"] = mac
args["minutes"] = strconv.Itoa(min)
if down > 0 {
args["down"] = strconv.Itoa(down)
}
if up > 0 {
args["up"] = strconv.Itoa(up)
}
if quota > 0 {
args["bytes"] = strconv.Itoa(quota)
}
b, err := json.Marshal(args)
if err != nil {
err = fmt.Errorf("json.Marshal() error: %v", err)
return err
}
buf := bytes.NewBuffer(b)
urlStr := u.urls["stamgr"].String()
// Replace $site with real site.
urlStr = strings.Replace(urlStr, "$site", site, -1)
if debugMode {
log.Printf("AuthorizeGuestWithQos(): POST URL: %v", urlStr)
log.Printf("AuthorizeGuestWithQos(): POST data: %v", string(b))
}
// Authorize Guest.
r, err := http.NewRequest("POST", urlStr, buf)
if err != nil {
err = fmt.Errorf("NewRequest error: %v", err)
return err
}
// Get a copy of req with its context changed to ctx.
r = r.WithContext(ctx)
r.Header.Set("Accept", "*/*")
r.Header.Set("Content-Type", "application/json")
_, err = u.Do(r, false)
return err
}
// AuthorizeGuest authorizes guest by MAC, time.It's a wrapper of AuthorizeGuestWithQos.
//
// Params:
// ctx: Parent context. You may use context.Background() to create an empty context.
// See http://godoc.org/context for more info.
// site: Site name. It's **NOT** the "Site Name"(just description) in Unifi GUI.
// If you only have 1 site. Just use "default" or leave it empty.
// If you've created new sites, follow this to get the site name:
// https://github.com/northbright/Notes/blob/master/Software/unifi/use-compass-to-explore-mongodb-of-unifi/use-compass-to-explore-mongodb-of-unifi.md
//
// mac: MAC address of guest to be authorized. It's in "aa:bb:cc:dd:ee:ff" format.
// min: Timeout in minutes.
func (u *Unifi) AuthorizeGuest(ctx context.Context, site, mac string, min int) error {
return u.AuthorizeGuestWithQos(ctx, site, mac, min, 0, 0, 0)
}
// UnAuthorizeGuest unauthorizes guest by MAC.
//
// Params:
// ctx: Parent context. You may use context.Background() to create an empty context.
// See http://godoc.org/context for more info.
// site: Site name. It's **NOT** the "Site Name"(just description) in Unifi GUI.
// If you only have 1 site. Just use "default" or leave it empty.
// If you've created new sites, follow this to get the site name:
// https://github.com/northbright/Notes/blob/master/Software/unifi/use-compass-to-explore-mongodb-of-unifi/use-compass-to-explore-mongodb-of-unifi.md
// mac: MAC address of guest to be unauthorized. It's in "aa:bb:cc:dd:ee:ff" format.
func (u *Unifi) UnAuthorizeGuest(ctx context.Context, site, mac string) error {
var err error
defer logFnResult("UnAuthorizeGuest", err)
if site == "" {
site = "default"
}
args := map[string]string{}
args["cmd"] = "unauthorize-guest"
args["mac"] = mac
b, err := json.Marshal(args)
if err != nil {
err = fmt.Errorf("json.Marshal() error: %v", err)
return err
}
buf := bytes.NewBuffer(b)
urlStr := u.urls["stamgr"].String()
// Replace $site with real site.
urlStr = strings.Replace(urlStr, "$site", site, -1)
if debugMode {
log.Printf("UnAuthorizeGuest(): POST URL: %v", urlStr)
log.Printf("UnAuthorizeGuest(): POST data: %v", string(b))
}
// Authorize Guest.
r, err := http.NewRequest("POST", urlStr, buf)
if err != nil {
err = fmt.Errorf("NewRequest error: %v", err)
return err
}
// Get a copy of req with its context changed to ctx.
r = r.WithContext(ctx)
r.Header.Set("Content-Type", "application/json")
_, err = u.Do(r, false)
return err
}