Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion internal/protocol/activity_center.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,12 @@ func (n *ActivityCenterNotification) Valid() error {
return nil
}

func chatShowsMentionAndReplyActivityCenterNotifications(chat *Chat) bool {
return chat != nil && chat.Active && (chat.CommunityChat() || chat.PrivateGroupChat()) && !chat.Muted
}

func showMentionOrReplyActivityCenterNotification(publicKey ecdsa.PublicKey, message *common.Message, chat *Chat, responseTo *common.Message) (bool, ActivityCenterType) {
if chat == nil || !chat.Active || (!chat.CommunityChat() && !chat.PrivateGroupChat()) || chat.Muted {
if !chatShowsMentionAndReplyActivityCenterNotifications(chat) {
return false, ActivityCenterNotificationNoType
}

Expand Down
29 changes: 16 additions & 13 deletions internal/protocol/activity_center_persistence.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,26 +112,29 @@ func (db sqlitePersistence) DeleteActivityCenterNotificationForMessage(chatID st
}

func (db sqlitePersistence) SaveActivityCenterNotification(notification *ActivityCenterNotification, updateState bool) (int64, error) {
var tx *sql.Tx
var err error

err = notification.Valid()
tx, err := db.db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return 0, err
}
defer func() {
_ = tx.Rollback()
}()

tx, err = db.db.BeginTx(context.Background(), &sql.TxOptions{})
n, err := db.saveActivityCenterNotification(tx, notification, updateState)
if err != nil {
return n, err
}
if err := tx.Commit(); err != nil {
return n, err
}
return n, nil
}

func (db sqlitePersistence) saveActivityCenterNotification(tx *sql.Tx, notification *ActivityCenterNotification, updateState bool) (int64, error) {
if err := notification.Valid(); err != nil {
return 0, err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
// don't shadow original error
_ = tx.Rollback()
}()
var err error

// encode message
var encodedMessage []byte
Expand Down
72 changes: 72 additions & 0 deletions internal/protocol/message_persistence.go
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,78 @@ func (db sqlitePersistence) SetThreadCreator(threadID, chatID, creatorID string)
return db.setThreadCreator(tx, threadID, chatID, creatorID)
}

// ClaimThreadStartNotification reports whether message is the earliest message
// from someone else in a thread started on ownID's message by someone else,
// and records it so the parent author is notified only once per thread.
// It returns the thread's stored parent message ID when claimed. Threads whose
// creator is unknown are skipped, since the parent author may have created them.
func (db sqlitePersistence) ClaimThreadStartNotification(message *common.Message, ownID string) (string, bool, error) {
return claimThreadStartNotification(db.db, message, ownID)
}

func (db sqlitePersistence) ClaimThreadStartNotificationAndSave(message *common.Message, ownID string, notification *ActivityCenterNotification) (bool, error) {
tx, err := db.db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return false, err
}
defer tx.Rollback()

_, claimed, err := claimThreadStartNotification(tx, message, ownID)
if err != nil || !claimed {
return claimed, err
}
if _, err := db.saveActivityCenterNotification(tx, notification, true); err != nil {
return false, err
}
if err := tx.Commit(); err != nil {
return false, err
}
return true, nil
}

type threadStartNotificationQueryer interface {
QueryRow(query string, args ...interface{}) *sql.Row
}

func claimThreadStartNotification(queryer threadStartNotificationQueryer, message *common.Message, ownID string) (string, bool, error) {
var parentMessageID string
err := queryer.QueryRow(`UPDATE threads SET parent_author_notified = TRUE
WHERE thread_id = ? AND chat_id = ? AND NOT parent_author_notified AND NOT deleted
AND NOT creator_pending AND creator_id NOT IN ('', ?)
AND EXISTS (
SELECT 1 FROM user_messages parent
WHERE parent.id = threads.parent_message_id AND parent.local_chat_id = threads.chat_id
AND parent.source = ? AND NOT parent.deleted AND NOT parent.deleted_for_me)
AND NOT EXISTS (
SELECT 1 FROM user_messages earlier
WHERE earlier.thread_id = threads.thread_id AND earlier.local_chat_id = threads.chat_id
AND earlier.source != ? AND earlier.id != ?
AND (earlier.clock_value < ? OR (earlier.clock_value = ? AND earlier.id < ?)))
RETURNING parent_message_id`,
message.GetThreadId(), message.LocalChatID, ownID, ownID, ownID, message.ID,
message.Clock, message.Clock, message.ID).Scan(&parentMessageID)
if errors.Is(err, sql.ErrNoRows) || errors.Is(err, common.ErrRecordNotFound) {
return "", false, nil
}
if err != nil {
return "", false, err
}
return parentMessageID, true, nil
}

// EarliestThreadMessageIDFromOthers returns the ID of the earliest message in
// a thread that was not sent by ownID, in the order ClaimThreadStartNotification uses.
func (db sqlitePersistence) EarliestThreadMessageIDFromOthers(chatID, threadID, ownID string) (string, error) {
var id string
err := db.db.QueryRow(`SELECT id FROM user_messages
WHERE local_chat_id = ? AND thread_id = ? AND source != ?
ORDER BY clock_value, id LIMIT 1`, chatID, threadID, ownID).Scan(&id)
if errors.Is(err, sql.ErrNoRows) || errors.Is(err, common.ErrRecordNotFound) {
return "", nil
}
return id, err
}

func (db sqlitePersistence) UpdateThreadMetadata(chatID, threadID, name string, clock uint64) (bool, error) {
result, err := db.db.Exec(
`UPDATE threads SET name = ?, metadata_clock = ?
Expand Down
167 changes: 152 additions & 15 deletions internal/protocol/messenger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3146,7 +3146,13 @@ func (r *ReceivedMessageState) updateExistingActivityCenterNotification(publicKe
}

notification.Message = message
notification.ReplyMessage = responseTo
// A thread start notification points to the thread's parent rather than to
// the message's reply target, so keep that parent across edits.
keepThreadParent := message.GetThreadId() != "" && notification.Type == ActivityCenterNotificationTypeReply &&
notification.ReplyMessage != nil && notification.ReplyMessage.ID != message.ResponseTo
if !keepThreadParent {
notification.ReplyMessage = responseTo
}
notification.UpdatedAt = m.GetCurrentTimeInMillis()

err = m.addActivityCenterNotification(r.Response, notification, nil)
Expand Down Expand Up @@ -3193,7 +3199,13 @@ func (r *ReceivedMessageState) addNewActivityCenterNotification(publicKey ecdsa.

// Thread muting preserves mentions and replies in the activity center.
isNotification, notificationType := showMentionOrReplyActivityCenterNotification(publicKey, message, chat, responseTo)
if !isNotification {
ownID := ""
mayStartThreadOnOwnMessage := false
if m.featureFlags.Threads && message.GetThreadId() != "" && chatShowsMentionAndReplyActivityCenterNotifications(chat) {
ownID = crypto.PubkeyToHex(&publicKey)
mayStartThreadOnOwnMessage = message.From != ownID
}
if !isNotification && !mayStartThreadOnOwnMessage {
return nil
}

Expand All @@ -3205,32 +3217,159 @@ func (r *ReceivedMessageState) addNewActivityCenterNotification(publicKey ecdsa.
}
}

// Use albumId as notificationId to prevent multiple notifications
// for same message with multiple images
var notificationID string
if mayStartThreadOnOwnMessage {
if !isNotification {
thread, err := m.persistence.ThreadByID(chat.ID, message.GetThreadId())
if errors.Is(err, common.ErrRecordNotFound) {
return nil
}
if err != nil {
return err
}
if thread.Deleted || thread.CreatorPending || thread.CreatorID == "" || thread.CreatorID == ownID {
return nil
}
parent, err := m.persistence.MessageByID(thread.ParentMessageID)
if errors.Is(err, common.ErrRecordNotFound) {
return nil
}
if err != nil {
return err
}
if err := m.prepareMessage(parent, m.httpServer); err != nil {
return err
}
notification, err := m.buildMessageActivityCenterNotification(
chat, message, parent, ActivityCenterNotificationTypeReply)
if err != nil {
return err
}
claimed, err := m.persistence.ClaimThreadStartNotificationAndSave(message, ownID, notification)
if err != nil || !claimed {
return err
}
return m.appendActivityCenterNotification(r.Response, notification)
}
}
if !isNotification {
return nil
}

if err := m.addMessageActivityCenterNotification(r.Response, chat, message, responseTo, notificationType); err != nil {
return err
}
if mayStartThreadOnOwnMessage {
_, _, err := m.persistence.ClaimThreadStartNotification(message, ownID)
return err
}
return nil
}

// notifyThreadStartAfterCreation notifies the parent author once a thread's
// creator is known, when someone else's first message arrived before the
// creation metadata and could not be attributed yet.
func (m *Messenger) notifyThreadStartAfterCreation(response *MessengerResponse, chat *Chat, threadID string) error {
if !m.featureFlags.Threads || !chatShowsMentionAndReplyActivityCenterNotifications(chat) {
return nil
}
ownID := m.myHexIdentity()
messageID, err := m.persistence.EarliestThreadMessageIDFromOthers(chat.ID, threadID, ownID)
if err != nil || messageID == "" {
return err
}
message, err := m.persistence.MessageByID(messageID)
if err != nil {
return err
}
thread, err := m.persistence.ThreadByID(chat.ID, threadID)
if errors.Is(err, common.ErrRecordNotFound) {
return nil
}
if err != nil {
return err
}
if thread.Deleted || thread.CreatorPending || thread.CreatorID == "" || thread.CreatorID == ownID {
return nil
}
if chat.CommunityChat() {
ok, err := m.isCommunityJoinedBeforeClock(m.identity.PublicKey, chat.CommunityID, message.Clock)
if err != nil || !ok {
return nil
}
}
if message.Deleted || message.DeletedForMe {
return nil
}
// The message may already have notified the user, e.g. as a mention.
existing, err := m.persistence.GetActivityCenterNotificationByID(activityCenterMessageNotificationID(message))
if err != nil {
return err
}
if existing != nil {
_, _, err := m.persistence.ClaimThreadStartNotification(message, ownID)
return err
}
parent, err := m.persistence.MessageByID(thread.ParentMessageID)
if errors.Is(err, common.ErrRecordNotFound) {
return nil
}
Comment on lines +3312 to +3315
if err != nil {
return err
}
if err := m.prepareMessage(message, m.httpServer); err != nil {
return err
}
if err := m.prepareMessage(parent, m.httpServer); err != nil {
return err
}
notification, err := m.buildMessageActivityCenterNotification(chat, message, parent, ActivityCenterNotificationTypeReply)
if err != nil {
return err
}
claimed, err := m.persistence.ClaimThreadStartNotificationAndSave(message, ownID, notification)
if err != nil || !claimed {
return err
}
return m.appendActivityCenterNotification(response, notification)
}

// activityCenterMessageNotificationID uses the album ID for images, so an album
// gets one notification rather than one per image.
func activityCenterMessageNotificationID(message *common.Message) cryptotypes.HexBytes {
if image := message.GetImage(); image != nil && image.GetAlbumId() != "" {
return cryptotypes.FromHex(image.GetAlbumId())
}
return cryptotypes.FromHex(message.ID)
}

func (m *Messenger) addMessageActivityCenterNotification(response *MessengerResponse, chat *Chat, message *common.Message, responseTo *common.Message, notificationType ActivityCenterType) error {
notification, err := m.buildMessageActivityCenterNotification(chat, message, responseTo, notificationType)
if err != nil {
return err
}
return m.addActivityCenterNotification(response, notification, nil)
}

func (m *Messenger) buildMessageActivityCenterNotification(chat *Chat, message *common.Message, responseTo *common.Message, notificationType ActivityCenterType) (*ActivityCenterNotification, error) {
image := message.GetImage()
var albumMessages = []*common.Message{}
if image != nil && image.GetAlbumId() != "" {
notificationID = image.GetAlbumId()
album, err := m.persistence.albumMessages(message.LocalChatID, image.AlbumId)
if err != nil {
return err
return nil, err
}
if m.httpServer != nil {
err = m.prepareMessagesList(album)
if err != nil {
return err
return nil, err
}
}

albumMessages = album
} else {
notificationID = message.ID
}

notification := &ActivityCenterNotification{
ID: cryptotypes.FromHex(notificationID),
return &ActivityCenterNotification{
ID: activityCenterMessageNotificationID(message),
Name: chat.Name,
Message: message,
ReplyMessage: responseTo,
Expand All @@ -3242,9 +3381,7 @@ func (r *ReceivedMessageState) addNewActivityCenterNotification(publicKey ecdsa.
UpdatedAt: m.GetCurrentTimeInMillis(),
AlbumMessages: albumMessages,
Read: message.Seen,
}

return m.addActivityCenterNotification(r.Response, notification, nil)
}, nil
}

func (m *Messenger) buildMessageState() *ReceivedMessageState {
Expand Down
19 changes: 13 additions & 6 deletions internal/protocol/messenger_activity_center.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,14 +295,9 @@ func (m *Messenger) addActivityCenterNotification(response *MessengerResponse, n
return err
}

state, err := m.persistence.GetActivityCenterState()
if err != nil {
m.logger.Error("failed to obtain activity center state", zap.Error(err))
if err := m.appendActivityCenterNotification(response, notification); err != nil {
return err
}
m.populateActivityCenterThreadNames([]*ActivityCenterNotification{notification})
response.AddActivityCenterNotification(notification)
response.SetActivityCenterState(state)

if syncAction != nil {
//TODO a way to pass context
Expand All @@ -315,6 +310,18 @@ func (m *Messenger) addActivityCenterNotification(response *MessengerResponse, n
return nil
}

func (m *Messenger) appendActivityCenterNotification(response *MessengerResponse, notification *ActivityCenterNotification) error {
state, err := m.persistence.GetActivityCenterState()
if err != nil {
m.logger.Error("failed to obtain activity center state", zap.Error(err))
return err
}
m.populateActivityCenterThreadNames([]*ActivityCenterNotification{notification})
response.AddActivityCenterNotification(notification)
response.SetActivityCenterState(state)
return nil
}

func (m *Messenger) syncActivityCenterReadByIDs(ctx context.Context, ids []types.HexBytes, clock uint64) error {
syncMessage := &protobuf.SyncActivityCenterRead{
Clock: clock,
Expand Down
Loading
Loading