forked from keybase/client
/
livelocation.go
428 lines (398 loc) · 12.6 KB
/
livelocation.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
package maps
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/clockwork"
"golang.org/x/sync/errgroup"
)
type LiveLocationTracker struct {
globals.Contextified
utils.DebugLabeler
sync.Mutex
clock clockwork.Clock
storage *trackStorage
updateInterval time.Duration
uid gregor1.UID
eg errgroup.Group
trackers map[types.LiveLocationKey]*locationTrack
lastCoord chat1.Coordinate
maxCoords int
// testing only
TestingCoordsAddedCh chan struct{}
}
func NewLiveLocationTracker(g *globals.Context) *LiveLocationTracker {
return &LiveLocationTracker{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "LiveLocationTracker", false),
storage: newTrackStorage(g),
trackers: make(map[types.LiveLocationKey]*locationTrack),
updateInterval: 30 * time.Second,
maxCoords: 500,
clock: clockwork.NewRealClock(),
}
}
func (l *LiveLocationTracker) Start(ctx context.Context, uid gregor1.UID) {
defer l.Trace(ctx, nil, "Start")()
l.Lock()
defer l.Unlock()
l.uid = uid
// bring back any trackers that we have stored. This is most relavent when being woken
// up on iOS due to a location update. THe app might need to recreate all of its trackers
// if the app had been killed.
l.restoreLocked(ctx)
}
func (l *LiveLocationTracker) Stop(ctx context.Context) chan struct{} {
defer l.Trace(ctx, nil, "Stop")()
l.Lock()
defer l.Unlock()
ch := make(chan struct{})
for _, t := range l.trackers {
t.Stop()
}
go func() {
_ = l.eg.Wait()
close(ch)
}()
return ch
}
func (l *LiveLocationTracker) ActivelyTracking(ctx context.Context) bool {
l.Lock()
defer l.Unlock()
return len(l.trackers) > 0
}
func (l *LiveLocationTracker) saveLocked(ctx context.Context) {
var trackers []*locationTrack
for _, t := range l.trackers {
trackers = append(trackers, t)
}
if err := l.storage.Save(ctx, trackers); err != nil {
l.Debug(ctx, "save: failed to save: %s", err)
}
}
func (l *LiveLocationTracker) restoreLocked(ctx context.Context) {
trackers, err := l.storage.Restore(ctx)
if err != nil {
l.Debug(ctx, "restoreLocked: failed to read, skipping: %s", err)
return
}
if len(trackers) == 0 {
return
}
l.Debug(ctx, "restoreLocked: restored %d trackers", len(trackers))
l.trackers = make(map[types.LiveLocationKey]*locationTrack)
for _, t := range trackers {
if t.IsStopped() {
continue
}
l.trackers[t.Key()] = t
l.eg.Go(func() error { return l.tracker(t) })
}
}
func (l *LiveLocationTracker) getChatUI(ctx context.Context) libkb.ChatUI {
ui, err := l.G().UIRouter.GetChatUI()
if err != nil || ui == nil {
l.Debug(ctx, "getChatUI: no chat UI found: err: %s", err)
return utils.NullChatUI{}
}
return ui
}
type unfurlNotifyListener struct {
globals.Contextified
utils.DebugLabeler
libkb.NoopNotifyListener
outboxID chat1.OutboxID
doneCh chan struct{}
}
func newUnfurlNotifyListener(g *globals.Context, outboxID chat1.OutboxID, doneCh chan struct{}) *unfurlNotifyListener {
return &unfurlNotifyListener{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "maps.unfurlNotifyListener", false),
outboxID: outboxID,
doneCh: doneCh,
}
}
func (n *unfurlNotifyListener) NewChatActivity(uid keybase1.UID, activity chat1.ChatActivity,
source chat1.ChatActivitySource) {
ctx := context.Background()
st, err := activity.ActivityType()
if err != nil {
n.Debug(ctx, "NewChatActivity: failed to get type: %s", err)
return
}
switch st {
case chat1.ChatActivityType_INCOMING_MESSAGE:
msg := activity.IncomingMessage().Message
if msg.IsOutbox() {
return
}
if n.outboxID.Eq(msg.GetOutboxID()) {
n.doneCh <- struct{}{}
}
case chat1.ChatActivityType_FAILED_MESSAGE:
recs := activity.FailedMessage().OutboxRecords
for _, r := range recs {
if n.outboxID.Eq(&r.OutboxID) {
n.doneCh <- struct{}{}
break
}
}
}
}
func (l *LiveLocationTracker) updateMapUnfurl(ctx context.Context, t *locationTrack, done bool) (err error) {
ctx = globals.ChatCtx(ctx, l.G(), keybase1.TLFIdentifyBehavior_CHAT_GUI, nil, nil)
defer l.Trace(ctx, &err, "updateMapUnfurl")()
msg, err := l.G().ChatHelper.GetMessage(ctx, l.uid, t.convID, t.msgID, true, nil)
if err != nil {
return err
}
if !msg.IsValid() {
return errors.New("invalid message")
}
mvalid := msg.Valid()
var coords []chat1.Coordinate
trackerCoords := t.GetCoords()
if len(trackerCoords) == 0 {
if !l.lastCoord.IsZero() {
coords = []chat1.Coordinate{l.lastCoord}
} else {
return errors.New("no coordinates")
}
} else {
coords = trackerCoords
}
last := coords[len(coords)-1]
conv, err := utils.GetVerifiedConv(ctx, l.G(), l.uid, t.convID, types.InboxSourceDataSourceAll)
if err != nil {
return err
}
// Prefetch the next unfurl, and then delete any others. We do the prefetch so that there isn't
// a large lag after we delete the unfurl and when we post the next one. We link back to the
// tracker in the URL so we can get all the coordinates in the scraper. The cb param
// makes it so the unfurler doesn't think it has already unfurled this URL and skips it.
body := fmt.Sprintf("https://%s/?lat=%f&lon=%f&acc=%f&cb=%s&done=%v", types.MapsDomain,
last.Lat, last.Lon, last.Accuracy, libkb.RandStringB64(3), done)
if !t.getCurrentPosition {
body += fmt.Sprintf("&livekey=%s", t.Key())
}
l.G().Unfurler.Prefetch(ctx, l.uid, t.convID, body)
for unfurlMsgID := range mvalid.Unfurls {
// delete the old unfurl first to make way for the new
if err := l.G().ChatHelper.DeleteMsg(ctx, t.convID, conv.Info.TlfName, unfurlMsgID); err != nil {
return err
}
}
// Create a new unfurl on the new URL, and wait for it to complete before charging forward. This way
// we won't get into a state with multiple unfurls in the thread
mvalid.MessageBody = chat1.NewMessageBodyWithText(chat1.MessageText{
Body: body,
})
newMsg := chat1.NewMessageUnboxedWithValid(mvalid)
unfurlDoneCh := make(chan struct{}, 10)
outboxID := storage.GetOutboxIDFromURL(body, t.convID, newMsg)
listenerID := l.G().NotifyRouter.AddListener(newUnfurlNotifyListener(l.G(), outboxID, unfurlDoneCh))
l.G().Unfurler.UnfurlAndSend(ctx, l.uid, t.convID, newMsg)
select {
case <-unfurlDoneCh:
case <-time.After(time.Minute):
l.Debug(ctx, "updateMapUnfurl: timed out waiting for unfurl callback, charging...")
}
l.G().NotifyRouter.RemoveListener(listenerID)
return nil
}
func (l *LiveLocationTracker) startWatch(ctx context.Context, t *locationTrack) (watchID chat1.LocationWatchID, err error) {
// try this a couple times in case we are starting fresh and the UI isn't ready yet
maxWatchAttempts := 20
watchAttempts := 0
for {
if watchID, err = l.getChatUI(ctx).ChatWatchPosition(ctx, t.convID, t.perm); err != nil {
l.Debug(ctx, "startWatch: unable to watch position: attempt: %d msg: %s", watchAttempts, err)
if watchAttempts > maxWatchAttempts {
return 0, err
}
} else {
break
}
maxWatchAttempts++
time.Sleep(time.Second)
}
return watchID, nil
}
func (l *LiveLocationTracker) tracker(t *locationTrack) error {
ctx := context.Background()
// check to see if we are being asked to start a tracker that is already expired
if t.endTime.Before(l.clock.Now()) {
l.Lock()
defer l.Unlock()
delete(l.trackers, t.Key())
l.saveLocked(ctx)
l.Debug(ctx, "tracker: old tracker, not running and clearing")
return errors.New("tracker from the past")
}
// start up the OS watch routine
watchID, err := l.startWatch(ctx, t)
if err != nil {
return err
}
defer func() {
// drop everything when our live location ends
err := l.getChatUI(ctx).ChatClearWatch(ctx, watchID)
if err != nil {
l.Debug(ctx, "tracker[%v]: error clearing watch: %+v", watchID, err)
}
l.Lock()
defer l.Unlock()
delete(l.trackers, t.Key())
l.saveLocked(ctx)
}()
// if this is a live location request, just put whatever the last coord is on the screen, makes it
// feel more live
if !l.lastCoord.IsZero() {
l.Debug(ctx, "tracker[%v]: updating with last coord", watchID)
t.updateCh <- l.lastCoord
}
firstUpdate := true
shouldUpdate := false
nextUpdate := l.clock.Now().Add(l.updateInterval)
for {
select {
case coord := <-t.updateCh:
added := t.Drain(coord)
l.Debug(ctx, "tracker[%v]: got coords", watchID)
if firstUpdate {
l.Debug(ctx, "tracker[%v]: updating due to live location first update", watchID)
_ = l.updateMapUnfurl(ctx, t, false)
} else {
shouldUpdate = true
}
firstUpdate = false
l.Lock()
l.saveLocked(ctx)
l.Unlock()
l.Debug(ctx, "tracker[%v]: added %d coords", watchID, added)
if l.TestingCoordsAddedCh != nil {
for i := 0; i < added; i++ {
l.TestingCoordsAddedCh <- struct{}{}
}
}
case <-l.clock.AfterTime(nextUpdate):
// we update the map unfurl on a timer so we don't spam delete and recreate it
if shouldUpdate {
// drain anything in the buffer if we are being updated and posting at the same time
t.Drain(chat1.Coordinate{})
l.Debug(ctx, "tracker[%v]: updating due to next update", watchID)
_ = l.updateMapUnfurl(ctx, t, false)
shouldUpdate = false
}
nextUpdate = l.clock.Now().Add(l.updateInterval)
case <-l.clock.AfterTime(t.endTime):
l.Debug(ctx, "tracker[%v]: live location complete, updating", watchID)
added := t.Drain(chat1.Coordinate{})
if t.getCurrentPosition && !shouldUpdate && added == 0 {
// only bother for current position if we have a coordinate
return nil
}
_ = l.updateMapUnfurl(ctx, t, true)
return nil
case <-t.stopCh:
l.Debug(ctx, "tracker[%v]: stopped, updating with done status", watchID)
if t.getCurrentPosition {
// don't need to update here
return nil
}
_ = l.updateMapUnfurl(ctx, t, true)
return nil
}
}
}
func (l *LiveLocationTracker) GetCurrentPosition(ctx context.Context, convID chat1.ConversationID,
msgID chat1.MessageID) {
defer l.Trace(ctx, nil, "GetCurrentPosition")()
l.Lock()
defer l.Unlock()
// start up a live location tracker for a small amount of time to make sure we get a good
// coordinate
t := newLocationTrack(convID, msgID, l.clock.Now().Add(4*time.Second), true, l.maxCoords, false)
l.trackers[t.Key()] = t
l.saveLocked(ctx)
l.eg.Go(func() error { return l.tracker(t) })
}
func (l *LiveLocationTracker) StartTracking(ctx context.Context, convID chat1.ConversationID,
msgID chat1.MessageID, endTime time.Time) {
defer l.Trace(ctx, nil, "StartTracking")()
l.Lock()
defer l.Unlock()
t := newLocationTrack(convID, msgID, endTime, false, l.maxCoords, false)
l.trackers[t.Key()] = t
l.saveLocked(ctx)
l.eg.Go(func() error { return l.tracker(t) })
}
func (l *LiveLocationTracker) LocationUpdate(ctx context.Context, coord chat1.Coordinate) {
defer l.Trace(ctx, nil, "LocationUpdate")()
l.Lock()
defer l.Unlock()
if l.G().IsMobileAppType() {
// if the app is woken up as the result of a location update, and we think we are currently
// backgrounded, then go ahead and mark us as background active so that we can get
// location updates out
l.G().MobileAppState.UpdateWithCheck(keybase1.MobileAppState_BACKGROUNDACTIVE,
func(curState keybase1.MobileAppState) bool {
return curState == keybase1.MobileAppState_BACKGROUND
})
}
if l.lastCoord.Eq(coord) {
l.Debug(ctx, "LocationUpdate: ignoring dup coordinate")
return
}
l.lastCoord = coord
for _, t := range l.trackers {
select {
case t.updateCh <- coord:
default:
l.Debug(ctx, "LocationUpdate: failed to push coordinate, queue full")
}
}
}
func (l *LiveLocationTracker) GetCoordinates(ctx context.Context, key types.LiveLocationKey) (res []chat1.Coordinate) {
defer l.Trace(ctx, nil, "GetCoordinates")()
l.Lock()
defer l.Unlock()
if t, ok := l.trackers[key]; ok {
res = t.GetCoords()
}
if len(res) == 0 {
res = append(res, l.lastCoord)
}
return res
}
func (l *LiveLocationTracker) GetEndTime(ctx context.Context, key types.LiveLocationKey) *time.Time {
defer l.Trace(ctx, nil, "GetEndTime")()
l.Lock()
defer l.Unlock()
if t, ok := l.trackers[key]; ok {
return &t.endTime
}
return nil
}
func (l *LiveLocationTracker) StopAllTracking(ctx context.Context) {
defer l.Trace(ctx, nil, "StopAllTracking")()
l.Lock()
defer l.Unlock()
for _, t := range l.trackers {
t.Stop()
}
l.saveLocked(ctx)
}
func (l *LiveLocationTracker) SetClock(clock clockwork.Clock) {
l.clock = clock
}