github.com/dim13/unifi@v0.0.0-20230308161331-9b04946f5e93/vouchers.go (about) 1 // Copyright (c) 2014 The unifi Authors. All rights reserved. 2 // Use of this source code is governed by ISC-style license 3 // that can be found in the LICENSE file. 4 5 package unifi 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "io" 11 "log" 12 "net/url" 13 "reflect" 14 ) 15 16 type VoucherMap map[string]Voucher 17 18 type Voucher struct { 19 u *Unifi 20 AdminName string `json:"admin_name"` 21 Code string 22 CreateTime int `json:"create_time"` 23 Duration int 24 ForHotspot bool `json:"for_hotspot"` 25 Note string 26 QosOverwrite bool `json:"qos_overwrite"` 27 Quota int 28 SiteID string `json:"site_id"` 29 Used int 30 } 31 32 type NewVoucher struct { 33 Cmd string `json:"cmd"` 34 Expire string `json:"expire"` 35 ExpireNumber string `json:"expire_number"` 36 ExpireUnit string `json:"expire_unit"` 37 N string `json:"n"` 38 Note string `json:"note"` 39 Quota string `json:"quota"` 40 } 41 42 // Value with parameters for create New Voucher 43 var Nv NewVoucher 44 45 func (u *Unifi) Voucher(site *Site) ([]Voucher, error) { 46 var response struct { 47 Data []Voucher 48 Meta meta 49 } 50 err := u.parse(site, "stat/voucher", nil, &response) 51 for i := range response.Data { 52 response.Data[i].u = u 53 } 54 55 return response.Data, err 56 } 57 58 func (u *Unifi) VoucherMap(site *Site) (VoucherMap, error) { 59 vouch, err := u.Voucher(site) 60 if err != nil { 61 return nil, err 62 } 63 m := make(VoucherMap) 64 for _, a := range vouch { 65 m[a.Code] = a 66 } 67 return m, nil 68 } 69 70 //Functions creating new Vouchers 71 72 func (u *Unifi) NewVoucher(site *Site, nv NewVoucher) ([]Voucher, error) { 73 var response struct { 74 Data []Voucher 75 Meta meta 76 } 77 78 Nv = nv 79 err := u.parseNewVoucher(site, "cmd/hotspot", &response) 80 return response.Data, err 81 82 } 83 84 func (u *Unifi) apicmdNewVoucher(site *Site, cmd string) ([]byte, error) { 85 jsonData := Nv 86 87 // Setup url 88 cmdurl := u.apiURL 89 cmdurl += fmt.Sprintf("s/%s/%s", site.Name, cmd) 90 91 data, err := json.Marshal(jsonData) 92 93 if err != nil { 94 return nil, err 95 } 96 val := url.Values{"json": {string(data)}} 97 98 resp, err := u.client.PostForm(cmdurl, val) 99 100 if err != nil { 101 return nil, err 102 } 103 104 defer resp.Body.Close() 105 body, err := io.ReadAll(resp.Body) 106 107 if err != nil { 108 return nil, err 109 } 110 111 return body, nil 112 } 113 114 func (u *Unifi) parseNewVoucher(site *Site, cmd string, v any) error { 115 body, err := u.apicmdNewVoucher(site, cmd) 116 if err != nil { 117 return err 118 } 119 if err := json.Unmarshal(body, &v); err != nil { 120 log.Println(cmd) 121 log.Println(string(body)) 122 return err 123 } 124 m := reflect.ValueOf(v).Elem().FieldByName("Meta").Interface().(meta) 125 if m.Rc != "ok" { 126 return fmt.Errorf("bad request: %s", m.Rc) 127 } 128 return nil 129 }