diff --git a/keyserver/src/creators/message-report-creator.js b/keyserver/src/creators/message-report-creator.js new file mode 100644 --- /dev/null +++ b/keyserver/src/creators/message-report-creator.js @@ -0,0 +1,70 @@ +// @flow + +import bots from 'lib/facts/bots'; +import { createMessageReply } from 'lib/shared/message-utils'; +import { type MessageReportCreationRequest } from 'lib/types/message-report-types'; +import { messageTypes } from 'lib/types/message-types'; + +import { createCommbotThread } from '../bots/commbot'; +import { fetchUsername } from '../fetchers/user-fetchers'; +import { searchForPersonalThread } from '../search/threads'; +import { createBotViewer } from '../session/bots'; +import type { Viewer } from '../session/viewer'; +import createMessages from './message-creator'; + +const { commbot } = bots; + +async function createMessageReport( + viewer: Viewer, + request: MessageReportCreationRequest, + recipientID: string, +) { + await sendCommbotMessage(viewer, request, recipientID); +} + +async function sendCommbotMessage( + viewer: Viewer, + request: MessageReportCreationRequest, + recipientID: string, +) { + const username = await fetchUsername(viewer.id); + if (!username) { + return; + } + const message = getCommbotMessage(request, username); + + const [threads] = await searchForPersonalThread(recipientID, commbot.userID); + let threadID = threads[0]?.id.toString(); + if (!threadID) { + threadID = await createCommbotThread(recipientID); + } + + const time = Date.now(); + await createMessages(createBotViewer(commbot.userID), [ + { + type: messageTypes.TEXT, + threadID, + creatorID: commbot.userID, + time, + text: message, + }, + ]); +} + +function getCommbotMessage( + request: MessageReportCreationRequest, + username: string, +): string { + const messageAuthor = request.messageAuthorInfo.username + ? `${request.messageAuthorInfo.username}’s` + : 'this'; + const thread = request.thread?.name + ? `chat titled "${request.thread.name}"` + : 'chat'; + return ( + `user ${username} reported ${messageAuthor} message in ${thread}\n` + + createMessageReply(request.message) + ); +} + +export default createMessageReport; diff --git a/lib/types/message-report-types.js b/lib/types/message-report-types.js new file mode 100644 --- /dev/null +++ b/lib/types/message-report-types.js @@ -0,0 +1,10 @@ +// @flow + +import { type RawThreadInfo } from './thread-types'; +import type { UserInfo } from './user-types'; + +export type MessageReportCreationRequest = { + +thread: RawThreadInfo, + +messageAuthorInfo: UserInfo, + +message: string, +};