forked from clockworksoul/mediawiki
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
344 lines (276 loc) · 7.89 KB
/
Copy pathclient.go
File metadata and controls
344 lines (276 loc) · 7.89 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
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
package mediawiki
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strings"
"sync"
"time"
)
// If you modify this package, please change DefaultUserAgent.
// DefaultUserAgent is the HTTP User-Agent used by default.
const DefaultUserAgent = "go-mediawiki (https://github.com/clockworksoul/mediawiki)"
type Client struct {
Client *http.Client
apiURL *url.URL
// HTTP user agent
UserAgent string
// API token cache.
// Maps from name of token (e.g., "csrf") to token value.
// Use GetToken to obtain tokens.
Tokens *Tokens
Debug io.Writer
// Used for keep-alive
lastLoginTime time.Time
username, password string
loginBot bool
keepAliveMutex sync.Mutex
}
type Token string
type Tokens struct {
sync.RWMutex
m map[Token]string
}
// These consts represents MW API token names.
// They are meant to be used with the GetToken method like so:
//
// ClientInstance.GetToken(mwclient.CSRFToken)
const (
CSRFToken Token = "csrf"
DeleteGlobalAccountToken Token = "deleteglobalaccount"
PatrolToken Token = "patrol"
RollbackToken Token = "rollback"
SetGlobalAccountStatusToken Token = "setglobalaccountstatus"
UserRightsToken Token = "userrights"
WatchToken Token = "watch"
LoginToken Token = "login"
)
// New returns a pointer to an initialized Client object. If the provided API URL
// is invalid (as defined by the net/url package), then it will return nil and
// the error from url.Parse().
//
// The userAgent parameter will be joined with the DefaultUserAgent const and
// used as HTTP User-Agent. If userAgent is an empty string, DefaultUserAgent
// will be used by itself as User-Agent. The User-Agent set by New can be
// overriden by setting the UserAgent field on the returned *Client.
//
// New disables maxlag by default. To enable it, simply set
// Client.Maxlag.On to true. The default timeout is 5 seconds and the default
// amount of retries is 3.
func New(inURL, userAgent string) (*Client, error) {
apiurl, err := url.Parse(inURL)
if err != nil {
return nil, err
}
var ua string
if userAgent != "" {
ua = userAgent + " " + DefaultUserAgent
} else {
ua = DefaultUserAgent
}
client := &Client{}
client.init(apiurl, ua)
return client, nil
}
// Login attempts to login using the provided username and password.
// Do not use Login with OAuth.
func (w *Client) GetToken(ctx context.Context, token Token) (string, error) {
if w.apiURL.String() == "" {
return "", fmt.Errorf("api URL is undefined")
}
w.Tokens.Lock()
defer w.Tokens.Unlock()
if t, exists := w.Tokens.m[token]; exists {
return t, nil
}
url := fmt.Sprintf("%s?format=json&action=query&meta=tokens&type=%s", w.apiURL.String(), token)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return "", fmt.Errorf("error requesting token: %w", err)
}
req.Header.Set("User-Agent", w.UserAgent)
// if w.Debug != nil {
// reqdump, err := httputil.DumpRequestOut(req, true)
// if err != nil {
// fmt.Fprintf(w.Debug, "Err dumping request: %v\n", err)
// } else {
// w.Debug.Write(reqdump)
// }
// }
resp, err := w.Client.Do(req)
if err != nil {
return "", fmt.Errorf("error receiving token: %w", err)
}
// if w.Debug != nil {
// respdump, err := httputil.DumpResponse(resp, true)
// if err != nil {
// fmt.Fprintf(w.Debug, "Err dumping response: %v\n", err)
// } else {
// w.Debug.Write(respdump)
// }
// }
r := Response{}
err = ParseResponseReader(resp.Body, &r)
if err != nil {
return "", fmt.Errorf("error parsing response: %w", err)
}
if e := r.Error; e != nil {
return "", fmt.Errorf("%s: %s", e.Code, e.Info)
}
ts := r.Query.Tokens[string(token)+"token"]
if ts != "" {
w.Tokens.m[token] = ts
}
return ts, nil
}
func (w *Client) BotLogin(ctx context.Context, username, password string) (Response, error) {
token, err := w.GetToken(ctx, LoginToken)
if err != nil {
return Response{}, err
}
w.username = username
w.password = password
w.loginBot = true
v := Values{
"action": "login",
"lgname": username,
"lgpassword": password,
"lgtoken": token,
}
r := Response{}
j, err := w.PostInto(ctx, v, &r)
r.RawJSON = j
if err != nil {
return r, fmt.Errorf("error parsing response: %w", err)
}
if e := r.Error; e != nil {
return r, fmt.Errorf("%s: %s", e.Code, e.Info)
} else if r.BotLogin == nil {
return r, fmt.Errorf("unexpected error in login")
} else if r.BotLogin.Result != Success {
return r, fmt.Errorf("login failure: (%s) %s", r.BotLogin.Result, r.BotLogin.Reason)
}
w.lastLoginTime = time.Now()
return r, nil
}
func (w *Client) GetInto(ctx context.Context, v Values, a any) (string, error) {
v["format"] = "json"
query := w.apiURL.String() + "?" + v.Encode()
if w.Debug != nil {
fmt.Fprintln(w.Debug, query)
}
req, err := http.NewRequestWithContext(ctx, "GET", query, nil)
if err != nil {
return "", fmt.Errorf("error constructing GET: %w", err)
}
req.Header.Set("User-Agent", w.UserAgent)
resp, err := w.Client.Do(req)
if err != nil {
return "", fmt.Errorf("error executing Get: %w", err)
}
b, _ := io.ReadAll(resp.Body)
buf := &bytes.Buffer{}
json.Indent(buf, b, "", " ")
j := buf.String()
if w.Debug != nil {
fmt.Fprintln(w.Debug, j)
}
err = ParseResponseReader(buf, a)
if err != nil {
return j, fmt.Errorf("error parsing response: %w", err)
}
if w.Debug != nil {
fmt.Fprintln(w.Debug, "-----")
b, _ = json.MarshalIndent(a, "", " ")
fmt.Fprintln(w.Debug, string(b))
}
return j, nil
}
func (w *Client) PostInto(ctx context.Context, v Values, a any) (string, error) {
v["format"] = "json"
req, err := http.NewRequestWithContext(ctx, "POST", w.apiURL.String(), strings.NewReader(v.Encode()))
if err != nil {
return "", fmt.Errorf("error constructing POST: %w", err)
}
req.Header.Set("User-Agent", w.UserAgent)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := w.Client.Do(req)
if err != nil {
return "", fmt.Errorf("error executing POST: %w", err)
}
b, _ := io.ReadAll(resp.Body)
buf := &bytes.Buffer{}
json.Indent(buf, b, "", " ")
j := buf.String()
if w.Debug != nil {
fmt.Fprintln(w.Debug, j)
}
err = ParseResponseReader(buf, a)
if err != nil {
return j, fmt.Errorf("error parsing response: %w", err)
}
if w.Debug != nil {
fmt.Fprintln(w.Debug, "-----")
b, _ = json.MarshalIndent(a, "", " ")
fmt.Fprintln(w.Debug, string(b))
}
return j, nil
}
// checkKeepAlive checks for the presence of an active session cookie,
// and attempts to re-initialize the connection if one isn't found.
func (w *Client) checkKeepAlive(ctx context.Context) error {
if w.username == "" && w.password == "" {
return nil
}
w.keepAliveMutex.Lock()
defer w.keepAliveMutex.Unlock()
if w.hasCookie("^.*_session$") {
return nil
}
if err := w.init(w.apiURL, w.UserAgent); err != nil {
return fmt.Errorf("keep-alive re-init failure: %w", err)
}
if w.loginBot {
if _, err := w.BotLogin(ctx, w.username, w.password); err != nil {
return fmt.Errorf("keep-alive login failure: %w", err)
}
} else {
if _, err := w.ClientLogin(ctx, w.username, w.password); err != nil {
return fmt.Errorf("keep-alive login failure: %w", err)
}
}
return nil
}
func (w *Client) hasCookie(regex string) bool {
p := regexp.MustCompile(regex)
for _, c := range w.Client.Jar.Cookies(w.apiURL) {
if p.Match([]byte(c.Name)) {
return true
}
}
return false
}
// init is used by both New and checkKeepAlive to (re-)initialize
// the client.
func (w *Client) init(apiurl *url.URL, ua string) error {
cookies, err := cookiejar.New(nil)
if err != nil {
return err
}
w.Client = &http.Client{
Transport: nil,
CheckRedirect: nil,
Jar: cookies,
Timeout: 30 * time.Second,
}
w.apiURL = apiurl
w.UserAgent = ua
w.Tokens = &Tokens{m: map[Token]string{}}
return nil
}