Server/project/src/controllers/DialogueController.ts

443 lines
15 KiB
TypeScript
Raw Normal View History

import { inject, injectAll, injectable } from "tsyringe";
2023-03-03 15:23:46 +00:00
import { IDialogueChatBot } from "@spt-aki/helpers/Dialogue/IDialogueChatBot";
import { DialogueHelper } from "@spt-aki/helpers/DialogueHelper";
import { IGetAllAttachmentsResponse } from "@spt-aki/models/eft/dialog/IGetAllAttachmentsResponse";
import { IGetFriendListDataResponse } from "@spt-aki/models/eft/dialog/IGetFriendListDataResponse";
import { IGetMailDialogViewRequestData } from "@spt-aki/models/eft/dialog/IGetMailDialogViewRequestData";
import { IGetMailDialogViewResponseData } from "@spt-aki/models/eft/dialog/IGetMailDialogViewResponseData";
import { ISendMessageRequest } from "@spt-aki/models/eft/dialog/ISendMessageRequest";
import { Dialogue, DialogueInfo, IAkiProfile, IUserDialogInfo, Message } from "@spt-aki/models/eft/profile/IAkiProfile";
import { MessageType } from "@spt-aki/models/enums/MessageType";
import { ILogger } from "@spt-aki/models/spt/utils/ILogger";
import { SaveServer } from "@spt-aki/servers/SaveServer";
import { MailSendService } from "@spt-aki/services/MailSendService";
import { TimeUtil } from "@spt-aki/utils/TimeUtil";
2023-03-03 15:23:46 +00:00
@injectable()
export class DialogueController
{
protected registeredDialogueChatBots: Map<string, IDialogueChatBot> = new Map<string, IDialogueChatBot>();
2023-03-03 15:23:46 +00:00
constructor(
@inject("WinstonLogger") protected logger: ILogger,
2023-03-03 15:23:46 +00:00
@inject("SaveServer") protected saveServer: SaveServer,
@inject("TimeUtil") protected timeUtil: TimeUtil,
@inject("DialogueHelper") protected dialogueHelper: DialogueHelper,
@inject("MailSendService") protected mailSendService: MailSendService,
@injectAll("DialogueChatBot") protected dialogueChatBots: IDialogueChatBot[],
2023-03-03 15:23:46 +00:00
)
{
for (const dialogueChatBot of dialogueChatBots)
{
if (this.registeredDialogueChatBots.has(dialogueChatBot.getChatBot()._id))
{
this.logger.error(
`Could not register ${dialogueChatBot.getChatBot()._id} as it is already in use. Skipping.`,
);
continue;
}
this.registeredDialogueChatBots.set(dialogueChatBot.getChatBot()._id, dialogueChatBot);
}
}
2023-03-03 15:23:46 +00:00
/** Handle onUpdate spt event */
2023-03-03 15:23:46 +00:00
public update(): void
{
const profiles = this.saveServer.getProfiles();
for (const sessionID in profiles)
{
this.removeExpiredItemsFromMessages(sessionID);
2023-03-03 15:23:46 +00:00
}
}
/**
* Handle client/friend/list
* @returns IGetFriendListDataResponse
*/
2023-03-03 15:23:46 +00:00
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public getFriendList(sessionID: string): IGetFriendListDataResponse
{
// Force a fake friend called SPT into friend list
return {
Friends: Array.from(this.registeredDialogueChatBots.values()).map((v) => v.getChatBot()),
Ignore: [],
InIgnoreList: [],
};
2023-03-03 15:23:46 +00:00
}
/**
* Handle client/mail/dialog/list
2023-03-03 15:23:46 +00:00
* Create array holding trader dialogs and mail interactions with player
* Set the content of the dialogue on the list tab.
* @param sessionID Session Id
* @returns array of dialogs
*/
public generateDialogueList(sessionID: string): DialogueInfo[]
{
const data: DialogueInfo[] = [];
2023-08-04 18:58:00 +01:00
for (const dialogueId in this.dialogueHelper.getDialogsForProfile(sessionID))
2023-03-03 15:23:46 +00:00
{
data.push(this.getDialogueInfo(dialogueId, sessionID));
}
return data;
}
/**
* Get the content of a dialogue
* @param dialogueID Dialog id
* @param sessionID Session Id
* @returns DialogueInfo
*/
public getDialogueInfo(dialogueID: string, sessionID: string): DialogueInfo
{
2023-08-04 18:58:00 +01:00
const dialogs = this.dialogueHelper.getDialogsForProfile(sessionID);
const dialogue = dialogs[dialogueID];
2023-03-03 15:23:46 +00:00
const result: DialogueInfo = {
_id: dialogueID,
type: dialogue.type ? dialogue.type : MessageType.NPC_TRADER,
message: this.dialogueHelper.getMessagePreview(dialogue),
new: dialogue.new,
attachmentsNew: dialogue.attachmentsNew,
pinned: dialogue.pinned,
Users: this.getDialogueUsers(dialogue, dialogue.type, sessionID),
2023-03-03 15:23:46 +00:00
};
return result;
2023-03-03 15:23:46 +00:00
}
/**
* Get the users involved in a dialog (player + other party)
* @param dialog The dialog to check for users
* @param messageType What type of message is being sent
* @param sessionID Player id
* @returns IUserDialogInfo array
*/
public getDialogueUsers(dialog: Dialogue, messageType: MessageType, sessionID: string): IUserDialogInfo[]
{
const profile = this.saveServer.getProfile(sessionID);
// User to user messages are special in that they need the player to exist in them, add if they don't
if (
messageType === MessageType.USER_MESSAGE
&& !dialog.Users?.find((x) => x._id === profile.characters.pmc.sessionId)
)
{
if (!dialog.Users)
{
dialog.Users = [];
}
dialog.Users.push({
_id: profile.characters.pmc.sessionId,
info: {
Level: profile.characters.pmc.Info.Level,
Nickname: profile.characters.pmc.Info.Nickname,
Side: profile.characters.pmc.Info.Side,
MemberCategory: profile.characters.pmc.Info.MemberCategory,
},
});
}
return dialog.Users ? dialog.Users : undefined;
}
2023-03-03 15:23:46 +00:00
/**
* Handle client/mail/dialog/view
2023-03-03 15:23:46 +00:00
* Handle player clicking 'messenger' and seeing all the messages they've recieved
* Set the content of the dialogue on the details panel, showing all the messages
* for the specified dialogue.
* @param request Get dialog request
* @param sessionId Session id
2023-03-03 15:23:46 +00:00
* @returns IGetMailDialogViewResponseData object
*/
public generateDialogueView(
request: IGetMailDialogViewRequestData,
sessionId: string,
): IGetMailDialogViewResponseData
2023-03-03 15:23:46 +00:00
{
const dialogueId = request.dialogId;
const fullProfile = this.saveServer.getProfile(sessionId);
const dialogue = this.getDialogByIdFromProfile(fullProfile, request);
// Dialog was opened, remove the little [1] on screen
2023-03-03 15:23:46 +00:00
dialogue.new = 0;
// Set number of new attachments, but ignore those that have expired.
dialogue.attachmentsNew = this.getUnreadMessagesWithAttachmentsCount(sessionId, dialogueId);
2023-03-03 15:23:46 +00:00
return {
2023-03-03 15:23:46 +00:00
messages: dialogue.messages,
profiles: this.getProfilesForMail(fullProfile, dialogue.Users),
hasMessagesWithRewards: this.messagesHaveUncollectedRewards(dialogue.messages),
2023-03-03 15:23:46 +00:00
};
}
/**
* Get dialog from player profile, create if doesn't exist
* @param profile Player profile
* @param request get dialog request (params used when dialog doesnt exist in profile)
* @returns Dialogue
*/
protected getDialogByIdFromProfile(profile: IAkiProfile, request: IGetMailDialogViewRequestData): Dialogue
{
if (!profile.dialogues[request.dialogId])
{
profile.dialogues[request.dialogId] = {
_id: request.dialogId,
attachmentsNew: 0,
pinned: false,
messages: [],
new: 0,
type: request.type,
};
if (request.type === MessageType.USER_MESSAGE)
{
profile.dialogues[request.dialogId].Users = [];
if (this.registeredDialogueChatBots.has(request.dialogId))
{
profile.dialogues[request.dialogId].Users.push(
this.registeredDialogueChatBots.get(request.dialogId).getChatBot(),
);
}
}
}
return profile.dialogues[request.dialogId];
}
/**
* Get the users involved in a mail between two entities
* @param fullProfile Player profile
* @param dialogUsers The participants of the mail
* @returns IUserDialogInfo array
*/
protected getProfilesForMail(fullProfile: IAkiProfile, dialogUsers: IUserDialogInfo[]): IUserDialogInfo[]
{
const result: IUserDialogInfo[] = [];
if (dialogUsers)
{
result.push(...dialogUsers);
// Player doesnt exist, add them in before returning
if (!result.find((x) => x._id === fullProfile.info.id))
{
const pmcProfile = fullProfile.characters.pmc;
result.push({
_id: fullProfile.info.id,
info: {
Nickname: pmcProfile.Info.Nickname,
Side: pmcProfile.Info.Side,
Level: pmcProfile.Info.Level,
MemberCategory: pmcProfile.Info.MemberCategory,
},
});
}
}
return result;
}
2023-03-03 15:23:46 +00:00
/**
* Get a count of messages with attachments from a particular dialog
* @param sessionID Session id
* @param dialogueID Dialog id
* @returns Count of messages with attachments
*/
protected getUnreadMessagesWithAttachmentsCount(sessionID: string, dialogueID: string): number
{
let newAttachmentCount = 0;
const activeMessages = this.getActiveMessagesFromDialog(sessionID, dialogueID);
for (const message of activeMessages)
{
if (message.hasRewards && !message.rewardCollected)
{
newAttachmentCount++;
}
}
return newAttachmentCount;
}
/**
* Does array have messages with uncollected rewards (includes expired rewards)
* @param messages Messages to check
* @returns true if uncollected rewards found
*/
protected messagesHaveUncollectedRewards(messages: Message[]): boolean
{
return messages.some((x) => x.items?.data?.length > 0);
2023-03-03 15:23:46 +00:00
}
/**
* Handle client/mail/dialog/remove
* Remove an entire dialog with an entity (trader/user)
* @param dialogueId id of the dialog to remove
* @param sessionId Player id
*/
public removeDialogue(dialogueId: string, sessionId: string): void
2023-03-03 15:23:46 +00:00
{
const profile = this.saveServer.getProfile(sessionId);
const dialog = profile.dialogues[dialogueId];
if (!dialog)
{
this.logger.error(`No dialog in profile: ${sessionId} found with id: ${dialogueId}`);
return;
}
delete profile.dialogues[dialogueId];
2023-03-03 15:23:46 +00:00
}
/** Handle client/mail/dialog/pin && Handle client/mail/dialog/unpin */
public setDialoguePin(dialogueId: string, shouldPin: boolean, sessionId: string): void
2023-03-03 15:23:46 +00:00
{
const dialog = this.dialogueHelper.getDialogsForProfile(sessionId)[dialogueId];
if (!dialog)
{
this.logger.error(`No dialog in profile: ${sessionId} found with id: ${dialogueId}`);
return;
}
dialog.pinned = shouldPin;
2023-03-03 15:23:46 +00:00
}
/**
* Handle client/mail/dialog/read
* Set a dialog to be read (no number alert/attachment alert)
* @param dialogueIds Dialog ids to set as read
* @param sessionId Player profile id
*/
public setRead(dialogueIds: string[], sessionId: string): void
2023-03-03 15:23:46 +00:00
{
const dialogs = this.dialogueHelper.getDialogsForProfile(sessionId);
if (!dialogs)
2023-03-03 15:23:46 +00:00
{
this.logger.error(`No dialog object in profile: ${sessionId}`);
return;
}
for (const dialogId of dialogueIds)
{
dialogs[dialogId].new = 0;
dialogs[dialogId].attachmentsNew = 0;
2023-03-03 15:23:46 +00:00
}
}
/**
* Handle client/mail/dialog/getAllAttachments
2023-03-03 15:23:46 +00:00
* Get all uncollected items attached to mail in a particular dialog
* @param dialogueId Dialog to get mail attachments from
* @param sessionId Session id
* @returns
2023-03-03 15:23:46 +00:00
*/
public getAllAttachments(dialogueId: string, sessionId: string): IGetAllAttachmentsResponse
2023-03-03 15:23:46 +00:00
{
const dialogs = this.dialogueHelper.getDialogsForProfile(sessionId);
const dialog = dialogs[dialogueId];
if (!dialog)
{
this.logger.error(`No dialog in profile: ${sessionId} found with id: ${dialogueId}`);
return;
}
2023-03-03 15:23:46 +00:00
// Removes corner 'new messages' tag
dialog.attachmentsNew = 0;
const activeMessages = this.getActiveMessagesFromDialog(sessionId, dialogueId);
2023-03-03 15:23:46 +00:00
const messagesWithAttachments = this.getMessagesWithAttachments(activeMessages);
return {
2023-03-03 15:23:46 +00:00
messages: messagesWithAttachments,
profiles: [],
hasMessagesWithRewards: this.messagesHaveUncollectedRewards(messagesWithAttachments),
2023-03-03 15:23:46 +00:00
};
}
/** client/mail/msg/send */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public sendMessage(sessionId: string, request: ISendMessageRequest): string
{
this.mailSendService.sendPlayerMessageToNpc(sessionId, request.dialogId, request.text);
if (this.registeredDialogueChatBots.has(request.dialogId))
{
return this.registeredDialogueChatBots.get(request.dialogId).handleMessage(sessionId, request);
}
return request.dialogId;
}
2023-03-03 15:23:46 +00:00
/**
* Get messages from a specific dialog that have items not expired
* @param sessionId Session id
* @param dialogueId Dialog to get mail attachments from
* @returns Message array
*/
protected getActiveMessagesFromDialog(sessionId: string, dialogueId: string): Message[]
{
const timeNow = this.timeUtil.getTimestamp();
const dialogs = this.dialogueHelper.getDialogsForProfile(sessionId);
return dialogs[dialogueId].messages.filter((x) => timeNow < (x.dt + x.maxStorageTime));
2023-03-03 15:23:46 +00:00
}
/**
* Return array of messages with uncollected items (includes expired)
* @param messages Messages to parse
* @returns messages with items to collect
*/
protected getMessagesWithAttachments(messages: Message[]): Message[]
{
return messages.filter((x) => x.items?.data?.length > 0);
2023-03-03 15:23:46 +00:00
}
/**
* Delete expired items from all messages in player profile. triggers when updating traders.
* @param sessionId Session id
2023-03-03 15:23:46 +00:00
*/
protected removeExpiredItemsFromMessages(sessionId: string): void
2023-03-03 15:23:46 +00:00
{
for (const dialogueId in this.dialogueHelper.getDialogsForProfile(sessionId))
2023-03-03 15:23:46 +00:00
{
this.removeExpiredItemsFromMessage(sessionId, dialogueId);
}
}
/**
* Removes expired items from a message in player profile
* @param sessionId Session id
* @param dialogueId Dialog id
*/
protected removeExpiredItemsFromMessage(sessionId: string, dialogueId: string): void
{
const dialogs = this.dialogueHelper.getDialogsForProfile(sessionId);
const dialog = dialogs[dialogueId];
if (!dialog.messages)
{
return;
}
for (const message of dialog.messages)
{
if (this.messageHasExpired(message))
2023-03-03 15:23:46 +00:00
{
message.items = {};
2023-03-03 15:23:46 +00:00
}
}
}
/**
* Has a dialog message expired
* @param message Message to check expiry of
* @returns true or false
*/
protected messageHasExpired(message: Message): boolean
{
return (this.timeUtil.getTimestamp()) > (message.dt + message.maxStorageTime);
}
}