forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat_local.go
355 lines (307 loc) · 9.11 KB
/
chat_local.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
// Copyright 2018 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"context"
"fmt"
"sort"
"sync"
"time"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/chat1"
"github.com/pkg/errors"
)
type convLocal struct {
convID chat1.ConversationID
chanName string
messages []string
cbs []ChatChannelNewMessageCB
mtime time.Time
}
type convLocalByIDMap map[string]*convLocal
type convLocalByNameMap map[tlf.CanonicalName]convLocalByIDMap
type convLocalByTypeMap map[tlf.Type]convLocalByNameMap
type newConvCB func(context.Context, *TlfHandle, chat1.ConversationID, string)
type chatLocalSharedData struct {
lock sync.RWMutex
newChannelCBs map[Config]newConvCB
convs convLocalByTypeMap
convsByID convLocalByIDMap
}
type selfConvInfo struct {
convID chat1.ConversationID
tlfName tlf.CanonicalName
tlfType tlf.Type
}
// chatLocal is a local implementation for chat.
type chatLocal struct {
config Config
log logger.Logger
deferLog logger.Logger
data *chatLocalSharedData
lock sync.Mutex
selfConvInfos []selfConvInfo
}
func newChatLocalWithData(config Config, data *chatLocalSharedData) *chatLocal {
log := config.MakeLogger("")
deferLog := log.CloneWithAddedDepth(1)
return &chatLocal{
log: log,
deferLog: deferLog,
config: config,
data: data,
}
}
// newChatLocal constructs a new local chat implementation.
func newChatLocal(config Config) *chatLocal {
return newChatLocalWithData(config, &chatLocalSharedData{
convs: make(convLocalByTypeMap),
convsByID: make(convLocalByIDMap),
newChannelCBs: map[Config]newConvCB{
config: nil,
},
})
}
var _ Chat = (*chatLocal)(nil)
// GetConversationID implements the Chat interface.
func (c *chatLocal) GetConversationID(
ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
channelName string, chatType chat1.TopicType) (
chat1.ConversationID, error) {
if chatType != chat1.TopicType_KBFSFILEEDIT {
panic(fmt.Sprintf("Bad topic type: %d", chatType))
}
c.data.lock.Lock()
defer c.data.lock.Unlock()
byID, ok := c.data.convs[tlfType][tlfName]
if !ok {
if _, ok := c.data.convs[tlfType]; !ok {
c.data.convs[tlfType] = make(convLocalByNameMap)
}
if _, ok := c.data.convs[tlfType][tlfName]; !ok {
byID = make(convLocalByIDMap)
c.data.convs[tlfType][tlfName] = byID
}
}
for _, conv := range byID {
if conv.chanName == channelName {
return conv.convID, nil
}
}
// Make a new conversation.
var idBytes [8]byte
err := kbfscrypto.RandRead(idBytes[:])
if err != nil {
return nil, err
}
id := chat1.ConversationID(idBytes[:])
c.log.CDebugf(ctx, "Making new conversation for %s, %s: %s",
tlfName, channelName, id)
conv := &convLocal{
convID: id,
chanName: channelName,
}
c.data.convs[tlfType][tlfName][id.String()] = conv
c.data.convsByID[id.String()] = conv
h, err := GetHandleFromFolderNameAndType(
ctx, c.config.KBPKI(), c.config.MDOps(), string(tlfName), tlfType)
if err != nil {
return nil, err
}
for config, cb := range c.data.newChannelCBs {
// Only send notifications to those that can read the TLF.
session, err := config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return nil, err
}
isReader, err := isReaderFromHandle(ctx, h, config.KBPKI(), session.UID)
if err != nil {
return nil, err
}
if !isReader {
continue
}
if cb == nil && config.KBFSOps() != nil {
cb = config.KBFSOps().NewNotificationChannel
}
cb(ctx, h, id, channelName)
}
return id, nil
}
// SendTextMessage implements the Chat interface.
func (c *chatLocal) SendTextMessage(
ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
convID chat1.ConversationID, body string) error {
c.data.lock.Lock()
defer c.data.lock.Unlock()
conv, ok := c.data.convs[tlfType][tlfName][convID.String()]
if !ok {
return errors.Errorf("Conversation %s doesn't exist", convID.String())
}
conv.messages = append(conv.messages, body)
conv.mtime = c.config.Clock().Now()
c.lock.Lock()
// For testing purposes just keep a running tab of all
// self-written conversations. Reconsider if we run into memory
// or performance issues. TODO: if we ever run an edit history
// test with multiple devices from the same user, we'll need to
// save this data in the shared info.
c.selfConvInfos = append(
c.selfConvInfos, selfConvInfo{convID, tlfName, tlfType})
c.lock.Unlock()
// TODO: if there are some users who can read this folder but who
// haven't yet subscribed to the conversation, we should send them
// a new channel notification.
for _, cb := range conv.cbs {
cb(convID, body)
}
return nil
}
type chatHandleAndTime struct {
h *TlfHandle
mtime time.Time
}
type chatHandleAndTimeByMtime []chatHandleAndTime
func (chatbm chatHandleAndTimeByMtime) Len() int {
return len(chatbm)
}
func (chatbm chatHandleAndTimeByMtime) Less(i, j int) bool {
// Reverse sort so newest conversation is at index 0.
return chatbm[i].mtime.After(chatbm[j].mtime)
}
func (chatbm chatHandleAndTimeByMtime) Swap(i, j int) {
chatbm[i], chatbm[j] = chatbm[j], chatbm[i]
}
// GetGroupedInbox implements the Chat interface.
func (c *chatLocal) GetGroupedInbox(
ctx context.Context, chatType chat1.TopicType, maxChats int) (
results []*TlfHandle, err error) {
if chatType != chat1.TopicType_KBFSFILEEDIT {
panic(fmt.Sprintf("Bad topic type: %d", chatType))
}
session, err := c.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return nil, err
}
var handlesAndTimes chatHandleAndTimeByMtime
seen := make(map[string]bool)
c.data.lock.Lock()
defer c.data.lock.Unlock()
for t, byName := range c.data.convs {
for name, byID := range byName {
if t == tlf.Public && string(name) != string(session.Name) {
// Skip public TLFs that aren't our own.
continue
}
h, err := GetHandleFromFolderNameAndType(
ctx, c.config.KBPKI(), c.config.MDOps(), string(name), t)
if err != nil {
return nil, err
}
// Only include if the current user can read the folder.
isReader, err := isReaderFromHandle(
ctx, h, c.config.KBPKI(), session.UID)
if err != nil {
return nil, err
}
if !isReader {
continue
}
hAndT := chatHandleAndTime{h: h}
for _, conv := range byID {
if conv.mtime.After(hAndT.mtime) {
hAndT.mtime = conv.mtime
}
}
handlesAndTimes = append(handlesAndTimes, hAndT)
seen[h.GetCanonicalPath()] = true
}
}
sort.Sort(handlesAndTimes)
for i := 0; i < len(handlesAndTimes) && i < maxChats; i++ {
results = append(results, handlesAndTimes[i].h)
}
c.lock.Lock()
defer c.lock.Unlock()
var selfHandles []*TlfHandle
max := numSelfTlfs
for i := len(c.selfConvInfos) - 1; i >= 0 && len(selfHandles) < max; i-- {
info := c.selfConvInfos[i]
h, err := GetHandleFromFolderNameAndType(
ctx, c.config.KBPKI(), c.config.MDOps(),
string(info.tlfName), info.tlfType)
if err != nil {
return nil, err
}
p := h.GetCanonicalPath()
if seen[p] {
continue
}
seen[p] = true
selfHandles = append(selfHandles, h)
}
numOver := len(results) + len(selfHandles) - maxChats
if numOver < 0 {
numOver = 0
}
results = append(results[:len(results)-numOver], selfHandles...)
return results, nil
}
// GetChannels implements the Chat interface.
func (c *chatLocal) GetChannels(
ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
chatType chat1.TopicType) (
convIDs []chat1.ConversationID, channelNames []string, err error) {
if chatType != chat1.TopicType_KBFSFILEEDIT {
panic(fmt.Sprintf("Bad topic type: %d", chatType))
}
c.data.lock.RLock()
defer c.data.lock.RUnlock()
byID := c.data.convs[tlfType][tlfName]
for _, conv := range byID {
convIDs = append(convIDs, conv.convID)
channelNames = append(channelNames, conv.chanName)
}
return convIDs, channelNames, nil
}
// ReadChannel implements the Chat interface.
func (c *chatLocal) ReadChannel(
ctx context.Context, convID chat1.ConversationID, startPage []byte) (
messages []string, nextPage []byte, err error) {
c.data.lock.RLock()
defer c.data.lock.RUnlock()
conv, ok := c.data.convsByID[convID.String()]
if !ok {
return nil, nil, errors.Errorf(
"Conversation %s doesn't exist", convID.String())
}
// For now, no paging, just return the complete list.
return conv.messages, nil, nil
}
// RegisterForMessages implements the Chat interface.
func (c *chatLocal) RegisterForMessages(
convID chat1.ConversationID, cb ChatChannelNewMessageCB) {
c.data.lock.Lock()
defer c.data.lock.Unlock()
conv, ok := c.data.convsByID[convID.String()]
if !ok {
panic(fmt.Sprintf("Conversation %s doesn't exist", convID.String()))
}
conv.cbs = append(conv.cbs, cb)
}
func (c *chatLocal) copy(config Config) *chatLocal {
copy := newChatLocalWithData(config, c.data)
c.data.lock.Lock()
defer c.data.lock.Unlock()
c.data.newChannelCBs[config] = config.KBFSOps().NewNotificationChannel
return copy
}
// ClearCache implements the Chat interface.
func (c *chatLocal) ClearCache() {
c.lock.Lock()
defer c.lock.Unlock()
c.selfConvInfos = nil
}