-
Notifications
You must be signed in to change notification settings - Fork 63
/
etherpad.go
410 lines (348 loc) · 9.37 KB
/
etherpad.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
package models
import (
"context"
"errors"
"fmt"
"github.com/goccy/go-json"
"github.com/google/uuid"
"github.com/mynaparrot/plugnmeet-protocol/plugnmeet"
"github.com/mynaparrot/plugnmeet-server/pkg/config"
"github.com/redis/go-redis/v9"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
type EtherpadModel struct {
SharedNotePad config.SharedNotePad
NodeId string
Host string
ClientId string
ClientSecret string
context context.Context
rc *redis.Client
rs *RoomService
analyticsModel *AnalyticsModel
}
type EtherpadHttpRes struct {
Code int64 `json:"code"`
Message string `json:"message"`
Data EtherpadDataTypes `json:"data"`
}
type EtherpadDataTypes struct {
AuthorID string `json:"authorID"`
GroupID string `json:"groupID"`
SessionID string `json:"sessionID"`
PadID string `json:"padID"`
ReadOnlyID string `json:"readOnlyID"`
TotalPads int64 `json:"totalPads"`
TotalSessions int64 `json:"totalSessions"`
TotalActivePads int64 `json:"totalActivePads"`
}
const (
APIVersion = "1.3.0"
EtherpadKey = "pnm:etherpad:"
EtherpadTokenKey = "pnm:etherpadToken"
)
func NewEtherpadModel() *EtherpadModel {
return &EtherpadModel{
rc: config.AppCnf.RDS,
context: context.Background(),
SharedNotePad: config.AppCnf.SharedNotePad,
rs: NewRoomService(),
analyticsModel: NewAnalyticsModel(),
}
}
type CreateSessionRes struct {
PadId string
ReadOnlyPadId string
}
// CreateSession will create group, pad, session
// return padId, readonlyPadId
func (m *EtherpadModel) CreateSession(roomId, requestedUserId string) (*plugnmeet.CreateEtherpadSessionRes, error) {
if len(m.SharedNotePad.EtherpadHosts) < 1 {
return nil, errors.New("need at least one etherpad host")
}
err := m.selectHost()
if err != nil {
return nil, err
}
res := new(plugnmeet.CreateEtherpadSessionRes)
pid := uuid.NewString()
res.PadId = &pid
// step 1: create pad using session id
r, err := m.createPad(pid, requestedUserId)
if err != nil {
return nil, err
}
if r.Code > 0 {
return nil, errors.New(r.Message)
}
// step 2: create readonly pad
r, err = m.createReadonlyPad(pid)
if err != nil {
return nil, err
}
if r.Code > 0 {
return nil, errors.New(r.Message)
}
res.ReadonlyPadId = &r.Data.ReadOnlyID
// add roomId to redis for this node
m.rc.SAdd(m.context, EtherpadKey+m.NodeId, roomId)
// finally, update to room
err = m.addPadToRoomMetadata(roomId, res)
if err != nil {
log.Errorln(err)
}
res.Status = true
res.Msg = "success"
return res, nil
}
func (m *EtherpadModel) addPadToRoomMetadata(roomId string, c *plugnmeet.CreateEtherpadSessionRes) error {
_, meta, err := m.rs.LoadRoomWithMetadata(roomId)
if err != nil {
return err
}
f := &plugnmeet.SharedNotePadFeatures{
AllowedSharedNotePad: meta.RoomFeatures.SharedNotePadFeatures.AllowedSharedNotePad,
IsActive: true,
NodeId: m.NodeId,
Host: m.Host,
NotePadId: *c.PadId,
ReadOnlyPadId: *c.ReadonlyPadId,
}
meta.RoomFeatures.SharedNotePadFeatures = f
_, err = m.rs.UpdateRoomMetadataByStruct(roomId, meta)
if err != nil {
log.Errorln(err)
}
// send analytics
val := plugnmeet.AnalyticsStatus_ANALYTICS_STATUS_STARTED.String()
m.analyticsModel.HandleEvent(&plugnmeet.AnalyticsDataMsg{
EventType: plugnmeet.AnalyticsEventType_ANALYTICS_EVENT_TYPE_ROOM,
EventName: plugnmeet.AnalyticsEvents_ANALYTICS_EVENT_ROOM_ETHERPAD_STATUS,
RoomId: roomId,
HsetValue: &val,
})
return err
}
// CleanPad will delete group, session & pad
func (m *EtherpadModel) CleanPad(roomId, nodeId, padId string) error {
for _, h := range m.SharedNotePad.EtherpadHosts {
if h.Id == nodeId {
m.NodeId = nodeId
m.Host = h.Host
m.ClientId = h.ClientId
m.ClientSecret = h.ClientSecret
}
}
if m.Host == "" {
return errors.New("no host found")
}
// step 1: delete pad
vals := url.Values{}
vals.Add("padID", padId)
_, err := m.postToEtherpad("deletePad", vals)
if err != nil {
log.Errorln(err)
}
// add roomId to redis for this node
_ = m.rc.SRem(m.context, EtherpadKey+nodeId, roomId)
return nil
}
func (m *EtherpadModel) CleanAfterRoomEnd(roomId, metadata string) error {
if metadata == "" {
return nil
}
roomMeta, _ := m.rs.UnmarshalRoomMetadata(metadata)
if roomMeta.GetRoomFeatures() == nil || roomMeta.GetRoomFeatures().GetSharedNotePadFeatures() == nil {
return nil
}
np := roomMeta.RoomFeatures.SharedNotePadFeatures
if !np.AllowedSharedNotePad {
return nil
}
err := m.CleanPad(roomId, np.NodeId, np.NotePadId)
return err
}
func (m *EtherpadModel) ChangeEtherpadStatus(r *plugnmeet.ChangeEtherpadStatusReq) error {
_, meta, err := m.rs.LoadRoomWithMetadata(r.RoomId)
if err != nil {
return err
}
meta.RoomFeatures.SharedNotePadFeatures.IsActive = r.IsActive
_, err = m.rs.UpdateRoomMetadataByStruct(r.RoomId, meta)
if err != nil {
log.Errorln(err)
}
// send analytics
val := plugnmeet.AnalyticsStatus_ANALYTICS_STATUS_STARTED.String()
d := &plugnmeet.AnalyticsDataMsg{
EventType: plugnmeet.AnalyticsEventType_ANALYTICS_EVENT_TYPE_ROOM,
EventName: plugnmeet.AnalyticsEvents_ANALYTICS_EVENT_ROOM_ETHERPAD_STATUS,
RoomId: r.RoomId,
HsetValue: &val,
}
if !r.IsActive {
val = plugnmeet.AnalyticsStatus_ANALYTICS_STATUS_ENDED.String()
d.EventName = plugnmeet.AnalyticsEvents_ANALYTICS_EVENT_ROOM_ETHERPAD_STATUS
d.HsetValue = &val
}
m.analyticsModel.HandleEvent(d)
return err
}
func (m *EtherpadModel) createPad(sessionId, requestedUserId string) (*EtherpadHttpRes, error) {
vals := url.Values{}
vals.Add("padID", sessionId)
if requestedUserId != "" {
vals.Add("authorId", requestedUserId)
}
res, err := m.postToEtherpad("createPad", vals)
if err != nil {
log.Errorln(err)
}
return res, err
}
func (m *EtherpadModel) createReadonlyPad(sessionId string) (*EtherpadHttpRes, error) {
vals := url.Values{}
vals.Add("padID", sessionId)
res, err := m.postToEtherpad("getReadOnlyID", vals)
if err != nil {
log.Errorln(err)
}
return res, err
}
// selectHost will choose server based on simple active number
func (m *EtherpadModel) selectHost() error {
type host struct {
i int
id string
active int64
}
var hosts []host
for i, h := range m.SharedNotePad.EtherpadHosts {
ok := m.checkStatus(h)
if ok {
c := m.rc.SCard(m.context, EtherpadKey+h.Id)
hosts = append(hosts, host{
i: i,
id: h.Id,
active: c.Val(),
})
}
}
if len(hosts) == 0 {
return errors.New("no active etherpad host found")
}
sort.Slice(hosts, func(i, j int) bool {
return hosts[i].active < hosts[j].active
})
selectedHost := m.SharedNotePad.EtherpadHosts[hosts[0].i]
m.NodeId = selectedHost.Id
m.Host = selectedHost.Host
m.ClientId = selectedHost.ClientId
m.ClientSecret = selectedHost.ClientSecret
return nil
}
func (m *EtherpadModel) checkStatus(h config.EtherpadInfo) bool {
m.NodeId = h.Id
m.Host = h.Host
m.ClientId = h.ClientId
m.ClientSecret = h.ClientSecret
vals := url.Values{}
_, err := m.postToEtherpad("getStats", vals)
if err != nil {
log.Errorln(err)
return false
}
return true
}
func (m *EtherpadModel) postToEtherpad(method string, vals url.Values) (*EtherpadHttpRes, error) {
if m.NodeId == "" {
return nil, errors.New("no notepad nodeId found")
}
token, err := m.getAccessToken()
if err != nil {
return nil, err
}
client := &http.Client{}
en := vals.Encode()
endPoint := fmt.Sprintf("%s/api/%s/%s?%s", m.Host, APIVersion, method, en)
req, err := http.NewRequest("GET", endPoint, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+token)
res, err := client.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, errors.New("error code: " + res.Status)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
mar := new(EtherpadHttpRes)
err = json.Unmarshal(body, mar)
if err != nil {
log.Errorln(err)
return nil, err
}
return mar, nil
}
func (m *EtherpadModel) getAccessToken() (string, error) {
key := fmt.Sprintf("%s:%s", EtherpadTokenKey, m.NodeId)
token, err := m.rc.Get(m.context, key).Result()
switch {
case err == redis.Nil:
//
case err != nil:
log.Errorln(err)
}
if token != "" {
return token, nil
}
data := url.Values{}
data.Set("grant_type", "client_credentials")
data.Set("client_id", m.ClientId)
data.Set("client_secret", m.ClientSecret)
encodedData := data.Encode()
client := &http.Client{}
urlPath := fmt.Sprintf("%s/oidc/token", m.Host)
req, err := http.NewRequest("POST", urlPath, strings.NewReader(encodedData))
if err != nil {
return "", err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
vals := struct {
AccessToken string `json:"access_token"`
}{}
err = json.Unmarshal(body, &vals)
if err != nil {
return "", err
}
if vals.AccessToken == "" {
return "", errors.New("can not get access_token value")
}
// we'll store the value with expiry of 30 minutes max
_, err = m.rc.Set(m.context, key, vals.AccessToken, time.Minute*30).Result()
if err != nil {
log.Errorln(err)
}
return vals.AccessToken, nil
}