import { ChatMessageDTO } from "../dto/ChatMessageDTO"; import * as log from "loglevel"; import { ChatMessageViewModel } from "../viewmodel/ChatMessageViewModel"; import { JsonAPI } from "../singleton/JsonAPI"; import { fetchErrorHandler } from "./FetchErrorHandler"; import { EncryptionService } from "../service/EncryptionService"; import { SJCLEncryptionService } from "../service/SJCLEncryptionService"; import { ChatModel } from "./ChatModel" import { Sprintf } from "../singleton/Sprintf"; export class ChatModelHelper { private static readonly _encryptionService: EncryptionService = new SJCLEncryptionService(); public static async getMessages(userName: string, passphrase: string, lastMessageTime: string | null, chatModel: ChatModel): Promise { switch (lastMessageTime) { case null: { const data: ChatMessageDTO[] = await this.getAllMessagesAjax(userName); return data.map(vm => this.toChatMessageVM(vm, passphrase)); } default: { const data: ChatMessageDTO[] = await this.getNewMessagesAjax(userName, lastMessageTime); return data.map(vm => this.toChatMessageVM(vm, passphrase)); } } // return null; } private static toChatMessageVM(chatMessageDTO: ChatMessageDTO, passphrase: string): ChatMessageViewModel { const vm = new ChatMessageViewModel(); vm.fromUser = chatMessageDTO.fromUser; vm.toUser = chatMessageDTO.toUser; // vm.messageTime = chatMessageDTO.messageTime; chatMessageDTO.messageTime == null ? log.error("Message time somehow null") : vm.messageTime = chatMessageDTO.messageTime; vm.message = this._encryptionService.decrypt(passphrase, chatMessageDTO.messageCipher) as string; return vm; } private static async getAllMessagesAjax(toUser: string): Promise { const headers = new Headers(); if (JsonAPI.authToken == null) { log.error("authToken null"); return; }; headers.append('X-AUTH-TOKEN', JsonAPI.authToken); // const url = Sprintf(JsonAPI.CHAT_MESSAGES_GET, toUser); const url = Sprintf(JsonAPI.CHAT_MESSAGE_PAGE_GET, toUser,1,5); log.debug(url) // const response = await fetch(`${JsonAPI.CHAT_MESSAGES_GET}/${toUser}`, { // method: 'GET', // headers: headers // }); const response = await fetch(url, { method: 'GET', headers: headers }); console.log(response.clone()); if (fetchErrorHandler(response.clone())) { return null; } const data: Promise = await response.json(); return data; } private static async getNewMessagesAjax(toUser: string, lastMessageTimeStamp: string): Promise { const headers = new Headers(); if (JsonAPI.authToken == null) { log.error("authToken null"); return; }; headers.append('X-AUTH-TOKEN', JsonAPI.authToken); const response = await fetch(`${JsonAPI.CHAT_MESSAGES_GET}/${toUser}/${lastMessageTimeStamp}`, { method: 'GET', headers: headers }); console.log(response.clone()); if (fetchErrorHandler(response.clone())) { return null; } const data: Promise = await response.json(); return data; } }