forked from RunnerM/simply-com-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
258 lines (231 loc) · 7.9 KB
/
client.go
File metadata and controls
258 lines (231 loc) · 7.9 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
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
package simplyComClient
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"github.com/bobesa/go-domain-util/domainutil"
log "github.com/sirupsen/logrus"
)
const (
apiUrl = "https://api.simply.com/2"
)
type RecordType string
var recordTypes = [...]RecordType{"A", "AAAA", "CNAME", "MX", "NS", "TXT", "SRV", "CAA", "SSHFP", "TLSA", "PTR", "NAPTR", "DS", "DNSKEY", "RRSIG", "SPF", "URI", "ALIAS", "ANAME", "LOC", "HINFO", "RP", "AFSDB", "CERT", "DNAME", "KEY", "KX", "MB", "MG", "MINFO", "MR", "MX", "NAPTR", "NS", "PTR", "SOA", "TXT", "WKS", "X25"}
func validateRecordType(recordType RecordType) bool {
for _, t := range recordTypes {
if t == recordType {
return true
}
}
return false
}
func CreateSimplyClient(accountName string, apiKey string) SimplyClient {
return SimplyClient{
Credentials{
AccountName: accountName,
ApiKey: apiKey,
},
log.New(),
}
}
// SimplyClient base type
type SimplyClient struct {
Credentials Credentials `json:"credentials"`
Logger *log.Logger
}
// RecordResponse api type
type RecordResponse struct {
Records []struct {
RecordId int `json:"record_id"`
Name string `json:"name"`
Ttl int `json:"ttl"`
Data string `json:"data"`
Type string `json:"type"`
Priority int `json:"priority"`
} `json:"records"`
Status int `json:"status"`
Message string `json:"message"`
}
// CreateUpdateRecordBody api type
type CreateUpdateRecordBody struct {
Type RecordType `json:"type"`
Name string `json:"name"`
Data string `json:"data"`
Priority int `json:"priority"`
Ttl int `json:"ttl"`
}
// CreateRecordResponse api type
type CreateRecordResponse struct {
Record struct {
Id int `json:"id"`
} `json:"record"`
Status int `json:"status"`
Message string `json:"message"`
}
type Credentials struct {
AccountName string `json:"status"`
ApiKey string `json:"message"`
}
// AddRecord Add record to simply
func (c *SimplyClient) AddRecord(FQDNName string, Value string, recordType RecordType) (int, error) {
if !validateRecordType(recordType) {
log.Errorln("invalid record type: ", recordType)
return 0, errors.New("invalid record type")
}
// Trim one trailing dot
fqdnName := cutTrailingDotIfExist(FQDNName)
TXTRecordBody := CreateUpdateRecordBody{
Type: recordType,
Name: domainutil.Subdomain(fqdnName),
Data: Value,
Priority: 1,
Ttl: 3600,
}
postBody, _ := json.Marshal(TXTRecordBody)
req, err := http.NewRequest("POST", apiUrl+"/my/products/"+domainutil.Domain(fqdnName)+"/dns/records", bytes.NewBuffer(postBody))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
req.SetBasicAuth(c.Credentials.AccountName, c.Credentials.ApiKey)
client := &http.Client{}
response, err := client.Do(req)
if err != nil || response.StatusCode != 200 {
log.Errorln("Failed request, response: ", response.StatusCode)
return 0, err
}
responseData, err := io.ReadAll(response.Body)
if err != nil {
log.Errorln("Failed to read body with error: ", err)
return 0, err
}
var data CreateRecordResponse
err = json.Unmarshal(responseData, &data)
if err != nil {
log.Errorln("Failed to unmarshal body with error: ", err)
return 0, err
}
return data.Record.Id, nil
}
// RemoveRecord Remove record from simply
func (c *SimplyClient) RemoveRecord(RecordId int, DnsName string) bool {
dnsName := cutTrailingDotIfExist(DnsName)
req, err := http.NewRequest("DELETE", apiUrl+"/my/products/"+domainutil.Domain(dnsName)+"/dns/records/"+strconv.Itoa(RecordId), nil)
req.SetBasicAuth(c.Credentials.AccountName, c.Credentials.ApiKey)
client := &http.Client{}
response, err := client.Do(req)
if err != nil || response.StatusCode != 200 {
log.Errorln("Failed request, response code: ", response.StatusCode)
return false
}
return true
}
// GetRecord Fetch record by FQDNName, RecordData and RecordType,TTL and priority are ignored, returns id of first record found.
func (c *SimplyClient) GetRecord(FQDNName string, RecordData string, recordType RecordType) (int, string, error) {
fqdnName := cutTrailingDotIfExist(FQDNName)
responseData, err2, failed := getRecords(fqdnName, c)
if failed {
return 0, "", err2
}
var records RecordResponse
err := json.Unmarshal(responseData, &records)
if err == nil {
for i := 0; i < len(records.Records); i++ {
if records.Records[i].Data == RecordData && records.Records[i].Type == string(recordType) && records.Records[i].Name == domainutil.Subdomain(fqdnName) {
return records.Records[i].RecordId, records.Records[i].Data, nil
}
}
if RecordData == "" {
for i := 0; i < len(records.Records); i++ {
if records.Records[i].Type == string(recordType) && records.Records[i].Name == domainutil.Subdomain(fqdnName) {
return records.Records[i].RecordId, records.Records[i].Data, nil
}
}
}
log.Errorln("Record not found")
return 0, "", errors.New("record not found")
} else {
log.Errorln("Failed to unmarshal body with error: ", err)
return 0, "", err
}
}
// GetRecords Fetch records by FQDNName returns id
func (c *SimplyClient) GetRecords(FQDNName string) (string, error) {
fqdnName := cutTrailingDotIfExist(FQDNName)
responseData, err2, failed := getRecords(fqdnName, c)
if failed {
return "", err2
}
return string(responseData), nil
}
func getRecords(fqdnName string, c *SimplyClient) ([]byte, error, bool) {
req, err := http.NewRequest("GET", apiUrl+"/my/products/"+domainutil.Domain(fqdnName)+"/dns/records", nil)
req.SetBasicAuth(c.Credentials.AccountName, c.Credentials.ApiKey)
client := &http.Client{}
response, err := client.Do(req)
if err != nil || response.StatusCode != 200 {
log.Errorln("Failed request, response code: ", response.StatusCode)
return nil, err, true
}
responseData, err := io.ReadAll(response.Body)
if err != nil {
log.Errorln("Error on read: ", err)
return nil, err, true
}
return responseData, nil, false
}
// UpdateRecord Update record by RecordId, FQDNName, Value and RecordType
func (c *SimplyClient) UpdateRecord(RecordId int, FQDNName string, Value string, recordType RecordType) (bool, error) {
if !validateRecordType(recordType) {
log.Errorln("Invalid record type: ", recordType)
return false, errors.New("invalid record type")
}
// Trim one trailing dot
fqdnName := cutTrailingDotIfExist(FQDNName)
TXTRecordBody := CreateUpdateRecordBody{
Type: recordType,
Name: domainutil.Subdomain(fqdnName),
Data: Value,
Priority: 1,
Ttl: 3600,
}
putBody, _ := json.Marshal(TXTRecordBody)
req, err := http.NewRequest("PUT", apiUrl+"/my/products/"+domainutil.Domain(fqdnName)+"/dns/records/"+strconv.Itoa(RecordId), bytes.NewBuffer(putBody))
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
req.SetBasicAuth(c.Credentials.AccountName, c.Credentials.ApiKey)
client := &http.Client{}
response, err := client.Do(req)
if err != nil || response.StatusCode != 200 {
log.Errorln("Failed request, response code: ", response.StatusCode)
return false, err
}
return true, nil
}
// DDNS update/create record if Ip omited Simply api will use client IP
func (c *SimplyClient) UpdateDDNS(FQDNName string, Ip string) (bool, error) {
fqdnName := cutTrailingDotIfExist(FQDNName)
domain := domainutil.Domain(fqdnName)
path := ""
if Ip == "" {
path = "/ddns/?domain="+ domain+ "&hostname=" + fqdnName
} else {
path = "/ddns/?domain="+ domain+ "&hostname=" + fqdnName + "&myip=" + Ip
}
//body, _ := json.Marshal("")
req, err := http.NewRequest("POST", apiUrl+path, nil)
req.SetBasicAuth(c.Credentials.AccountName, c.Credentials.ApiKey)
client := &http.Client{}
response, err := client.Do(req)
if err != nil || response.StatusCode != 200 {
log.Errorln("Failed request, response code: ", response.StatusCode)
return false, err
}
return true, nil
}
func cutTrailingDotIfExist(FQDNName string) string {
fqdnName := FQDNName
if last := len(fqdnName) - 1; last >= 0 && fqdnName[last] == '.' {
fqdnName = fqdnName[:last]
}
return fqdnName
}