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
|
package channel
import (
"citrons.xyz/talk/proto"
"citrons.xyz/talk/server/object"
"citrons.xyz/talk/server/session"
"citrons.xyz/talk/server/validate"
"citrons.xyz/talk/server/user"
"strings"
"strconv"
"slices"
"sort"
"maps"
"bytes"
"bufio"
bolt "go.etcd.io/bbolt"
"log"
)
type ChannelKind struct {
world *object.World
db *bolt.DB
}
type Channel struct {
kind *ChannelKind
id string
name string
isDirect bool
Stream session.Stream
}
func Kind(world *object.World) *ChannelKind {
return &ChannelKind {world, world.DB()}
}
func (cs *ChannelKind) CreateChannel(name string) (*Channel, *proto.Fail) {
if cs.ByName(name) != nil {
return nil, &proto.Fail {
"name-taken", "", map[string]string {"": name},
}
}
if !validate.Name(name) {
return nil, &proto.Fail {
"invalid-name", "", map[string]string {"": name},
}
}
var c Channel
c.kind = cs
c.name = name
c.id = proto.GenId()
c.SetDefaultMembership(DefaultMembership)
c.Save()
return &c, nil
}
func DirectHandle(among map[string]bool) string {
return strings.Join(slices.Sorted(maps.Keys(among)), "\x00")
}
func (cs *ChannelKind) GetDirect(among map[string]bool) *Channel {
handle := DirectHandle(among)
switch ch := cs.world.Lookup("direct-channel", handle).(type) {
case *Channel:
return ch
}
var c Channel
c.isDirect = true
c.kind = cs
c.id = proto.GenId()
for member, _ := range among {
c.SetMembership(member, DefaultMembership)
}
c.Save()
return &c
}
func (cs *ChannelKind) UserChannels(uid string) map[string]bool {
result := make(map[string]bool)
err := cs.db.View(func(tx *bolt.Tx) error {
channels := tx.Bucket([]byte("user channels"))
if channels == nil {
return nil
}
user := channels.Bucket([]byte(uid))
if user == nil {
return nil
}
return user.ForEach(func(k, v []byte) error {
result[string(k)] = true
return nil
})
})
if err != nil {
log.Fatal("error updating database: ", err)
}
return result
}
func (cs *ChannelKind) ByName(name string) *Channel {
switch ch := cs.world.Lookup("channel", name).(type) {
case *Channel:
return ch
default:
return nil
}
}
func (cs *ChannelKind) Undata(o proto.Object) object.Object {
var c Channel
c.kind = cs
c.id = o.Id
c.name = o.Fields[""]
c.isDirect = o.Kind == "direct-channel"
return &c
}
func (c *Channel) Name() string {
return c.NameFor("")
}
func (c *Channel) NameFor(uid string) string {
if !c.isDirect {
return c.name
} else {
var members []string
for member, _ := range c.Members() {
if member == uid && len(c.Members()) > 1 {
continue
}
u := c.kind.world.GetObject(member)
if u != nil {
members = append(members, u.InfoFor(uid).Fields[""])
}
}
sort.Strings(members)
return strings.Join(members, ", ")
}
}
func (c *Channel) Handle() string {
if !c.isDirect {
return c.name
} else {
members := make(map[string]bool)
for member := range c.Members() {
members[member] = true
}
return DirectHandle(members)
}
}
func (c *Channel) Data() proto.Object {
return c.InfoFor("")
}
func (c *Channel) Save() {
c.kind.world.PutObject(c.id, c)
}
func (c *Channel) Id() string {
return c.id
}
func (c *Channel) Rename(name string) *proto.Fail {
if !validate.Name(name) {
return &proto.Fail {
"invalid-name", "", map[string]string {"": name},
}
}
if c.kind.ByName(name) != nil {
return &proto.Fail {
"name-taken", "", map[string]string {"": name},
}
}
c.name = name
c.Save()
return nil
}
func (c *Channel) Put(m proto.Object, From *session.Session) proto.Object {
m.Id = proto.GenId()
m.Fields["t"] = proto.Timestamp()
err := c.kind.db.Update(func(tx *bolt.Tx) error {
history, _ := tx.CreateBucketIfNotExists([]byte("message history"))
channel, _ := history.CreateBucketIfNotExists([]byte(c.id))
ids, _ := channel.CreateBucketIfNotExists([]byte("ids"))
index, err := channel.NextSequence()
if err != nil {
return err
}
key := []byte(strconv.Itoa(int(index)))
var buf bytes.Buffer
writer := bufio.NewWriter(&buf)
proto.WriteObject(writer, m)
writer.Flush()
err = channel.Put(key, buf.Bytes())
if err != nil {
return err
}
return ids.Put([]byte(m.Id), key)
})
if err != nil {
log.Fatal("error updating database: ", err)
}
for s, _ := range c.Stream.Subscribers() {
if From == s {
continue
}
if c.GetMembership(s.UserId).See {
s.Event(proto.NewCmd("p", c.id, m))
}
}
return m
}
func (c *Channel) HistorySize() int {
var size int
err := c.kind.db.View(func(tx *bolt.Tx) error {
history := tx.Bucket([]byte("message history"))
if history == nil {
return nil
}
channel := history.Bucket([]byte(c.id))
if channel == nil {
return nil
}
size = int(channel.Sequence())
return nil
})
if err != nil {
log.Fatal("error reading database: ", err)
}
return size
}
func (c *Channel) MessageIndex(mid string) (index int, ok bool) {
err := c.kind.db.View(func(tx *bolt.Tx) error {
history := tx.Bucket([]byte("message history"))
if history == nil {
return nil
}
channel := history.Bucket([]byte(c.id))
if channel == nil {
return nil
}
ids := channel.Bucket([]byte("ids"))
data := ids.Get([]byte(mid))
ok = data != nil
index, _ = strconv.Atoi(string(data))
return nil
})
if err != nil {
log.Fatal("error reading database: ", err)
}
return index, ok
}
func (c *Channel) History(min, max int) []proto.Object {
var result []proto.Object
err := c.kind.db.View(func(tx *bolt.Tx) error {
history := tx.Bucket([]byte("message history"))
channel := history.Bucket([]byte(c.id))
for index := min; index < max; index++ {
data := channel.Get([]byte(strconv.Itoa(index)))
if data == nil {
continue
}
m, err := proto.ReadObject(bufio.NewReader(bytes.NewReader(data)))
if err != nil {
panic(err)
}
result = append(result, m)
}
return nil
})
if err != nil {
log.Fatal("error reading database: ", err)
}
return result
}
func (c *Channel) Join(u *user.User) *proto.Fail {
if c.isDirect {
return &proto.Fail {"invalid", "", nil}
}
if c.GetMembership(u.Id()).Yes {
return nil
}
c.SetMembership(u.Id(), c.GetDefaultMembership())
c.Put(proto.Object{"join", "", map[string]string {"f": u.Id()}}, nil)
return nil
}
func (c *Channel) Leave(u *user.User) *proto.Fail {
if c.isDirect {
return &proto.Fail {"invalid", "", nil}
}
if !c.GetMembership(u.Id()).Yes {
return nil
}
c.SetMembership(u.Id(), Membership {Yes: false})
c.Put(proto.Object{"leave", "", map[string]string {"f": u.Id()}}, nil)
return nil
}
func (c *Channel) Members() map[string]Membership {
result := make(map[string]Membership)
err := c.kind.db.View(func(tx *bolt.Tx) error {
channels := tx.Bucket([]byte("channel membership"))
if channels == nil {
return nil
}
members := channels.Bucket([]byte(c.id))
if members == nil {
return nil
}
return members.ForEach(func(k, v []byte) error {
var mship Membership
o, _ := proto.ReadObject(bufio.NewReader(bytes.NewReader(v)))
result[string(k)], _ = mship.Change(o)
return nil
})
})
if err != nil {
log.Fatal("error updating database: ", err)
}
return result
}
func (c *Channel) GetMembership(uid string) Membership {
var mship Membership
err := c.kind.db.View(func(tx *bolt.Tx) error {
channels := tx.Bucket([]byte("channel membership"))
if channels == nil {
return nil
}
members := channels.Bucket([]byte(c.id))
if members == nil {
return nil
}
data := members.Get([]byte(uid))
if data != nil {
o, _ := proto.ReadObject(bufio.NewReader(bytes.NewReader(data)))
mship.Undata(o)
}
return nil
})
if err != nil {
log.Fatal("error updating database: ", err)
}
return mship
}
func (c *Channel) SetMembership(uid string, m Membership) {
err := c.kind.db.Update(func(tx *bolt.Tx) error {
channels := tx.Bucket([]byte("channel membership"))
userChannels := tx.Bucket([]byte("user channels"))
members, _ := channels.CreateBucketIfNotExists([]byte(c.id))
user, _ := userChannels.CreateBucketIfNotExists([]byte(uid))
if m.Yes {
err := user.Put([]byte(c.id), []byte("yes"))
if err != nil {
return err
}
var buf bytes.Buffer
writer := bufio.NewWriter(&buf)
proto.WriteObject(writer, m.GetInfo())
writer.Flush()
return members.Put([]byte(uid), buf.Bytes())
} else {
user.Delete([]byte(c.id))
return members.Delete([]byte(uid))
}
})
if err != nil {
log.Fatal("error updating database: ", err)
}
}
func (c *Channel) GetDefaultMembership() Membership {
return DefaultMembership
}
func (c *Channel) SetDefaultMembership(m Membership) {
}
func (c *Channel) Delete() {
c.Stream.Event(proto.NewCmd("delete", c.id))
c.Stream.UnsubscribeAll()
deleted := object.Tombstone {
c.id, map[string]string {"": c.name, "kind": c.Kind()},
}
c.kind.world.PutObject(c.id, deleted)
err := c.kind.db.Update(func(tx *bolt.Tx) error {
channels := tx.Bucket([]byte("channel membership"))
return channels.DeleteBucket([]byte(c.id))
})
if err != nil {
log.Fatal("error updating database: ", err)
}
}
func (c *Channel) Kind() string {
switch {
case c.isDirect:
return "direct-channel"
default:
return "channel"
}
}
func (c *Channel) InfoFor(uid string) proto.Object {
return proto.Object {
c.Kind(), c.id, map[string]string {"": c.NameFor(uid)},
}
}
|