Debian Codegraph @

pushrules/ruleset.go

raw
1 // Copyright (c) 2020 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package pushrules
8
9 import (
10 "encoding/json"
11
12 "maunium.net/go/mautrix/event"
13 )
14
15 type PushRuleset struct {
16 Override PushRuleArray
17 Content PushRuleArray
18 Room PushRuleMap
19 Sender PushRuleMap
20 Underride PushRuleArray
21 }
22
23 type rawPushRuleset struct {
24 Override PushRuleArray `json:"override"`
25 Content PushRuleArray `json:"content"`
26 Room PushRuleArray `json:"room"`
27 Sender PushRuleArray `json:"sender"`
28 Underride PushRuleArray `json:"underride"`
29 }
30
31 // UnmarshalJSON parses JSON into this PushRuleset.
32 //
33 // For override, sender and underride push rule arrays, the type is added
34 // to each PushRule and the array is used as-is.
35 //
36 // For room and sender push rule arrays, the type is added to each PushRule
37 // and the array is converted to a map with the rule ID as the key and the
38 // PushRule as the value.
39 func (rs *PushRuleset) UnmarshalJSON(raw []byte) (err error) {
40 data := rawPushRuleset{}
41 err = json.Unmarshal(raw, &data)
42 if err != nil {
43 return
44 }
45
46 rs.Override = data.Override.SetType(OverrideRule)
47 rs.Content = data.Content.SetType(ContentRule)
48 rs.Room = data.Room.SetTypeAndMap(RoomRule)
49 rs.Sender = data.Sender.SetTypeAndMap(SenderRule)
50 rs.Underride = data.Underride.SetType(UnderrideRule)
51 return
52 }
53
54 // MarshalJSON is the reverse of UnmarshalJSON()
55 func (rs *PushRuleset) MarshalJSON() ([]byte, error) {
56 data := rawPushRuleset{
57 Override: rs.Override,
58 Content: rs.Content,
59 Room: rs.Room.Unmap(),
60 Sender: rs.Sender.Unmap(),
61 Underride: rs.Underride,
62 }
63 return json.Marshal(&data)
64 }
65
66 // DefaultPushActions is the value returned if none of the rule
67 // collections in a Ruleset match the event given to GetActions()
68 var DefaultPushActions = PushActionArray{&PushAction{Action: ActionDontNotify}}
69
70 // GetActions matches the given event against all of the push rule
71 // collections in this push ruleset in the order of priority as
72 // specified in spec section 11.12.1.4.
73 func (rs *PushRuleset) GetActions(room Room, evt *event.Event) (match PushActionArray) {
74 // Add push rule collections to array in priority order
75 arrays := []PushRuleCollection{rs.Override, rs.Content, rs.Room, rs.Sender, rs.Underride}
76 // Loop until one of the push rule collections matches the room/event combo.
77 for _, pra := range arrays {
78 if pra == nil {
79 continue
80 }
81 if match = pra.GetActions(room, evt); match != nil {
82 // Match found, return it.
83 return
84 }
85 }
86 // No match found, return default actions.
87 return DefaultPushActions
88 }