| 1 |
/* |
| 2 |
Copyright 2013-2014 Canonical Ltd. |
| 3 |
|
| 4 |
This program is free software: you can redistribute it and/or modify it |
| 5 |
under the terms of the GNU General Public License version 3, as published |
| 6 |
by the Free Software Foundation. |
| 7 |
|
| 8 |
This program is distributed in the hope that it will be useful, but |
| 9 |
WITHOUT ANY WARRANTY; without even the implied warranties of |
| 10 |
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR |
| 11 |
PURPOSE. See the GNU General Public License for more details. |
| 12 |
|
| 13 |
You should have received a copy of the GNU General Public License along |
| 14 |
with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
*/ |
| 16 |
|
| 17 |
// Package seenstate holds implementations of the SeenState that the client |
| 18 |
// session uses to keep track of what messages it has seen. |
| 19 |
package seenstate |
| 20 |
|
| 21 |
import ( |
| 22 |
"gitlab.com/ubports/development/core/lomiri-push-service/protocol" |
| 23 |
) |
| 24 |
|
| 25 |
type SeenState interface { |
| 26 |
// Set() (re)sets the given level to the given value. |
| 27 |
SetLevel(level string, top int64) error |
| 28 |
// GetAll() returns a "simple" map of the current levels. |
| 29 |
GetAllLevels() (map[string]int64, error) |
| 30 |
// FilterBySeen filters notifications already seen, keep track |
| 31 |
// of them as well. |
| 32 |
FilterBySeen([]protocol.Notification) ([]protocol.Notification, error) |
| 33 |
// Close closes state. |
| 34 |
Close() |
| 35 |
} |
| 36 |
|
| 37 |
type memSeenState struct { |
| 38 |
levels map[string]int64 |
| 39 |
seenMsgs map[string]bool |
| 40 |
} |
| 41 |
|
| 42 |
func (m *memSeenState) SetLevel(level string, top int64) error { |
| 43 |
m.levels[level] = top |
| 44 |
return nil |
| 45 |
} |
| 46 |
func (m *memSeenState) GetAllLevels() (map[string]int64, error) { |
| 47 |
return m.levels, nil |
| 48 |
} |
| 49 |
|
| 50 |
func (m *memSeenState) FilterBySeen(notifs []protocol.Notification) ([]protocol.Notification, error) { |
| 51 |
acc := make([]protocol.Notification, 0, len(notifs)) |
| 52 |
for _, notif := range notifs { |
| 53 |
seen := m.seenMsgs[notif.MsgId] |
| 54 |
if seen { |
| 55 |
continue |
| 56 |
} |
| 57 |
m.seenMsgs[notif.MsgId] = true |
| 58 |
acc = append(acc, notif) |
| 59 |
} |
| 60 |
return acc, nil |
| 61 |
} |
| 62 |
|
| 63 |
func (m *memSeenState) Close() { |
| 64 |
} |
| 65 |
|
| 66 |
var _ SeenState = (*memSeenState)(nil) |
| 67 |
|
| 68 |
// NewSeenState returns an implementation of SeenState that is memory-based and |
| 69 |
// does not save state. |
| 70 |
func NewSeenState() (SeenState, error) { |
| 71 |
return &memSeenState{ |
| 72 |
levels: make(map[string]int64), |
| 73 |
seenMsgs: make(map[string]bool), |
| 74 |
}, nil |
| 75 |
} |