-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
104 lines (88 loc) · 2.27 KB
/
client.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
package mezonsdk
import (
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"net/http"
"time"
"github.com/nccasia/mezon-go-sdk/configs"
"github.com/nccasia/mezon-go-sdk/constants"
"github.com/nccasia/mezon-go-sdk/utils"
swagger "github.com/nccasia/mezon-go-sdk/mezon-api"
)
type Client struct {
cfg *configs.Config
token string
Api *swagger.MezonApiService
Socket IWSConnection
}
func NewClient(apiKey string) (*Client, error) {
c := &configs.Config{
ApiKey: apiKey,
Timeout: 15,
}
cfg := getSwaggerConfig(c)
api := swagger.NewAPIClient(cfg).MezonApi
token, err := getAuthenticate(c, api)
if err != nil {
return nil, err
}
cfg.AddDefaultHeader("Authorization", fmt.Sprintf("Bearer %s", token))
return (&Client{
cfg: c,
token: token,
Api: api,
}), nil
}
func (c *Client) CreateSocket() (IWSConnection, error) {
clanDescs, _, err := c.Api.MezonListClanDescs(context.Background(), nil)
if err != nil {
return nil, err
}
listJoinedClan := make([]string, len(clanDescs.Clandesc))
// for DM
listJoinedClan = append(listJoinedClan, "0")
for _, clan := range clanDescs.Clandesc {
listJoinedClan = append(listJoinedClan, clan.ClanId)
}
socket, err := NewWSConnection(c.cfg, c.token, listJoinedClan)
if err != nil {
return nil, err
}
c.Socket = socket
return socket, nil
}
func getAuthenticate(c *configs.Config, api *swagger.MezonApiService) (string, error) {
cfg := getSwaggerConfig(c)
cfg.AddDefaultHeader("Authorization", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("Basic %s:", c.ApiKey))))
token, _, err := api.MezonAuthenticate(context.Background(), swagger.ApiAuthenticateRequest{
Account: &swagger.ApiAccountApp{
Token: c.ApiKey,
},
})
if err != nil {
return "", err
}
return token.Token, err
}
func getSwaggerConfig(c *configs.Config) *swagger.Configuration {
cfg := swagger.NewConfiguration()
cfg.BasePath = utils.GetBasePath("http", constants.MznBasePath, constants.UseSSL)
if c.Timeout == 0 {
c.Timeout = 15
}
if constants.InsecureSkip {
cfg.HTTPClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
} else {
cfg.HTTPClient = http.DefaultClient
}
cfg.HTTPClient.Timeout = time.Duration(c.Timeout) * time.Second
return cfg
}