-
Notifications
You must be signed in to change notification settings - Fork 1
/
etherpadlite.go
484 lines (410 loc) · 17.8 KB
/
etherpadlite.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
// Copyright 2017 - 2019 Fabian Wenzelmann <fabianwen@posteo.eu>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package etherpadlite provides an interface for Etherpad-Lite's HTTP API
// written entirely in Go.
// The API documentation can be found at https://github.com/ether/etherpad-lite/wiki/HTTP-API.
// To use it create an instance of etherpadlite.EtherpadLite and call the
// API methods on it, for example CreatePad(nil, padID, text).
// If a parameter is optional, like text is in createPad,
// simply set the value to etherpadlite.OptionalParam.
// If there is a parameter with a default value, like copyPad(sourceID, destinationID[, force=false]),
// setting the parameter to OptionalParam will set the value to the default value.
//
// All methods return a Response and an error (!= nil if something went wrong).
// The first argument of all methods is always a Context ctx. If set to a non-nil
// context the method will return nil and an error != nil when the
// context gets cancelled.
// If you don't want to use any context stuff just set it to nil.
// This is however not the best practice to set the context, better set it to
// context.Background or context.TODO if you don't want to use the context.
//
// It is safe to call the API methods simultaneously from multiple goroutines.
//
// I didn't document the methods since they're documented very well on the
// etherpad homepage: https://etherpad.org/doc/v1.7.5/#index_http_api
package etherpadlite
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// optionalParamType is an unexported type to identify an optional parameter
// we don't want to use.
type optionalParamType int
const (
// CurrentVersion is the default version to use.
CurrentVersion = "1.2.13"
// OptionalParam is a constant used to identify an optional parameter we don't
// want to use.
OptionalParam optionalParamType = 0
)
// EtherpadLite is a struct that is used to connect to the etherpadlite API.
type EtherpadLite struct {
// APIVersion is the api version to use. It defaults to "1.2.13" in
// NewEtherpadLite.
APIVersion string
// BaseParams are the parameter that are required in each request, i.e.
// will be sent in each request.
// The entry BaseParams["apikey"] = YOUR-API-KEY
// should always be present.
// NewEtherpadLite will take care of this.
BaseParams map[string]interface{}
// BaseURL is the URL pointing to the API of your pad, i.e.
// http://pad.domain/api
// It defaults to http://localhost:9001/api in NewEtherpadLite.
BaseURL string
// Client is used to send the GET requests to the API.
// Set the values as required.
// It defaults to the http.DefaultClient in NewEtherpadLite.
Client *http.Client
// RaiseEtherpadErrors specifies if errors returned by etherpad should be
// returned as errors in Go or should be handled by the caller by checking
// the response code.
// It defaults to False.
// By setting it to true the calls to all functions will return an error
// for all responses with Response.Code != EverythingOk.
// In this case an instance of EtherpadError is raised.
RaiseEtherpadErrors bool
}
// NewEtherpadLite creates a new EtherpadLite instance given the
// mandatory apiKey.
// Create a new instance with this method and then configure it if you must.
func NewEtherpadLite(apiKey string) *EtherpadLite {
baseParams := make(map[string]interface{})
baseParams["apikey"] = apiKey
client := http.DefaultClient
return &EtherpadLite{APIVersion: CurrentVersion,
BaseParams: baseParams,
BaseURL: "http://localhost:9001/api",
Client: client,
RaiseEtherpadErrors: false,
}
}
// ReturnCode is the code return by the etherpad API, see API documentation
// for more details.
type ReturnCode int
const (
EverythingOk ReturnCode = iota
WrongParameters
InternalError
NoSuchFunction
WrongAPIKey
)
func (c ReturnCode) String() string {
switch c {
case EverythingOk:
return "0 everything ok"
case WrongParameters:
return "1 wrong parameters"
case InternalError:
return "2 internal error"
case NoSuchFunction:
return "3 no such function"
case WrongAPIKey:
return "4 no or wrong API Key"
default:
return fmt.Sprintf("%d unknown return code", int(c))
}
}
// Response is the response from the etherpad API.
// See https://github.com/ether/etherpad-lite/wiki/HTTP-API
type Response struct {
Code ReturnCode
Message string
Data map[string]interface{}
}
// EtherpadError is an error returned by all methods if
// EtherpadLite.RaiseEtherpadErrors is true. It reports any internal error
// returned by calling the HTTP API of etherpad, signaling that the ReturnCode
// is not EverythingOk.
type EtherpadError struct {
code ReturnCode
message string
}
// NewEtherpadError returns a new EtherpadError.
// The code should be != EverythingOk and the message is the error message
// returned by the HTTP API.
func NewEtherpadError(code ReturnCode, message string) EtherpadError {
return EtherpadError{code: code, message: message}
}
// Error returns the error as a string.
func (e EtherpadError) Error() string {
codeStr := e.code.String()
return fmt.Sprintf("%s: %s", codeStr, e.message)
}
// sendRequest is the function doing most of the work by sending the real
// request. It will encode the BaseParams and params into URL queries and
// do the http GET.
// It decodes the JSON result and returns the decoded version.
// If ctx != nil the method will be cancelled once ctx gets cancelled.
// Note that ctx = nil, should not be used according to the documentation,
// but we allow it since it's much easier.
// Instead we could always use context.Background().
func (pad *EtherpadLite) sendRequest(ctx context.Context, path string, params map[string]interface{}) (*Response, error) {
getURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", pad.BaseURL, pad.APIVersion, path))
if err != nil {
return nil, err
}
parameters := url.Values{}
for key, value := range pad.BaseParams {
parameters.Add(key, fmt.Sprintf("%v", value))
}
for key, value := range params {
parameters.Add(key, fmt.Sprintf("%v", value))
}
getURL.RawQuery = parameters.Encode()
req, reqErr := http.NewRequest("GET", getURL.String(), nil)
if reqErr != nil {
return nil, reqErr
}
if ctx != nil {
req = req.WithContext(ctx)
}
resp, doErr := pad.Client.Do(req)
if resp != nil {
defer resp.Body.Close()
}
if doErr != nil {
return nil, doErr
}
var padResponse Response
if jsonErr := json.NewDecoder(resp.Body).Decode(&padResponse); jsonErr != nil {
return nil, jsonErr
}
// check how to handle response errors
// and if we have to care about them what to do about it
if pad.RaiseEtherpadErrors && padResponse.Code != EverythingOk {
return &padResponse, NewEtherpadError(padResponse.Code, padResponse.Message)
}
return &padResponse, nil
}
// Groups
func (pad *EtherpadLite) CreateGroup(ctx context.Context) (*Response, error) {
return pad.sendRequest(ctx, "createGroup", nil)
}
func (pad *EtherpadLite) CreateGroupIfNotExistsFor(ctx context.Context, groupMapper interface{}) (*Response, error) {
return pad.sendRequest(ctx, "createGroupIfNotExistsFor", map[string]interface{}{"groupMapper": groupMapper})
}
func (pad *EtherpadLite) DeleteGroup(ctx context.Context, groupID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "deleteGroup", map[string]interface{}{"groupID": groupID})
}
func (pad *EtherpadLite) ListPads(ctx context.Context, groupID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "listPads", map[string]interface{}{"groupID": groupID})
}
func (pad *EtherpadLite) CreateGroupPad(ctx context.Context, groupID, padName, text interface{}) (*Response, error) {
params := map[string]interface{}{"groupID": groupID, "padName": padName}
if text != OptionalParam {
params["text"] = text
}
return pad.sendRequest(ctx, "createGroupPad", params)
}
func (pad *EtherpadLite) ListAllGroups(ctx context.Context) (*Response, error) {
return pad.sendRequest(ctx, "listAllGroups", nil)
}
// Author
func (pad *EtherpadLite) CreateAuthor(ctx context.Context, name interface{}) (*Response, error) {
params := make(map[string]interface{})
if name != OptionalParam {
params["name"] = name
}
return pad.sendRequest(ctx, "createAuthor", params)
}
func (pad *EtherpadLite) CreateAuthorIfNotExistsFor(ctx context.Context, authorMapper, name interface{}) (*Response, error) {
params := map[string]interface{}{"authorMapper": authorMapper}
if name != OptionalParam {
params["name"] = name
}
return pad.sendRequest(ctx, "createAuthorIfNotExistsFor", params)
}
func (pad *EtherpadLite) ListPadsOfAuthor(ctx context.Context, authorID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "listPadsOfAuthor", map[string]interface{}{"authorID": authorID})
}
func (pad *EtherpadLite) GetAuthorName(ctx context.Context, authorID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getAuthorName", map[string]interface{}{"authorID": authorID})
}
// Session
func (pad *EtherpadLite) CreateSession(ctx context.Context, groupID, authorID, validUntil interface{}) (*Response, error) {
return pad.sendRequest(ctx,
"createSession",
map[string]interface{}{"groupID": groupID, "authorID": authorID, "validUntil": validUntil})
}
func (pad *EtherpadLite) DeleteSession(ctx context.Context, sessionID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "deleteSession", map[string]interface{}{"sessionID": sessionID})
}
func (pad *EtherpadLite) GetSessionInfo(ctx context.Context, sessionID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getSessionInfo", map[string]interface{}{"sessionID": sessionID})
}
func (pad *EtherpadLite) ListSessionsOfGroup(ctx context.Context, groupID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "listSessionsOfGroup", map[string]interface{}{"groupID": groupID})
}
func (pad *EtherpadLite) ListSessionsOfAuthor(ctx context.Context, authorID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "listSessionsOfAuthor", map[string]interface{}{"authorID": authorID})
}
// Pad Content
func (pad *EtherpadLite) GetText(ctx context.Context, padID, rev interface{}) (*Response, error) {
params := map[string]interface{}{"padID": padID}
if rev != OptionalParam {
params["rev"] = rev
}
return pad.sendRequest(ctx, "getText", params)
}
func (pad *EtherpadLite) SetText(ctx context.Context, padID, text interface{}) (*Response, error) {
return pad.sendRequest(ctx, "setText", map[string]interface{}{"padID": padID, "text": text})
}
func (pad *EtherpadLite) AppendText(ctx context.Context, padID, text interface{}) (*Response, error) {
return pad.sendRequest(ctx, "appendText", map[string]interface{}{"padID": padID, "text": text})
}
func (pad *EtherpadLite) GetHTML(ctx context.Context, padID, rev interface{}) (*Response, error) {
params := map[string]interface{}{"padID": padID}
if rev != OptionalParam {
params["rev"] = rev
}
return pad.sendRequest(ctx, "getHTML", params)
}
func (pad *EtherpadLite) SetHTML(ctx context.Context, padID, html interface{}) (*Response, error) {
return pad.sendRequest(ctx, "setHTML", map[string]interface{}{"padID": padID, "html": html})
}
func (pad *EtherpadLite) GetAttributePool(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getAttributePool", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) GetRevisionChangeset(ctx context.Context, padID, rev interface{}) (*Response, error) {
params := map[string]interface{}{"padID": padID}
if rev != OptionalParam {
params["rev"] = rev
}
return pad.sendRequest(ctx, "getRevisionChangeset", params)
}
func (pad *EtherpadLite) CreateDiffHTML(ctx context.Context, padID, startRev, endRev interface{}) (*Response, error) {
return pad.sendRequest(ctx,
"createDiffHTML",
map[string]interface{}{
"padID": padID,
"startRev": startRev,
"endRev": endRev,
})
}
func (pad *EtherpadLite) RestoreRevision(ctx context.Context, padId, rev interface{}) (*Response, error) {
return pad.sendRequest(ctx, "restoreRevision", map[string]interface{}{"padId": padId, "rev": rev})
}
// Chat
func (pad *EtherpadLite) GetChatHistory(ctx context.Context, padID, start, end interface{}) (*Response, error) {
params := map[string]interface{}{"padID": padID}
// actually here both start and end must be != OptionalParam, not just one
// of them. But we let the user read the docs, errors here are only for things
// that really go wrong
if start != OptionalParam {
params["start"] = start
}
if end != OptionalParam {
params["end"] = end
}
return pad.sendRequest(ctx, "getChatHistory", params)
}
func (pad *EtherpadLite) GetChatHead(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getChatHead", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) appendChatMessage(ctx context.Context, padID, text, authorID, time interface{}) (*Response, error) {
params := map[string]interface{}{"padID": padID, "text": text, "authorID": authorID}
if time != OptionalParam {
params["time"] = time
}
return pad.sendRequest(ctx, "appendChatMessage", params)
}
// Pad
func (pad *EtherpadLite) CreatePad(ctx context.Context, padID, text interface{}) (*Response, error) {
params := map[string]interface{}{"padID": padID}
if text != OptionalParam {
params["text"] = text
}
return pad.sendRequest(ctx, "createPad", params)
}
func (pad *EtherpadLite) GetRevisionsCount(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getRevisionsCount", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) GetSavedRevisionsCount(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getSavedRevisionsCount", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) ListSavedRevisions(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "listSavedRevisions", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) SaveRevision(ctx context.Context, padID, rev interface{}) (*Response, error) {
params := map[string]interface{}{"padID": padID}
if rev != OptionalParam {
params["rev"] = rev
}
return pad.sendRequest(ctx, "saveRevision", params)
}
func (pad *EtherpadLite) PadUsersCount(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "padUsersCount", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) PadUsers(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "padUsers", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) DeletePad(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "deletePad", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) CopyPad(ctx context.Context, sourceID, destinationID, force interface{}) (*Response, error) {
params := map[string]interface{}{"sourceID": sourceID, "destinationID": destinationID}
if force == OptionalParam {
params["force"] = false
} else {
params["force"] = force
}
return pad.sendRequest(ctx, "copyPad", params)
}
func (pad *EtherpadLite) MovePad(ctx context.Context, sourceID, destinationID, force interface{}) (*Response, error) {
params := map[string]interface{}{"sourceID": sourceID, "destinationID": destinationID}
if force == OptionalParam {
params["force"] = false
} else {
params["force"] = force
}
return pad.sendRequest(ctx, "movePad", params)
}
func (pad *EtherpadLite) GetReadOnlyID(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getReadOnlyID", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) GetPadID(ctx context.Context, readOnlyID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getPadID", map[string]interface{}{"readOnlyID": readOnlyID})
}
func (pad *EtherpadLite) SetPublicStatus(ctx context.Context, padID, publicStatus interface{}) (*Response, error) {
return pad.sendRequest(ctx, "setPublicStatus", map[string]interface{}{"padID": padID, "publicStatus": publicStatus})
}
func (pad *EtherpadLite) GetPublicStatus(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getPublicStatus", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) SetPassword(ctx context.Context, padID, password interface{}) (*Response, error) {
return pad.sendRequest(ctx, "setPassword", map[string]interface{}{"padID": padID, "password": password})
}
func (pad *EtherpadLite) IsPasswordProtected(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "isPasswordProtected", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) ListAuthorsOfPad(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "listAuthorsOfPad", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) GetLastEdited(ctx context.Context, padID interface{}) (*Response, error) {
return pad.sendRequest(ctx, "getLastEdited", map[string]interface{}{"padID": padID})
}
func (pad *EtherpadLite) SendClientsMessage(ctx context.Context, padID, msg interface{}) (*Response, error) {
return pad.sendRequest(ctx, "sendClientsMessage", map[string]interface{}{"padID": padID, "msg": msg})
}
func (pad *EtherpadLite) CheckToken(ctx context.Context) (*Response, error) {
return pad.sendRequest(ctx, "checkToken", nil)
}
// Pads
func (pad *EtherpadLite) ListAllPads(ctx context.Context) (*Response, error) {
return pad.sendRequest(ctx, "listAllPads", nil)
}