2019-11-21 16:19:22 +00:00
|
|
|
package protocol
|
2019-10-14 14:10:48 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2019-12-02 15:34:05 +00:00
|
|
|
"github.com/status-im/status-go/protocol/protobuf"
|
2019-11-21 16:19:22 +00:00
|
|
|
v1protocol "github.com/status-im/status-go/protocol/v1"
|
2019-10-14 14:10:48 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// HandleMembershipUpdate updates a Chat instance according to the membership updates.
|
|
|
|
// It retrieves chat, if exists, and merges membership updates from the message.
|
|
|
|
// Finally, the Chat is updated with the new group events.
|
2019-12-02 15:34:05 +00:00
|
|
|
func HandleMembershipUpdate(chat *Chat, m *v1protocol.MembershipUpdateMessage, myIdentity string, translations map[protobuf.MembershipUpdateEvent_EventType]string) (*Chat, []*Message, error) {
|
|
|
|
if chat == nil {
|
|
|
|
if len(m.Events) == 0 {
|
|
|
|
return nil, nil, errors.New("can't create new group chat without events")
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-12-02 15:34:05 +00:00
|
|
|
group, err := v1protocol.NewGroupWithEvents(m.ChatID, m.Events)
|
2019-10-14 14:10:48 +00:00
|
|
|
if err != nil {
|
2019-12-02 15:34:05 +00:00
|
|
|
return nil, nil, err
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-12-02 15:34:05 +00:00
|
|
|
|
|
|
|
// A new chat must contain us
|
|
|
|
if !group.IsMember(myIdentity) {
|
|
|
|
return nil, nil, errors.New("can't create a new group chat without us being a member")
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-12-02 15:34:05 +00:00
|
|
|
newChat := createGroupChat()
|
|
|
|
newChat.updateChatFromProtocolGroup(group)
|
|
|
|
return &newChat, buildSystemMessages(m.Events, translations), nil
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-12-02 15:34:05 +00:00
|
|
|
existingGroup, err := newProtocolGroupFromChat(chat)
|
2019-10-14 14:10:48 +00:00
|
|
|
if err != nil {
|
2019-12-02 15:34:05 +00:00
|
|
|
return nil, nil, errors.Wrap(err, "failed to create a Group from Chat")
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-12-02 15:34:05 +00:00
|
|
|
updateGroup, err := v1protocol.NewGroupWithEvents(m.ChatID, m.Events)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, errors.Wrap(err, "invalid membership update")
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-12-02 15:34:05 +00:00
|
|
|
merged := v1protocol.MergeMembershipUpdateEvents(existingGroup.Events(), updateGroup.Events())
|
|
|
|
newGroup, err := v1protocol.NewGroup(chat.ID, merged)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, errors.Wrap(err, "failed to create a group with new membership updates")
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
2019-12-02 15:34:05 +00:00
|
|
|
chat.updateChatFromProtocolGroup(newGroup)
|
|
|
|
return chat, buildSystemMessages(m.Events, translations), nil
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|