generated from Brightscout/mattermost-plugin-boilerplate
/
subscriptions.go
76 lines (62 loc) · 2.08 KB
/
subscriptions.go
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
package serializer
import (
"encoding/json"
"github.com/thoas/go-funk"
)
type StringSubscription map[string]Subscription
type Subscriptions struct {
ByChannelID map[string]StringSubscription // store the list of subscriptions for a channelID
ByKey map[string][]string // stores the list of channelIDs to which the message needs to be posted for a subscription
}
func NewSubscriptions() *Subscriptions {
return &Subscriptions{
ByChannelID: map[string]StringSubscription{},
ByKey: map[string][]string{},
}
}
func SubscriptionsFromJSON(bytes []byte) (*Subscriptions, error) {
var subs *Subscriptions
if len(bytes) != 0 {
unmarshalErr := json.Unmarshal(bytes, &subs)
if unmarshalErr != nil {
return nil, unmarshalErr
}
} else {
subs = NewSubscriptions()
}
return subs, nil
}
// Add adds a new subscription to the list of all subscriptions
func (list *Subscriptions) Add(s Subscription) {
key := s.GetKey()
if _, contains := list.ByKey[key]; !contains {
list.ByKey[key] = make([]string, 0)
}
if !funk.Contains(list.ByKey[key], s.ChannelID) {
list.ByKey[key] = append(list.ByKey[key], s.ChannelID)
}
if _, found := list.ByChannelID[s.ChannelID]; !found {
list.ByChannelID[s.ChannelID] = make(StringSubscription)
}
list.ByChannelID[s.ChannelID][key] = s
}
// Remove removes a subscription from the list of all subscriptions
func (list *Subscriptions) Remove(s Subscription) {
key := s.GetKey()
delete(list.ByChannelID[s.ChannelID], key)
list.ByKey[key] = funk.FilterString(list.ByKey[key], func(el string) bool {
return el == s.ChannelID
})
}
// GetChannelID returns the channelID to which the message for a subscription should be posted to
func (list *Subscriptions) GetChannelIDs(s Subscription) []string {
return list.ByKey[s.GetKey()]
}
// List returns the list for a particular channel as a formatted mattermost message
func (list *Subscriptions) List(channelID string) []Subscription {
values := make([]Subscription, 0, len(list.ByChannelID[channelID]))
for _, v := range list.ByChannelID[channelID] {
values = append(values, v)
}
return values
}