Files
CT/src/Model/Chat/chatModel.ts
T

526 lines
14 KiB
TypeScript
Raw Normal View History

2024-07-21 20:50:05 +02:00
// this file is responsible for managing chats.
2024-07-19 19:47:07 +02:00
2026-04-06 20:47:49 +00:00
import {
checkMatchesObjectStructure,
DATA_VERSION,
ValidObject,
} from "../Utility/typeSafety";
2024-07-22 18:11:18 +02:00
import FileModel, { FileContent } from "../Files/fileModel";
import {
2026-04-01 08:29:39 +00:00
HandlerManager,
createTimestamp,
localeCompare,
2026-04-06 20:47:49 +00:00
parse,
2026-04-01 08:29:39 +00:00
parseValidObject,
stringify,
2024-07-22 02:05:27 +02:00
} from "../Utility/utility";
2024-07-26 03:14:55 +02:00
import StorageModel, {
2026-04-01 08:29:39 +00:00
StorageModelSubPath,
filePaths,
2024-07-26 03:14:55 +02:00
} from "../Global/storageModel";
2024-07-22 02:05:27 +02:00
import { decryptString, encryptString } from "../Utility/crypto";
2024-07-19 20:07:14 +02:00
2024-07-20 14:16:26 +02:00
import ChatListModel from "./chatListModel";
2024-07-22 19:52:08 +02:00
import { Color } from "../../colors";
2024-07-22 02:05:27 +02:00
import ConnectionModel from "../Global/connectionModel";
import SettingsModel from "../Global/settingsModel";
2024-07-19 20:50:42 +02:00
import { v4 } from "uuid";
2024-07-21 20:55:31 +02:00
export default class ChatModel {
2026-04-01 08:29:39 +00:00
connectionModel: ConnectionModel;
storageModel: StorageModel;
settingsModel: SettingsModel;
chatListModel: ChatListModel;
2024-07-22 23:33:57 +02:00
2026-04-01 08:29:39 +00:00
fileModel: FileModel;
2024-07-22 23:33:57 +02:00
2026-04-01 08:29:39 +00:00
// data
id: string;
info: ChatInfo;
color: Color;
2024-07-22 02:23:21 +02:00
2026-04-01 08:29:39 +00:00
chatMessageHandlerManager: HandlerManager<ChatMessage> =
new HandlerManager();
2026-04-06 20:47:49 +00:00
reactionHandlerManager: HandlerManager<ChatMessageReaction> =
new HandlerManager();
2024-07-22 02:23:21 +02:00
2026-04-01 08:29:39 +00:00
get secondaryChannels(): string[] {
return this.info.secondaryChannels.sort(localeCompare);
2024-07-19 20:50:42 +02:00
}
2024-07-21 01:56:10 +02:00
2026-04-01 08:29:39 +00:00
// paths
getBasePath = (): string[] => {
return StorageModel.getPath(
StorageModelSubPath.Chat,
filePaths.chat.chatBase(this.id),
);
};
getInfoPath = (): string[] => {
return StorageModel.getPath(
StorageModelSubPath.Chat,
filePaths.chat.info(this.id),
);
};
getColorPath = (): string[] => {
return StorageModel.getPath(
StorageModelSubPath.Chat,
filePaths.chat.color(this.id),
);
};
getMessageDirPath = (): string[] => {
return StorageModel.getPath(
StorageModelSubPath.Chat,
filePaths.chat.messages(this.id),
);
};
getMessagePath = (id: string): string[] => {
return [...this.getMessageDirPath(), id];
};
2026-04-06 20:47:49 +00:00
getReactionDirPath = (): string[] => {
return StorageModel.getPath(
StorageModelSubPath.Chat,
filePaths.chat.reactions(this.id),
);
};
getReactionPath = (id: string): string[] => {
return [...this.getReactionDirPath(), id];
};
2026-04-01 08:29:39 +00:00
// handlers
handleMessage = (body: string): void => {
const chatMessage: ChatMessage | null = parseValidObject(
body,
ChatMessageReference,
);
if (chatMessage == null) return;
chatMessage.status = ChatMessageStatus.Received;
2026-04-01 19:00:16 +00:00
2026-04-06 20:47:49 +00:00
this.addMessage(chatMessage);
2026-04-01 14:16:38 +00:00
this.setReadStatus(true);
2024-07-20 20:53:48 +02:00
};
2026-04-01 08:29:39 +00:00
2026-04-06 20:47:49 +00:00
handleReaction = (reaction: ChatMessageReaction | any): void => {
if (
!checkMatchesObjectStructure(reaction, ChatMessageReactionReference)
)
return;
2026-04-07 18:48:01 +00:00
const reactionPath: string[] = this.getReactionPath(reaction.fileId);
if (reaction.isDeleting == true) {
this.storageModel.remove(reactionPath);
} else {
this.storageModel.writeStringifiable(reactionPath, reaction);
}
2026-04-07 18:48:01 +00:00
this.reactionHandlerManager.trigger(reaction);
2026-04-06 20:47:49 +00:00
};
2026-04-01 08:29:39 +00:00
handleMessageSent = (chatMessage: ChatMessage): void => {
chatMessage.status = ChatMessageStatus.Sent;
this.addMessage(chatMessage);
2024-07-20 20:53:48 +02:00
};
2026-04-01 08:29:39 +00:00
// settings
setPrimaryChannel = (primaryChannel: string): void => {
this.info.primaryChannel = primaryChannel;
this.storeInfo();
this.subscribe();
};
setSecondaryChannels = (secondaryChannels: string[]): void => {
this.info.secondaryChannels = secondaryChannels;
this.storeInfo();
};
setEncryptionKey = (key: string): void => {
this.info.encryptionKey = key;
this.storeInfo();
};
setColor = (color: Color): void => {
this.color = color;
this.storeColor();
};
// messaging
addMessage = async (chatMessage: ChatMessage): Promise<void> => {
await this.decryptMessage(chatMessage);
// message
if (chatMessage.body != "") {
const messagePath: string[] = this.getMessagePath(chatMessage.id);
this.storageModel.writeStringifiable(messagePath, chatMessage);
this.chatMessageHandlerManager.trigger(chatMessage);
}
// file
this.fileModel.handleStringifiedFileContent(
chatMessage.stringifiedFile,
);
};
2026-04-06 20:47:49 +00:00
getNameAndChannel = (): [string, string] | false => {
2026-04-01 08:29:39 +00:00
const senderName = this.settingsModel.username;
if (senderName == "") return false;
const allChannels = [this.info.primaryChannel];
for (const secondaryChannel of this.info.secondaryChannels) {
allChannels.push(secondaryChannel);
}
const combinedChannel: string = allChannels.join("/");
2026-04-06 20:47:49 +00:00
return [senderName, combinedChannel];
};
sendMessage = async (
body: string,
fileContent?: FileContent<string>,
): Promise<boolean> => {
const nameAndChannel = this.getNameAndChannel();
if (nameAndChannel == false) return;
const [senderName, combinedChannel] = nameAndChannel;
2026-04-01 08:29:39 +00:00
const chatMessage: ChatMessage = await ChatModel.createChatMessage(
combinedChannel,
senderName,
this.info.encryptionKey,
body,
fileContent,
);
this.addMessage(chatMessage);
this.connectionModel.sendMessageOrStore(chatMessage);
return true;
};
decryptMessage = async (chatMessage: ChatMessage): Promise<void> => {
const decryptedBody: string = await decryptString(
chatMessage.body,
this.info.encryptionKey,
);
const decryptedFile: string = await decryptString(
chatMessage.stringifiedFile ?? "",
this.info.encryptionKey,
);
chatMessage.body = decryptedBody;
chatMessage.stringifiedFile = decryptedFile;
};
2026-04-06 20:47:49 +00:00
sendReaction = async (
messageId: string,
2026-04-07 18:39:55 +00:00
content: ReactionSymbols,
isDeleting?: boolean,
2026-04-06 20:47:49 +00:00
): Promise<void> => {
const nameAndChannel = this.getNameAndChannel();
if (nameAndChannel == false) return;
const [senderName, combinedChannel] = nameAndChannel;
const reaction = ChatModel.createMessageReaction(
messageId,
senderName,
content,
2026-04-07 18:48:01 +00:00
isDeleting,
2026-04-06 20:47:49 +00:00
);
this.sendMessage("", reaction);
2026-04-07 18:48:01 +00:00
this.handleReaction(reaction);
2026-04-06 20:47:49 +00:00
};
2026-04-01 08:29:39 +00:00
subscribe = (): void => {
this.connectionModel.addChannel(this.info.primaryChannel);
};
2026-04-01 14:16:38 +00:00
setReadStatus = (hasUnreadMessages: boolean): void => {
this.info.hasUnreadMessages = hasUnreadMessages;
2026-04-01 08:29:39 +00:00
this.storeInfo();
};
// storage
storeInfo = (): void => {
this.storageModel.writeStringifiable(this.getInfoPath(), this.info);
};
storeColor = (): void => {
this.storageModel.write(this.getColorPath(), this.color);
};
delete = () => {
// untrack
this.chatListModel.untrackChat(this);
// delete
const dirPath: string[] = this.getBasePath();
this.storageModel.removeRecursively(dirPath);
};
// load
loadInfo = (): void => {
const info: ChatInfo | null = this.storageModel.readStringifiable(
this.getInfoPath(),
ChatInfoReference,
);
if (info != null) {
this.info = info;
} else {
this.info = ChatModel.generateChatInfo("0");
}
};
loadColor = (): void => {
const path: string[] = this.getColorPath();
const color: string | null = this.storageModel.read(path);
if (!color) {
this.color = Color.Standard;
} else {
this.color = color as any;
}
};
get messages(): ChatMessage[] {
const messageIds: string[] = this.storageModel.list(
this.getMessageDirPath(),
);
if (!Array.isArray(messageIds)) return [];
const chatMessages: ChatMessage[] = [];
for (const messageId of messageIds) {
const messagePath: string[] = this.getMessagePath(messageId);
2026-04-06 20:47:49 +00:00
const chatMessage: ChatMessage | null =
2026-04-01 08:29:39 +00:00
this.storageModel.readStringifiable(
messagePath,
ChatMessageReference,
);
2026-04-06 20:47:49 +00:00
if (chatMessage == null) continue;
2026-04-01 08:29:39 +00:00
chatMessages.push(chatMessage);
}
const sorted = chatMessages.sort((a, b) =>
a.dateSent.localeCompare(b.dateSent),
);
return sorted;
}
2024-07-21 01:12:35 +02:00
2026-04-06 20:47:49 +00:00
get reactions(): ChatMessageReaction[] {
const reactionIds: string[] = this.storageModel.list(
this.getReactionDirPath(),
);
if (!Array.isArray(reactionIds)) return [];
const reactions: ChatMessageReaction[] = [];
for (const reactionId of reactionIds) {
const reactionPath: string[] = this.getReactionPath(reactionId);
const reaction: ChatMessageReaction | null =
this.storageModel.readStringifiable(
reactionPath,
ChatMessageReactionReference,
);
if (reaction == null) continue;
reactions.push(reaction);
}
return reactions;
}
2026-04-01 08:29:39 +00:00
// init
constructor(
storageModel: StorageModel,
connectionModel: ConnectionModel,
settingsModel: SettingsModel,
chatListModel: ChatListModel,
chatId: string,
) {
this.id = chatId;
this.connectionModel = connectionModel;
this.settingsModel = settingsModel;
this.storageModel = storageModel;
this.chatListModel = chatListModel;
this.loadInfo();
this.loadColor();
this.subscribe();
this.fileModel = new FileModel(
this.storageModel,
this.settingsModel,
this,
);
2024-07-21 01:12:35 +02:00
}
2026-04-01 08:29:39 +00:00
// utility
2026-04-01 19:00:16 +00:00
static splitChannel(channelString: string): string[] {
return channelString.split("/");
}
2026-04-01 08:29:39 +00:00
static generateChatInfo = (primaryChannel: string): ChatInfo => {
return {
dataVersion: DATA_VERSION,
primaryChannel,
secondaryChannels: [],
encryptionKey: "",
hasUnreadMessages: false,
};
};
static createChatMessage = async (
channel: string,
sender: string,
encryptionKey: string,
body: string,
fileContent?: FileContent<string>,
): Promise<ChatMessage> => {
const chatMessage: ChatMessage = {
dataVersion: DATA_VERSION,
id: v4(),
channel,
sender,
body,
dateSent: createTimestamp(),
status: ChatMessageStatus.Outbox,
stringifiedFile: "",
};
if (fileContent != undefined) {
const stringifiedFile = stringify(fileContent);
chatMessage.stringifiedFile = stringifiedFile;
}
if (encryptionKey != "") {
chatMessage.body = await encryptString(
chatMessage.body,
encryptionKey,
);
chatMessage.stringifiedFile = await encryptString(
chatMessage.stringifiedFile,
encryptionKey,
);
}
return chatMessage;
};
2026-04-06 20:47:49 +00:00
static createMessageReaction = (
messageId: string,
sender: string,
2026-04-07 18:39:55 +00:00
content: ReactionSymbols,
2026-04-07 18:48:01 +00:00
isDeleting: boolean,
2026-04-06 20:47:49 +00:00
): ChatMessageReaction => {
const fileContent = FileModel.createFileContent(v4(), "reaction");
const reaction: ChatMessageReaction = {
...fileContent,
fileId: ChatModel.createMessageReactionId(messageId, content, sender),
2026-04-06 20:47:49 +00:00
messageId,
sender,
content,
2026-04-07 18:48:01 +00:00
isDeleting,
2026-04-06 20:47:49 +00:00
};
return reaction;
};
static createMessageReactionId = (messageId: string, content: ReactionSymbols, sender: string): string => {
return messageId + sender + reactionStringMap[content];
}
}
2024-07-19 19:47:07 +02:00
// types
2026-04-07 18:39:55 +00:00
export enum ReactionSymbols {
ThumbsUp = "👍",
Check = "✅",
Stop = "🛑",
2026-04-07 18:39:55 +00:00
Attention = "❗️",
DoubleAttention = "‼️",
Question = "❓",
}
2026-04-06 20:47:49 +00:00
const reactionStringMap: {[key: ReactionSymbols|string]: string} = {}
Object.entries(ReactionSymbols).forEach(value => {
reactionStringMap[value[1]] = value[0];
});
2024-07-21 23:32:20 +02:00
export interface ChatInfo extends ValidObject {
2026-04-01 08:29:39 +00:00
primaryChannel: string;
secondaryChannels: string[];
encryptionKey: string;
2024-07-19 20:50:42 +02:00
2026-04-01 08:29:39 +00:00
hasUnreadMessages: boolean;
2024-07-19 20:07:14 +02:00
}
export enum ChatMessageStatus {
2026-04-01 08:29:39 +00:00
Outbox = "outbox",
Sent = "sent",
Received = "received",
Other = "other",
}
2024-07-21 23:32:20 +02:00
export interface ChatMessage extends ValidObject {
2026-04-01 08:29:39 +00:00
id: string;
2024-07-19 20:50:42 +02:00
2026-04-01 08:29:39 +00:00
channel: string;
sender: string;
body: string;
dateSent: string;
2024-07-19 20:50:42 +02:00
2026-04-01 08:29:39 +00:00
status: ChatMessageStatus;
2026-04-01 08:29:39 +00:00
stringifiedFile: string;
2024-07-21 21:45:18 +02:00
}
2024-07-22 01:16:13 +02:00
2026-04-06 20:47:49 +00:00
export interface ChatMessageReaction
extends ValidObject, FileContent<"reaction"> {
messageId: string;
sender: string;
2026-04-07 18:39:55 +00:00
content: ReactionSymbols | string;
2026-04-07 18:48:01 +00:00
isDeleting: boolean;
2026-04-06 20:47:49 +00:00
}
2024-07-22 01:22:53 +02:00
// references
export const ChatInfoReference: ChatInfo = {
2026-04-01 08:29:39 +00:00
dataVersion: DATA_VERSION,
2024-07-22 01:22:53 +02:00
2026-04-01 08:29:39 +00:00
primaryChannel: "",
secondaryChannels: [""],
encryptionKey: "",
2024-07-22 01:22:53 +02:00
2026-04-01 08:29:39 +00:00
hasUnreadMessages: true,
2024-07-22 01:22:53 +02:00
};
2024-07-22 01:16:13 +02:00
export const ChatMessageReference: ChatMessage = {
2026-04-01 08:29:39 +00:00
dataVersion: DATA_VERSION,
2024-07-22 01:16:13 +02:00
2026-04-01 08:29:39 +00:00
id: "",
2024-07-22 01:16:13 +02:00
2026-04-01 08:29:39 +00:00
channel: "",
sender: "",
body: "",
dateSent: "",
2024-07-22 01:16:13 +02:00
2026-04-01 08:29:39 +00:00
status: "" as ChatMessageStatus,
2024-07-22 01:16:13 +02:00
2026-04-01 08:29:39 +00:00
stringifiedFile: "",
2024-07-22 01:16:13 +02:00
};
2026-04-06 20:47:49 +00:00
export const ChatMessageReactionReference: ChatMessageReaction = {
dataVersion: DATA_VERSION,
fileId: "",
fileContentId: "",
creationDate: "",
type: "reaction",
messageId: "",
sender: "",
content: "",
2026-04-07 18:48:01 +00:00
isDeleting: false,
2026-04-06 20:47:49 +00:00
};