A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {UserID} from '@app/api/BrandedTypes';
import {userIdToChannelId} from '@app/api/BrandedTypes';
import {isPersonalNotesChannelId, personalNotesEnabled} from '@app/api/channel/services/PersonalNotesChannelRepair';
import type {Channel} from '@app/api/models/Channel';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
export type DmSearchScope = 'all_dms' | 'open_dms';
interface DmScopeOptions {
scope: DmSearchScope;
userId: UserID;
userRepository: UserRepository;
includeChannel?: Channel | null;
}
export function isDmScopeChannelForUser(channel: Channel, userId: UserID): boolean {
if (channel.type === ChannelTypes.DM_PERSONAL_NOTES) {
return isPersonalNotesChannelId({userId, channelId: channel.id});
}
const isDm = channel.type === ChannelTypes.DM || channel.type === ChannelTypes.GROUP_DM;
return isDm && channel.recipientIds.has(userId);
}
export async function getDmChannelIdsForScope({
scope,
userId,
userRepository,
includeChannel,
}: DmScopeOptions): Promise<Array<string>> {
const summaryResults = await userRepository.listPrivateChannelSummaries(userId);
const channelIdStrings = new Set<string>();
for (const summary of summaryResults) {
const isDm =
summary.channelType === ChannelTypes.DM || summary.channelType === ChannelTypes.GROUP_DM || summary.isGroupDm;
if (!isDm) {
continue;
}
if (scope === 'open_dms' && !summary.open) {
continue;
}
channelIdStrings.add(summary.channelId.toString());
}
if (scope === 'all_dms') {
const historicalIds = await userRepository.listHistoricalDmChannelIds(userId);
for (const channelId of historicalIds) {
channelIdStrings.add(channelId.toString());
}
}
if (includeChannel && isDmScopeChannelForUser(includeChannel, userId)) {
channelIdStrings.add(includeChannel.id.toString());
}
const personalNotesChannelId = userIdToChannelId(userId).toString();
if (await personalNotesEnabled()) {
channelIdStrings.add(personalNotesChannelId);
} else {
channelIdStrings.delete(personalNotesChannelId);
}
return Array.from(channelIdStrings);
}