2022-03-03 11:40:53 +00:00
|
|
|
package consumers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-11-07 08:47:18 +00:00
|
|
|
"database/sql"
|
2022-03-03 11:40:53 +00:00
|
|
|
"encoding/json"
|
2022-11-07 08:47:18 +00:00
|
|
|
"errors"
|
2022-03-03 11:40:53 +00:00
|
|
|
"fmt"
|
|
|
|
"strings"
|
2022-11-02 10:18:11 +00:00
|
|
|
"sync"
|
2022-03-03 11:40:53 +00:00
|
|
|
"time"
|
|
|
|
|
2022-11-07 08:47:18 +00:00
|
|
|
"github.com/tidwall/gjson"
|
|
|
|
|
2022-08-30 13:54:57 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2023-04-19 15:50:33 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2022-08-30 13:54:57 +01:00
|
|
|
"github.com/nats-io/nats.go"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
2022-03-03 11:40:53 +00:00
|
|
|
"github.com/matrix-org/dendrite/internal/eventutil"
|
|
|
|
"github.com/matrix-org/dendrite/internal/pushgateway"
|
|
|
|
"github.com/matrix-org/dendrite/internal/pushrules"
|
|
|
|
rsapi "github.com/matrix-org/dendrite/roomserver/api"
|
2023-04-27 12:54:20 +01:00
|
|
|
rstypes "github.com/matrix-org/dendrite/roomserver/types"
|
2022-03-03 11:40:53 +00:00
|
|
|
"github.com/matrix-org/dendrite/setup/config"
|
|
|
|
"github.com/matrix-org/dendrite/setup/jetstream"
|
|
|
|
"github.com/matrix-org/dendrite/setup/process"
|
2023-04-04 18:16:53 +01:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/synctypes"
|
2022-03-03 11:40:53 +00:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/types"
|
|
|
|
"github.com/matrix-org/dendrite/userapi/api"
|
|
|
|
"github.com/matrix-org/dendrite/userapi/producers"
|
|
|
|
"github.com/matrix-org/dendrite/userapi/storage"
|
|
|
|
"github.com/matrix-org/dendrite/userapi/storage/tables"
|
2022-11-02 10:18:11 +00:00
|
|
|
userAPITypes "github.com/matrix-org/dendrite/userapi/types"
|
2022-03-03 11:40:53 +00:00
|
|
|
"github.com/matrix-org/dendrite/userapi/util"
|
|
|
|
)
|
|
|
|
|
2022-09-27 14:01:34 +01:00
|
|
|
type OutputRoomEventConsumer struct {
|
2022-03-03 11:40:53 +00:00
|
|
|
ctx context.Context
|
|
|
|
cfg *config.UserAPI
|
2022-05-05 19:30:38 +01:00
|
|
|
rsAPI rsapi.UserRoomserverAPI
|
2022-03-03 11:40:53 +00:00
|
|
|
jetstream nats.JetStreamContext
|
|
|
|
durable string
|
2023-02-20 13:58:03 +00:00
|
|
|
db storage.UserDatabase
|
2022-03-03 11:40:53 +00:00
|
|
|
topic string
|
|
|
|
pgClient pushgateway.Client
|
|
|
|
syncProducer *producers.SyncAPI
|
2023-04-19 15:50:33 +01:00
|
|
|
msgCounts map[spec.ServerName]userAPITypes.MessageStats
|
|
|
|
roomCounts map[spec.ServerName]map[string]bool // map from serverName to map from rommID to "isEncrypted"
|
2022-11-02 10:18:11 +00:00
|
|
|
lastUpdate time.Time
|
|
|
|
countsLock sync.Mutex
|
2023-04-19 15:50:33 +01:00
|
|
|
serverName spec.ServerName
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
2022-09-27 14:01:34 +01:00
|
|
|
func NewOutputRoomEventConsumer(
|
2022-03-03 11:40:53 +00:00
|
|
|
process *process.ProcessContext,
|
|
|
|
cfg *config.UserAPI,
|
|
|
|
js nats.JetStreamContext,
|
2023-02-20 13:58:03 +00:00
|
|
|
store storage.UserDatabase,
|
2022-03-03 11:40:53 +00:00
|
|
|
pgClient pushgateway.Client,
|
2022-05-05 19:30:38 +01:00
|
|
|
rsAPI rsapi.UserRoomserverAPI,
|
2022-03-03 11:40:53 +00:00
|
|
|
syncProducer *producers.SyncAPI,
|
2022-09-27 14:01:34 +01:00
|
|
|
) *OutputRoomEventConsumer {
|
|
|
|
return &OutputRoomEventConsumer{
|
2022-03-03 11:40:53 +00:00
|
|
|
ctx: process.Context(),
|
|
|
|
cfg: cfg,
|
|
|
|
jetstream: js,
|
|
|
|
db: store,
|
2022-09-27 14:01:34 +01:00
|
|
|
durable: cfg.Matrix.JetStream.Durable("UserAPIRoomServerConsumer"),
|
|
|
|
topic: cfg.Matrix.JetStream.Prefixed(jetstream.OutputRoomEvent),
|
2022-03-03 11:40:53 +00:00
|
|
|
pgClient: pgClient,
|
|
|
|
rsAPI: rsAPI,
|
|
|
|
syncProducer: syncProducer,
|
2023-04-19 15:50:33 +01:00
|
|
|
msgCounts: map[spec.ServerName]userAPITypes.MessageStats{},
|
|
|
|
roomCounts: map[spec.ServerName]map[string]bool{},
|
2022-11-02 10:18:11 +00:00
|
|
|
lastUpdate: time.Now(),
|
|
|
|
countsLock: sync.Mutex{},
|
|
|
|
serverName: cfg.Matrix.ServerName,
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-27 14:01:34 +01:00
|
|
|
func (s *OutputRoomEventConsumer) Start() error {
|
2022-03-03 11:40:53 +00:00
|
|
|
if err := jetstream.JetStreamConsumer(
|
2022-08-31 12:21:56 +01:00
|
|
|
s.ctx, s.jetstream, s.topic, s.durable, 1,
|
|
|
|
s.onMessage, nats.DeliverAll(), nats.ManualAck(),
|
2022-03-03 11:40:53 +00:00
|
|
|
); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-09-27 14:01:34 +01:00
|
|
|
func (s *OutputRoomEventConsumer) onMessage(ctx context.Context, msgs []*nats.Msg) bool {
|
2022-08-31 12:21:56 +01:00
|
|
|
msg := msgs[0] // Guaranteed to exist if onMessage is called
|
2022-10-05 11:12:42 +01:00
|
|
|
// Only handle events we care about
|
2023-09-26 14:47:37 +01:00
|
|
|
|
|
|
|
var event *rstypes.HeaderedEvent
|
|
|
|
var isNewRoomEvent bool
|
|
|
|
switch rsapi.OutputType(msg.Header.Get(jetstream.RoomEventType)) {
|
|
|
|
case rsapi.OutputTypeNewRoomEvent:
|
|
|
|
isNewRoomEvent = true
|
|
|
|
fallthrough
|
|
|
|
case rsapi.OutputTypeNewInviteEvent:
|
|
|
|
var output rsapi.OutputEvent
|
|
|
|
if err := json.Unmarshal(msg.Data, &output); err != nil {
|
|
|
|
// If the message was invalid, log it and move on to the next message in the stream
|
|
|
|
log.WithError(err).Errorf("roomserver output log: message parse failure")
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if isNewRoomEvent {
|
|
|
|
event = output.NewRoomEvent.Event
|
|
|
|
} else {
|
|
|
|
event = output.NewInviteEvent.Event
|
|
|
|
}
|
|
|
|
|
|
|
|
if event == nil {
|
|
|
|
log.Errorf("userapi consumer: expected event")
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event_id": event.EventID(),
|
|
|
|
"event_type": event.Type(),
|
|
|
|
}).Tracef("Received message from roomserver: %#v", output)
|
|
|
|
default:
|
2022-03-03 11:40:53 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-11-02 10:18:11 +00:00
|
|
|
if s.cfg.Matrix.ReportStats.Enabled {
|
2023-09-15 15:39:06 +01:00
|
|
|
go s.storeMessageStats(ctx, event.Type(), string(event.SenderID()), event.RoomID().String())
|
2022-11-02 10:18:11 +00:00
|
|
|
}
|
|
|
|
|
2022-09-27 14:01:34 +01:00
|
|
|
metadata, err := msg.Metadata()
|
|
|
|
if err != nil {
|
|
|
|
return true
|
|
|
|
}
|
2022-03-03 11:40:53 +00:00
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
if err := s.processMessage(ctx, event, uint64(spec.AsTimestamp(metadata.Timestamp))); err != nil {
|
2022-03-03 11:40:53 +00:00
|
|
|
log.WithFields(log.Fields{
|
2022-09-27 14:01:34 +01:00
|
|
|
"event_id": event.EventID(),
|
2022-03-03 11:40:53 +00:00
|
|
|
}).WithError(err).Errorf("userapi consumer: process room event failure")
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-11-02 10:18:11 +00:00
|
|
|
func (s *OutputRoomEventConsumer) storeMessageStats(ctx context.Context, eventType, eventSender, roomID string) {
|
|
|
|
s.countsLock.Lock()
|
|
|
|
defer s.countsLock.Unlock()
|
|
|
|
|
|
|
|
// reset the roomCounts on a day change
|
|
|
|
if s.lastUpdate.Day() != time.Now().Day() {
|
|
|
|
s.roomCounts[s.serverName] = make(map[string]bool)
|
|
|
|
s.lastUpdate = time.Now()
|
|
|
|
}
|
|
|
|
|
|
|
|
_, sender, err := gomatrixserverlib.SplitID('@', eventSender)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
msgCount := s.msgCounts[s.serverName]
|
|
|
|
roomCount := s.roomCounts[s.serverName]
|
|
|
|
if roomCount == nil {
|
|
|
|
roomCount = make(map[string]bool)
|
|
|
|
}
|
|
|
|
switch eventType {
|
|
|
|
case "m.room.message":
|
|
|
|
roomCount[roomID] = false
|
|
|
|
msgCount.Messages++
|
|
|
|
if sender == s.serverName {
|
|
|
|
msgCount.SentMessages++
|
|
|
|
}
|
|
|
|
case "m.room.encrypted":
|
|
|
|
roomCount[roomID] = true
|
|
|
|
msgCount.MessagesE2EE++
|
|
|
|
if sender == s.serverName {
|
|
|
|
msgCount.SentMessagesE2EE++
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
s.msgCounts[s.serverName] = msgCount
|
|
|
|
s.roomCounts[s.serverName] = roomCount
|
|
|
|
|
|
|
|
for serverName, stats := range s.msgCounts {
|
|
|
|
var normalRooms, encryptedRooms int64 = 0, 0
|
|
|
|
for _, isEncrypted := range s.roomCounts[s.serverName] {
|
|
|
|
if isEncrypted {
|
|
|
|
encryptedRooms++
|
|
|
|
} else {
|
|
|
|
normalRooms++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err := s.db.UpsertDailyRoomsMessages(ctx, serverName, stats, normalRooms, encryptedRooms)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("failed to upsert daily messages")
|
|
|
|
}
|
|
|
|
// Clear stats if we successfully stored it
|
|
|
|
if err == nil {
|
|
|
|
stats.Messages = 0
|
|
|
|
stats.SentMessages = 0
|
|
|
|
stats.MessagesE2EE = 0
|
|
|
|
stats.SentMessagesE2EE = 0
|
|
|
|
s.msgCounts[serverName] = stats
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-07 08:47:18 +00:00
|
|
|
func (s *OutputRoomEventConsumer) handleRoomUpgrade(ctx context.Context, oldRoomID, newRoomID string, localMembers []*localMembership, roomSize int) error {
|
|
|
|
for _, membership := range localMembers {
|
|
|
|
// Copy any existing push rules from old -> new room
|
2022-11-11 16:41:37 +00:00
|
|
|
if err := s.copyPushrules(ctx, oldRoomID, newRoomID, membership.Localpart, membership.Domain); err != nil {
|
2022-11-07 08:47:18 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// preserve m.direct room state
|
2022-11-11 16:41:37 +00:00
|
|
|
if err := s.updateMDirect(ctx, oldRoomID, newRoomID, membership.Localpart, membership.Domain, roomSize); err != nil {
|
2022-11-07 08:47:18 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// copy existing m.tag entries, if any
|
2022-11-11 16:41:37 +00:00
|
|
|
if err := s.copyTags(ctx, oldRoomID, newRoomID, membership.Localpart, membership.Domain); err != nil {
|
2022-11-07 08:47:18 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
func (s *OutputRoomEventConsumer) copyPushrules(ctx context.Context, oldRoomID, newRoomID string, localpart string, serverName spec.ServerName) error {
|
2022-11-11 16:41:37 +00:00
|
|
|
pushRules, err := s.db.QueryPushRules(ctx, localpart, serverName)
|
2022-11-07 08:47:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to query pushrules for user: %w", err)
|
|
|
|
}
|
|
|
|
if pushRules == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, roomRule := range pushRules.Global.Room {
|
|
|
|
if roomRule.RuleID != oldRoomID {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
cpRool := *roomRule
|
|
|
|
cpRool.RuleID = newRoomID
|
|
|
|
pushRules.Global.Room = append(pushRules.Global.Room, &cpRool)
|
|
|
|
rules, err := json.Marshal(pushRules)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-11-11 16:41:37 +00:00
|
|
|
if err = s.db.SaveAccountData(ctx, localpart, serverName, "", "m.push_rules", rules); err != nil {
|
2022-11-07 08:47:18 +00:00
|
|
|
return fmt.Errorf("failed to update pushrules: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateMDirect copies the "is_direct" flag from oldRoomID to newROomID
|
2023-04-19 15:50:33 +01:00
|
|
|
func (s *OutputRoomEventConsumer) updateMDirect(ctx context.Context, oldRoomID, newRoomID, localpart string, serverName spec.ServerName, roomSize int) error {
|
2022-11-07 08:47:18 +00:00
|
|
|
// this is most likely not a DM, so skip updating m.direct state
|
|
|
|
if roomSize > 2 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// Get direct message state
|
2022-11-11 16:41:37 +00:00
|
|
|
directChatsRaw, err := s.db.GetAccountDataByType(ctx, localpart, serverName, "", "m.direct")
|
2022-11-07 08:47:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to get m.direct from database: %w", err)
|
|
|
|
}
|
|
|
|
directChats := gjson.ParseBytes(directChatsRaw)
|
|
|
|
newDirectChats := make(map[string][]string)
|
|
|
|
// iterate over all userID -> roomIDs
|
2023-09-28 06:36:34 +01:00
|
|
|
var found bool
|
2022-11-07 08:47:18 +00:00
|
|
|
directChats.ForEach(func(userID, roomIDs gjson.Result) bool {
|
|
|
|
for _, roomID := range roomIDs.Array() {
|
|
|
|
newDirectChats[userID.Str] = append(newDirectChats[userID.Str], roomID.Str)
|
|
|
|
// add the new roomID to m.direct
|
|
|
|
if roomID.Str == oldRoomID {
|
|
|
|
found = true
|
|
|
|
newDirectChats[userID.Str] = append(newDirectChats[userID.Str], newRoomID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
})
|
2023-09-28 06:36:34 +01:00
|
|
|
|
|
|
|
// Only hit the database if we found the old room as a DM for this user
|
|
|
|
if found {
|
|
|
|
var data []byte
|
|
|
|
data, err = json.Marshal(newDirectChats)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err = s.db.SaveAccountData(ctx, localpart, serverName, "", "m.direct", data); err != nil {
|
|
|
|
return fmt.Errorf("failed to update m.direct state: %w", err)
|
|
|
|
}
|
2022-11-07 08:47:18 +00:00
|
|
|
}
|
2023-09-28 06:36:34 +01:00
|
|
|
|
2022-11-07 08:47:18 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
func (s *OutputRoomEventConsumer) copyTags(ctx context.Context, oldRoomID, newRoomID, localpart string, serverName spec.ServerName) error {
|
2022-11-11 16:41:37 +00:00
|
|
|
tag, err := s.db.GetAccountDataByType(ctx, localpart, serverName, oldRoomID, "m.tag")
|
2022-11-07 08:47:18 +00:00
|
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if tag == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2022-11-11 16:41:37 +00:00
|
|
|
return s.db.SaveAccountData(ctx, localpart, serverName, newRoomID, "m.tag", tag)
|
2022-11-07 08:47:18 +00:00
|
|
|
}
|
|
|
|
|
2023-04-27 12:54:20 +01:00
|
|
|
func (s *OutputRoomEventConsumer) processMessage(ctx context.Context, event *rstypes.HeaderedEvent, streamPos uint64) error {
|
2023-09-15 15:39:06 +01:00
|
|
|
members, roomSize, err := s.localRoomMembers(ctx, event.RoomID().String())
|
2022-03-03 11:40:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("s.localRoomMembers: %w", err)
|
|
|
|
}
|
|
|
|
|
2022-11-07 08:47:18 +00:00
|
|
|
switch {
|
2023-04-19 15:50:33 +01:00
|
|
|
case event.Type() == spec.MRoomMember:
|
2023-09-15 16:25:09 +01:00
|
|
|
cevent, clientEvErr := synctypes.ToClientEvent(event, synctypes.FormatAll, func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
|
|
|
return s.rsAPI.QueryUserIDForSender(ctx, roomID, senderID)
|
|
|
|
})
|
|
|
|
if clientEvErr != nil {
|
|
|
|
return clientEvErr
|
2023-06-06 21:55:18 +01:00
|
|
|
}
|
2022-03-03 11:40:53 +00:00
|
|
|
var member *localMembership
|
2023-09-15 16:25:09 +01:00
|
|
|
member, err = newLocalMembership(cevent)
|
2022-03-03 11:40:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("newLocalMembership: %w", err)
|
|
|
|
}
|
2023-04-19 15:50:33 +01:00
|
|
|
if member.Membership == spec.Invite && member.Domain == s.cfg.Matrix.ServerName {
|
2022-03-03 11:40:53 +00:00
|
|
|
// localRoomMembers only adds joined members. An invite
|
|
|
|
// should also be pushed to the target user.
|
|
|
|
members = append(members, member)
|
|
|
|
}
|
2022-11-07 08:47:18 +00:00
|
|
|
case event.Type() == "m.room.tombstone" && event.StateKeyEquals(""):
|
|
|
|
// Handle room upgrades
|
2023-09-15 15:39:06 +01:00
|
|
|
oldRoomID := event.RoomID().String()
|
2022-11-07 08:47:18 +00:00
|
|
|
newRoomID := gjson.GetBytes(event.Content(), "replacement_room").Str
|
|
|
|
if err = s.handleRoomUpgrade(ctx, oldRoomID, newRoomID, members, roomSize); err != nil {
|
|
|
|
// while inconvenient, this shouldn't stop us from sending push notifications
|
|
|
|
log.WithError(err).Errorf("UserAPI: failed to handle room upgrade for users")
|
|
|
|
}
|
|
|
|
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: run in parallel with localRoomMembers.
|
|
|
|
roomName, err := s.roomName(ctx, event)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("s.roomName: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event_id": event.EventID(),
|
2023-09-15 15:39:06 +01:00
|
|
|
"room_id": event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
"num_members": len(members),
|
|
|
|
"room_size": roomSize,
|
|
|
|
}).Tracef("Notifying members")
|
|
|
|
|
|
|
|
// Notification.UserIsTarget is a per-member field, so we
|
|
|
|
// cannot group all users in a single request.
|
|
|
|
//
|
|
|
|
// TODO: does it have to be set? It's not required, and
|
|
|
|
// removing it means we can send all notifications to
|
|
|
|
// e.g. Element's Push gateway in one go.
|
|
|
|
for _, mem := range members {
|
2022-09-27 14:01:34 +01:00
|
|
|
if err := s.notifyLocal(ctx, event, mem, roomSize, roomName, streamPos); err != nil {
|
2022-03-03 11:40:53 +00:00
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"localpart": mem.Localpart,
|
2022-09-27 14:01:34 +01:00
|
|
|
}).WithError(err).Error("Unable to push to local user")
|
2022-03-03 11:40:53 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type localMembership struct {
|
|
|
|
gomatrixserverlib.MemberContent
|
|
|
|
UserID string
|
|
|
|
Localpart string
|
2023-04-19 15:50:33 +01:00
|
|
|
Domain spec.ServerName
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
2023-04-04 18:16:53 +01:00
|
|
|
func newLocalMembership(event *synctypes.ClientEvent) (*localMembership, error) {
|
2022-03-03 11:40:53 +00:00
|
|
|
if event.StateKey == nil {
|
|
|
|
return nil, fmt.Errorf("missing state_key")
|
|
|
|
}
|
|
|
|
|
|
|
|
var member localMembership
|
|
|
|
if err := json.Unmarshal(event.Content, &member.MemberContent); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
localpart, domain, err := gomatrixserverlib.SplitID('@', *event.StateKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
member.UserID = *event.StateKey
|
|
|
|
member.Localpart = localpart
|
|
|
|
member.Domain = domain
|
|
|
|
return &member, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// localRoomMembers fetches the current local members of a room, and
|
|
|
|
// the total number of members.
|
2022-09-27 14:01:34 +01:00
|
|
|
func (s *OutputRoomEventConsumer) localRoomMembers(ctx context.Context, roomID string) ([]*localMembership, int, error) {
|
2023-07-13 13:19:08 +01:00
|
|
|
// Get only locally joined users to avoid unmarshalling and caching
|
|
|
|
// membership events we only use to calculate the room size.
|
2022-03-03 11:40:53 +00:00
|
|
|
req := &rsapi.QueryMembershipsForRoomRequest{
|
|
|
|
RoomID: roomID,
|
|
|
|
JoinedOnly: true,
|
2023-07-13 13:19:08 +01:00
|
|
|
LocalOnly: true,
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
var res rsapi.QueryMembershipsForRoomResponse
|
|
|
|
if err := s.rsAPI.QueryMembershipsForRoom(ctx, req, &res); err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
2023-07-13 13:19:08 +01:00
|
|
|
// Since we only queried locally joined users above,
|
|
|
|
// we also need to ask the roomserver about the joined user count.
|
|
|
|
totalCount, err := s.rsAPI.JoinedUserCount(ctx, roomID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
2022-03-03 11:40:53 +00:00
|
|
|
var members []*localMembership
|
|
|
|
for _, event := range res.JoinEvents {
|
2022-11-30 11:40:36 +00:00
|
|
|
// Filter out invalid join events
|
|
|
|
if event.StateKey == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if *event.StateKey == "" {
|
|
|
|
continue
|
|
|
|
}
|
2023-07-13 13:19:08 +01:00
|
|
|
// We're going to trust the Query from above to really just return
|
|
|
|
// local users
|
2022-03-03 11:40:53 +00:00
|
|
|
member, err := newLocalMembership(&event)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("Parsing MemberContent")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
members = append(members, member)
|
|
|
|
}
|
|
|
|
|
2023-07-13 13:19:08 +01:00
|
|
|
return members, totalCount, nil
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// roomName returns the name in the event (if type==m.room.name), or
|
|
|
|
// looks it up in roomserver. If there is no name,
|
|
|
|
// m.room.canonical_alias is consulted. Returns an empty string if the
|
|
|
|
// room has no name.
|
2023-04-27 12:54:20 +01:00
|
|
|
func (s *OutputRoomEventConsumer) roomName(ctx context.Context, event *rstypes.HeaderedEvent) (string, error) {
|
2023-04-19 15:50:33 +01:00
|
|
|
if event.Type() == spec.MRoomName {
|
2022-03-03 11:40:53 +00:00
|
|
|
name, err := unmarshalRoomName(event)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if name != "" {
|
|
|
|
return name, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-26 14:47:37 +01:00
|
|
|
// Special case for invites, as we don't store any "current state" for these events,
|
|
|
|
// we need to make sure that, if present, the m.room.name is sent as well.
|
|
|
|
if event.Type() == spec.MRoomMember &&
|
|
|
|
gjson.GetBytes(event.Content(), "membership").Str == "invite" {
|
|
|
|
invState := gjson.GetBytes(event.JSON(), "unsigned.invite_room_state")
|
|
|
|
for _, ev := range invState.Array() {
|
|
|
|
if ev.Get("type").Str == spec.MRoomName {
|
|
|
|
name := ev.Get("content.name").Str
|
|
|
|
return name, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-03 11:40:53 +00:00
|
|
|
req := &rsapi.QueryCurrentStateRequest{
|
2023-09-15 15:39:06 +01:00
|
|
|
RoomID: event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
StateTuples: []gomatrixserverlib.StateKeyTuple{roomNameTuple, canonicalAliasTuple},
|
|
|
|
}
|
|
|
|
var res rsapi.QueryCurrentStateResponse
|
|
|
|
|
|
|
|
if err := s.rsAPI.QueryCurrentState(ctx, req, &res); err != nil {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if eventS := res.StateEvents[roomNameTuple]; eventS != nil {
|
|
|
|
return unmarshalRoomName(eventS)
|
|
|
|
}
|
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
if event.Type() == spec.MRoomCanonicalAlias {
|
2022-03-03 11:40:53 +00:00
|
|
|
alias, err := unmarshalCanonicalAlias(event)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if alias != "" {
|
|
|
|
return alias, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if event = res.StateEvents[canonicalAliasTuple]; event != nil {
|
|
|
|
return unmarshalCanonicalAlias(event)
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
2023-04-19 15:50:33 +01:00
|
|
|
canonicalAliasTuple = gomatrixserverlib.StateKeyTuple{EventType: spec.MRoomCanonicalAlias}
|
|
|
|
roomNameTuple = gomatrixserverlib.StateKeyTuple{EventType: spec.MRoomName}
|
2022-03-03 11:40:53 +00:00
|
|
|
)
|
|
|
|
|
2023-04-27 12:54:20 +01:00
|
|
|
func unmarshalRoomName(event *rstypes.HeaderedEvent) (string, error) {
|
2022-03-03 11:40:53 +00:00
|
|
|
var nc eventutil.NameContent
|
|
|
|
if err := json.Unmarshal(event.Content(), &nc); err != nil {
|
|
|
|
return "", fmt.Errorf("unmarshaling NameContent: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nc.Name, nil
|
|
|
|
}
|
|
|
|
|
2023-04-27 12:54:20 +01:00
|
|
|
func unmarshalCanonicalAlias(event *rstypes.HeaderedEvent) (string, error) {
|
2022-03-03 11:40:53 +00:00
|
|
|
var cac eventutil.CanonicalAliasContent
|
|
|
|
if err := json.Unmarshal(event.Content(), &cac); err != nil {
|
|
|
|
return "", fmt.Errorf("unmarshaling CanonicalAliasContent: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return cac.Alias, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// notifyLocal finds the right push actions for a local user, given an event.
|
2023-04-27 12:54:20 +01:00
|
|
|
func (s *OutputRoomEventConsumer) notifyLocal(ctx context.Context, event *rstypes.HeaderedEvent, mem *localMembership, roomSize int, roomName string, streamPos uint64) error {
|
2022-03-03 11:40:53 +00:00
|
|
|
actions, err := s.evaluatePushRules(ctx, event, mem, roomSize)
|
|
|
|
if err != nil {
|
2022-11-11 16:41:37 +00:00
|
|
|
return fmt.Errorf("s.evaluatePushRules: %w", err)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
a, tweaks, err := pushrules.ActionsToTweaks(actions)
|
|
|
|
if err != nil {
|
2022-11-11 16:41:37 +00:00
|
|
|
return fmt.Errorf("pushrules.ActionsToTweaks: %w", err)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
2023-10-24 10:51:08 +01:00
|
|
|
|
|
|
|
if a != pushrules.NotifyAction {
|
2022-03-03 11:40:53 +00:00
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event_id": event.EventID(),
|
2023-09-15 15:39:06 +01:00
|
|
|
"room_id": event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
"localpart": mem.Localpart,
|
2022-09-27 14:01:34 +01:00
|
|
|
}).Tracef("Push rule evaluation rejected the event")
|
2022-03-03 11:40:53 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-11-11 16:41:37 +00:00
|
|
|
devicesByURLAndFormat, profileTag, err := s.localPushDevices(ctx, mem.Localpart, mem.Domain, tweaks)
|
2022-03-03 11:40:53 +00:00
|
|
|
if err != nil {
|
2022-11-11 16:41:37 +00:00
|
|
|
return fmt.Errorf("s.localPushDevices: %w", err)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
2023-09-15 16:25:09 +01:00
|
|
|
clientEvent, err := synctypes.ToClientEvent(event, synctypes.FormatSync, func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
|
|
|
return s.rsAPI.QueryUserIDForSender(ctx, roomID, senderID)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-06-06 21:55:18 +01:00
|
|
|
}
|
2023-06-12 12:19:25 +01:00
|
|
|
|
2022-03-03 11:40:53 +00:00
|
|
|
n := &api.Notification{
|
|
|
|
Actions: actions,
|
|
|
|
// UNSPEC: the spec doesn't say this is a ClientEvent, but the
|
|
|
|
// fields seem to match. room_id should be missing, which
|
|
|
|
// matches the behaviour of FormatSync.
|
2023-09-15 16:25:09 +01:00
|
|
|
Event: *clientEvent,
|
2022-03-03 11:40:53 +00:00
|
|
|
// TODO: this is per-device, but it's not part of the primary
|
|
|
|
// key. So inserting one notification per profile tag doesn't
|
|
|
|
// make sense. What is this supposed to be? Sytests require it
|
|
|
|
// to "work", but they only use a single device.
|
|
|
|
ProfileTag: profileTag,
|
2023-09-15 15:39:06 +01:00
|
|
|
RoomID: event.RoomID().String(),
|
2023-04-19 15:50:33 +01:00
|
|
|
TS: spec.AsTimestamp(time.Now()),
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
2022-11-11 16:41:37 +00:00
|
|
|
if err = s.db.InsertNotification(ctx, mem.Localpart, mem.Domain, event.EventID(), streamPos, tweaks, n); err != nil {
|
|
|
|
return fmt.Errorf("s.db.InsertNotification: %w", err)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
2023-09-15 15:39:06 +01:00
|
|
|
if err = s.syncProducer.GetAndSendNotificationData(ctx, mem.UserID, event.RoomID().String()); err != nil {
|
2022-11-11 16:41:37 +00:00
|
|
|
return fmt.Errorf("s.syncProducer.GetAndSendNotificationData: %w", err)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We do this after InsertNotification. Thus, this should always return >=1.
|
2022-11-11 16:41:37 +00:00
|
|
|
userNumUnreadNotifs, err := s.db.GetNotificationCount(ctx, mem.Localpart, mem.Domain, tables.AllNotifications)
|
2022-03-03 11:40:53 +00:00
|
|
|
if err != nil {
|
2022-11-11 16:41:37 +00:00
|
|
|
return fmt.Errorf("s.db.GetNotificationCount: %w", err)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event_id": event.EventID(),
|
2023-09-15 15:39:06 +01:00
|
|
|
"room_id": event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
"localpart": mem.Localpart,
|
|
|
|
"num_urls": len(devicesByURLAndFormat),
|
|
|
|
"num_unread": userNumUnreadNotifs,
|
2022-09-27 14:01:34 +01:00
|
|
|
}).Trace("Notifying single member")
|
2022-03-03 11:40:53 +00:00
|
|
|
|
|
|
|
// Push gateways are out of our control, and we cannot risk
|
|
|
|
// looking up the server on a misbehaving push gateway. Each user
|
|
|
|
// receives a goroutine now that all internal API calls have been
|
|
|
|
// made.
|
|
|
|
//
|
|
|
|
// TODO: think about bounding this to one per user, and what
|
|
|
|
// ordering guarantees we must provide.
|
|
|
|
go func() {
|
|
|
|
// This background processing cannot be tied to a request.
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
var rejected []*pushgateway.Device
|
|
|
|
for url, fmts := range devicesByURLAndFormat {
|
|
|
|
for format, devices := range fmts {
|
|
|
|
// TODO: support "email".
|
|
|
|
if !strings.HasPrefix(url, "http") {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// UNSPEC: the specification suggests there can be
|
|
|
|
// more than one device per request. There is at least
|
|
|
|
// one Sytest that expects one HTTP request per
|
|
|
|
// device, rather than per URL. For now, we must
|
|
|
|
// notify each one separately.
|
|
|
|
for _, dev := range devices {
|
|
|
|
rej, err := s.notifyHTTP(ctx, event, url, format, []*pushgateway.Device{dev}, mem.Localpart, roomName, int(userNumUnreadNotifs))
|
|
|
|
if err != nil {
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event_id": event.EventID(),
|
|
|
|
"localpart": mem.Localpart,
|
|
|
|
}).WithError(err).Errorf("Unable to notify HTTP pusher")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
rejected = append(rejected, rej...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(rejected) > 0 {
|
2022-11-11 16:41:37 +00:00
|
|
|
s.deleteRejectedPushers(ctx, rejected, mem.Localpart, mem.Domain)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// evaluatePushRules fetches and evaluates the push rules of a local
|
|
|
|
// user. Returns actions (including dont_notify).
|
2023-04-27 12:54:20 +01:00
|
|
|
func (s *OutputRoomEventConsumer) evaluatePushRules(ctx context.Context, event *rstypes.HeaderedEvent, mem *localMembership, roomSize int) ([]*pushrules.Action, error) {
|
2023-06-06 21:55:18 +01:00
|
|
|
user := ""
|
2023-09-15 15:39:06 +01:00
|
|
|
sender, err := s.rsAPI.QueryUserIDForSender(ctx, event.RoomID(), event.SenderID())
|
2023-06-06 21:55:18 +01:00
|
|
|
if err == nil {
|
|
|
|
user = sender.String()
|
|
|
|
}
|
|
|
|
if user == mem.UserID {
|
2022-03-03 11:40:53 +00:00
|
|
|
// SPEC: Homeservers MUST NOT notify the Push Gateway for
|
|
|
|
// events that the user has sent themselves.
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2022-04-07 15:08:19 +01:00
|
|
|
// Get accountdata to check if the event.Sender() is ignored by mem.LocalPart
|
2022-11-11 16:41:37 +00:00
|
|
|
data, err := s.db.GetAccountDataByType(ctx, mem.Localpart, mem.Domain, "", "m.ignored_user_list")
|
2022-04-07 15:08:19 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if data != nil {
|
|
|
|
ignored := types.IgnoredUsers{}
|
|
|
|
err = json.Unmarshal(data, &ignored)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-06-06 21:55:18 +01:00
|
|
|
if _, ok := ignored.List[sender.String()]; ok {
|
|
|
|
return nil, fmt.Errorf("user %s is ignored", sender.String())
|
2022-04-07 15:08:19 +01:00
|
|
|
}
|
|
|
|
}
|
2022-11-11 16:41:37 +00:00
|
|
|
ruleSets, err := s.db.QueryPushRules(ctx, mem.Localpart, mem.Domain)
|
2022-09-09 12:56:33 +01:00
|
|
|
if err != nil {
|
2022-03-03 11:40:53 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ec := &ruleSetEvalContext{
|
|
|
|
ctx: ctx,
|
|
|
|
rsAPI: s.rsAPI,
|
|
|
|
mem: mem,
|
2023-09-15 15:39:06 +01:00
|
|
|
roomID: event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
roomSize: roomSize,
|
|
|
|
}
|
2022-09-09 12:56:33 +01:00
|
|
|
eval := pushrules.NewRuleSetEvaluator(ec, &ruleSets.Global)
|
2023-06-14 15:23:46 +01:00
|
|
|
rule, err := eval.MatchEvent(event.PDU, func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
2023-06-06 21:55:18 +01:00
|
|
|
return s.rsAPI.QueryUserIDForSender(ctx, roomID, senderID)
|
|
|
|
})
|
2022-03-03 11:40:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if rule == nil {
|
|
|
|
// SPEC: If no rules match an event, the homeserver MUST NOT
|
|
|
|
// notify the Push Gateway for that event.
|
2022-11-30 11:40:36 +00:00
|
|
|
return nil, nil
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event_id": event.EventID(),
|
2023-09-15 15:39:06 +01:00
|
|
|
"room_id": event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
"localpart": mem.Localpart,
|
|
|
|
"rule_id": rule.RuleID,
|
2022-09-27 14:01:34 +01:00
|
|
|
}).Trace("Matched a push rule")
|
2022-03-03 11:40:53 +00:00
|
|
|
|
|
|
|
return rule.Actions, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type ruleSetEvalContext struct {
|
|
|
|
ctx context.Context
|
2022-05-05 19:30:38 +01:00
|
|
|
rsAPI rsapi.UserRoomserverAPI
|
2022-03-03 11:40:53 +00:00
|
|
|
mem *localMembership
|
|
|
|
roomID string
|
|
|
|
roomSize int
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rse *ruleSetEvalContext) UserDisplayName() string { return rse.mem.DisplayName }
|
|
|
|
|
|
|
|
func (rse *ruleSetEvalContext) RoomMemberCount() (int, error) { return rse.roomSize, nil }
|
|
|
|
|
2023-06-07 18:14:35 +01:00
|
|
|
func (rse *ruleSetEvalContext) HasPowerLevel(senderID spec.SenderID, levelKey string) (bool, error) {
|
2022-03-03 11:40:53 +00:00
|
|
|
req := &rsapi.QueryLatestEventsAndStateRequest{
|
|
|
|
RoomID: rse.roomID,
|
|
|
|
StateToFetch: []gomatrixserverlib.StateKeyTuple{
|
2023-04-19 15:50:33 +01:00
|
|
|
{EventType: spec.MRoomPowerLevels},
|
2022-03-03 11:40:53 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
var res rsapi.QueryLatestEventsAndStateResponse
|
|
|
|
if err := rse.rsAPI.QueryLatestEventsAndState(rse.ctx, req, &res); err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
for _, ev := range res.StateEvents {
|
2023-04-19 15:50:33 +01:00
|
|
|
if ev.Type() != spec.MRoomPowerLevels {
|
2022-03-03 11:40:53 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-05-02 15:03:16 +01:00
|
|
|
plc, err := gomatrixserverlib.NewPowerLevelContentFromEvent(ev.PDU)
|
2022-03-03 11:40:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
2023-06-06 21:55:18 +01:00
|
|
|
return plc.UserLevel(senderID) >= plc.NotificationLevel(levelKey), nil
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// localPushDevices pushes to the configured devices of a local
|
|
|
|
// user. The map keys are [url][format].
|
2023-04-19 15:50:33 +01:00
|
|
|
func (s *OutputRoomEventConsumer) localPushDevices(ctx context.Context, localpart string, serverName spec.ServerName, tweaks map[string]interface{}) (map[string]map[string][]*pushgateway.Device, string, error) {
|
2022-11-11 16:41:37 +00:00
|
|
|
pusherDevices, err := util.GetPushDevices(ctx, localpart, serverName, tweaks, s.db)
|
2022-03-03 11:40:53 +00:00
|
|
|
if err != nil {
|
2022-11-11 16:41:37 +00:00
|
|
|
return nil, "", fmt.Errorf("util.GetPushDevices: %w", err)
|
2022-03-03 11:40:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var profileTag string
|
|
|
|
devicesByURL := make(map[string]map[string][]*pushgateway.Device, len(pusherDevices))
|
|
|
|
for _, pusherDevice := range pusherDevices {
|
|
|
|
if profileTag == "" {
|
|
|
|
profileTag = pusherDevice.Pusher.ProfileTag
|
|
|
|
}
|
|
|
|
|
|
|
|
url := pusherDevice.URL
|
|
|
|
if devicesByURL[url] == nil {
|
|
|
|
devicesByURL[url] = make(map[string][]*pushgateway.Device, 2)
|
|
|
|
}
|
|
|
|
devicesByURL[url][pusherDevice.Format] = append(devicesByURL[url][pusherDevice.Format], &pusherDevice.Device)
|
|
|
|
}
|
|
|
|
|
|
|
|
return devicesByURL, profileTag, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// notifyHTTP performs a notificatation to a Push Gateway.
|
2023-04-27 12:54:20 +01:00
|
|
|
func (s *OutputRoomEventConsumer) notifyHTTP(ctx context.Context, event *rstypes.HeaderedEvent, url, format string, devices []*pushgateway.Device, localpart, roomName string, userNumUnreadNotifs int) ([]*pushgateway.Device, error) {
|
2022-03-03 11:40:53 +00:00
|
|
|
logger := log.WithFields(log.Fields{
|
|
|
|
"event_id": event.EventID(),
|
|
|
|
"url": url,
|
|
|
|
"localpart": localpart,
|
|
|
|
"num_devices": len(devices),
|
|
|
|
})
|
|
|
|
|
|
|
|
var req pushgateway.NotifyRequest
|
|
|
|
switch format {
|
|
|
|
case "event_id_only":
|
|
|
|
req = pushgateway.NotifyRequest{
|
|
|
|
Notification: pushgateway.Notification{
|
2022-08-30 13:54:57 +01:00
|
|
|
Counts: &pushgateway.Counts{
|
|
|
|
Unread: userNumUnreadNotifs,
|
|
|
|
},
|
2022-03-03 11:40:53 +00:00
|
|
|
Devices: devices,
|
|
|
|
EventID: event.EventID(),
|
2023-09-15 15:39:06 +01:00
|
|
|
RoomID: event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
2023-09-15 15:39:06 +01:00
|
|
|
sender, err := s.rsAPI.QueryUserIDForSender(ctx, event.RoomID(), event.SenderID())
|
2023-06-06 21:55:18 +01:00
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).Errorf("Failed to get userID for sender %s", event.SenderID())
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-03-03 11:40:53 +00:00
|
|
|
req = pushgateway.NotifyRequest{
|
|
|
|
Notification: pushgateway.Notification{
|
|
|
|
Content: event.Content(),
|
|
|
|
Counts: &pushgateway.Counts{
|
|
|
|
Unread: userNumUnreadNotifs,
|
|
|
|
},
|
|
|
|
Devices: devices,
|
|
|
|
EventID: event.EventID(),
|
|
|
|
ID: event.EventID(),
|
2023-09-15 15:39:06 +01:00
|
|
|
RoomID: event.RoomID().String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
RoomName: roomName,
|
2023-06-06 21:55:18 +01:00
|
|
|
Sender: sender.String(),
|
2022-03-03 11:40:53 +00:00
|
|
|
Type: event.Type(),
|
|
|
|
},
|
|
|
|
}
|
2023-06-12 12:19:25 +01:00
|
|
|
if mem, memberErr := event.Membership(); memberErr == nil {
|
2022-03-03 11:40:53 +00:00
|
|
|
req.Notification.Membership = mem
|
|
|
|
}
|
2023-06-12 12:19:25 +01:00
|
|
|
userID, err := spec.NewUserID(fmt.Sprintf("@%s:%s", localpart, s.cfg.Matrix.ServerName), true)
|
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).Errorf("Failed to convert local user to userID %s", localpart)
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-09-15 15:39:06 +01:00
|
|
|
localSender, err := s.rsAPI.QuerySenderIDForUser(ctx, event.RoomID(), *userID)
|
2023-06-12 12:19:25 +01:00
|
|
|
if err != nil {
|
2023-09-15 15:39:06 +01:00
|
|
|
logger.WithError(err).Errorf("Failed to get local user senderID for room %s: %s", userID.String(), event.RoomID().String())
|
2023-06-12 12:19:25 +01:00
|
|
|
return nil, err
|
2023-08-02 11:12:14 +01:00
|
|
|
} else if localSender == nil {
|
2023-09-15 15:39:06 +01:00
|
|
|
logger.WithError(err).Errorf("Failed to get local user senderID for room %s: %s", userID.String(), event.RoomID().String())
|
|
|
|
return nil, fmt.Errorf("no sender ID for user %s in %s", userID.String(), event.RoomID().String())
|
2023-06-12 12:19:25 +01:00
|
|
|
}
|
2023-08-02 11:12:14 +01:00
|
|
|
if event.StateKey() != nil && *event.StateKey() == string(*localSender) {
|
2022-03-03 11:40:53 +00:00
|
|
|
req.Notification.UserIsTarget = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-27 14:01:34 +01:00
|
|
|
logger.Tracef("Notifying push gateway %s", url)
|
2022-03-03 11:40:53 +00:00
|
|
|
var res pushgateway.NotifyResponse
|
|
|
|
if err := s.pgClient.Notify(ctx, url, &req, &res); err != nil {
|
|
|
|
logger.WithError(err).Errorf("Failed to notify push gateway %s", url)
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-09-27 14:01:34 +01:00
|
|
|
logger.WithField("num_rejected", len(res.Rejected)).Trace("Push gateway result")
|
2022-03-03 11:40:53 +00:00
|
|
|
|
|
|
|
if len(res.Rejected) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
devMap := make(map[string]*pushgateway.Device, len(devices))
|
|
|
|
for _, d := range devices {
|
|
|
|
devMap[d.PushKey] = d
|
|
|
|
}
|
|
|
|
rejected := make([]*pushgateway.Device, 0, len(res.Rejected))
|
|
|
|
for _, pushKey := range res.Rejected {
|
|
|
|
d := devMap[pushKey]
|
|
|
|
if d != nil {
|
|
|
|
rejected = append(rejected, d)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return rejected, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// deleteRejectedPushers deletes the pushers associated with the given devices.
|
2023-04-19 15:50:33 +01:00
|
|
|
func (s *OutputRoomEventConsumer) deleteRejectedPushers(ctx context.Context, devices []*pushgateway.Device, localpart string, serverName spec.ServerName) {
|
2022-03-03 11:40:53 +00:00
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"localpart": localpart,
|
|
|
|
"app_id0": devices[0].AppID,
|
|
|
|
"num_devices": len(devices),
|
|
|
|
}).Warnf("Deleting pushers rejected by the HTTP push gateway")
|
|
|
|
|
|
|
|
for _, d := range devices {
|
2022-11-11 16:41:37 +00:00
|
|
|
if err := s.db.RemovePusher(ctx, d.AppID, d.PushKey, localpart, serverName); err != nil {
|
2022-03-03 11:40:53 +00:00
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"localpart": localpart,
|
|
|
|
}).WithError(err).Errorf("Unable to delete rejected pusher")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|