aboutsummaryrefslogtreecommitdiff
path: root/userapi/util/devices.go
blob: 117da08ea9e57754438e8c7a7bfdb03bf6ad2451 (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
package util

import (
	"context"
	"fmt"

	"github.com/matrix-org/dendrite/internal/pushgateway"
	"github.com/matrix-org/dendrite/userapi/api"
	"github.com/matrix-org/dendrite/userapi/storage"
	"github.com/matrix-org/gomatrixserverlib/spec"
	log "github.com/sirupsen/logrus"
)

type PusherDevice struct {
	Device pushgateway.Device
	Pusher *api.Pusher
	URL    string
	Format string
}

// GetPushDevices pushes to the configured devices of a local user.
func GetPushDevices(ctx context.Context, localpart string, serverName spec.ServerName, tweaks map[string]interface{}, db storage.UserDatabase) ([]*PusherDevice, error) {
	pushers, err := db.GetPushers(ctx, localpart, serverName)
	if err != nil {
		return nil, fmt.Errorf("db.GetPushers: %w", err)
	}

	devices := make([]*PusherDevice, 0, len(pushers))
	for _, pusher := range pushers {
		var url, format string
		data := pusher.Data
		switch pusher.Kind {
		case api.EmailKind:
			url = "mailto:"

		case api.HTTPKind:
			// TODO: The spec says only event_id_only is supported,
			// but Sytests assume "" means "full notification".
			fmtIface := pusher.Data["format"]
			var ok bool
			format, ok = fmtIface.(string)
			if ok && format != "event_id_only" {
				log.WithFields(log.Fields{
					"localpart": localpart,
					"app_id":    pusher.AppID,
				}).Errorf("Only data.format event_id_only or empty is supported")
				continue
			}

			urlIface := pusher.Data["url"]
			url, ok = urlIface.(string)
			if !ok {
				log.WithFields(log.Fields{
					"localpart": localpart,
					"app_id":    pusher.AppID,
				}).Errorf("No data.url configured for HTTP Pusher")
				continue
			}
			data = mapWithout(data, "url")

		default:
			log.WithFields(log.Fields{
				"localpart": localpart,
				"app_id":    pusher.AppID,
				"kind":      pusher.Kind,
			}).Errorf("Unhandled pusher kind")
			continue
		}

		devices = append(devices, &PusherDevice{
			Device: pushgateway.Device{
				AppID:     pusher.AppID,
				Data:      data,
				PushKey:   pusher.PushKey,
				PushKeyTS: pusher.PushKeyTS,
				Tweaks:    tweaks,
			},
			Pusher: &pusher,
			URL:    url,
			Format: format,
		})
	}

	return devices, nil
}

// mapWithout returns a shallow copy of the map, without the given
// key. Returns nil if the resulting map is empty.
func mapWithout(m map[string]interface{}, key string) map[string]interface{} {
	ret := make(map[string]interface{}, len(m))
	for k, v := range m {
		// The specification says we do not send "url".
		if k == key {
			continue
		}
		ret[k] = v
	}
	if len(ret) == 0 {
		return nil
	}
	return ret
}