-
Notifications
You must be signed in to change notification settings - Fork 1
/
space.go
244 lines (212 loc) · 6.05 KB
/
space.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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"sync"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
jose "gopkg.in/square/go-jose.v2"
)
type SpaceTags []string
func (s SpaceTags) Contains(tag string) bool {
for _, v := range s {
if v == tag {
return true
}
}
return false
}
type Space struct {
Id string
EncryptionKey *jose.JSONWebKey
DefaultActivityEncryptionKey *jose.JSONWebKey
DisplayName string
Participants []string
Tags SpaceTags
Team *Team
Activities []*Activity
conversation *Conversation
logger *log.Entry
activitiesMap map[string]*Activity
activitiesMutex sync.RWMutex
}
type RawSpace struct {
Id string
DisplayName string
EncryptionKeyUrl string
DefaultActivityEncryptionKeyUrl string
Tags SpaceTags
Participants struct {
Items []struct {
DisplayName string
EntryUUID string
}
}
Team struct {
Id string
}
Activities struct {
Items []Activity
}
}
func (s *Space) Update(r RawSpace) {
logger := s.conversation.logger.WithField("func", "Update").WithField("rawSpace", r)
// Team ?
if r.Team.Id != "" {
logger = logger.WithField("teamId", r.Team.Id)
team, err := s.conversation.GetTeam(r.Team.Id)
if err != nil {
logger.WithError(err).Error("Failed to get team infos")
} else {
s.Team = team
}
}
// (Other) Participants
newParticipants := []string{}
for _, v := range r.Participants.Items {
if v.EntryUUID == s.conversation.device.UserID {
continue
}
newParticipants = append(newParticipants, v.DisplayName)
}
s.Participants = newParticipants
// Activities
for _, v := range r.Activities.Items {
if v.Verb == "post" || v.Verb == "share" {
s.AddActivity(v)
}
}
// DisplayName
if s.Tags.Contains("TEAM") {
s.DisplayName = "General"
} else if r.DisplayName != "" {
if strings.Count(r.DisplayName, ".") == 4 {
// DisplayName is encrypted
displayName, err := s.Decrypt(r.DisplayName)
if err == nil {
s.DisplayName = string(displayName)
} else {
logger.WithError(err).Error("Failed to decrypt display name")
// Failed to decrypt, keep value
s.DisplayName = r.DisplayName
}
} else {
// Doesn't looks like JWE, keep value
s.DisplayName = r.DisplayName
}
} else {
// No DisplayName, use participants
s.DisplayName = strings.Join(s.Participants, ", ")
}
return
}
func (s *Space) SendMessage(msg string) error {
logger := s.logger.WithField("func", "SendMessage")
encryptedMessage, err := s.EncryptActivity([]byte(msg))
if err != nil {
return errors.Wrap(err, "failed to encrypt message")
}
activity := struct {
ClientTempId string `json:"clientTempId"`
EncryptionKeyUrl string `json:"encryptionKeyUrl"`
ObjectType string `json:"objectType"`
Object struct {
DisplayName string `json:"displayName"`
ObjectType string `json:"objectType"`
} `json:"object"`
Target struct {
Id string `json:"id"`
ObjectType string `json:"objectType"`
} `json:"target"`
Verb string `json:"verb"`
}{
ClientTempId: uuid.Must(uuid.NewV4()).String(),
EncryptionKeyUrl: s.EncryptionKey.KeyID,
ObjectType: "activity",
Verb: "post",
}
activity.Object.DisplayName = encryptedMessage
activity.Object.ObjectType = "comment"
activity.Target.Id = s.Id
activity.Target.ObjectType = "conversation"
data, err := json.Marshal(activity)
if err != nil {
return errors.Wrap(err, "failed to marshal activity")
}
logger.Trace("Send message")
response, err := s.conversation.device.RequestService("POST", "conversationServiceUrl", "/activities", bytes.NewReader(data))
if err != nil {
return errors.Wrap(err, "failed to create request")
}
if response.StatusCode != http.StatusOK {
responseError, err := ioutil.ReadAll(response.Body)
if err != nil {
return errors.Wrap(err, "failed to read error response")
}
return errors.Errorf("failed to send message: %s", responseError)
}
return nil
}
func (s *Space) Decrypt(encryptedString string) ([]byte, error) {
encryptedObject, err := jose.ParseEncrypted(encryptedString)
if err != nil {
return nil, errors.Wrap(err, "failed to parse encrypted message")
}
key := s.EncryptionKey
if key == nil {
key = s.DefaultActivityEncryptionKey
}
decrypted, err := encryptedObject.Decrypt(key)
if err != nil {
return nil, errors.Wrap(err, "failed to decrypt message")
}
return decrypted, nil
}
func (s *Space) EncryptActivity(data []byte) (string, error) {
encrypter, err := jose.NewEncrypter(jose.A256GCM, jose.Recipient{Algorithm: jose.DIRECT, Key: s.DefaultActivityEncryptionKey}, nil)
if err != nil {
return "", errors.Wrap(err, "failed to create jose encrypter")
}
object, err := encrypter.Encrypt(data)
if err != nil {
return "", errors.Wrap(err, "failed to encrypt kms request")
}
return object.CompactSerialize()
}
func (s *Space) AddActivity(a Activity) *Activity {
logger := s.logger.WithField("func", "AddActivity").WithField("activity", a)
s.activitiesMutex.Lock()
defer s.activitiesMutex.Unlock()
// Already seen activity, drop
if a, ok := s.activitiesMap[a.Id]; ok {
return a
}
// Decrypt name if defined
if a.Object.DisplayName != "" {
displayName, err := s.Decrypt(a.Object.DisplayName)
if err != nil {
logger.WithError(err).Error("Failed to decrypt display name")
} else {
a.Object.DisplayName = string(displayName)
}
}
// Insert at the end and see if we need to move the data
s.Activities = append(s.Activities, &a)
length := len(s.Activities)
if length > 1 && s.Activities[length-2].Published.After(a.Published) {
// Our inserted element is older than the last one, walk until we find its place
i := length - 2
for ; i >= 0; i-- {
if s.Activities[i].Published.Before(a.Published) {
break
}
}
copy(s.Activities[i+2:], s.Activities[i+1:length-1])
s.Activities[i+1] = &a
}
return &a
}