2018-03-09 20:44:13 +00:00
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
2018-04-28 17:52:59 +00:00
|
|
|
"sort"
|
2018-04-02 21:10:29 +00:00
|
|
|
"sync"
|
2018-03-09 20:44:13 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2018-04-02 21:10:29 +00:00
|
|
|
type Timeline struct {
|
|
|
|
Messages []Message
|
|
|
|
lock sync.Mutex
|
|
|
|
}
|
|
|
|
|
2018-03-15 16:33:26 +00:00
|
|
|
// Message is a local representation of a given message sent over a group chat channel.
|
2018-03-09 20:44:13 +00:00
|
|
|
type Message struct {
|
2018-04-02 21:10:29 +00:00
|
|
|
Timestamp time.Time
|
2018-05-09 19:09:00 +00:00
|
|
|
Received time.Time
|
2018-04-02 21:10:29 +00:00
|
|
|
PeerID string
|
|
|
|
Message string
|
|
|
|
Signature []byte
|
|
|
|
Verified bool
|
|
|
|
PreviousMessageSig []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func compareSignatures(a []byte, b []byte) bool {
|
|
|
|
if len(a) != len(b) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for i := range a {
|
|
|
|
if a[i] != b[i] {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2018-04-28 17:52:59 +00:00
|
|
|
func (t Timeline) Len() int {
|
|
|
|
return len(t.Messages)
|
|
|
|
}
|
|
|
|
func (t Timeline) Swap(i, j int) {
|
|
|
|
t.Messages[i], t.Messages[j] = t.Messages[j], t.Messages[i]
|
|
|
|
}
|
|
|
|
func (t Timeline) Less(i, j int) bool {
|
2018-04-02 21:10:29 +00:00
|
|
|
|
2018-05-03 17:59:58 +00:00
|
|
|
if t.Messages[i].Timestamp.Before(t.Messages[j].Timestamp) {
|
2018-04-28 17:52:59 +00:00
|
|
|
return true
|
|
|
|
}
|
2018-04-02 21:10:29 +00:00
|
|
|
|
2018-05-03 17:59:58 +00:00
|
|
|
if compareSignatures(t.Messages[i].PreviousMessageSig, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) {
|
2018-04-28 17:52:59 +00:00
|
|
|
return true
|
2018-04-02 21:10:29 +00:00
|
|
|
}
|
|
|
|
|
2018-04-28 17:52:59 +00:00
|
|
|
if compareSignatures(t.Messages[i].Signature, t.Messages[j].PreviousMessageSig) {
|
|
|
|
return true
|
2018-04-02 21:10:29 +00:00
|
|
|
}
|
2018-04-28 17:52:59 +00:00
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timeline) Insert(mi *Message) {
|
|
|
|
t.lock.Lock()
|
2018-05-03 04:12:45 +00:00
|
|
|
|
2018-05-03 06:01:15 +00:00
|
|
|
for _, m := range t.Messages {
|
2018-05-03 04:12:45 +00:00
|
|
|
if compareSignatures(m.Signature, mi.Signature) {
|
|
|
|
t.lock.Unlock()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-28 17:52:59 +00:00
|
|
|
t.Messages = append(t.Messages, *mi)
|
|
|
|
sort.Sort(t)
|
2018-04-02 21:10:29 +00:00
|
|
|
t.lock.Unlock()
|
2018-03-09 20:44:13 +00:00
|
|
|
}
|