aboutsummaryrefslogtreecommitdiff
path: root/matrix/ext/pushrules.go
blob: 6cb16d2834b51358bf929ff0a7363c35b14d74d6 (plain)
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package gomx_ext

import (
	"encoding/json"
	"net/url"
	"regexp"
	"strconv"
	"strings"

	"github.com/zyedidia/glob"
	"maunium.net/go/gomatrix"
	"maunium.net/go/gomuks/matrix/room"
)

// GetPushRules returns the push notification rules for the given scope.
func GetPushRules(client *gomatrix.Client) (resp *PushRuleset, err error) {
	u, _ := url.Parse(client.BuildURL("pushrules", "global"))
	u.Path += "/"
	_, err = client.MakeRequest("GET", u.String(), nil, &resp)
	return
}

type PushRuleset struct {
	Override  PushRuleArray
	Content   PushRuleArray
	Room      PushRuleMap
	Sender    PushRuleMap
	Underride PushRuleArray
}

type rawPushRuleset struct {
	Override  PushRuleArray `json:"override"`
	Content   PushRuleArray `json:"content"`
	Room      PushRuleArray `json:"room"`
	Sender    PushRuleArray `json:"sender"`
	Underride PushRuleArray `json:"underride"`
}

func (rs *PushRuleset) UnmarshalJSON(raw []byte) (err error) {
	data := rawPushRuleset{}
	err = json.Unmarshal(raw, &data)
	if err != nil {
		return
	}

	rs.Override = data.Override.setType(OverrideRule)
	rs.Content = data.Content.setType(ContentRule)
	rs.Room = data.Room.setTypeAndMap(RoomRule)
	rs.Sender = data.Sender.setTypeAndMap(SenderRule)
	rs.Underride = data.Underride.setType(UnderrideRule)
	return
}

func (rs *PushRuleset) MarshalJSON() ([]byte, error) {
	data := rawPushRuleset{
		Override:  rs.Override,
		Content:   rs.Content,
		Room:      rs.Room.unmap(),
		Sender:    rs.Sender.unmap(),
		Underride: rs.Underride,
	}
	return json.Marshal(&data)
}

func (rs *PushRuleset) GetActions(room *rooms.Room, event *gomatrix.Event) (match []*PushAction) {
	if match = rs.Override.GetActions(room, event); match != nil {
		return
	}
	if match = rs.Content.GetActions(room, event); match != nil {
		return
	}
	if match = rs.Room.GetActions(room, event); match != nil {
		return
	}
	if match = rs.Sender.GetActions(room, event); match != nil {
		return
	}
	if match = rs.Underride.GetActions(room, event); match != nil {
		return
	}
	return
}

type PushRuleArray []*PushRule

func (rules PushRuleArray) setType(typ PushRuleType) PushRuleArray {
	for _, rule := range rules {
		rule.Type = typ
	}
	return rules
}

func (rules PushRuleArray) GetActions(room *rooms.Room, event *gomatrix.Event) []*PushAction {
	for _, rule := range rules {
		if !rule.Match(room, event) {
			continue
		}
		return rule.Actions
	}
	return nil
}

type PushRuleMap struct {
	Map  map[string]*PushRule
	Type PushRuleType
}

func (rules PushRuleArray) setTypeAndMap(typ PushRuleType) PushRuleMap {
	data := PushRuleMap{
		Map:  make(map[string]*PushRule),
		Type: typ,
	}
	for _, rule := range rules {
		rule.Type = typ
		data.Map[rule.RuleID] = rule
	}
	return data
}

func (ruleMap PushRuleMap) GetActions(room *rooms.Room, event *gomatrix.Event) []*PushAction {
	var rule *PushRule
	var found bool
	switch ruleMap.Type {
	case RoomRule:
		rule, found = ruleMap.Map[event.RoomID]
	case SenderRule:
		rule, found = ruleMap.Map[event.Sender]
	}
	if found && rule.Match(room, event) {
		return rule.Actions
	}
	return nil
}

func (ruleMap PushRuleMap) unmap() PushRuleArray {
	array := make(PushRuleArray, len(ruleMap.Map))
	index := 0
	for _, rule := range ruleMap.Map {
		array[index] = rule
		index++
	}
	return array
}

type PushRuleType string

const (
	OverrideRule  PushRuleType = "override"
	ContentRule   PushRuleType = "content"
	RoomRule      PushRuleType = "room"
	SenderRule    PushRuleType = "sender"
	UnderrideRule PushRuleType = "underride"
)

type PushRule struct {
	// The type of this rule.
	Type PushRuleType `json:"-"`
	// The ID of this rule.
	// For room-specific rules and user-specific rules, this is the room or user ID (respectively)
	// For other types of rules, this doesn't affect anything.
	RuleID string `json:"rule_id"`
	// The actions this rule should trigger when matched.
	Actions []*PushAction `json:"actions"`
	// Whether this is a default rule, or has been set explicitly.
	Default bool `json:"default"`
	// Whether or not this push rule is enabled.
	Enabled bool `json:"enabled"`
	// The conditions to match in order to trigger this rule.
	// Only applicable to generic underride/override rules.
	Conditions []*PushCondition `json:"conditions,omitempty"`
	// Pattern for content-specific push rules
	Pattern string `json:"pattern,omitempty"`
}

func (rule *PushRule) Match(room *rooms.Room, event *gomatrix.Event) bool {
	if !rule.Enabled {
		return false
	}
	switch rule.Type {
	case OverrideRule, UnderrideRule:
		return rule.matchConditions(room, event)
	case ContentRule:
		return rule.matchPattern(room, event)
	case RoomRule:
		return rule.RuleID == event.RoomID
	case SenderRule:
		return rule.RuleID == event.Sender
	default:
		return false
	}
}

func (rule *PushRule) matchConditions(room *rooms.Room, event *gomatrix.Event) bool {
	for _, cond := range rule.Conditions {
		if !cond.Match(room, event) {
			return false
		}
	}
	return true
}

func (rule *PushRule) matchPattern(room *rooms.Room, event *gomatrix.Event) bool {
	pattern, err := glob.Compile(rule.Pattern)
	if err != nil {
		return false
	}
	text, _ := event.Content["body"].(string)
	return pattern.MatchString(text)
}

type PushActionType string

const (
	ActionNotify     PushActionType = "notify"
	ActionDontNotify PushActionType = "dont_notify"
	ActionCoalesce   PushActionType = "coalesce"
	ActionSetTweak   PushActionType = "set_tweak"
)

type PushActionTweak string

const (
	TweakSound     PushActionTweak = "sound"
	TweakHighlight PushActionTweak = "highlight"
)

type PushAction struct {
	Action PushActionType
	Tweak  PushActionTweak
	Value  string
}

func (action *PushAction) UnmarshalJSON(raw []byte) error {
	var data interface{}

	err := json.Unmarshal(raw, &data)
	if err != nil {
		return err
	}

	switch val := data.(type) {
	case string:
		action.Action = PushActionType(val)
	case map[string]interface{}:
		tweak, ok := val["set_tweak"].(string)
		if ok {
			action.Action = ActionSetTweak
			action.Tweak = PushActionTweak(tweak)
			action.Value, _ = val["value"].(string)
		}
	}
	return nil
}

func (action *PushAction) MarshalJSON() (raw []byte, err error) {
	if action.Action == ActionSetTweak {
		data := map[string]interface{}{
			"set_tweak": action.Tweak,
			"value":     action.Value,
		}
		return json.Marshal(&data)
	} else {
		data := string(action.Action)
		return json.Marshal(&data)
	}
}

type PushKind string

const (
	KindEventMatch          PushKind = "event_match"
	KindContainsDisplayName PushKind = "contains_display_name"
	KindRoomMemberCount     PushKind = "room_member_count"
)

type PushCondition struct {
	Kind    PushKind `json:"kind"`
	Key     string   `json:"key,omitempty"`
	Pattern string   `json:"pattern,omitempty"`
	Is      string   `json:"string,omitempty"`
}

var MemberCountFilterRegex = regexp.MustCompile("^(==|[<>]=?)?([0-9]+)$")

func (cond *PushCondition) Match(room *rooms.Room, event *gomatrix.Event) bool {
	switch cond.Kind {
	case KindEventMatch:
		return cond.matchValue(room, event)
	case KindContainsDisplayName:
		return cond.matchDisplayName(room, event)
	case KindRoomMemberCount:
		return cond.matchMemberCount(room, event)
	default:
		return true
	}
}

func (cond *PushCondition) matchValue(room *rooms.Room, event *gomatrix.Event) bool {
	index := strings.IndexRune(cond.Key, '.')
	key := cond.Key
	subkey := ""
	if index > 0 {
		subkey = key[index+1:]
		key = key[0:index]
	}

	pattern, err := glob.Compile(cond.Pattern)
	if err != nil {
		return false
	}

	switch key {
	case "type":
		return pattern.MatchString(event.Type)
	case "sender":
		return pattern.MatchString(event.Sender)
	case "room_id":
		return pattern.MatchString(event.RoomID)
	case "state_key":
		if event.StateKey == nil {
			return cond.Pattern == ""
		}
		return pattern.MatchString(*event.StateKey)
	case "content":
		val, _ := event.Content[subkey].(string)
		return pattern.MatchString(val)
	default:
		return false
	}
}

func (cond *PushCondition) matchDisplayName(room *rooms.Room, event *gomatrix.Event) bool {
	member := room.GetMember(room.Owner)
	if member == nil {
		return false
	}
	text, _ := event.Content["body"].(string)
	return strings.Contains(text, member.DisplayName)
}

func (cond *PushCondition) matchMemberCount(room *rooms.Room, event *gomatrix.Event) bool {
	groupGroups := MemberCountFilterRegex.FindAllStringSubmatch(cond.Is, -1)
	if len(groupGroups) != 1 {
		return true
	}

	operator := "=="
	wantedMemberCount := 0

	group := groupGroups[0]
	if len(group) == 0 {
		return true
	} else if len(group) == 1 {
		wantedMemberCount, _ = strconv.Atoi(group[0])
	} else {
		operator = group[0]
		wantedMemberCount, _ = strconv.Atoi(group[1])
	}

	memberCount := len(room.GetMembers())

	switch operator {
	case "==":
		return wantedMemberCount == memberCount
	case ">":
		return wantedMemberCount > memberCount
	case ">=":
		return wantedMemberCount >= memberCount
	case "<":
		return wantedMemberCount < memberCount
	case "<=":
		return wantedMemberCount <= memberCount
	default:
		return false
	}
}