/
messagetags.go
103 lines (85 loc) · 2.32 KB
/
messagetags.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
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
package webircgateway
import (
"strings"
"sync"
"time"
"github.com/OneOfOne/xxhash"
"github.com/kiwiirc/webircgateway/pkg/irc"
)
type MessageTagManager struct {
Mutex sync.Mutex
knownTags map[uint64]MessageTags
gcTimes map[uint64]time.Time
}
type MessageTags struct {
Tags map[string]string
}
func NewMessageTagManager() *MessageTagManager {
tm := &MessageTagManager{
knownTags: make(map[uint64]MessageTags),
gcTimes: make(map[uint64]time.Time),
}
go tm.RunGarbageCollectionLoop()
return tm
}
func (tags *MessageTagManager) CanMessageContainClientTags(msg *irc.Message) bool {
return stringInSlice(msg.Command, []string{
"PRIVMSG",
"NOTICE",
"TAGMSG",
})
}
func (tags *MessageTagManager) RunGarbageCollectionLoop() {
for {
tags.Mutex.Lock()
for messageHash, timeCreated := range tags.gcTimes {
if timeCreated.Add(time.Second * 30).After(time.Now()) {
delete(tags.knownTags, messageHash)
}
}
tags.Mutex.Unlock()
time.Sleep(time.Second * 30)
}
}
func (tags *MessageTagManager) AddTagsFromMessage(client *Client, fromNick string, msg *irc.Message) {
if !tags.CanMessageContainClientTags(msg) {
return
}
clientTags := MessageTags{
Tags: make(map[string]string),
}
for tagName, tagVal := range msg.Tags {
if len(tagName) > 0 && tagName[0] == '+' {
clientTags.Tags[tagName] = tagVal
}
}
if len(clientTags.Tags) > 0 {
tags.Mutex.Lock()
msgHash := tags.messageHash(client, fromNick, msg)
tags.knownTags[msgHash] = clientTags
tags.gcTimes[msgHash] = time.Now()
tags.Mutex.Unlock()
}
}
func (tags *MessageTagManager) GetTagsFromMessage(client *Client, fromNick string, msg *irc.Message) (MessageTags, bool) {
if !tags.CanMessageContainClientTags(msg) {
return MessageTags{}, false
}
msgHash := tags.messageHash(client, fromNick, msg)
tags.Mutex.Lock()
defer tags.Mutex.Unlock()
clientTags, tagsExist := tags.knownTags[msgHash]
if !tagsExist {
return clientTags, false
}
return clientTags, true
}
func (tags *MessageTagManager) messageHash(client *Client, fromNick string, msg *irc.Message) uint64 {
h := xxhash.New64()
h.WriteString(strings.ToLower(client.UpstreamConfig.Hostname))
h.WriteString(strings.ToLower(fromNick))
// make target case insensitive
h.WriteString(strings.ToLower(msg.GetParam(0, "")))
h.WriteString(msg.GetParam(1, ""))
return h.Sum64()
}