Skip to content

Commit

Permalink
Refactor misc community updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucas Leblow committed Mar 27, 2024
1 parent 1e78feb commit 315dd50
Show file tree
Hide file tree
Showing 15 changed files with 56 additions and 165 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ import { LazyModuleLoader } from '@nestjs/core'
import Logger from '../common/logger'
import { emitError } from '../socket/socket.errors'
import { createLibp2pAddress, isPSKcodeValid } from '@quiet/common'
import { createRootCA } from '@quiet/identity'
import { CertFieldsTypes, createRootCA, getCertFieldValue, loadCertificate } from '@quiet/identity'

@Injectable()
export class ConnectionsManagerService extends EventEmitter implements OnModuleInit {
Expand Down Expand Up @@ -599,10 +599,16 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
// creating the community.
this.socketService.on(
SocketActionTypes.SET_COMMUNITY_METADATA,
async (payload: CommunityMetadata, callback: (response?: CommunityMetadata) => void) => {
const meta = await this.storageService?.updateCommunityMetadata(payload)
// TODO: Update community in local DB and emit COMMUNITY_UPDATED event
// Fields: rootCa, ownerCertificate, name
async (payload: CommunityMetadata, callback: (response: CommunityMetadata | undefined) => void) => {
const meta = await this.storageService.updateCommunityMetadata(payload)
const community = await this.localDbService.getCurrentCommunity()

if (meta && community) {
await this.localDbService.setCommunity({
...community,
ownerOrbitDbIdentity: meta.ownerOrbitDbIdentity,
})
}
callback(meta)
}
)
Expand Down Expand Up @@ -718,8 +724,8 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
this.storageService.on(StorageEvents.MESSAGE_MEDIA_UPDATED, (payload: FileMetadata) => {
this.serverIoProvider.io.emit(SocketActionTypes.MESSAGE_MEDIA_UPDATED, payload)
})
this.storageService.on(StorageEvents.UPDATE_PEERS_LIST, (payload: StorePeerListPayload) => {
this.serverIoProvider.io.emit(SocketActionTypes.PEER_LIST, payload)
this.storageService.on(StorageEvents.COMMUNITY_UPDATED, (payload: Community) => {
this.serverIoProvider.io.emit(SocketActionTypes.COMMUNITY_UPDATED, payload)
})
this.storageService.on(StorageEvents.SEND_PUSH_NOTIFICATION, (payload: PushNotificationPayload) => {
this.serverIoProvider.io.emit(SocketActionTypes.PUSH_NOTIFICATION, payload)
Expand All @@ -732,8 +738,27 @@ export class ConnectionsManagerService extends EventEmitter implements OnModuleI
})
this.storageService.on(StorageEvents.COMMUNITY_METADATA_STORED, async (meta: CommunityMetadata) => {
this.logger(`Storage - ${StorageEvents.COMMUNITY_METADATA_STORED}: ${meta}`)
// TODO: Update community in local DB and emit COMMUNITY_UPDATED event
this.serverIoProvider.io.emit(SocketActionTypes.COMMUNITY_METADATA_STORED, meta)
const community = await this.localDbService.getCurrentCommunity()

if (community) {
const rootCaCert = loadCertificate(meta.rootCa)
const communityName = getCertFieldValue(rootCaCert, CertFieldsTypes.commonName)

if (!communityName) {
this.logger.error(`Could not retrieve ${CertFieldsTypes.commonName} from CommunityMetadata.rootCa`)
}

const updatedCommunity = {
...community,
name: communityName ?? undefined,
rootCa: meta.rootCa,
ownerCertificate: meta.ownerCertificate,
ownerOrbitDbIdentity: meta.ownerOrbitDbIdentity,
}
await this.localDbService.setCommunity(updatedCommunity)

this.serverIoProvider.io.emit(SocketActionTypes.COMMUNITY_UPDATED, updatedCommunity)
}
})
this.storageService.on(StorageEvents.USER_PROFILES_STORED, (payload: UserProfilesStoredEvent) => {
this.serverIoProvider.io.emit(SocketActionTypes.USER_PROFILES_STORED, payload)
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/nest/socket/socket.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export class SocketService extends EventEmitter implements OnModuleInit {

socket.on(
SocketActionTypes.SET_COMMUNITY_METADATA,
(payload: CommunityMetadata, callback: (response?: CommunityMetadata) => void) => {
(payload: CommunityMetadata, callback: (response: CommunityMetadata | undefined) => void) => {
this.emit(SocketActionTypes.SET_COMMUNITY_METADATA, payload, callback)
}
)
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/nest/storage/storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ export class StorageService extends EventEmitter {
community.peerList = sortedPeers
await this.localDbService.setCommunity(community)
}
this.emit(StorageEvents.UPDATE_PEERS_LIST, { communityId: community.id, peerList: peers })
this.emit(StorageEvents.COMMUNITY_UPDATED, community)
}

public async loadAllCertificates() {
Expand Down
3 changes: 1 addition & 2 deletions packages/backend/src/nest/storage/storage.types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { Certificates } from '@quiet/types'

export enum StorageEvents {
// Peers
UPDATE_PEERS_LIST = 'updatePeersList',
// Public Channels
CHANNEL_SUBSCRIBED = 'channelSubscribed',
CHANNELS_STORED = 'channelsStored',
Expand All @@ -22,6 +20,7 @@ export enum StorageEvents {
USER_PROFILES_STORED = 'userProfilesStored',
// Community
COMMUNITY_METADATA_STORED = 'communityMetadataStored',
COMMUNITY_UPDATED = 'communityUpdated',
}

export interface CsrReplicatedPromiseValues {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,18 @@ import { type Socket } from '../../types'
import { all, takeEvery } from 'typed-redux-saga'
import { communitiesActions } from './communities.slice'
import { connectionActions } from '../appConnection/connection.slice'
import { updateCommunitySaga } from './updateCommunity/updateCommunity.saga'
import { createCommunitySaga } from './createCommunity/createCommunity.saga'
import { initCommunities, launchCommunitySaga } from './launchCommunity/launchCommunity.saga'
import { createNetworkSaga } from './createNetwork/createNetwork.saga'
import { saveCommunityMetadataSaga } from './saveCommunityMetadata/saveCommunityMetadata.saga'
import { sendCommunityMetadataSaga } from './updateCommunityMetadata/updateCommunityMetadata.saga'
import { sendCommunityCaDataSaga } from './sendCommunityCaData/sendCommunityCaData.saga'

export function* communitiesMasterSaga(socket: Socket): Generator {
yield all([
takeEvery(communitiesActions.createNetwork.type, createNetworkSaga, socket),
takeEvery(communitiesActions.updateCommunity.type, updateCommunitySaga),
takeEvery(connectionActions.torBootstrapped.type, initCommunities),
takeEvery(communitiesActions.createCommunity.type, createCommunitySaga, socket),
takeEvery(communitiesActions.launchCommunity.type, launchCommunitySaga, socket),
takeEvery(communitiesActions.saveCommunityMetadata.type, saveCommunityMetadataSaga, socket),
takeEvery(communitiesActions.sendCommunityMetadata.type, sendCommunityMetadataSaga, socket),
takeEvery(communitiesActions.sendCommunityCaData.type, sendCommunityCaDataSaga, socket),
])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ describe('communitiesSelectors', () => {
expect(communityId).toBe(communityAlpha.id)
})

it('select current community', () => {
it.only('select current community', () => {
const community = communitiesSelectors.currentCommunity(store.getState())
expect(community).toEqual({ ...communityAlpha })
expect(community).toEqual({ ...communityAlpha, ownerCertificate: identity.userCertificate })
})

it('returns proper ownerNickname - ownerCertificate exist', async () => {
Expand Down
13 changes: 3 additions & 10 deletions packages/state-manager/src/sagas/communities/communities.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ export const communitiesSlice = createSlice({
addNewCommunity: (state, action: PayloadAction<Community>) => {
communitiesAdapter.addOne(state.communities, action.payload)
},
updateCommunity: (state, _action: PayloadAction<Community>) => state,
updateCommunityData: (state, action: PayloadAction<Community>) => {
communitiesAdapter.updateOne(state.communities, {
id: action.payload.id,
Expand All @@ -39,14 +38,6 @@ export const communitiesSlice = createSlice({
sendCommunityCaData: state => state,
sendCommunityMetadata: state => state,
createNetwork: (state, _action: PayloadAction<CreateNetworkPayload>) => state,
storePeerList: (state, action: PayloadAction<StorePeerListPayload>) => {
communitiesAdapter.updateOne(state.communities, {
id: action.payload.communityId,
changes: {
...action.payload,
},
})
},
resetApp: (state, _action) => state,
createCommunity: (state, _action: PayloadAction<string>) => state,
launchCommunity: (state, _action: PayloadAction<string>) => state,
Expand All @@ -57,11 +48,13 @@ export const communitiesSlice = createSlice({
clearInvitationCodes: state => {
state.invitationCodes = []
},
saveCommunityMetadata: (state, _action: PayloadAction<CommunityMetadata>) => state,
/**
* Migrate data in this store. This is necessary because we persist the
* Redux data to disk (it's not reset on each app start). This function is
* meant to be called once the store has been rehydrated from storage.
*
* TODO: This type of thing might be better suited in a saga where we can
* organize complicated migration code easier.
*/
migrate: state => {
// MIGRATION: Move CommunitiesState.psk to Community.psk
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,9 @@ export function* sendCommunityMetadataSaga(
rootCa: community.rootCa,
}

const meta = yield* apply(
yield* apply(
socket,
socket.emitWithAck,
applyEmitParams(SocketActionTypes.SET_COMMUNITY_METADATA, communityMetadataPayload)
)

if (meta) {
yield* put(communitiesActions.saveCommunityMetadata(meta))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
type ResponseLaunchCommunityPayload,
type ChannelMessageIdsResponse,
type ChannelsReplicatedPayload,
type Community,
type CommunityId,
type DownloadStatus,
type ErrorPayload,
Expand Down Expand Up @@ -65,10 +66,9 @@ export function subscribe(socket: Socket) {
| ReturnType<typeof identityActions.storeUserCertificate>
| ReturnType<typeof identityActions.throwIdentityError>
| ReturnType<typeof identityActions.checkLocalCsr>
| ReturnType<typeof communitiesActions.storePeerList>
| ReturnType<typeof communitiesActions.updateCommunity>
| ReturnType<typeof communitiesActions.createCommunity>
| ReturnType<typeof communitiesActions.launchCommunity>
| ReturnType<typeof communitiesActions.updateCommunityData>
| ReturnType<typeof networkActions.addInitializedCommunity>
| ReturnType<typeof networkActions.removeConnectedPeer>
| ReturnType<typeof connectionActions.updateNetworkData>
Expand All @@ -84,7 +84,6 @@ export function subscribe(socket: Socket) {
| ReturnType<typeof communitiesActions.clearInvitationCodes>
| ReturnType<typeof identityActions.saveUserCsr>
| ReturnType<typeof connectionActions.setTorInitialized>
| ReturnType<typeof communitiesActions.saveCommunityMetadata>
| ReturnType<typeof communitiesActions.sendCommunityMetadata>
| ReturnType<typeof communitiesActions.sendCommunityCaData>
| ReturnType<typeof usersActions.setUserProfiles>
Expand Down Expand Up @@ -140,9 +139,6 @@ export function subscribe(socket: Socket) {

// Community

socket.on(SocketActionTypes.PEER_LIST, (payload: StorePeerListPayload) => {
emit(communitiesActions.storePeerList(payload))
})
socket.on(SocketActionTypes.COMMUNITY_LAUNCHED, (payload: ResponseLaunchCommunityPayload) => {
console.log('Hunting for heisenbug: Community event received in state-manager')
// TODO: We can send this once when creating the community and
Expand All @@ -152,6 +148,11 @@ export function subscribe(socket: Socket) {
emit(networkActions.addInitializedCommunity(payload.id))
emit(communitiesActions.clearInvitationCodes())
})

socket.on(SocketActionTypes.COMMUNITY_UPDATED, (payload: Community) => {
emit(communitiesActions.updateCommunityData(payload))
})

// Errors
socket.on(SocketActionTypes.ERROR, (payload: ErrorPayload) => {
// FIXME: It doesn't look like log errors have the red error
Expand All @@ -171,10 +172,6 @@ export function subscribe(socket: Socket) {
socket.on(SocketActionTypes.CERTIFICATES_STORED, (payload: SendCertificatesResponse) => {
emit(usersActions.responseSendCertificates(payload))
})
socket.on(SocketActionTypes.COMMUNITY_METADATA_STORED, (payload: CommunityMetadata) => {
log(`${SocketActionTypes.COMMUNITY_METADATA_STORED}: ${payload}`)
emit(communitiesActions.saveCommunityMetadata(payload))
})

// User Profile

Expand Down
5 changes: 4 additions & 1 deletion packages/state-manager/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,10 @@ export interface EmitEvents {
[SocketActionTypes.LEAVE_COMMUNITY]: () => void
[SocketActionTypes.CREATE_NETWORK]: EmitEvent<string, (response: NetworkInfo | undefined) => void>
[SocketActionTypes.ADD_CSR]: EmitEvent<SaveCSRPayload>
[SocketActionTypes.SET_COMMUNITY_METADATA]: EmitEvent<CommunityMetadata, (response: CommunityMetadata) => void>
[SocketActionTypes.SET_COMMUNITY_METADATA]: EmitEvent<
CommunityMetadata,
(response: CommunityMetadata | undefined) => void
>
[SocketActionTypes.SET_COMMUNITY_CA_DATA]: EmitEvent<PermsData>
[SocketActionTypes.SET_USER_PROFILE]: EmitEvent<UserProfile>
[SocketActionTypes.LOAD_MIGRATION_DATA]: EmitEvent<Record<string, any>>
Expand Down
2 changes: 1 addition & 1 deletion packages/state-manager/src/utils/tests/factories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export const getFactory = async (store: Store) => {

if (!community.ownerCertificate) {
store.dispatch(
communities.actions.updateCommunity({
communities.actions.updateCommunityData({
id: community.id,
ownerCertificate: action.payload.userCertificate,
})
Expand Down
Loading

0 comments on commit 315dd50

Please sign in to comment.