reorganize models
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
// this file is responsible for managing UDN connections.
|
||||
|
||||
import { ChatMessage, ChatMessageReference } from "../Chat/chatModel";
|
||||
import StorageModel, { storageKeys } from "./storageModel";
|
||||
import UDNFrontend, { Message } from "udn-frontend";
|
||||
|
||||
import { stringify } from "../Utility/utility";
|
||||
|
||||
export default class ConnectionModel {
|
||||
udn: UDNFrontend;
|
||||
storageModel: StorageModel;
|
||||
|
||||
// data
|
||||
get isConnected(): boolean {
|
||||
return this.udn.ws != undefined && this.udn.ws.readyState == 1;
|
||||
}
|
||||
|
||||
get address(): string | undefined {
|
||||
return this.udn.ws?.url;
|
||||
}
|
||||
|
||||
connectionChangeHandler: () => void = () => {};
|
||||
messageHandler: (data: Message) => void = () => {};
|
||||
messageSentHandler: (chatMessage: ChatMessage) => void = () => {};
|
||||
|
||||
channelsToSubscribe: Set<string> = new Set();
|
||||
|
||||
// connection
|
||||
connect = (address: string): void => {
|
||||
this.udn.connect(address);
|
||||
};
|
||||
|
||||
disconnect = (): void => {
|
||||
this.udn.disconnect();
|
||||
|
||||
// do not reconnect
|
||||
const reconnectAddressPath: string[] = storageKeys.reconnectAddress;
|
||||
this.storageModel.remove(reconnectAddressPath);
|
||||
};
|
||||
|
||||
handleMessage = (data: Message): void => {
|
||||
this.messageHandler(data);
|
||||
};
|
||||
|
||||
handleConnectionChange = (): void => {
|
||||
console.log("connection status:", this.isConnected, this.address);
|
||||
this.connectionChangeHandler();
|
||||
|
||||
if (this.isConnected == false) return;
|
||||
if (!this.address) return;
|
||||
|
||||
this.connectMailbox();
|
||||
this.storeAddress(this.address);
|
||||
this.sendSubscriptionRequest();
|
||||
this.sendMessagesInOutbox();
|
||||
};
|
||||
|
||||
// mailbox
|
||||
requestNewMailbox = (): void => {
|
||||
console.trace("requesting mailbox");
|
||||
this.udn.requestMailbox();
|
||||
};
|
||||
|
||||
connectMailbox = (): void => {
|
||||
if (this.address == undefined) return;
|
||||
const path = [...storageKeys.mailboxes, this.address];
|
||||
const mailboxId = this.storageModel.read(path);
|
||||
console.log("connecting mailbox", mailboxId);
|
||||
if (mailboxId == null) return this.requestNewMailbox();
|
||||
|
||||
this.udn.connectMailbox(mailboxId);
|
||||
};
|
||||
|
||||
storeMailbox = (mailboxId: string): void => {
|
||||
if (this.address == undefined) return;
|
||||
const path = [...storageKeys.mailboxes, this.address];
|
||||
this.storageModel.write(path, mailboxId);
|
||||
};
|
||||
|
||||
// subscription
|
||||
addChannel = (channel: string): void => {
|
||||
this.channelsToSubscribe.add(channel);
|
||||
this.sendSubscriptionRequest();
|
||||
};
|
||||
|
||||
sendSubscriptionRequest = (): void => {
|
||||
if (this.isConnected == false) return;
|
||||
|
||||
for (const channel of this.channelsToSubscribe) {
|
||||
this.udn.subscribe(channel);
|
||||
}
|
||||
// update mailbox
|
||||
this.connectMailbox();
|
||||
};
|
||||
|
||||
// outbox
|
||||
getOutboxMessags = (): ChatMessage[] => {
|
||||
const outboxPath: string[] = storageKeys.outbox;
|
||||
const messageIds: string[] = this.storageModel.list(outboxPath);
|
||||
|
||||
let chatMessages: ChatMessage[] = [];
|
||||
for (const messageId of messageIds) {
|
||||
const chatMessage: ChatMessage | null =
|
||||
this.storageModel.readStringifiable(
|
||||
[...outboxPath, messageId],
|
||||
ChatMessageReference
|
||||
);
|
||||
|
||||
if (chatMessage == null) continue;
|
||||
chatMessages.push(chatMessage);
|
||||
}
|
||||
|
||||
return chatMessages;
|
||||
};
|
||||
|
||||
addToOutbox = (chatMessage: ChatMessage): void => {
|
||||
const messagePath: string[] = [...storageKeys.outbox, chatMessage.id];
|
||||
this.storageModel.writeStringifiable(messagePath, chatMessage);
|
||||
};
|
||||
|
||||
removeFromOutbox = (chatMessage: ChatMessage): void => {
|
||||
const messagePath: string[] = [...storageKeys.outbox, chatMessage.id];
|
||||
this.storageModel.remove(messagePath);
|
||||
};
|
||||
|
||||
sendMessagesInOutbox = (): void => {
|
||||
const messages: ChatMessage[] = this.getOutboxMessags();
|
||||
|
||||
for (const message of messages) {
|
||||
const isSent: boolean = this.tryToSendMessage(message);
|
||||
if (isSent == false) return;
|
||||
|
||||
this.removeFromOutbox(message);
|
||||
}
|
||||
};
|
||||
|
||||
// messaging
|
||||
sendMessageOrStore = (chatMessage: ChatMessage): void => {
|
||||
const isSent = this.tryToSendMessage(chatMessage);
|
||||
if (isSent == true) return;
|
||||
|
||||
this.addToOutbox(chatMessage);
|
||||
};
|
||||
|
||||
tryToSendMessage = (chatMessage: ChatMessage): boolean => {
|
||||
const stringifiedBody: string = stringify(chatMessage);
|
||||
const isSent: boolean = this.udn.sendMessage(
|
||||
chatMessage.channel,
|
||||
stringifiedBody
|
||||
);
|
||||
if (isSent) this.messageSentHandler(chatMessage);
|
||||
return isSent;
|
||||
};
|
||||
|
||||
// storage
|
||||
private getAddressPath = (address: string): string[] => {
|
||||
const dirPath = storageKeys.previousAddresses;
|
||||
return [...dirPath, address];
|
||||
};
|
||||
|
||||
storeAddress = (address: string): void => {
|
||||
// history
|
||||
const addressPath = this.getAddressPath(address);
|
||||
this.storageModel.write(addressPath, "");
|
||||
|
||||
// reconnect
|
||||
const reconnectAddressPath: string[] = storageKeys.reconnectAddress;
|
||||
this.storageModel.write(reconnectAddressPath, address);
|
||||
};
|
||||
|
||||
removeAddress = (address: string): void => {
|
||||
const addressPath = this.getAddressPath(address);
|
||||
this.storageModel.remove(addressPath);
|
||||
};
|
||||
|
||||
get addresses(): string[] {
|
||||
const dirPath = storageKeys.previousAddresses;
|
||||
return this.storageModel.list(dirPath);
|
||||
}
|
||||
|
||||
// handlers
|
||||
setConnectionChangeHandler = (handler: () => void): void => {
|
||||
this.connectionChangeHandler = handler;
|
||||
};
|
||||
|
||||
setMessageHandler = (handler: (data: Message) => void): void => {
|
||||
this.messageHandler = handler;
|
||||
};
|
||||
|
||||
setMessageSentHandler = (
|
||||
handler: (chatMessage: ChatMessage) => void
|
||||
): void => {
|
||||
this.messageSentHandler = handler;
|
||||
};
|
||||
|
||||
// setup
|
||||
constructor(storageModel: StorageModel) {
|
||||
// create frontend
|
||||
this.udn = new UDNFrontend();
|
||||
this.storageModel = storageModel;
|
||||
|
||||
// setup handlers
|
||||
this.udn.onmessage = (data: Message) => {
|
||||
this.handleMessage(data);
|
||||
};
|
||||
this.udn.onconnect = () => {
|
||||
this.handleConnectionChange();
|
||||
};
|
||||
this.udn.ondisconnect = () => {
|
||||
this.handleConnectionChange();
|
||||
};
|
||||
|
||||
this.udn.onmailboxcreate = (mailboxId: string) => {
|
||||
console.log("created mailbox", mailboxId);
|
||||
this.storeMailbox(mailboxId);
|
||||
this.connectMailbox();
|
||||
};
|
||||
this.udn.onmailboxdelete = (mailboxId: string) => {
|
||||
console.log(`mailbox ${mailboxId} deleted`);
|
||||
this.requestNewMailbox();
|
||||
};
|
||||
this.udn.onmailboxconnect = (mailboxId: string) => {
|
||||
console.log(`using mailbox ${mailboxId}`);
|
||||
};
|
||||
|
||||
// reconnect
|
||||
const reconnectAddressPath: string[] = storageKeys.reconnectAddress;
|
||||
const reconnectAddress: string | null =
|
||||
storageModel.read(reconnectAddressPath);
|
||||
if (reconnectAddress != null) {
|
||||
this.connect(reconnectAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// this file is responsible for all settings.
|
||||
|
||||
import StorageModel, { storageKeys } from "./storageModel";
|
||||
|
||||
export default class SettingsModel {
|
||||
storageModel: StorageModel;
|
||||
|
||||
username: string;
|
||||
firstDayOfWeek: string;
|
||||
|
||||
// set
|
||||
setName(newValue: string): void {
|
||||
this.username = newValue;
|
||||
const path = storageKeys.username;
|
||||
this.storageModel.write(path, newValue);
|
||||
}
|
||||
|
||||
setFirstDayOfWeek(newValue: string): void {
|
||||
this.firstDayOfWeek = newValue;
|
||||
const path = storageKeys.firstDayOfWeek;
|
||||
this.storageModel.write(path, newValue);
|
||||
}
|
||||
|
||||
// load
|
||||
loadUsernam(): void {
|
||||
const path = storageKeys.username;
|
||||
const content = this.storageModel.read(path);
|
||||
this.username = content ?? "";
|
||||
}
|
||||
|
||||
loadFirstDayofWeek(): void {
|
||||
const path = storageKeys.firstDayOfWeek;
|
||||
const content = this.storageModel.read(path);
|
||||
this.firstDayOfWeek = content ?? "0";
|
||||
}
|
||||
|
||||
// init
|
||||
constructor(storageModel: StorageModel) {
|
||||
this.storageModel = storageModel;
|
||||
|
||||
this.loadUsernam();
|
||||
this.loadFirstDayofWeek();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// this file is responsible for reading and writing persistent data; all storage shall be handled by this file.
|
||||
|
||||
import {
|
||||
DATA_VERSION,
|
||||
ValidObject,
|
||||
checkMatchesObjectStructure,
|
||||
} from "../Utility/typeSafety";
|
||||
import { localeCompare, parseValidObject, stringify } from "../Utility/utility";
|
||||
|
||||
export const PATH_COMPONENT_SEPARATOR = "\\";
|
||||
|
||||
export default class StorageModel {
|
||||
storageEntryTree: StorageEntry = {};
|
||||
|
||||
// basic
|
||||
write = (pathComponents: string[], value: string): void => {
|
||||
const pathString: string = StorageModel.pathComponentsToString(
|
||||
...pathComponents
|
||||
);
|
||||
localStorage.setItem(pathString, value);
|
||||
this.updateTree(...pathComponents);
|
||||
};
|
||||
|
||||
read = (pathComponents: string[]): string | null => {
|
||||
const pathString: string = StorageModel.pathComponentsToString(
|
||||
...pathComponents
|
||||
);
|
||||
return localStorage.getItem(pathString);
|
||||
};
|
||||
|
||||
remove = (
|
||||
pathComponents: string[],
|
||||
shouldInitialize: boolean = true
|
||||
): void => {
|
||||
const pathString: string = StorageModel.pathComponentsToString(
|
||||
...pathComponents
|
||||
);
|
||||
localStorage.removeItem(pathString);
|
||||
|
||||
if (shouldInitialize == true) {
|
||||
this.initializeTree();
|
||||
}
|
||||
};
|
||||
|
||||
removeRecursively = (pathComponentsOfEntityToDelete: string[]): void => {
|
||||
a: for (const key of Object.keys(localStorage)) {
|
||||
const pathComponentsOfCurrentEntity: string[] =
|
||||
StorageModel.stringToPathComponents(key);
|
||||
|
||||
for (let i = 0; i < pathComponentsOfEntityToDelete.length; i++) {
|
||||
if (!pathComponentsOfCurrentEntity[i]) continue a;
|
||||
if (
|
||||
pathComponentsOfCurrentEntity[i] != pathComponentsOfEntityToDelete[i]
|
||||
)
|
||||
continue a;
|
||||
}
|
||||
|
||||
this.remove(pathComponentsOfCurrentEntity, false);
|
||||
}
|
||||
this.initializeTree();
|
||||
};
|
||||
|
||||
list = (pathComponents: string[]): string[] => {
|
||||
let currentParent: StorageEntry = this.storageEntryTree;
|
||||
for (const component of pathComponents) {
|
||||
const nextParent: StorageEntry | undefined = currentParent[component];
|
||||
if (nextParent == undefined) return [];
|
||||
currentParent = nextParent;
|
||||
}
|
||||
|
||||
return [...Object.keys(currentParent).sort(localeCompare)];
|
||||
};
|
||||
|
||||
// stringifiable
|
||||
writeStringifiable = (pathComponents: string[], value: ValidObject): void => {
|
||||
const valueString: string = stringify(value);
|
||||
this.write(pathComponents, valueString);
|
||||
};
|
||||
|
||||
readStringifiable = <T extends ValidObject>(
|
||||
pathComponents: string[],
|
||||
reference: T
|
||||
): T | null => {
|
||||
const valueString: string | null = this.read(pathComponents);
|
||||
if (!valueString) return null;
|
||||
|
||||
const object: any | null = parseValidObject(valueString, reference);
|
||||
if (object == null) return null;
|
||||
|
||||
return object;
|
||||
};
|
||||
|
||||
// init
|
||||
constructor() {
|
||||
this.initializeTree();
|
||||
}
|
||||
|
||||
// utility
|
||||
initializeTree = (): void => {
|
||||
console.log("initializing tree");
|
||||
|
||||
this.storageEntryTree = {};
|
||||
for (const key of Object.keys(localStorage)) {
|
||||
const components: string[] = StorageModel.stringToPathComponents(key);
|
||||
this.updateTree(...components);
|
||||
}
|
||||
};
|
||||
|
||||
updateTree = (...pathComponents: string[]): void => {
|
||||
let currentParent: StorageEntry = this.storageEntryTree;
|
||||
for (const pathPart of pathComponents) {
|
||||
if (!currentParent[pathPart]) {
|
||||
currentParent[pathPart] = {};
|
||||
}
|
||||
|
||||
currentParent = currentParent[pathPart];
|
||||
}
|
||||
};
|
||||
|
||||
printTree = (): string => {
|
||||
return stringify(this.storageEntryTree);
|
||||
};
|
||||
|
||||
static getFileName = (pathComponents: string[]): string => {
|
||||
return pathComponents[pathComponents.length - 1] || "\\";
|
||||
};
|
||||
|
||||
static getFileNameFromString = (pathString: string): string => {
|
||||
const pathComponents: string[] = this.stringToPathComponents(pathString);
|
||||
return pathComponents[pathComponents.length - 1] || "\\";
|
||||
};
|
||||
|
||||
static pathComponentsToString = (...pathComponents: string[]): string => {
|
||||
return pathComponents.join(PATH_COMPONENT_SEPARATOR);
|
||||
};
|
||||
|
||||
static stringToPathComponents = (string: string): string[] => {
|
||||
return string.split(PATH_COMPONENT_SEPARATOR).filter((x) => x != "");
|
||||
};
|
||||
|
||||
static join = (...items: string[]): string => {
|
||||
let allComponents: string[] = [];
|
||||
for (const item of items) {
|
||||
const parts = this.stringToPathComponents(item);
|
||||
allComponents.push(...parts);
|
||||
}
|
||||
return StorageModel.pathComponentsToString(...allComponents);
|
||||
};
|
||||
}
|
||||
|
||||
// types
|
||||
export type StorageEntry = { [key: string]: StorageEntry };
|
||||
|
||||
// keys
|
||||
export const storageKeys = {
|
||||
// connection
|
||||
socketAddress: [DATA_VERSION, "connection", "socket-address"],
|
||||
reconnectAddress: [DATA_VERSION, "connection", "reconnect-address"],
|
||||
outbox: [DATA_VERSION, "connection", "outbox"],
|
||||
mailboxes: [DATA_VERSION, "connection", "mailboxes"],
|
||||
|
||||
// settings
|
||||
username: [DATA_VERSION, "settings", "user-name"],
|
||||
firstDayOfWeek: [DATA_VERSION, "settings", "first-day-of-week"],
|
||||
|
||||
// history
|
||||
previousAddresses: [DATA_VERSION, "history", "previous-addresses"],
|
||||
|
||||
// chat
|
||||
chats: [DATA_VERSION, "chat"],
|
||||
chatInfo: (id: string) => [DATA_VERSION, "chat", id, "info"],
|
||||
chatLastUsedPage: (id: string) => [
|
||||
DATA_VERSION,
|
||||
"chat",
|
||||
id,
|
||||
"last-used-page",
|
||||
],
|
||||
chatColor: (id: string) => [DATA_VERSION, "chat", id, "color"],
|
||||
chatMessages: (id: string) => [DATA_VERSION, "chat", id, "messages"],
|
||||
chatFiles: [DATA_VERSION, "chat", "files"],
|
||||
};
|
||||
Reference in New Issue
Block a user