refactor: improve community functions naming

This commit is contained in:
Patryk Osmaczko 2023-07-06 19:44:31 +02:00 committed by osmaczko
parent 9267e58143
commit 9eaf229161
6 changed files with 54 additions and 84 deletions

View File

@ -517,8 +517,8 @@ func (m *Manager) DeletedCommunities() ([]*Community, error) {
return m.persistence.DeletedCommunities(&m.identity.PublicKey) return m.persistence.DeletedCommunities(&m.identity.PublicKey)
} }
func (m *Manager) Created() ([]*Community, error) { func (m *Manager) ControlledCommunities() ([]*Community, error) {
return m.persistence.CreatedCommunities(&m.identity.PublicKey) return m.persistence.CommunitiesWithPrivateKey(&m.identity.PublicKey)
} }
// CreateCommunity takes a description, generates an ID for it, saves it and return it // CreateCommunity takes a description, generates an ID for it, saves it and return it
@ -2973,14 +2973,14 @@ func (m *Manager) UpdateCommunitySettings(settings CommunitySettings) error {
return m.persistence.UpdateCommunitySettings(settings) return m.persistence.UpdateCommunitySettings(settings)
} }
func (m *Manager) GetAdminCommunitiesChatIDs() (map[string]bool, error) { func (m *Manager) GetControlledCommunitiesChatIDs() (map[string]bool, error) {
adminCommunities, err := m.Created() controlledCommunities, err := m.ControlledCommunities()
if err != nil { if err != nil {
return nil, err return nil, err
} }
chatIDs := make(map[string]bool) chatIDs := make(map[string]bool)
for _, c := range adminCommunities { for _, c := range controlledCommunities {
if c.Joined() { if c.Joined() {
for _, id := range c.ChatIDs() { for _, id := range c.ChatIDs() {
chatIDs[id] = true chatIDs[id] = true
@ -2990,37 +2990,6 @@ func (m *Manager) GetAdminCommunitiesChatIDs() (map[string]bool, error) {
return chatIDs, nil return chatIDs, nil
} }
func (m *Manager) IsAdminCommunityByID(communityID types.HexBytes) (bool, error) {
pubKey, err := crypto.DecompressPubkey(communityID)
if err != nil {
return false, err
}
return m.IsAdminCommunity(pubKey)
}
func (m *Manager) IsAdminCommunity(pubKey *ecdsa.PublicKey) (bool, error) {
adminCommunities, err := m.Created()
if err != nil {
return false, err
}
for _, c := range adminCommunities {
if c.PrivateKey().PublicKey.Equal(pubKey) {
return true, nil
}
}
return false, nil
}
func (m *Manager) IsJoinedCommunity(pubKey *ecdsa.PublicKey) (bool, error) {
community, err := m.GetByID(crypto.CompressPubkey(pubKey))
if err != nil {
return false, err
}
return community != nil && community.Joined(), nil
}
func (m *Manager) GetCommunityChatsFilters(communityID types.HexBytes) ([]*transport.Filter, error) { func (m *Manager) GetCommunityChatsFilters(communityID types.HexBytes) ([]*transport.Filter, error) {
chatIDs, err := m.persistence.GetCommunityChatIDs(communityID) chatIDs, err := m.persistence.GetCommunityChatIDs(communityID)
if err != nil { if err != nil {
@ -4138,7 +4107,7 @@ func (m *Manager) saveAndPublish(community *Community) error {
// //
// However, it's safe to run this migration/fixup multiple times. // However, it's safe to run this migration/fixup multiple times.
func (m *Manager) fixupChannelMembers() error { func (m *Manager) fixupChannelMembers() error {
controlledCommunities, err := m.Created() controlledCommunities, err := m.ControlledCommunities()
if err != nil { if err != nil {
return err return err
} }

View File

@ -370,15 +370,14 @@ func (s *ManagerSuite) TestEditCommunity() {
s.Require().Equal(storedCommunity.config.CommunityDescription.Identity.Description, update.CreateCommunity.Description) s.Require().Equal(storedCommunity.config.CommunityDescription.Identity.Description, update.CreateCommunity.Description)
} }
func (s *ManagerSuite) TestGetAdminCommuniesChatIDs() { func (s *ManagerSuite) TestGetControlledCommunitiesChatIDs() {
community, _, err := s.buildCommunityWithChat() community, _, err := s.buildCommunityWithChat()
s.Require().NoError(err) s.Require().NoError(err)
s.Require().NotNil(community) s.Require().NotNil(community)
adminChatIDs, err := s.manager.GetAdminCommunitiesChatIDs() controlledChatIDs, err := s.manager.GetControlledCommunitiesChatIDs()
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(adminChatIDs, 1) s.Require().Len(controlledChatIDs, 1)
} }
func (s *ManagerSuite) TestStartAndStopTorrentClient() { func (s *ManagerSuite) TestStartAndStopTorrentClient() {

View File

@ -255,7 +255,7 @@ WHERE NOT c.Joined AND (r.community_id IS NULL or r.state != ?)`
return p.rowsToCommunities(memberIdentity, rows) return p.rowsToCommunities(memberIdentity, rows)
} }
func (p *Persistence) CreatedCommunities(memberIdentity *ecdsa.PublicKey) ([]*Community, error) { func (p *Persistence) CommunitiesWithPrivateKey(memberIdentity *ecdsa.PublicKey) ([]*Community, error) {
query := communitiesBaseQuery + ` WHERE c.private_key IS NOT NULL` query := communitiesBaseQuery + ` WHERE c.private_key IS NOT NULL`
return p.queryCommunities(memberIdentity, query) return p.queryCommunities(memberIdentity, query)
} }

View File

@ -812,15 +812,15 @@ func (m *Messenger) Start() (*MessengerResponse, error) {
} }
if m.torrentClientReady() { if m.torrentClientReady() {
adminCommunities, err := m.communitiesManager.Created() controlledCommunities, err := m.communitiesManager.ControlledCommunities()
if err == nil && len(adminCommunities) > 0 { if err == nil && len(controlledCommunities) > 0 {
available := m.SubscribeMailserverAvailable() available := m.SubscribeMailserverAvailable()
go func() { go func() {
<-available <-available
m.InitHistoryArchiveTasks(adminCommunities) m.InitHistoryArchiveTasks(controlledCommunities)
}() }()
for _, c := range adminCommunities { for _, c := range controlledCommunities {
if c.Joined() && c.HasTokenPermissions() { if c.Joined() && c.HasTokenPermissions() {
go m.communitiesManager.ReevaluateMembersPeriodically(c.ID()) go m.communitiesManager.ReevaluateMembersPeriodically(c.ID())
} }
@ -1658,18 +1658,18 @@ func (m *Messenger) Init() error {
publicChatIDs = append(publicChatIDs, org.DefaultFilters()...) publicChatIDs = append(publicChatIDs, org.DefaultFilters()...)
} }
// Init filters for the communities we are an admin of // Init filters for the communities we control
var adminCommunitiesPks []*ecdsa.PrivateKey var controlledCommunitiesPks []*ecdsa.PrivateKey
adminCommunities, err := m.communitiesManager.Created() controlledCommunities, err := m.communitiesManager.ControlledCommunities()
if err != nil { if err != nil {
return err return err
} }
for _, c := range adminCommunities { for _, c := range controlledCommunities {
adminCommunitiesPks = append(adminCommunitiesPks, c.PrivateKey()) controlledCommunitiesPks = append(controlledCommunitiesPks, c.PrivateKey())
} }
_, err = m.transport.InitCommunityFilters(adminCommunitiesPks) _, err = m.transport.InitCommunityFilters(controlledCommunitiesPks)
if err != nil { if err != nil {
return err return err
} }
@ -3498,7 +3498,7 @@ func (m *Messenger) handleRetrievedMessages(chatWithMessages map[transport.Filte
logger := m.logger.With(zap.String("site", "RetrieveAll")) logger := m.logger.With(zap.String("site", "RetrieveAll"))
adminCommunitiesChatIDs, err := m.communitiesManager.GetAdminCommunitiesChatIDs() controlledCommunitiesChatIDs, err := m.communitiesManager.GetControlledCommunitiesChatIDs()
if err != nil { if err != nil {
logger.Info("failed to retrieve admin communities", zap.Error(err)) logger.Info("failed to retrieve admin communities", zap.Error(err))
} }
@ -3510,7 +3510,7 @@ func (m *Messenger) handleRetrievedMessages(chatWithMessages map[transport.Filte
// Indicates tha all messages in the batch have been processed correctly // Indicates tha all messages in the batch have been processed correctly
allMessagesProcessed := true allMessagesProcessed := true
if adminCommunitiesChatIDs[filter.ChatID] && storeWakuMessages { if controlledCommunitiesChatIDs[filter.ChatID] && storeWakuMessages {
logger.Debug("storing waku message") logger.Debug("storing waku message")
err := m.communitiesManager.StoreWakuMessage(shhMessage) err := m.communitiesManager.StoreWakuMessage(shhMessage)
if err != nil { if err != nil {

View File

@ -217,13 +217,13 @@ func (m *Messenger) handleCommunitiesSubscription(c chan *communities.Subscripti
recentlyPublishedOrgs := func() map[string]*communities.Community { recentlyPublishedOrgs := func() map[string]*communities.Community {
result := make(map[string]*communities.Community) result := make(map[string]*communities.Community)
ownedOrgs, err := m.communitiesManager.Created() controlledCommunities, err := m.communitiesManager.ControlledCommunities()
if err != nil { if err != nil {
m.logger.Warn("failed to retrieve orgs", zap.Error(err)) m.logger.Warn("failed to retrieve orgs", zap.Error(err))
return result return result
} }
for _, org := range ownedOrgs { for _, org := range controlledCommunities {
result[org.IDString()] = org result[org.IDString()] = org
} }
@ -295,13 +295,13 @@ func (m *Messenger) handleCommunitiesSubscription(c chan *communities.Subscripti
continue continue
} }
orgs, err := m.communitiesManager.Created() controlledCommunities, err := m.communitiesManager.ControlledCommunities()
if err != nil { if err != nil {
m.logger.Warn("failed to retrieve orgs", zap.Error(err)) m.logger.Warn("failed to retrieve orgs", zap.Error(err))
} }
for idx := range orgs { for idx := range controlledCommunities {
org := orgs[idx] org := controlledCommunities[idx]
_, beingImported := m.importingCommunities[org.IDString()] _, beingImported := m.importingCommunities[org.IDString()]
if !beingImported { if !beingImported {
publishOrgAndDistributeEncryptionKeys(org) publishOrgAndDistributeEncryptionKeys(org)
@ -329,12 +329,12 @@ func (m *Messenger) updateCommunitiesActiveMembersPeriodically() {
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
ownedCommunities, err := m.communitiesManager.Created() controlledCommunities, err := m.communitiesManager.ControlledCommunities()
if err != nil { if err != nil {
m.logger.Error("failed to update community active members count", zap.Error(err)) m.logger.Error("failed to update community active members count", zap.Error(err))
} }
for _, community := range ownedCommunities { for _, community := range controlledCommunities {
lastUpdated, ok := communitiesLastUpdated[community.IDString()] lastUpdated, ok := communitiesLastUpdated[community.IDString()]
if !ok { if !ok {
lastUpdated = 0 lastUpdated = 0
@ -1364,6 +1364,11 @@ func (m *Messenger) LeaveCommunity(communityID types.HexBytes) (*MessengerRespon
return nil, err return nil, err
} }
community, ok := mr.communities[communityID.String()]
if !ok {
return nil, communities.ErrOrgNotFound
}
err = m.communitiesManager.DeleteCommunitySettings(communityID) err = m.communitiesManager.DeleteCommunitySettings(communityID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -1371,19 +1376,12 @@ func (m *Messenger) LeaveCommunity(communityID types.HexBytes) (*MessengerRespon
m.communitiesManager.StopHistoryArchiveTasksInterval(communityID) m.communitiesManager.StopHistoryArchiveTasksInterval(communityID)
if com, ok := mr.communities[communityID.String()]; ok { err = m.syncCommunity(context.Background(), community, m.dispatchMessage)
err = m.syncCommunity(context.Background(), com, m.dispatchMessage)
if err != nil {
return nil, err
}
}
isAdmin, err := m.communitiesManager.IsAdminCommunityByID(communityID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if !isAdmin { if !community.IsControlNode() {
requestToLeaveProto := &protobuf.CommunityRequestToLeave{ requestToLeaveProto := &protobuf.CommunityRequestToLeave{
Clock: uint64(time.Now().Unix()), Clock: uint64(time.Now().Unix()),
CommunityId: communityID, CommunityId: communityID,
@ -2915,13 +2913,13 @@ func (m *Messenger) EnableCommunityHistoryArchiveProtocol() error {
return err return err
} }
communities, err := m.communitiesManager.Created() controlledCommunities, err := m.communitiesManager.ControlledCommunities()
if err != nil { if err != nil {
return err return err
} }
if len(communities) > 0 { if len(controlledCommunities) > 0 {
go m.InitHistoryArchiveTasks(communities) go m.InitHistoryArchiveTasks(controlledCommunities)
} }
m.config.messengerSignalsHandler.HistoryArchivesProtocolEnabled() m.config.messengerSignalsHandler.HistoryArchivesProtocolEnabled()
return nil return nil

View File

@ -1186,23 +1186,27 @@ func (m *Messenger) HandleCommunityInvitation(state *ReceivedMessageState, signe
} }
func (m *Messenger) HandleHistoryArchiveMagnetlinkMessage(state *ReceivedMessageState, communityPubKey *ecdsa.PublicKey, magnetlink string, clock uint64) error { func (m *Messenger) HandleHistoryArchiveMagnetlinkMessage(state *ReceivedMessageState, communityPubKey *ecdsa.PublicKey, magnetlink string, clock uint64) error {
id := types.HexBytes(crypto.CompressPubkey(communityPubKey)) id := types.HexBytes(crypto.CompressPubkey(communityPubKey))
community, err := m.communitiesManager.GetByID(id)
if err != nil {
m.logger.Debug("Couldn't get community for community with id: ", zap.Any("id", id))
return err
}
if community == nil {
return nil
}
settings, err := m.communitiesManager.GetCommunitySettingsByID(id) settings, err := m.communitiesManager.GetCommunitySettingsByID(id)
if err != nil { if err != nil {
m.logger.Debug("Couldn't get community settings for community with id: ", zap.Any("id", id)) m.logger.Debug("Couldn't get community settings for community with id: ", zap.Any("id", id))
return err return err
} }
if settings == nil {
return nil
}
if m.torrentClientReady() && settings != nil && settings.HistoryArchiveSupportEnabled { if m.torrentClientReady() && settings.HistoryArchiveSupportEnabled {
signedByOwnedCommunity, err := m.communitiesManager.IsAdminCommunity(communityPubKey)
if err != nil {
return err
}
joinedCommunity, err := m.communitiesManager.IsJoinedCommunity(communityPubKey)
if err != nil {
return err
}
lastClock, err := m.communitiesManager.GetMagnetlinkMessageClock(id) lastClock, err := m.communitiesManager.GetMagnetlinkMessageClock(id)
if err != nil { if err != nil {
return err return err
@ -1214,7 +1218,7 @@ func (m *Messenger) HandleHistoryArchiveMagnetlinkMessage(state *ReceivedMessage
// We are only interested in a community archive magnet link // We are only interested in a community archive magnet link
// if it originates from a community that the current account is // if it originates from a community that the current account is
// part of and doesn't own the private key at the same time // part of and doesn't own the private key at the same time
if !signedByOwnedCommunity && joinedCommunity && clock >= lastClock { if !community.IsControlNode() && community.Joined() && clock >= lastClock {
if lastSeenMagnetlink == magnetlink { if lastSeenMagnetlink == magnetlink {
m.communitiesManager.LogStdout("already processed this magnetlink") m.communitiesManager.LogStdout("already processed this magnetlink")
return nil return nil