A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(api): clarify thread creation, settings and activity
Hampus5409bd55de83
diff --git a/fluxer_api/src/api/channel/services/message/MessageActivity.ts b/fluxer_api/src/api/channel/services/message/MessageActivity.tsindex 37b0d7760..ef825455c 100644--- a/fluxer_api/src/api/channel/services/message/MessageActivity.ts+++ b/fluxer_api/src/api/channel/services/message/MessageActivity.ts@@ -23,8 +23,12 @@ function linkDomains(content: string): Array<string> {const domains = new Set<string>();for (const host of extractLinkHosts(content)) {const domain = host.replace(WWW_PREFIX_RE, '');- if (domain) domains.add(domain);- if (domains.size >= LIST_MAX) break;+ if (domain) {+ domains.add(domain);+ }+ if (domains.size >= LIST_MAX) {+ break;+ }}return [...domains];}@@ -37,28 +41,28 @@ interface InviteTarget {async function inviteTarget(code: string): Promise<InviteTarget> {try {const invite = await getInviteRepository().findUnique(createInviteCode(code));- if (!invite?.guildId) return {guildId: null, ownerId: null};+ if (!invite?.guildId) {+ return {guildId: null, ownerId: null};+ }const guild = await getGuildRepository().findUnique(invite.guildId);return {guildId: invite.guildId.toString(), ownerId: guild ? guild.ownerId.toString() : null};- } catch {+ } catch (error) {+ Logger.warn({error, inviteCode: code}, 'Failed to look up invite target for message activity');return {guildId: null, ownerId: null};}}-function inviteTargets(codes: ReadonlyArray<string>): Promise<Array<InviteTarget>> {- return Promise.all(codes.map(inviteTarget));-}-async function guildMemberCount(guildId: GuildID): Promise<number | null> {try {const guild = await getGuildRepository().findUnique(guildId);return guild ? guild.memberCount : null;- } catch {+ } catch (error) {+ Logger.warn({error, guildId: guildId.toString()}, 'Failed to look up guild member count for message activity');return null;}}-export interface MessageCreatedActivity {+interface MessageCreatedActivity {user: User;message: Message;channel: Channel;@@ -89,13 +93,19 @@ async function buildAndEmit(const inviteCodes = findInvites(message.content, LIST_MAX);const domains = linkDomains(message.content ?? '');const [targets, memberCount] = await Promise.all([- inviteTargets(inviteCodes),+ Promise.all(inviteCodes.map(inviteTarget)),guildId && (domains.length > 0 || inviteCodes.length > 0) ? guildMemberCount(guildId) : Promise.resolve(null),]);const mentionedIds = [...message.mentionedUserIds];const recipientIsFriend = dmRecipientId? (await params.userRepository.getRelationship(user.id, dmRecipientId, RelationshipTypes.FRIEND)) !== null: false;+ let channelType: 'guild' | 'group_dm' | 'dm' = 'dm';+ if (guildId) {+ channelType = 'guild';+ } else if (channel.type === ChannelTypes.GROUP_DM) {+ channelType = 'group_dm';+ }await emitActivity(kind,user.id.toString(),@@ -103,7 +113,7 @@ async function buildAndEmit(user_id: user.id.toString(),message_id: message.id.toString(),channel_id: channel.id.toString(),- channel_type: guildId ? 'guild' : channel.type === ChannelTypes.GROUP_DM ? 'group_dm' : 'dm',+ channel_type: channelType,guild_id: guildId ? guildId.toString() : null,dm_recipient_id: dmRecipientId ? dmRecipientId.toString() : null,recipient_is_friend: recipientIsFriend,diff --git a/fluxer_api/src/api/channel/services/thread/ThreadCreationService.ts b/fluxer_api/src/api/channel/services/thread/ThreadCreationService.tsindex b7c1147cc..110172142 100644--- a/fluxer_api/src/api/channel/services/thread/ThreadCreationService.ts+++ b/fluxer_api/src/api/channel/services/thread/ThreadCreationService.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import {type ChannelID,channelIdToMessageId,@@ -11,6 +12,7 @@ import {} from '@app/api/BrandedTypes';import {mapChannelToResponse} from '@app/api/channel/ChannelMappers';import type {MessageRequest} from '@app/api/channel/MessageTypes';+import type {CreateThreadParams} from '@app/api/channel/repositories/ThreadRepository';import type {AuthenticatedChannel} from '@app/api/channel/services/AuthenticatedChannel';import {withChannelFollowLock} from '@app/api/channel/services/ChannelFollowers';import {dispatchChannelEvent} from '@app/api/channel/services/ChannelGatewayDispatch';@@ -119,11 +121,15 @@ export class ThreadCreationService {}): Promise<ThreadChannelResponse> {const parentAuth = await this.authorizeParent(params.viewer, params.user, params.channelId, 'from_message');const source = await this.ctx.channelRepository.messages.getMessage(parentAuth.channel.id, params.messageId);- if (!source) throw new UnknownMessageError();+ if (!source) {+ throw new UnknownMessageError();+ }if (source.type !== MessageTypes.DEFAULT && source.type !== MessageTypes.REPLY) {throw new CannotEditSystemMessageError();}- if ((source.flags & ServerMessageFlags.HAS_THREAD) !== 0) throw new ThreadAlreadyCreatedForMessageError();+ if ((source.flags & ServerMessageFlags.HAS_THREAD) !== 0) {+ throw new ThreadAlreadyCreatedForMessageError();+ }const {view, members} = await this.create({parent: parentAuth.channel,creator: {kind: 'user', user: params.user, parentAuth},@@ -157,7 +163,9 @@ export class ThreadCreationService {});}const starter = await this.buildStarterEvent(params.viewer, params.user.id, view, params.requestCache);- if (starter) events.push(starter);+ if (starter) {+ events.push(starter);+ }if (!(await this.isAmongRecentMessages(parentAuth.channel.id, source.id))) {events.push(await this.createThreadCreatedMessage(parentAuth.channel, view, params.user.id));}@@ -187,7 +195,9 @@ export class ThreadCreationService {auditLogReason: string | null;}): Promise<ThreadChannelResponse> {const type = resolveTextThreadType(params.parentAuth.channel.type, params.type);- if (type === null) throw new InvalidChannelTypeError();+ if (type === null) {+ throw new InvalidChannelTypeError();+ }const isPrivate = type === ChannelTypes.PRIVATE_THREAD;const parentAuth = await this.authorizeAuthenticatedParent(params.parentAuth,@@ -206,7 +216,9 @@ export class ThreadCreationService {});await this.recordCreateAudit(view, params.user.id, params.auditLogReason);const events: Array<ThreadDispatchEvent> = [threadCreateEvent(view, {members, newlyCreated: true})];- if (!isPrivate) events.push(await this.createThreadCreatedMessage(parentAuth.channel, view, params.user.id));+ if (!isPrivate) {+ events.push(await this.createThreadCreatedMessage(parentAuth.channel, view, params.user.id));+ }await dispatchThreadEvents(this.ctx.gatewayService, view.state.guildId, events);return mapThreadToResponse(view);}@@ -222,11 +234,17 @@ export class ThreadCreationService {const {parentAuth, user, body} = params;assertAccountNotLimited(user);const {channel: parent, guild} = parentAuth;- if (!guild || !parent.isThreadOnly()) throw new InvalidChannelTypeError();- if (body.type !== undefined && body.type !== ChannelTypes.PUBLIC_THREAD) throw new InvalidChannelTypeError();+ if (!guild || !parent.isThreadOnly()) {+ throw new InvalidChannelTypeError();+ }+ if (body.type !== undefined && body.type !== ChannelTypes.PUBLIC_THREAD) {+ throw new InvalidChannelTypeError();+ }const actor = await this.ctx.parentActor(parentAuth, user.id);assertThreadAllowed(canCreateThread(actor, 'forum_post'));- const config = await this.ctx.channelRepository.threads.getParentConfig(parent.guildId!, parent.id);+ const guildId = parent.guildId;+ assert(guildId !== null);+ const config = await this.ctx.channelRepository.threads.getParentConfig(guildId, parent.id);const appliedTags = resolveAppliedTags({config,requested: (body.applied_tags ?? []).map((id) => BigInt(id)),@@ -281,7 +299,9 @@ export class ThreadCreationService {sendStarter: (thread: Channel) => Promise<Message>;}): Promise<Message> {const {parent} = params;- if (!parent.isThreadOnly() || parent.guildId === null) throw new InvalidChannelTypeError();+ if (!parent.isThreadOnly() || parent.guildId === null) {+ throw new InvalidChannelTypeError();+ }const config = await this.ctx.channelRepository.threads.getParentConfig(parent.guildId, parent.id);const appliedTags = resolveAppliedTags({config, requested: params.appliedTags, previous: [], moderator: false});const threadId = createChannelID(await this.ctx.snowflakeService.generate());@@ -342,7 +362,9 @@ export class ThreadCreationService {}private async ackForumPost(viewer: ThreadViewer, user: User, parent: Channel, threadId: ChannelID): Promise<void> {- if (user.isBot || viewer.kind !== 'user') return;+ if (user.isBot || viewer.kind !== 'user') {+ return;+ }try {await this.ctx.readStateService.ackMessage({userId: user.id,@@ -374,15 +396,21 @@ export class ThreadCreationService {): Promise<AuthenticatedChannel> {assertAccountNotLimited(user);const {channel, guild} = parentAuth;- if (!guild || !TEXT_THREAD_PARENT_CHANNEL_TYPES.has(channel.type)) throw new InvalidChannelTypeError();+ if (!guild || !TEXT_THREAD_PARENT_CHANNEL_TYPES.has(channel.type)) {+ throw new InvalidChannelTypeError();+ }assertThreadAllowed(canCreateThread(await this.ctx.parentActor(parentAuth, user.id), kind));return parentAuth;}private async enforceCreateSlowmode(parentAuth: AuthenticatedChannel, user: User): Promise<void> {const rateLimitPerUser = parentAuth.channel.rateLimitPerUser ?? 0;- if (rateLimitPerUser <= 0 || user.isBot) return;- if (await parentAuth.hasPermission(Permissions.BYPASS_SLOWMODE)) return;+ if (rateLimitPerUser <= 0 || user.isBot) {+ return;+ }+ if (await parentAuth.hasPermission(Permissions.BYPASS_SLOWMODE)) {+ return;+ }const result = await this.ctx.rateLimitService.checkLimit({identifier: slowmodeThreadKey(parentAuth.channel.id, user.id),maxAttempts: 1,@@ -395,13 +423,16 @@ export class ThreadCreationService {private async create(params: NewThread): Promise<{view: ThreadView; members: Array<ThreadMember>}> {const {parent, creator} = params;- const guildId = parent.guildId!;+ const guildId = parent.guildId;+ assert(guildId !== null);const ownerId = creator.kind === 'user' ? creator.user.id : creator.ownerId;const {threads} = this.ctx.channelRepository;if ((await threads.countActiveThreads(guildId)) >= MAX_ACTIVE_THREADS_PER_GUILD) {throw new MaxActiveThreadsError(MAX_ACTIVE_THREADS_PER_GUILD);}- if (creator.kind === 'user') await this.enforceCreateSlowmode(creator.parentAuth, creator.user);+ if (creator.kind === 'user') {+ await this.enforceCreateSlowmode(creator.parentAuth, creator.user);+ }const state = await this.storeThread(params).catch(async (error: unknown) => {if (creator.kind === 'user') {await this.ctx.rateLimitService.resetLimit(slowmodeThreadKey(parent.id, creator.user.id));@@ -409,10 +440,17 @@ export class ThreadCreationService {throw error;});const channel = await this.ctx.channelRepository.channelData.findUnique(params.threadId);- if (!channel) throw new InvalidChannelTypeError();+ if (!channel) {+ throw new InvalidChannelTypeError();+ }const view = await loadThreadView(this.ctx.channelRepository, channel, state, parent);const members = creator.kind === 'user' ? await threads.getMembers(params.threadId, [ownerId]) : [];- const kind = parent.isThreadOnly() ? 'forum_post' : params.hasStarter ? 'from_message' : 'standalone';+ let kind = 'standalone';+ if (parent.isThreadOnly()) {+ kind = 'forum_post';+ } else if (params.hasStarter) {+ kind = 'from_message';+ }threadsCreatedTotal.inc(`kind="${kind}",type="${params.type}"`);await this.ctx.archiveQueue.schedule(state, null);enqueueThreadSearchSync(params.threadId);@@ -421,7 +459,8 @@ export class ThreadCreationService {private async storeThread(params: NewThread): Promise<ThreadState> {const {parent, creator} = params;- const guildId = parent.guildId!;+ const guildId = parent.guildId;+ assert(guildId !== null);const ownerId = creator.kind === 'user' ? creator.user.id : creator.ownerId;const {threads} = this.ctx.channelRepository;contentModerationService.scanText(params.input.name, {@@ -461,8 +500,8 @@ export class ThreadCreationService {indexed_at: now,version: 1,};- const write = () =>- threads.create({+ const write = () => {+ const options: CreateThreadParams = {channel: row,parentType: parent.type,autoArchiveDuration: params.input.autoArchiveDuration ?? DEFAULT_THREAD_AUTO_ARCHIVE_DURATION,@@ -471,15 +510,23 @@ export class ThreadCreationService {appliedTags: params.appliedTags ?? [],hasStarter: params.hasStarter,createdAt: now,- members:- creator.kind === 'user'- ? [{userId: creator.user.id, flags: creator.user.isBot ? 0 : ThreadMemberFlags.HAS_INTERACTED}]- : [],- });- if (!TEXT_THREAD_PARENT_CHANNEL_TYPES.has(parent.type)) return write();+ members: [],+ };+ if (creator.kind === 'user') {+ const userId = creator.user.id;+ const flags = creator.user.isBot ? 0 : ThreadMemberFlags.HAS_INTERACTED;+ options.members.push({userId, flags});+ }+ return threads.create(options);+ };+ if (!TEXT_THREAD_PARENT_CHANNEL_TYPES.has(parent.type)) {+ return write();+ }return withChannelFollowLock(this.ctx.cacheService, parent.id, async () => {const current = await this.ctx.channelRepository.channelData.findUnique(parent.id);- if (current?.type !== parent.type) throw new InvalidChannelTypeError();+ if (current?.type !== parent.type) {+ throw new InvalidChannelTypeError();+ }return write();});}@@ -514,7 +561,9 @@ export class ThreadCreationService {messageId: createMessageID(BigInt(view.channel.id)),requestCache,});- if (!starter) return null;+ if (!starter) {+ return null;+ }const referenced = starter.referenced_message;if (referenced?.thread) {const {member: _member, ...thread} = referenced.thread;@@ -551,7 +600,7 @@ export class ThreadCreationService {sticker_items: null,message_reference: {channel_id: view.channel.id,- message_id: null as unknown as MessageID,+ message_id: null,guild_id: createGuildID(BigInt(view.state.guildId)),type: MessageReferenceTypes.DEFAULT,},diff --git a/fluxer_api/src/api/channel/services/thread/ThreadMemberSettingsService.ts b/fluxer_api/src/api/channel/services/thread/ThreadMemberSettingsService.tsindex 4c5cdfa13..0102d5fe1 100644--- a/fluxer_api/src/api/channel/services/thread/ThreadMemberSettingsService.ts+++ b/fluxer_api/src/api/channel/services/thread/ThreadMemberSettingsService.ts@@ -6,7 +6,6 @@ import {mapThreadMemberToResponse} from '@app/api/channel/services/thread/Threadimport type {ThreadServiceContext} from '@app/api/channel/services/thread/ThreadServiceContext';import type {MuteConfig} from '@app/api/database/types/UserTypes';import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';-import type {ThreadMember} from '@app/api/models/ThreadMember';import {isValidThreadMemberSettingsFlags, ThreadMemberFlags} from '@fluxer/constants/src/ThreadConstants';import {InvalidChannelTypeError} from '@fluxer/errors/src/domains/channel/InvalidChannelTypeError';import {InvalidThreadNotificationSettingsError} from '@fluxer/errors/src/domains/channel/InvalidThreadNotificationSettingsError';@@ -18,7 +17,9 @@ import type {ThreadMemberSettingsRequest} from '@fluxer/schema/src/domains/user/const SETTINGS_CAS_ATTEMPTS = 3;function sameMuteConfig(a: MuteConfig | null, b: MuteConfig | null): boolean {- if (a === null || b === null) return a === b;+ if (a === null || b === null) {+ return a === b;+ }return ((a.end_time?.getTime() ?? null) === (b.end_time?.getTime() ?? null) &&a.selected_time_window === b.selected_time_window@@ -44,40 +45,46 @@ export class ThreadMemberSettingsService {viewer: params.viewer,skipNsfwValidation: true,});- if (!auth.thread) throw new InvalidChannelTypeError();+ if (!auth.thread) {+ throw new InvalidChannelTypeError();+ }const threadId = auth.thread.state.threadId;for (let attempt = 0; attempt < SETTINGS_CAS_ATTEMPTS; attempt++) {const member =(attempt === 0 ? auth.thread.member : null) ??(await this.ctx.channelRepository.threads.getMember(threadId, userId));- if (!member) throw new UnknownThreadMemberError();+ if (!member) {+ throw new UnknownThreadMemberError();+ }const flags =data.flags === undefined ? member.flags : (member.flags & ThreadMemberFlags.HAS_INTERACTED) | data.flags;const muted = data.muted ?? member.muted;const current = member.muteConfig?.toMuteConfig() ?? null;- const muteConfig =- data.mute_config === undefined- ? current- : data.mute_config === null- ? null- : {- end_time: data.mute_config.end_time ?? null,- selected_time_window: data.mute_config.selected_time_window,- };- if (flags === member.flags && muted === member.muted && sameMuteConfig(muteConfig, current)) return null;+ let muteConfig: MuteConfig | null;+ if (data.mute_config === undefined) {+ muteConfig = current;+ } else if (data.mute_config === null) {+ muteConfig = null;+ } else {+ muteConfig = {+ end_time: data.mute_config.end_time ?? null,+ selected_time_window: data.mute_config.selected_time_window,+ };+ }+ if (flags === member.flags && muted === member.muted && sameMuteConfig(muteConfig, current)) {+ return null;+ }const updated = await this.ctx.channelRepository.threads.updateMemberSettings(member, {flags,muted,...(data.mute_config === undefined ? {} : {muteConfig}),});- if (!updated) continue;- await this.dispatch(updated);+ if (!updated) {+ continue;+ }+ await dispatchThreadEvents(this.ctx.gatewayService, updated.guildId, [threadMemberUpdateEvent(updated)]);return mapThreadMemberToResponse(updated, {self: true});}throw new ServiceUnavailableError();}-- private async dispatch(member: ThreadMember): Promise<void> {- await dispatchThreadEvents(this.ctx.gatewayService, member.guildId, [threadMemberUpdateEvent(member)]);- }}