-
Notifications
You must be signed in to change notification settings - Fork 243
/
messenger_status_updates.go
324 lines (270 loc) · 8.89 KB
/
messenger_status_updates.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
package protocol
import (
"context"
"fmt"
"time"
"github.com/golang/protobuf/proto"
"go.uber.org/zap"
"github.com/status-im/status-go/multiaccounts/settings"
"github.com/status-im/status-go/protocol/common"
"github.com/status-im/status-go/protocol/communities"
"github.com/status-im/status-go/protocol/protobuf"
"github.com/status-im/status-go/protocol/transport"
)
func (m *Messenger) GetCurrentUserStatus() (*UserStatus, error) {
status := &UserStatus{
StatusType: int(protobuf.StatusUpdate_AUTOMATIC),
Clock: 0,
CustomText: "",
}
err := m.settings.GetCurrentStatus(status)
if err != nil {
m.logger.Debug("Error obtaining latest status", zap.Error(err))
return nil, err
}
return status, nil
}
func (m *Messenger) sendUserStatus(ctx context.Context, status UserStatus) error {
shouldBroadcastUserStatus, err := m.settings.ShouldBroadcastUserStatus()
if err != nil {
return err
}
if !shouldBroadcastUserStatus {
m.logger.Debug("user status should not be broadcasted")
return nil
}
status.Clock = uint64(time.Now().Unix())
err = m.settings.SaveSettingField(settings.CurrentUserStatus, status)
if err != nil {
return err
}
statusUpdate := &protobuf.StatusUpdate{
Clock: status.Clock,
StatusType: protobuf.StatusUpdate_StatusType(status.StatusType),
CustomText: status.CustomText,
}
encodedMessage, err := proto.Marshal(statusUpdate)
if err != nil {
return err
}
contactCodeTopic := transport.ContactCodeTopic(&m.identity.PublicKey)
rawMessage := common.RawMessage{
LocalChatID: contactCodeTopic,
Payload: encodedMessage,
MessageType: protobuf.ApplicationMetadataMessage_STATUS_UPDATE,
ResendAutomatically: true,
}
_, err = m.sender.SendPublic(ctx, contactCodeTopic, rawMessage)
if err != nil {
return err
}
joinedCommunities, err := m.communitiesManager.Joined()
if err != nil {
return err
}
for _, community := range joinedCommunities {
rawMessage.LocalChatID = community.StatusUpdatesChannelID()
_, err = m.sender.SendPublic(ctx, rawMessage.LocalChatID, rawMessage)
if err != nil {
return err
}
}
return nil
}
func (m *Messenger) sendCurrentUserStatus(ctx context.Context) {
err := m.persistence.CleanOlderStatusUpdates()
if err != nil {
m.logger.Debug("Error cleaning status updates", zap.Error(err))
return
}
shouldBroadcastUserStatus, err := m.settings.ShouldBroadcastUserStatus()
if err != nil {
m.logger.Debug("Error while getting status broadcast setting", zap.Error(err))
return
}
if !shouldBroadcastUserStatus {
m.logger.Debug("user status should not be broadcasted")
return
}
currStatus, err := m.GetCurrentUserStatus()
if err != nil {
m.logger.Debug("Error obtaining latest status", zap.Error(err))
return
}
if err := m.sendUserStatus(ctx, *currStatus); err != nil {
m.logger.Debug("Error when sending the latest user status", zap.Error(err))
}
}
func (m *Messenger) sendCurrentUserStatusToCommunity(ctx context.Context, community *communities.Community) error {
logger := m.logger.Named("sendCurrentUserStatusToCommunity")
shouldBroadcastUserStatus, err := m.settings.ShouldBroadcastUserStatus()
if err != nil {
logger.Debug("m.settings.ShouldBroadcastUserStatus error", zap.Error(err))
return err
}
if !shouldBroadcastUserStatus {
logger.Debug("user status should not be broadcasted")
return nil
}
status, err := m.GetCurrentUserStatus()
if err != nil {
logger.Debug("Error obtaining latest status", zap.Error(err))
return err
}
status.Clock = uint64(time.Now().Unix())
err = m.settings.SaveSettingField(settings.CurrentUserStatus, status)
if err != nil {
logger.Debug("m.settings.SaveSetting error",
zap.Any("current-user-status", status),
zap.Error(err))
return err
}
statusUpdate := &protobuf.StatusUpdate{
Clock: status.Clock,
StatusType: protobuf.StatusUpdate_StatusType(status.StatusType),
CustomText: status.CustomText,
}
encodedMessage, err := proto.Marshal(statusUpdate)
if err != nil {
logger.Debug("proto.Marshal error",
zap.Any("protobuf.StatusUpdate", statusUpdate),
zap.Error(err))
return err
}
rawMessage := common.RawMessage{
LocalChatID: community.StatusUpdatesChannelID(),
Payload: encodedMessage,
MessageType: protobuf.ApplicationMetadataMessage_STATUS_UPDATE,
ResendAutomatically: true,
}
_, err = m.sender.SendPublic(ctx, rawMessage.LocalChatID, rawMessage)
if err != nil {
logger.Debug("m.sender.SendPublic error", zap.Error(err))
return err
}
return nil
}
func (m *Messenger) broadcastLatestUserStatus() {
m.logger.Debug("broadcasting user status")
ctx := context.Background()
go func() {
// Ensure that we are connected before sending a message
time.Sleep(5 * time.Second)
m.sendCurrentUserStatus(ctx)
}()
go func() {
for {
select {
case <-time.After(5 * time.Minute):
m.sendCurrentUserStatus(ctx)
case <-m.quit:
return
}
}
}()
}
func (m *Messenger) SetUserStatus(ctx context.Context, newStatus int, newCustomText string) error {
if len([]rune(newCustomText)) > maxStatusMessageText {
return fmt.Errorf("custom text shouldn't be longer than %d", maxStatusMessageText)
}
if newStatus != int(protobuf.StatusUpdate_AUTOMATIC) &&
newStatus != int(protobuf.StatusUpdate_DO_NOT_DISTURB) &&
newStatus != int(protobuf.StatusUpdate_ALWAYS_ONLINE) &&
newStatus != int(protobuf.StatusUpdate_INACTIVE) {
return fmt.Errorf("unknown status type")
}
currStatus, err := m.GetCurrentUserStatus()
if err != nil {
m.logger.Debug("Error obtaining latest status", zap.Error(err))
return err
}
if newStatus == currStatus.StatusType && newCustomText == currStatus.CustomText {
m.logger.Debug("Status type did not change")
return nil
}
currStatus.StatusType = newStatus
currStatus.CustomText = newCustomText
return m.sendUserStatus(ctx, *currStatus)
}
func (m *Messenger) HandleStatusUpdate(state *ReceivedMessageState, statusMessage protobuf.StatusUpdate) error {
if err := ValidateStatusUpdate(statusMessage); err != nil {
return err
}
if common.IsPubKeyEqual(state.CurrentMessageState.PublicKey, &m.identity.PublicKey) { // Status message is ours
currentStatus, err := m.GetCurrentUserStatus()
if err != nil {
m.logger.Debug("Error obtaining latest status", zap.Error(err))
return err
}
if currentStatus.Clock >= statusMessage.Clock {
return nil // older status message, or status does not change ignoring it
}
newStatus := ToUserStatus(statusMessage)
err = m.settings.SaveSettingField(settings.CurrentUserStatus, newStatus)
if err != nil {
return err
}
state.Response.SetCurrentStatus(newStatus)
} else {
statusUpdate := ToUserStatus(statusMessage)
statusUpdate.PublicKey = state.CurrentMessageState.Contact.ID
err := m.persistence.InsertStatusUpdate(statusUpdate)
if err != nil {
return err
}
state.Response.AddStatusUpdate(statusUpdate)
}
return nil
}
func (m *Messenger) StatusUpdates() ([]UserStatus, error) {
return m.persistence.StatusUpdates()
}
func (m *Messenger) timeoutStatusUpdates(fromClock uint64, tillClock uint64) {
// Most of the time we only need to time out just one status update,
// but the range covers special cases like, other status updates had the same clock value
// or the received another status update with higher clock value than the reference clock but
// lower clock value than the nextClock
deactivatedStatusUpdates, err := m.persistence.DeactivatedAutomaticStatusUpdates(fromClock, tillClock)
// Send deactivatedStatusUpdates to Client
if err == nil {
m.config.messengerSignalsHandler.StatusUpdatesTimedOut(&deactivatedStatusUpdates)
} else {
m.logger.Debug("Unable to get deactivated automatic status updates from db", zap.Error(err))
}
}
func (m *Messenger) timeoutAutomaticStatusUpdates() {
nextClock := uint64(0)
waitDuration := uint64(10) // Initial 10 sec wait, to make sure new status updates are fetched before starting timing out loop
fiveMinutes := uint64(5 * 60)
referenceClock := uint64(time.Now().Unix()) - fiveMinutes
go func() {
for {
select {
case <-time.After(time.Duration(waitDuration) * time.Second):
tempNextClock, err := m.persistence.NextHigherClockValueOfAutomaticStatusUpdates(referenceClock)
if err == nil {
if nextClock == 0 || tempNextClock > nextClock {
nextClock = tempNextClock
// Extra 5 sec wait (broadcast receiving delay)
waitDuration = tempNextClock + fiveMinutes + 5 - uint64(time.Now().Unix())
if waitDuration < 0 {
waitDuration = 0
}
} else {
m.timeoutStatusUpdates(referenceClock, tempNextClock)
waitDuration = 0
referenceClock = tempNextClock
}
} else if err == common.ErrRecordNotFound {
// No More status updates to timeout, keep loop running at five minutes interval
waitDuration = fiveMinutes
} else {
m.logger.Debug("Unable to timeout automatic status updates", zap.Error(err))
return
}
case <-m.quit:
return
}
}
}()
}