From 01a28ef3b070aa0c240c6606981bd25ca9691e1e Mon Sep 17 00:00:00 2001 From: Sarah Jamie Lewis Date: Mon, 3 Dec 2018 11:12:34 -0800 Subject: [PATCH] Message Sorting --- model/group.go | 10 ++++------ model/message.go | 13 +++++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/model/group.go b/model/group.go index bd84bb3..d15dd6a 100644 --- a/model/group.go +++ b/model/group.go @@ -122,13 +122,11 @@ func (g *Group) AddMessage(message *protocol.DecryptedGroupMessage, sig []byte) return timelineMessage } -// GetTimeline provides a safe copy of the timeline-= -func (g *Group) GetTimeline() (t []Message) { +// GetTimeline provides a safe copy of the timeline +func (g *Group) GetTimeline() (timeline []Message) { g.lock.Lock() - t = g.Timeline.GetMessages() - g.lock.Unlock() - return - + defer g.lock.Unlock() + return g.Timeline.GetMessages() } //EncryptMessage takes a message and encrypts the message under the group key. diff --git a/model/message.go b/model/message.go index ded861d..065fc71 100644 --- a/model/message.go +++ b/model/message.go @@ -58,6 +58,11 @@ func (t *Timeline) Swap(i, j int) { // Less checks 2 messages (i and j) in the timeline and returns true if i occurred before j, else false func (t *Timeline) Less(i, j int) bool { + if t.Messages[i].Timestamp.Before(t.Messages[j].Timestamp) { + return true + } + + // Short circuit false if j is before i, signature checks will give a wrong order in this case. if t.Messages[j].Timestamp.Before(t.Messages[i].Timestamp) { return false } @@ -73,6 +78,14 @@ func (t *Timeline) Less(i, j int) bool { return false } +// Sort sorts the timeline in a canonical order. +// TODO: There is almost definitely a more efficient way of doing things that involve not calling this method on every timeline load. +func (t *Timeline) Sort() { + t.lock.Lock() + defer t.lock.Unlock() + sort.Sort(t) +} + // Insert inserts a message into the timeline in a thread safe way. func (t *Timeline) Insert(mi *Message) bool { t.lock.Lock()