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
|
// Eko: A terminal based social media platform
// Copyright (C) 2025 Kyren223
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package state
import (
"context"
"crypto/ed25519"
"encoding/json"
"log"
"slices"
"time"
"github.com/google/btree"
"github.com/kyren223/eko/internal/client/gateway"
"github.com/kyren223/eko/internal/data"
"github.com/kyren223/eko/internal/packet"
"github.com/kyren223/eko/pkg/assert"
"github.com/kyren223/eko/pkg/snowflake"
)
type ChatState struct {
IncompleteMessage string
Base int
MaxHeight int
}
type state struct {
ChatState map[snowflake.ID]ChatState // key is frequency id or receiver id
LastFrequency map[snowflake.ID]snowflake.ID // key is network id
Messages map[snowflake.ID]*btree.BTreeG[data.Message] // key is frequency id or receiver id
Networks map[snowflake.ID]data.Network // key is network id
Frequencies map[snowflake.ID][]data.Frequency // key is network id
Members map[snowflake.ID]map[snowflake.ID]data.Member // key is network id then user id
Users map[snowflake.ID]data.User // key is user id
TrustedUsers map[snowflake.ID]ed25519.PublicKey // key is user id
BlockedUsers map[snowflake.ID]struct{} // key is user id
BlockingUsers map[snowflake.ID]struct{} // key is user id
LastReadMessages map[snowflake.ID]*snowflake.ID // key is frequency id or receiver id
RemoteNotifications map[snowflake.ID]int // key is frequency id or receiver id
LocalNotifications map[snowflake.ID]int // key is frequency id or receiver id
}
var State state = state{
ChatState: map[snowflake.ID]ChatState{},
LastFrequency: map[snowflake.ID]snowflake.ID{},
Messages: map[snowflake.ID]*btree.BTreeG[data.Message]{},
Networks: map[snowflake.ID]data.Network{},
Frequencies: map[snowflake.ID][]data.Frequency{},
Members: map[snowflake.ID]map[snowflake.ID]data.Member{},
Users: map[snowflake.ID]data.User{},
TrustedUsers: map[snowflake.ID]ed25519.PublicKey{},
BlockedUsers: map[snowflake.ID]struct{}{},
BlockingUsers: map[snowflake.ID]struct{}{},
LastReadMessages: map[snowflake.ID]*snowflake.ID{},
RemoteNotifications: map[snowflake.ID]int{},
LocalNotifications: map[snowflake.ID]int{},
}
type UserData struct {
Networks []snowflake.ID
Signals []snowflake.ID
}
var Data UserData = UserData{
Networks: []snowflake.ID{},
Signals: []snowflake.ID{},
}
var UserID *snowflake.ID = nil
func UpdateNetworks(info *packet.NetworksInfo) {
networks := State.Networks
for _, removedNetworkId := range info.RemovedNetworks {
delete(networks, removedNetworkId)
delete(State.Frequencies, removedNetworkId)
delete(State.Members, removedNetworkId)
for i, network := range Data.Networks {
if network == removedNetworkId {
copy(Data.Networks[i:], Data.Networks[i+1:])
Data.Networks = Data.Networks[:len(Data.Networks)-1]
break
}
}
}
for _, network := range info.Networks {
if !slices.Contains(Data.Networks, network.ID) {
Data.Networks = append(Data.Networks, network.ID)
}
networks[network.ID] = network.Network
if info.Partial {
continue
}
State.Frequencies[network.ID] = network.Frequencies
for _, member := range network.Members {
if State.Members[network.ID] == nil {
State.Members[network.ID] = map[snowflake.ID]data.Member{}
}
State.Members[network.ID][member.UserID] = member
}
for _, user := range network.Users {
State.Users[user.ID] = user
}
}
// Remove any unrecognized networks
Data.Networks = slices.DeleteFunc(Data.Networks, func(id snowflake.ID) bool {
_, ok := State.Networks[id]
return !ok
})
}
func UpdateFrequencies(info *packet.FrequenciesInfo) {
frequencies := State.Frequencies[info.Network]
frequencies = slices.DeleteFunc(frequencies, func(frequency data.Frequency) bool {
return slices.Contains(info.RemovedFrequencies, frequency.ID)
})
for i, frequency := range frequencies {
frequency.Position = int64(i)
frequencies[i] = frequency
}
for _, newFrequency := range info.Frequencies {
position := int(newFrequency.Position)
if len(frequencies) == position {
frequencies = append(frequencies, newFrequency)
} else if position < len(frequencies) {
frequencies[position] = newFrequency
}
}
State.Frequencies[info.Network] = frequencies
}
func UpdateMessages(info *packet.MessagesInfo) {
for _, id := range info.RemovedMessages {
for _, btree := range State.Messages {
btree.Delete(data.Message{ID: id})
}
}
unknownUsers := []snowflake.ID{}
for _, message := range info.Messages {
msgSource := message.FrequencyID
if msgSource == nil {
msgSource = message.ReceiverID
if *message.ReceiverID == *UserID {
msgSource = &message.SenderID
}
}
bt := State.Messages[*msgSource]
if bt == nil {
bt = btree.NewG(2, func(a, b data.Message) bool {
return a.ID < b.ID
})
State.Messages[*msgSource] = bt
}
bt.ReplaceOrInsert(message)
if _, ok := State.Users[message.SenderID]; !ok {
unknownUsers = append(unknownUsers, message.SenderID)
}
}
gateway.SendAsync(&packet.GetUsers{
Users: unknownUsers,
})
// Note: this is a naive approach
// Ideally we check each message that was added/removed
// For the frequency/receiver/sender id and only remove that
// But it can be very slow when there are thousands of messages
// TODO: when msg chunking is implemented, consider doing it per-msg
// TODO: consider checking messages count and for small counts use
// the per message approach
for id, state := range State.ChatState {
state.MaxHeight = -1
State.ChatState[id] = state
}
}
func UpdateMembers(info *packet.MembersInfo) {
for _, member := range info.Members {
if State.Members[info.Network] == nil {
State.Members[info.Network] = map[snowflake.ID]data.Member{}
}
State.Members[info.Network][member.UserID] = member
}
for _, removedMember := range info.RemovedMembers {
delete(State.Members[info.Network], removedMember)
if removedMember != *UserID {
continue
}
delete(State.Networks, info.Network)
delete(State.Frequencies, info.Network)
delete(State.Members, info.Network)
for i, network := range Data.Networks {
if network == info.Network {
copy(Data.Networks[i:], Data.Networks[i+1:])
Data.Networks = Data.Networks[:len(Data.Networks)-1]
break
}
}
}
for _, user := range info.Users {
State.Users[user.ID] = user
}
}
func NetworkId(index int) *snowflake.ID {
if 0 <= index && index < len(Data.Networks) {
return &Data.Networks[index]
}
return nil
}
func JsonUserData() string {
bytes, err := json.Marshal(Data)
assert.NoError(err, "marshling should never fail")
return string(bytes)
}
func FromJsonUserData(s string) {
var data UserData
err := json.Unmarshal([]byte(s), &data)
if err != nil {
return
}
// log.Println("Previous user data:", Data)
if data.Networks != nil {
Data.Networks = data.Networks
}
if data.Signals != nil {
Data.Signals = data.Signals
}
log.Println("Updated user data:", Data)
}
func UpdateTrustedUsers(info *packet.TrustInfo) {
for _, removed := range info.RemovedTrustedUsers {
delete(State.TrustedUsers, removed)
}
for i, trusted := range info.TrustedUsers {
State.TrustedUsers[trusted] = info.TrustedPublicKeys[i]
}
}
func GetLastMessage(id snowflake.ID) *snowflake.ID {
btree := State.Messages[id]
if btree == nil {
return nil
}
msg, ok := btree.Max()
if !ok {
return nil
}
return &msg.ID
}
func IsFrequency(id snowflake.ID) bool {
// OPTIMIZE: this is very expensive and inefficient
// A map is better but as most of the time frequencies are iterated
// over based on a network id, this would add overhead
// And this function is only used once in notifications
// Maybe there should be a special bit in the snowflake to determine this?
// This could work if frequencies, user IDs, network IDs etc would all have
// their own "pool" to generate from (using the "machine id" bits)
for _, frequencies := range State.Frequencies {
for _, frequency := range frequencies {
if id == frequency.ID {
return true
}
}
}
return false
}
func UpdateNotifications(info *packet.NotificationsInfo) []snowflake.ID {
signals := []snowflake.ID{}
for i := 0; i < len(info.Source); i++ {
source := info.Source[i]
lastRead := snowflake.ID(info.LastRead[i])
State.LastReadMessages[source] = &lastRead
ping := info.Pings[i]
if ping != nil {
State.RemoteNotifications[source] = int(*ping)
// When someone messages you, and you don't have a signal with him
// already, add a signal with him so you see his messages
// PERF: IsFrequency is expensive so contains is checked first
if !slices.Contains(Data.Signals, source) && !IsFrequency(source) {
signals = append(signals, source)
}
} else {
delete(State.RemoteNotifications, info.Source[i])
}
}
return signals
}
func SendFinalData() {
data := JsonUserData()
// ch1 := gateway.SendAsync(&packet.SetUserData{
// Data: &data,
// User: nil,
// })
sources := []snowflake.ID{}
sources = append(sources, Data.Signals...)
for _, frequencies := range State.Frequencies {
for _, frequency := range frequencies {
sources = append(sources, frequency.ID)
}
}
lastReads := make([]int64, 0, len(sources))
for _, source := range sources {
if lastRead := State.LastReadMessages[source]; lastRead != nil {
lastReads = append(lastReads, int64(*lastRead))
} else {
lastReads = append(lastReads, 0)
}
}
ch1 := gateway.SendAsync(&packet.SetUserData{
Data: &data,
User: nil,
})
ch2 := gateway.SendAsync(&packet.SetLastReadMessages{
Source: sources,
LastRead: lastReads,
})
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
done := make(chan struct{})
go func() {
<-ch1
<-ch2
close(done)
}()
select {
case <-ctx.Done():
log.Println("Timeout while waiting for final writes to complete")
case <-done:
log.Println("All final writes completed successfully")
}
// HACK: Give a small grace period for the writes to be processed
// Tweak this value as needed
time.Sleep(20 * time.Millisecond)
// TODO:
// I think the issue is that it's random which of these 2 requests goes
// first (bcz it only does the first request after the client disconnects)
// I could fix it server side but eh maybe not
// this should instead use a method that blocks until a response was
// received, which may need a new gateway method to do that as currently
// it just always sends to the prograg
// If this is tedious enough it might be worth it to just do it on the
// server side
// Also later on I should probably remove the calculate notifs in core
// it can be replaced with just diff-ing incoming notifs
// this will most likely work fine although there are some issues with
// scopes like becoming an admin/no longer being admin or gaining
// or losing access to frequencies and of course msg deletions
// But it's probably the right approach (also WAYYYYYY faster)
// Then there is also the issue of when switching to a frequency
// not yet receiving the history so it says "no keep" bcz it's not loaded
// but with history it would've said "yes keep" so the solutin would
// be to rework it quite a bit to make it stateless or smthing
// Then that should be most issues when it comes to notifications
// just need to make sure local/remote notifs reset properly when
// reaching the bottom
// log.Println("BLOCKING...")
// <-ctx.Done()
// log.Println("CTX DANZO")
// TODO: remove this before release
// assert.NoError(ctx.Err(), "context has ran out of time!")
}
func UpdateBlockedUsers(info *packet.BlockInfo) {
for _, removed := range info.RemovedBlockedUsers {
delete(State.BlockedUsers, removed)
}
for _, blocked := range info.BlockedUsers {
State.BlockedUsers[blocked] = struct{}{}
delete(State.TrustedUsers, blocked)
}
for _, removed := range info.RemovedBlockingUsers {
delete(State.BlockingUsers, removed)
}
for _, blocking := range info.BlockingUsers {
State.BlockingUsers[blocking] = struct{}{}
}
}
func UpdateUsersInfo(info *packet.UsersInfo) {
for _, user := range info.Users {
State.Users[user.ID] = user
}
}
func MergedNotification(chatId snowflake.ID) (pings int, ok bool) {
remotePings, remoteOk := State.RemoteNotifications[chatId]
localPings, localOk := State.LocalNotifications[chatId]
return remotePings + localPings, remoteOk || localOk
}
|