-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.go
268 lines (225 loc) · 6.76 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
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
package ejabberd
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"reflect"
"strconv"
"time"
)
// Client is an ejabberd client API wrapper. It is used to manage
// ejabberd client API interactions.
type Client struct {
BaseURL string
Token OAuthToken
// Extra & Advanced features
OAuthPath string
APIPath string
HTTPClient *http.Client
}
//==============================================================================
// Generic Call functions
// call performs HTTP call to ejabberd API given client parameters. It
// returns a struct complying with Response interface.
func (c Client) call(req request) (Response, error) {
p, err := req.params()
if err != nil {
return nil, err
}
var admin bool
if p.admin {
admin = true
} else if needAdminForUser(req, c.Token.JID) {
admin = true
}
code, result, err := c.CallRaw(p.body, p.name, admin)
if err != nil {
return APIError{Code: 99}, err
}
if code != 200 {
apiError, err := parseError(result)
if err != nil {
return nil, err
}
return nil, apiError
}
return req.parseResponse(result)
}
// CallRaw performs HTTP call to ejabberd API and returns Raw Body
// reponse from the server as slice of bytes.
func (c Client) CallRaw(body []byte, name string, admin bool) (code int, result []byte, err error) {
if c.HTTPClient == nil {
c.HTTPClient = defaultHTTPClient(15 * time.Second)
}
var url string
if url, err = apiURL(c.BaseURL, c.APIPath, name); err != nil {
return 0, []byte{}, err
}
var r *http.Request
if len(body) == 0 {
r, _ = http.NewRequest("GET", url, nil)
} else {
r, _ = http.NewRequest("POST", url, bytes.NewBuffer(body))
}
r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
r.Header.Set("Content-Type", "application/json")
if admin {
r.Header.Set("X-Admin", "true")
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return 0, []byte{}, err
}
// TODO: We should limit the amount of data the client reads from ejabberd as response
result, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
return resp.StatusCode, result, err
}
// Check if Request struct has a field call JID.
// If this is the case, compare with the JID of the user making the
// query, based on the token data.
// If JID from the request and JID from the token are different, then
// we will need admin rights to perform user query
func needAdminForUser(command interface{}, JID string) bool {
cType := reflect.TypeOf(command)
// if a pointer to a struct is passed, get the type of the dereferenced object
if cType.Kind() == reflect.Ptr {
cType = cType.Elem()
}
// If command type is not a struct, we stop there
if cType.Kind() != reflect.Struct {
return false
}
val := reflect.ValueOf(command)
needAdmin := false
for i := 0; i < val.NumField(); i++ {
p := val.Type().Field(i)
v := val.Field(i)
if !p.Anonymous && p.Name == "JID" {
switch v.Kind() {
case reflect.String:
if v.String() != JID {
needAdmin = true
}
}
}
}
return needAdmin
}
//==============================================================================
// ==== Token ====
// TODO Get token from local file
// GetToken calls ejabberd API to get a token for a given scope, given
// valid jid and password. We also assume that the user has the right
// to generate a token. In case of doubt you need to check ejabberd
// access option 'oauth_access'.
func (c Client) GetToken(sjid, password, scope string, duration time.Duration) (OAuthToken, error) {
var j jid
var t OAuthToken
var err error
// Set default values
if c.HTTPClient == nil {
c.HTTPClient = defaultHTTPClient(15 * time.Second)
}
if j, err = parseJID(sjid); err != nil {
return t, err
}
var u string
if u, err = tokenURL(c.BaseURL, c.OAuthPath); err != nil {
return t, err
}
// Prepare token call parameters
ttl := int(duration.Seconds())
params := tokenParams(j, password, prepareScope(scope), strconv.Itoa(ttl))
// Request token from server
if t, err = httpGetToken(c.HTTPClient, u, params); err != nil {
return t, err
}
return t, nil
}
//==============================================================================
// Stats allows to query ejabberd for generic statistics. Supported statistic names are:
//
// registeredusers
// onlineusers
// onlineusersnode
// uptimeseconds
// processes
func (c Client) Stats(name string) (Stats, error) {
command := statsRequest{
Name: name,
}
result, err := c.call(command)
if err != nil {
return Stats{}, err
}
resp := result.(Stats)
return resp, nil
}
//==============================================================================
// RegisterUser creates a new user on a domain, from id (JID) and
// password. It will fail if domain is not handle by server, if user
// already exists, or if the user performing the registration does not
// have the right to create new users on the server or domain.
func (c Client) RegisterUser(bareJID string, password string) (Register, error) {
command := registerRequest{
JID: bareJID,
Password: password}
result, err := c.call(command)
if err != nil {
return "", err
}
resp := result.(Register)
return resp, nil
}
//==============================================================================
// GetOfflineCount returns the number of message in offline storage
// for a given user. It can be called as a user, if you try to read
// your own offline message count. It can also be called as an admin
// and in that case, you can read offline message count from any user
// on the server.
func (c Client) GetOfflineCount(bareJID string) (OfflineCount, error) {
command := offlineCountRequest{
JID: bareJID,
}
result, err := c.call(command)
if err != nil {
return OfflineCount{}, err
}
resp := result.(OfflineCount)
return resp, nil
}
//==============================================================================
// UserResources returns the list of resources connected for a given
// user. It can be called as a user, if you try to read your own
// connected resources. It can also be called as an admin and in that
// case, you can read the connected resources for any any user on the
// server.
func (c Client) UserResources(bareJID string) (UserResources, error) {
command := userResourcesRequest{
JID: bareJID,
}
result, err := c.call(command)
if err != nil {
return UserResources{}, err
}
resp := result.(UserResources)
return resp, nil
}
//==============================================================================
// Prepare HTTP client settings with proper values, like default
// timeout.
func defaultHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: timeout,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: timeout,
},
}
}