-
Notifications
You must be signed in to change notification settings - Fork 137
/
group.go
485 lines (444 loc) · 12.1 KB
/
group.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
485
package sharing
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"time"
"github.com/cozy/cozy-stack/client/request"
"github.com/cozy/cozy-stack/model/contact"
"github.com/cozy/cozy-stack/model/instance"
"github.com/cozy/cozy-stack/model/job"
"github.com/cozy/cozy-stack/model/permission"
"github.com/cozy/cozy-stack/pkg/consts"
"github.com/cozy/cozy-stack/pkg/couchdb"
"github.com/cozy/cozy-stack/pkg/jsonapi"
multierror "github.com/hashicorp/go-multierror"
"github.com/labstack/echo/v4"
)
// Group contains the information about a group of members of the sharing.
type Group struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
AddedBy int `json:"addedBy"` // The index of the member who added the group
ReadOnly bool `json:"read_only"`
Revoked bool `json:"revoked,omitempty"`
}
// AddGroup adds a group of contacts identified by its ID to the members of the
// sharing.
func (s *Sharing) AddGroup(inst *instance.Instance, groupID string, readOnly bool) error {
for _, g := range s.Groups {
if g.ID == groupID && !g.Revoked {
return ErrGroupCannotBeAddedTwice
}
}
group, err := contact.FindGroup(inst, groupID)
if err != nil {
return err
}
contacts, err := group.GetAllContacts(inst)
if err != nil {
return err
}
groupIndex := len(s.Groups)
for _, contact := range contacts {
m := buildMemberFromContact(contact, readOnly)
m.Groups = []int{groupIndex}
m.OnlyInGroups = true
_, idx, err := s.addMember(inst, m)
if err != nil {
return err
}
pos := sort.SearchInts(s.Members[idx].Groups, groupIndex)
if pos == len(s.Members[idx].Groups) || s.Members[idx].Groups[pos] != groupIndex {
s.Members[idx].Groups = append(s.Members[idx].Groups, groupIndex)
sort.Ints(s.Members[idx].Groups)
}
}
g := Group{ID: groupID, Name: group.Name(), AddedBy: 0, ReadOnly: readOnly}
s.Groups = append(s.Groups, g)
return nil
}
// RevokeGroup revokes a group of members on the sharer Cozy. After that, the
// sharing is disabled if there are no longer any active recipient.
func (s *Sharing) RevokeGroup(inst *instance.Instance, index int) error {
if !s.Owner {
return ErrInvalidSharing
}
var errm error
for i, m := range s.Members {
inGroup := false
for _, idx := range m.Groups {
if idx == index {
inGroup = true
}
}
if !inGroup {
continue
}
if len(m.Groups) == 1 {
s.Members[i].Groups = nil
} else {
var groups []int
for _, idx := range m.Groups {
if idx != index {
groups = append(groups, idx)
}
}
s.Members[i].Groups = groups
}
if m.OnlyInGroups && len(s.Members[i].Groups) == 0 {
if err := s.RevokeRecipient(inst, i); err != nil {
errm = multierror.Append(errm, err)
}
}
}
s.Groups[index].Revoked = true
if err := couchdb.UpdateDoc(inst, s); err != nil {
errm = multierror.Append(errm, err)
}
return errm
}
// UpdateGroups is called when a contact is added or removed to a group. It
// finds the sharings for this group, and adds or removes the member to those
// sharings.
func UpdateGroups(inst *instance.Instance, msg job.ShareGroupMessage) error {
if msg.RenamedGroup != nil {
return updateRenamedGroup(inst, msg.RenamedGroup)
}
var c *contact.Contact
if msg.DeletedDoc != nil {
c = &contact.Contact{JSONDoc: *msg.DeletedDoc}
} else {
doc, err := contact.Find(inst, msg.ContactID)
if err != nil {
return err
}
c = doc
}
sharings, err := FindActive(inst)
if err != nil {
return err
}
var errm error
for _, s := range sharings {
for _, added := range msg.GroupsAdded {
for idx, group := range s.Groups {
if group.ID == added {
if s.Owner {
if err := s.AddMemberToGroup(inst, idx, c); err != nil {
errm = multierror.Append(errm, err)
}
} else {
if err := s.DelegateAddMemberToGroup(inst, idx, c); err != nil {
errm = multierror.Append(errm, err)
}
}
}
}
}
for _, removed := range msg.GroupsRemoved {
for idx, group := range s.Groups {
if group.ID == removed {
if s.Owner {
if err := s.RemoveMemberFromGroup(inst, idx, c); err != nil {
errm = multierror.Append(errm, err)
}
} else {
if err := s.DelegateRemoveMemberFromGroup(inst, idx, c); err != nil {
errm = multierror.Append(errm, err)
}
}
}
}
}
if msg.BecomeInvitable {
if err := s.AddInvitationForContact(inst, c); err != nil {
errm = multierror.Append(errm, err)
}
}
}
return errm
}
func updateRenamedGroup(inst *instance.Instance, doc *couchdb.JSONDoc) error {
sharings, err := FindActive(inst)
if err != nil {
return err
}
var errm error
for _, s := range sharings {
for idx, group := range s.Groups {
if group.ID == doc.ID() {
if name, ok := doc.M["name"].(string); ok {
group.Name = name
s.Groups[idx] = group
if err := couchdb.UpdateDoc(inst, s); err != nil {
errm = multierror.Append(errm, err)
}
cloned := s.Clone().(*Sharing)
go cloned.NotifyRecipients(inst, nil)
}
}
}
}
return errm
}
// AddMemberToGroup adds a contact to a sharing via a group (on the owner).
func (s *Sharing) AddMemberToGroup(inst *instance.Instance, groupIndex int, contact *contact.Contact) error {
readOnly := s.Groups[groupIndex].ReadOnly
m := buildMemberFromContact(contact, readOnly)
m.OnlyInGroups = true
_, idx, err := s.addMember(inst, m)
if err != nil {
return err
}
s.Members[idx].Groups = append(s.Members[idx].Groups, groupIndex)
sort.Ints(s.Members[idx].Groups)
// We can ignore the error as we will try again to save the sharing
// after sending the invitation.
_ = couchdb.UpdateDoc(inst, s)
var perms *permission.Permission
if s.PreviewPath != "" {
if perms, err = s.CreatePreviewPermissions(inst); err != nil {
return err
}
}
if err = s.SendInvitations(inst, perms); err != nil {
return err
}
cloned := s.Clone().(*Sharing)
go cloned.NotifyRecipients(inst, nil)
return nil
}
// DelegateAddMemberToGroup adds a contact to a sharing via a group (on a recipient).
func (s *Sharing) DelegateAddMemberToGroup(inst *instance.Instance, groupIndex int, contact *contact.Contact) error {
readOnly := s.Groups[groupIndex].ReadOnly
m := buildMemberFromContact(contact, readOnly)
m.OnlyInGroups = true
m.Groups = []int{groupIndex}
api := &APIDelegateAddContacts{
sid: s.ID(),
members: []Member{m},
}
return s.SendDelegated(inst, api)
}
// RemoveMemberFromGroup removes a member of a group.
func (s *Sharing) RemoveMemberFromGroup(inst *instance.Instance, groupIndex int, contact *contact.Contact) error {
var email string
if addr, err := contact.ToMailAddress(); err == nil {
email = addr.Email
}
cozyURL := contact.PrimaryCozyURL()
matchMember := func(m Member) bool {
if m.Email != "" && m.Email == email {
return true
}
if m.Instance != "" && m.Instance == cozyURL {
return true
}
return false
}
for i, m := range s.Members {
if !matchMember(m) {
continue
}
var groups []int
for _, idx := range m.Groups {
if idx != groupIndex {
groups = append(groups, idx)
}
}
s.Members[i].Groups = groups
if m.OnlyInGroups && len(s.Members[i].Groups) == 0 {
return s.RevokeRecipient(inst, i)
} else {
return couchdb.UpdateDoc(inst, s)
}
}
return nil
}
// DelegateRemoveMemberFromGroup removes a member from a sharing group (on a recipient).
func (s *Sharing) DelegateRemoveMemberFromGroup(inst *instance.Instance, groupIndex int, contact *contact.Contact) error {
var email string
if addr, err := contact.ToMailAddress(); err == nil {
email = addr.Email
}
cozyURL := contact.PrimaryCozyURL()
for i, m := range s.Members {
if m.Email != "" && m.Email == email {
return s.SendRemoveMemberFromGroup(inst, groupIndex, i)
}
if m.Instance != "" && m.Instance == cozyURL {
return s.SendRemoveMemberFromGroup(inst, groupIndex, i)
}
}
return ErrMemberNotFound
}
func (s *Sharing) SendRemoveMemberFromGroup(inst *instance.Instance, groupIndex, memberIndex int) error {
u, err := url.Parse(s.Members[0].Instance)
if err != nil {
return err
}
c := &s.Credentials[0]
if c.AccessToken == nil {
return ErrInvalidSharing
}
opts := &request.Options{
Method: http.MethodDelete,
Scheme: u.Scheme,
Domain: u.Host,
Path: fmt.Sprintf("/sharings/%s/groups/%d/%d", s.SID, groupIndex, memberIndex),
Headers: request.Headers{
echo.HeaderAuthorization: "Bearer " + c.AccessToken.AccessToken,
},
ParseError: ParseRequestError,
}
res, err := request.Req(opts)
if res != nil && res.StatusCode/100 == 4 {
res, err = RefreshToken(inst, err, s, &s.Members[0], c, opts, nil)
}
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent {
return ErrInternalServerError
}
return nil
}
func (s *Sharing) DelegatedRemoveMemberFromGroup(inst *instance.Instance, groupIndex, memberIndex int) error {
var groups []int
for _, idx := range s.Members[memberIndex].Groups {
if idx != groupIndex {
groups = append(groups, idx)
}
}
s.Members[memberIndex].Groups = groups
if s.Members[memberIndex].OnlyInGroups && len(s.Members[memberIndex].Groups) == 0 {
return s.RevokeRecipient(inst, memberIndex)
} else {
return couchdb.UpdateDoc(inst, s)
}
}
func (s *Sharing) AddInvitationForContact(inst *instance.Instance, contact *contact.Contact) error {
var email string
if addr, err := contact.ToMailAddress(); err == nil {
email = addr.Email
}
cozyURL := contact.PrimaryCozyURL()
name := contact.PrimaryName()
groupIDs := contact.GroupIDs()
matchMember := func(m Member) bool {
if m.Name != name {
return false
}
for _, gid := range groupIDs {
for _, g := range m.Groups {
if s.Groups[g].ID == gid {
return true
}
}
}
return false
}
for i, m := range s.Members {
if i == 0 || m.Status != MemberStatusMailNotSent {
continue
}
if !matchMember(m) {
continue
}
m.Email = email
m.Instance = cozyURL
s.Members[i] = m
if !s.Owner {
return s.DelegateAddInvitation(inst, i)
}
// We can ignore the error as we will try again to save the sharing
// after sending the invitation.
_ = couchdb.UpdateDoc(inst, s)
var perms *permission.Permission
var err error
if s.PreviewPath != "" {
if perms, err = s.CreatePreviewPermissions(inst); err != nil {
return err
}
}
if err = s.SendInvitations(inst, perms); err != nil {
return err
}
cloned := s.Clone().(*Sharing)
go cloned.NotifyRecipients(inst, nil)
return nil
}
return nil
}
func (s *Sharing) DelegateAddInvitation(inst *instance.Instance, memberIndex int) error {
body, err := json.Marshal(map[string]interface{}{
"data": map[string]interface{}{
"type": consts.SharingsMembers,
"attributes": s.Members[memberIndex],
},
})
if err != nil {
return err
}
u, err := url.Parse(s.Members[0].Instance)
if err != nil {
return err
}
c := &s.Credentials[0]
if c.AccessToken == nil {
return ErrInvalidSharing
}
opts := &request.Options{
Method: http.MethodPost,
Scheme: u.Scheme,
Domain: u.Host,
Path: fmt.Sprintf("/sharings/%s/members/%d/invitation", s.ID(), memberIndex),
Headers: request.Headers{
echo.HeaderAccept: echo.MIMEApplicationJSON,
echo.HeaderContentType: jsonapi.ContentType,
echo.HeaderAuthorization: "Bearer " + c.AccessToken.AccessToken,
},
Body: bytes.NewReader(body),
ParseError: ParseRequestError,
}
res, err := request.Req(opts)
if res != nil && res.StatusCode/100 == 4 {
res, err = RefreshToken(inst, err, s, &s.Members[0], c, opts, body)
}
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return ErrInternalServerError
}
var states map[string]string
if err = json.NewDecoder(res.Body).Decode(&states); err != nil {
return err
}
// We can have conflicts when updating the sharing document, so we are
// retrying when it is the case.
maxRetries := 3
i := 0
for {
s.Members[i].Status = MemberStatusReady
if err := couchdb.UpdateDoc(inst, s); err == nil {
break
}
i++
if i > maxRetries {
return err
}
time.Sleep(1 * time.Second)
s, err = FindSharing(inst, s.SID)
if err != nil {
return err
}
}
return s.SendInvitationsToMembers(inst, []Member{s.Members[memberIndex]}, states)
}