-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiabhttp.go
1659 lines (1478 loc) · 48.2 KB
/
miabhttp.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package miabhttp
import (
"bytes"
"encoding/base32"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
neturl "net/url"
"strconv"
"strings"
"github.com/asaskevich/govalidator"
country "github.com/mikekonan/go-countries"
)
type Context struct {
cServer string // e.g. "box.example.com"
cAPIPath string // Optional, defaults to "admin" during CreateMiabContext() if left as empty str. If you don't want any path, use "/" (since an empty string defaults to "admin"). Using "/" is the only case where you should include the slash in this variable. The context resulting from CreateMiabContext() will never have an empty string, since it will always be "/", "admin", or something else.
cUsername string // Full e-mail, or whatever you normally use to login
cPassword string // This or APIToken must be provided
cAPIToken string // This or password must be provided
cOTPcode string // string of 6-digit 2FA code if needed. NOT THE SECRET. IF YOU NEED A LONG SESSION, USE YOUR 2FA CODE TO LoginAndReturnAPIKey() AND GET AN API token FOR AN INSTANCE OF THIS STRUCT WITHOUT A PASSWORD. DON'T FORGET TO Logout().
}
type MiabError struct {
IsHTTPStatusError bool
HTTPStatusCode int
CallingFunction string
ErrorMsg string
}
func (m MiabError) Error() string {
return m.ErrorMsg
}
func (m MiabError) String() string {
return fmt.Sprintf("MiabError{\n IsHTTPStatusError: %t,\n "+
"HTTPStatusCode: %d,\n "+
"CallingFunction: \"%s\",\n "+
"ErrorMsg: \"%s\",\n}",
m.IsHTTPStatusError, m.HTTPStatusCode, m.CallingFunction, m.ErrorMsg)
}
// See Context struct comments for notes on parameter requirements
func CreateMiabContext(server, apipath, username, password, apitoken, otpcode string) (*Context, error) {
if !govalidator.IsDNSName(server) {
return nil, MiabError{
IsHTTPStatusError: false,
CallingFunction: "CreateMiabContext",
ErrorMsg: "invalid server DNS name",
}
}
if username == "" {
return nil, MiabError{
IsHTTPStatusError: false,
CallingFunction: "CreateMiabContext",
ErrorMsg: "username must not be empty",
}
}
if password == "" && apitoken == "" {
return nil, MiabError{
IsHTTPStatusError: false,
CallingFunction: "CreateMiabContext",
ErrorMsg: "password and API token cannot both be empty",
}
}
if apipath == "" {
apipath = "admin"
}
return &Context{
cServer: server,
cAPIPath: apipath,
cUsername: username,
cPassword: password,
cAPIToken: apitoken,
cOTPcode: otpcode,
}, nil
}
func (c *Context) Server() string {
var valuecopy string = c.cServer
return valuecopy
}
func (c *Context) APIPath() string {
var valuecopy string = c.cAPIPath
return valuecopy
}
func (c *Context) Username() string {
var valuecopy string = c.cUsername
return valuecopy
}
func (c *Context) Password() string {
var valuecopy string = c.cPassword
return valuecopy
}
func (c *Context) APIToken() string {
var valuecopy string = c.cAPIToken
return valuecopy
}
func (c *Context) OTPcode() string {
var valuecopy string = c.cOTPcode
return valuecopy
}
func (c *Context) InsertAPITokenAndDeletePassword(apitoken string) error {
if apitoken == "" {
return MiabError{
IsHTTPStatusError: false,
CallingFunction: "InsertAPITokenAndDeletePassword",
ErrorMsg: "input API token cannot be blank",
}
}
c.cPassword = ""
c.cOTPcode = ""
c.cAPIToken = apitoken
return nil
}
type methodType string
type requestContentType string
type responseContentType string
const (
// Allowed HTTP methods
mGET methodType = "GET"
mPOST methodType = "POST"
mPUT methodType = "PUT"
mDELETE methodType = "DELETE"
// Allowed request content types
ctTextPlain requestContentType = "text/plain"
ctFormData requestContentType = "application/x-www-form-urlencoded"
// Non-erroring response content types
crTextHtml responseContentType = "text/html"
crTextPlain responseContentType = "text/plain"
ctJson responseContentType = "application/json"
)
func checkStatusCode(statuscode int, fn string) error {
x := MiabError{}
x.IsHTTPStatusError = true
x.HTTPStatusCode = statuscode
x.CallingFunction = fn
if statuscode == 400 {
x.ErrorMsg = "400 Bad Request"
} else if statuscode == 401 {
x.ErrorMsg = "401 Unauthorized"
} else if statuscode == 403 {
x.ErrorMsg = "403 Forbidden"
} else if statuscode == 500 {
x.ErrorMsg = "500 Internal Server Error"
} else if statuscode != 200 {
// This message is most likely to be part of a panic, so it is more detailed
x.ErrorMsg = "miabhttp." + fn + "(): Server sent unexpected status code response"
}
// We exclude 404 Not Found, since we control the path. A 404 means the
// upstream API has changed, so the non-200 fallback error message is more
// useful anyway.
if statuscode == 200 {
return nil
}
return x
}
// HTTP request wrapper func to allow me to include a text or
// map[string]interface{} body type, while also sanity checking some basic
// parameters
func (c *Context) makeRequest(method methodType, ct requestContentType, url string, body interface{}, prefer_apitoken bool) (*http.Request, error) {
var req *http.Request
if body != nil {
if ct == ctFormData {
vb := body.(map[interface{}]interface{})
nb := neturl.Values{}
for k, v := range vb {
nb.Add(k.(string), v.(string))
}
req, _ = http.NewRequest(string(method), url, strings.NewReader(nb.Encode()))
if method == mPOST {
req.Header.Set("content-type", string(ctFormData))
}
} else {
b, _ := body.(string)
req, _ = http.NewRequest(string(method), url, bytes.NewBuffer([]byte(b)))
req.Header.Set("content-type", string(ctTextPlain))
}
} else {
req, _ = http.NewRequest(string(method), url, nil)
req.Header.Set("content-type", string(ctFormData))
}
if prefer_apitoken {
if c.cAPIToken != "" {
req.SetBasicAuth(c.Username(), c.APIToken())
} else {
req.SetBasicAuth(c.Username(), c.Password())
if c.cOTPcode != "" {
req.Header.Add("x-auth-token", c.OTPcode())
}
}
} else {
if c.cPassword != "" {
req.SetBasicAuth(c.Username(), c.Password())
if c.cOTPcode != "" {
req.Header.Add("x-auth-token", c.OTPcode())
}
} else {
req.SetBasicAuth(c.Username(), c.APIToken())
}
}
return req, nil
}
func (c *Context) makeUrl(usetls bool) string {
url := "http"
if usetls {
url = url + "s"
}
url = url + "://"
url = url + c.cServer
if c.cAPIPath != "/" {
url = url + "/" + c.cAPIPath
}
return url
}
// HTTP client request/response wrapper specifically for the way this library
// works. It was made once I realized how often I was doing this, so I made this
// function as a generic for all possible library uses. Therefore, it is dumb
// and complicated, but it does what it needs to do.
func (c *Context) doTheThing(method methodType, urlpostfix string, ct requestContentType, input interface{}, callername string, jsonbool bool) (int, responseContentType, interface{}, error, error) {
switch method {
case mGET, mPOST, mPUT, mDELETE:
break
default:
return 0, ctJson, []byte{}, nil, MiabError{
IsHTTPStatusError: false,
CallingFunction: "doTheThing",
ErrorMsg: "invalid HTTP method",
}
}
switch ct {
case ctTextPlain, ctFormData:
break
default:
return 0, ctJson, []byte{}, nil, MiabError{
IsHTTPStatusError: false,
CallingFunction: "doTheThing",
ErrorMsg: "invalid HTTP content-type for request",
}
}
var req *http.Request
var resp *http.Response
var err error
client := &http.Client{}
if ct == ctTextPlain {
in, _ := input.(string)
if len(in) == 0 {
req, err = c.makeRequest(method, ct, c.makeUrl(true)+urlpostfix, nil, urlpostfix != "/login")
} else {
req, err = c.makeRequest(method, ct, c.makeUrl(true)+urlpostfix, in, urlpostfix != "/login")
}
} else if ct == ctFormData {
in, _ := input.(map[interface{}]interface{})
req, err = c.makeRequest(method, ct, c.makeUrl(true)+urlpostfix, in, urlpostfix != "/login")
} // else { should not get here }
if err != nil {
return 0, ctJson, []byte{}, nil, err
}
resp, err = client.Do(req)
if err != nil {
return 0, ctJson, []byte{}, nil, err
}
defer resp.Body.Close()
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return 0, ctJson, []byte{}, nil, err
}
var ctr responseContentType
var rb interface{}
rct := strings.ToLower(resp.Header.Get("Content-Type"))
if strings.Contains(rct, string(crTextHtml)) {
ctr = crTextHtml
rb = string(body)
} else if strings.Contains(rct, string(crTextPlain)) {
ctr = crTextPlain
rb = string(body)
} else if strings.Contains(rct, string(ctJson)) {
ctr = ctJson
if jsonbool {
rb = string(body)
} else {
rb = map[interface{}]interface{}{}
json.Unmarshal([]byte(body), &rb)
}
} else {
return 0, ctJson, []byte{}, nil, MiabError{
IsHTTPStatusError: false,
CallingFunction: "doTheThing",
ErrorMsg: "MIAB API has returned an unknown response content type",
}
}
statuserr := checkStatusCode(resp.StatusCode, callername)
return resp.StatusCode, ctr, rb, statuserr, nil
}
// https://mailinabox.email/api-docs.html#operation/login
// Return value is usually a map[string]interface{}, but may be string on
// non-200 status codes that return strings.
func (c *Context) Login() (interface{}, error) {
_, _, b, serr, err := c.doTheThing("POST", "/login", "text/plain", nil, "Login", false)
if err != nil {
return nil, err
} else if serr != nil {
return string(b.(string)), serr
}
return b.(map[string]interface{}), nil
}
// This performs a login without using a context, in order to keep the password
// scope inside this function, so it will be GC'd ASAP.
// If the return err is nil, the string returned will be the apikey or an empty
// string if the login credentials were invalid.
// All other scenarios should return an error.
// Much of the code is copied from doTheThing() and makeUrl().
// This is the only exportable function in this library that does not need the
// Context struct.
func LoginAndReturnAPIKey(server, apipath, username, password, otpcode string, https bool) (string, error) {
if !govalidator.IsDNSName(server) {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "LoginAndReturnAPIKey",
ErrorMsg: "server parameter is invalid",
}
}
if apipath == "" {
apipath = "admin"
}
urlpath := "http"
if https {
urlpath = urlpath + "s"
}
urlpath = urlpath + "://"
urlpath = urlpath + server
if apipath != "/" {
urlpath = urlpath + "/" + apipath
}
urlpath = urlpath + "/login"
var req *http.Request
client := &http.Client{}
req, _ = http.NewRequest("POST", urlpath, nil)
req.Header.Set("content-type", string(ctTextPlain))
req.SetBasicAuth(username, password)
if otpcode != "" {
req.Header.Add("x-auth-token", otpcode)
}
var resp *http.Response
var err error
resp, err = client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var body []byte
body, _ = ioutil.ReadAll(resp.Body)
statuserr := checkStatusCode(resp.StatusCode, "LoginAndReturnAPIKey")
if statuserr != nil {
return string(body), statuserr
}
var rb interface{}
isstring := true
rct := strings.ToLower(resp.Header.Get("Content-Type"))
if strings.Contains(rct, string(crTextHtml)) {
rb = string(body)
} else if strings.Contains(rct, string(crTextPlain)) {
rb = string(body)
} else if strings.Contains(rct, string(ctJson)) {
isstring = false
rb = map[interface{}]interface{}{}
json.Unmarshal([]byte(body), &rb)
} else {
return string(body), MiabError{
IsHTTPStatusError: false,
CallingFunction: "LoginAndReturnAPIKey",
ErrorMsg: "Response content type unknown",
}
}
if isstring {
return rb.(string), MiabError{
IsHTTPStatusError: false,
CallingFunction: "LoginAndReturnAPIKey",
ErrorMsg: "Response returned unexpected data",
}
}
rrb := rb.(map[string]interface{})
if rrb["status"].(string) == "ok" {
return rrb["api_key"].(string), nil
} else if rrb["status"].(string) == "invalid" {
return "", nil
}
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "LoginAndReturnAPIKey",
ErrorMsg: "upstream API has changed and this function has reached an unexpected area",
}
}
// https://mailinabox.email/api-docs.html#operation/logout
// Return value is usually a map[string]interface{}, but may be string on
// non-200 status codes that return strings.
func (c *Context) Logout() (interface{}, error) {
_, _, b, serr, err := c.doTheThing("POST", "/logout", "text/plain", nil, "Logout", false)
if err != nil {
return map[string]interface{}{}, err
} else if serr != nil {
return string(b.(string)), serr
}
return b.(map[string]interface{}), nil
}
// https://mailinabox.email/api-docs.html#operation/getMailUsers
// The returned interface{} will be type string or []map[string]interface{}
// depending on which format you choose.
// However, if you choose json and and a non-200 status is returned, the return
// will still be string, so you must check if error is nil.
// The return value will only be a []map[string]interface{} if format is json
// and response status code is 200.
// This is done to keep in line with how the MIAB HTTP API actually works.
func (c *Context) GetMailUsers(format string) (interface{}, error) {
switch format {
case "text", "json":
break
default:
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "GetMailUsers",
ErrorMsg: "invalid format parameter",
}
}
_, _, b, serr, err := c.doTheThing("GET", "/mail/users?format="+format, "text/plain", nil, "GetMailUsers", false)
if err != nil {
return "", err
} else if serr != nil {
return string(b.(string)), serr
}
if format == "text" {
return string(b.(string)), nil
}
b2 := b.([]interface{})
ret := []map[string]interface{}{}
for _, mapstringinterface := range b2 {
ret = append(ret, mapstringinterface.(map[string]interface{}))
}
return ret, nil
}
// https://mailinabox.email/api-docs.html#operation/addMailUser
func (c *Context) AddMailUser(email, password, privileges string) (string, error) {
if privileges != "" && privileges != "admin" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "AddMailUser",
ErrorMsg: "privileges parameter must be \"admin\" or empty string",
}
}
body := make(map[interface{}]interface{})
body["email"] = email
body["password"] = password
body["privileges"] = privileges
_, _, b, serr, err := c.doTheThing("POST", "/mail/users/add", "application/x-www-form-urlencoded", body, "AddMailUser", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/removeMailUser
func (c *Context) RemoveMailUser(email string) (string, error) {
body := make(map[interface{}]interface{})
body["email"] = email
_, _, b, serr, err := c.doTheThing("POST", "/mail/users/remove", "application/x-www-form-urlencoded", body, "RemoveMailUser", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/addMailUserPrivilege
// Note that although the docs say the privilege param can be admin or empty
// str, it will return a 400 bad request if you try to remove the privilege "",
// so for now, I ignore the input param and always set admin. Even so, the
// function signature is left as is since that's what the upstream docs have.
func (c *Context) AddMailUserPrivilege(email, privilege string) (string, error) {
if privilege != "" && privilege != "admin" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "AddMailUserPrivilege",
ErrorMsg: "privilege parameter must be \"admin\" or empty string",
}
}
body := make(map[interface{}]interface{})
body["email"] = email
// May be set to more than "admin" at some point in the future
//body["privilege"] = privilege
body["privilege"] = "admin"
_, _, b, serr, err := c.doTheThing("POST", "/mail/users/privileges/add", "application/x-www-form-urlencoded", body, "AddMailUserPrivilege", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/removeMailUserPrivilege
// Note that although the docs say the privilege param can be admin or empty
// str, it will return a 400 bad request if you try to remove the privilege "",
// so for now, I ignore the input param and always set admin. Even so, the
// function signature is left as is since that's what the upstream docs have.
func (c *Context) RemoveMailUserPrivilege(email, privilege string) (string, error) {
if privilege != "" && privilege != "admin" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "RemoveMailUserPrivilege",
ErrorMsg: "privilege parameter must be \"admin\" or empty string",
}
}
body := make(map[interface{}]interface{})
body["email"] = email
// May be set to more than "admin" at some point in the future
//body["privilege"] = privilege
body["privilege"] = "admin"
_, _, b, serr, err := c.doTheThing("POST", "/mail/users/privileges/remove", "application/x-www-form-urlencoded", body, "RemoveMailUserPrivilege", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/setMailUserPassword
// Returns 400 bad request err if (among other possibilities) the user
// doesn't exist
func (c *Context) SetMailUserPassword(email, password string) (string, error) {
body := make(map[interface{}]interface{})
body["email"] = email
body["password"] = password
_, _, b, serr, err := c.doTheThing("POST", "/mail/users/password", "application/x-www-form-urlencoded", body, "SetMailUserPassword", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/getMailUserPrivileges
// Returns empty str with no err if user is not admin;
// returns 400 bad request err if (among other possibilities) the user
// doesn't exist
func (c *Context) GetMailUserPrivileges(email string) (string, error) {
_, _, b, serr, err := c.doTheThing("GET", "/mail/users/privileges?email="+neturl.QueryEscape(email), "text/plain", nil, "GetMailUserPrivileges", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/getMailDomains
func (c *Context) GetMailDomains() (string, error) {
_, _, b, serr, err := c.doTheThing("GET", "/mail/domains", "text/plain", nil, "GetMailDomains", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/getMailAliases
// See comments for GetMailUsers() function for information about return types.
// It works the same here.
func (c *Context) GetMailAliases(format string) (interface{}, error) {
if format != "text" && format != "json" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "GetMailAliases",
ErrorMsg: "format parameter must be \"text\" or \"json\"",
}
}
_, _, b, serr, err := c.doTheThing("GET", "/mail/aliases?format="+format, "text/plain", nil, "GetMailAliases", false)
if err != nil {
return "", err
} else if serr != nil {
return string(b.(string)), serr
}
if format == "text" {
return string(b.(string)), nil
}
b2 := b.([]interface{})
ret := []map[string]interface{}{}
for _, mapstringinterface := range b2 {
ret = append(ret, mapstringinterface.(map[string]interface{}))
}
return ret, nil
}
// https://mailinabox.email/api-docs.html#operation/upsertMailAlias
func (c *Context) UpsertMailAlias(update_if_exists int, address, forwards_to string, permitted_senders interface{}) (string, error) {
if update_if_exists != 0 && update_if_exists != 1 {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "UpsertMailAlias",
ErrorMsg: "update_if_exists parameter must be 0 or 1",
}
}
body := make(map[interface{}]interface{})
body["update_if_exists"] = strconv.Itoa(update_if_exists)
body["address"] = address
body["forwards_to"] = forwards_to
if permitted_senders == nil {
body["permitted_senders"] = ""
} else {
body["permitted_senders"] = permitted_senders.(string)
}
_, _, b, serr, err := c.doTheThing("POST", "/mail/aliases/add", "application/x-www-form-urlencoded", body, "UpsertMailAlias", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/removeMailAlias
func (c *Context) RemoveMailAlias(address string) (string, error) {
body := make(map[interface{}]interface{})
body["address"] = address
_, _, b, serr, err := c.doTheThing("POST", "/mail/aliases/remove", "application/x-www-form-urlencoded", body, "RemoveMailAlias", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/getDnsSecondaryNameserver
// Will return a string when there is an error, but if err == nil, then the
// return will be a map[string][]string
func (c *Context) GetDnsSecondaryNameserver() (interface{}, error) {
_, _, b, serr, err := c.doTheThing("GET", "/dns/secondary-nameserver", "text/plain", nil, "GetDnsSecondaryNameserver", false)
if err != nil {
return "", err
} else if serr != nil {
return string(b.(string)), serr
}
rb := b.(map[string]interface{})
ret := make(map[string][]string)
for k, v := range rb {
vd := v.([]interface{})
value := []string{}
for _, v2 := range vd {
value = append(value, v2.(string))
}
ret[k] = value
}
return ret, nil
}
// https://mailinabox.email/api-docs.html#operation/addDnsSecondaryNameserver
func (c *Context) AddDnsSecondaryNameserver(hostnames string) (string, error) {
body := make(map[interface{}]interface{})
body["hostnames"] = hostnames
_, _, b, serr, err := c.doTheThing("POST", "/dns/secondary-nameserver", "application/x-www-form-urlencoded", body, "AddDnsSecondaryNameserver", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/getDnsZones
// returns a slice of strings if err != nil, otherwise return value is a string
func (c *Context) GetDnsZones() (interface{}, error) {
_, _, b, serr, err := c.doTheThing("GET", "/dns/zones", "text/plain", nil, "GetDnsZones", false)
if err != nil {
return "", err
} else if serr != nil {
return string(b.(string)), serr
}
b2 := b.([]interface{})
ret := []string{}
for _, v := range b2 {
ret = append(ret, v.(string))
}
return ret, nil
}
// https://mailinabox.email/api-docs.html#operation/getDnsZonefile
func (c *Context) GetDnsZonefile(zone string) (string, error) {
if !govalidator.IsDNSName(zone) {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "GetDnsZonefile",
ErrorMsg: "zone parameter is invalid",
}
}
_, _, b, serr, err := c.doTheThing("GET", "/dns/zonefile/"+neturl.QueryEscape(zone), "text/plain", nil, "GetDnsZonefile", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/updateDns
func (c *Context) UpdateDns(force int) (string, error) {
if force != 0 && force != 1 {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "UpdateDns",
ErrorMsg: "force parameter must be 0 or 1",
}
}
body := make(map[interface{}]interface{})
body["force"] = strconv.Itoa(force)
_, _, b, serr, err := c.doTheThing("POST", "/dns/update", "application/x-www-form-urlencoded", body, "UpdateDns", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/getDnsCustomRecords
// returns []map[string]interface{} if err == nil, otherwise returns string
//
// Example slice item of map[string]interface{} with all values:
//
// {
// "qname": "box.example.com",
// "rtype": "A",
// "sort-order": {
// "created": 0,
// "qname": 0
// },
// "value": "1.2.3.4",
// "zone": "example.com"
// }
//
// The interface{} value of the map is a string for everything but sort-order,
// which is a map[string]int
func (c *Context) GetDnsCustomRecords() (interface{}, error) {
_, _, b, serr, err := c.doTheThing("GET", "/dns/custom", "text/plain", nil, "GetDnsCustomRecords", false)
if err != nil {
return "", err
} else if serr != nil {
return string(b.(string)), serr
}
ret := []map[string]interface{}{}
b2 := b.([]interface{})
for _, v := range b2 {
val := map[string]interface{}{}
vv := v.(map[string]interface{})
for k2, v2 := range vv {
if k2 != "sort-order" {
val[k2] = v2.(string)
} else {
vret := map[string]int{}
vv2 := v2.(map[string]interface{})
for k3, v3 := range vv2 {
vret[k3] = int(math.Round(v3.(float64)))
}
val[k2] = vret
}
}
ret = append(ret, val)
}
return ret, nil
}
// https://mailinabox.email/api-docs.html#operation/getDnsCustomRecordsForQNameAndType
// See comments on GetDnsCustomRecords() for explanation of return values
func (c *Context) GetDnsCustomRecordsForQNameAndType(qname, rtype string) (interface{}, error) {
if !govalidator.IsDNSName(qname) {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "GetDnsCustomRecordsForQNameAndType",
ErrorMsg: "qname parameter is invalid",
}
}
if rtype != "A" && rtype != "AAAA" && rtype != "CAA" && rtype != "CNAME" && rtype != "TXT" && rtype != "MX" && rtype != "SRV" && rtype != "SSHFP" && rtype != "NS" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "GetDnsCustomRecordsForQNameAndType",
ErrorMsg: "rtype parameter is invalid",
}
}
_, _, b, serr, err := c.doTheThing("GET", "/dns/custom/"+neturl.QueryEscape(qname)+"/"+rtype, "text/plain", nil, "GetDnsCustomRecordsForQNameAndType", false)
if err != nil {
return "", err
} else if serr != nil {
return string(b.(string)), serr
}
ret := []map[string]interface{}{}
b2 := b.([]interface{})
for _, v := range b2 {
val := map[string]interface{}{}
vv := v.(map[string]interface{})
for k2, v2 := range vv {
if k2 != "sort-order" {
val[k2] = v2.(string)
} else {
vret := map[string]int{}
vv2 := v2.(map[string]interface{})
for k3, v3 := range vv2 {
vret[k3] = int(math.Round(v3.(float64)))
}
val[k2] = vret
}
}
ret = append(ret, val)
}
return ret, nil
}
// https://mailinabox.email/api-docs.html#operation/addDnsCustomRecord
func (c *Context) AddDnsCustomRecord(qname, rtype, value string) (string, error) {
if !govalidator.IsDNSName(qname) {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "AddDnsCustomRecord",
ErrorMsg: "qname parameter is invalid",
}
}
if rtype != "A" && rtype != "AAAA" && rtype != "CAA" && rtype != "CNAME" && rtype != "TXT" && rtype != "MX" && rtype != "SRV" && rtype != "SSHFP" && rtype != "NS" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "AddDnsCustomRecord",
ErrorMsg: "rtype parameter is invalid",
}
}
_, _, b, serr, err := c.doTheThing("POST", "/dns/custom/"+neturl.QueryEscape(qname)+"/"+rtype, "text/plain", value, "AddDnsCustomRecord", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/updateDnsCustomRecord
func (c *Context) UpdateDnsCustomRecord(qname, rtype, value string) (string, error) {
if !govalidator.IsDNSName(qname) {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "UpdateDnsCustomRecord",
ErrorMsg: "qname parameter is invalid",
}
}
if rtype != "A" && rtype != "AAAA" && rtype != "CAA" && rtype != "CNAME" && rtype != "TXT" && rtype != "MX" && rtype != "SRV" && rtype != "SSHFP" && rtype != "NS" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "UpdateDnsCustomRecord",
ErrorMsg: "rtype parameter is invalid",
}
}
_, _, b, serr, err := c.doTheThing("PUT", "/dns/custom/"+neturl.QueryEscape(qname)+"/"+rtype, "text/plain", value, "UpdateDnsCustomRecord", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/removeDnsCustomRecord
func (c *Context) RemoveDnsCustomRecord(qname, rtype, value string) (string, error) {
if !govalidator.IsDNSName(qname) {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "RemoveDnsCustomRecord",
ErrorMsg: "qname parameter is invalid",
}
}
if rtype != "A" && rtype != "AAAA" && rtype != "CAA" && rtype != "CNAME" && rtype != "TXT" && rtype != "MX" && rtype != "SRV" && rtype != "SSHFP" && rtype != "NS" {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "RemoveDnsCustomRecord",
ErrorMsg: "rtype parameter is invalid",
}
}
_, _, b, serr, err := c.doTheThing("DELETE", "/dns/custom/"+neturl.QueryEscape(qname)+"/"+rtype, "text/plain", value, "RemoveDnsCustomRecord", false)
if err != nil {
return "", err
}
return string(b.(string)), serr
}
// https://mailinabox.email/api-docs.html#operation/getDnsCustomARecordsForQName
// See comments on GetDnsCustomRecords() for explanation of return values
func (c *Context) GetDnsCustomARecordsForQName(qname string) (interface{}, error) {
if !govalidator.IsDNSName(qname) {
return "", MiabError{
IsHTTPStatusError: false,
CallingFunction: "GetDnsCustomARecordsForQName",
ErrorMsg: "qname parameter is invalid",
}
}
_, _, b, serr, err := c.doTheThing("GET", "/dns/custom/"+neturl.QueryEscape(qname), "text/plain", nil, "GetDnsCustomARecordsForQName", false)
if err != nil {
return "", err
} else if serr != nil {
return string(b.(string)), serr
}
ret := []map[string]interface{}{}
b2 := b.([]interface{})
for _, v := range b2 {
val := map[string]interface{}{}
vv := v.(map[string]interface{})
for k2, v2 := range vv {
if k2 != "sort-order" {
val[k2] = v2.(string)
} else {
vret := map[string]int{}
vv2 := v2.(map[string]interface{})
for k3, v3 := range vv2 {
vret[k3] = int(math.Round(v3.(float64)))
}
val[k2] = vret
}
}
ret = append(ret, val)
}