Cleaned up frontend code a bit

This commit is contained in:
Rohan Sircar 2020-05-27 23:03:42 +05:30
parent aff632a091
commit a400e555fa
4 changed files with 548 additions and 604 deletions

View File

@ -14,8 +14,7 @@ export class UserModel implements Subject<ActiveUserViewModel> {
*/ */
private readonly observers: Observer<ActiveUserViewModel>[] = []; private readonly observers: Observer<ActiveUserViewModel>[] = [];
private _activeUsersList: ActiveUserViewModel[] = Array();
private _activeUsersList: ActiveUserViewModel[];
private readonly _notificationService: NotificationService; private readonly _notificationService: NotificationService;
constructor(notificationService: NotificationService) { constructor(notificationService: NotificationService) {
@ -31,26 +30,25 @@ export class UserModel implements Subject<ActiveUserViewModel> {
return this._activeUsersList; return this._activeUsersList;
} }
/** /**
* The subscription management methods. * The subscription management methods.
*/ */
public attach(observer: Observer<ActiveUserViewModel>): void { public attach(observer: Observer<ActiveUserViewModel>): void {
log.info('Subject: Attached an observer.'); log.info("Subject: Attached an observer.");
this.observers.push(observer); this.observers.push(observer);
} }
public detach(observer: Observer<ActiveUserViewModel>): void { public detach(observer: Observer<ActiveUserViewModel>): void {
const observerIndex = this.observers.indexOf(observer); const observerIndex = this.observers.indexOf(observer);
this.observers.splice(observerIndex, 1); this.observers.splice(observerIndex, 1);
log.info('Subject: Detached an observer.'); log.info("Subject: Detached an observer.");
} }
/** /**
* Trigger an update in each subscriber. * Trigger an update in each subscriber.
*/ */
public notify(): void { public notify(): void {
log.info('Subject: Notifying observers...'); log.info("Subject: Notifying observers...");
for (const observer of this.observers) { for (const observer of this.observers) {
observer.update({ data: this._activeUsersList!, op: "" }); observer.update({ data: this._activeUsersList!, op: "" });
} }
@ -69,34 +67,31 @@ export class UserModel implements Subject<ActiveUserViewModel> {
*/ */
public getActiveUsers(): void { public getActiveUsers(): void {
if (JsonAPI.authToken != null) { if (JsonAPI.authToken != null) {
this._getActiveUsersAjax(JsonAPI.authToken) this._getActiveUsersAjax(JsonAPI.authToken).then((data) => {
.then(data => {
// // activeUsers = data; // // activeUsers = data;
// sessionStorage.setItem('activeUsers', JSON.stringify(data)); // sessionStorage.setItem('activeUsers', JSON.stringify(data));
// log.trace(sessionStorage.getItem('activeUsers')); // log.trace(sessionStorage.getItem('activeUsers'));
log.info(`Subject: received ajax active users`); log.info(`Subject: received ajax active users`);
data.map((d: any) => { data.map((d: any) => {
if( d.lastActive == null ) if (d.lastActive == null) return null;
return null;
d.lastActive = new Date(d.lastActive) d.lastActive = new Date(d.lastActive);
return d; return d;
}); });
this._activeUsersList = data; this._activeUsersList = data;
this.notify(); this.notify();
}) });
} } else {
else { log.error("Auth token is null");
log.error('Auth token is null');
} }
} }
private async _getActiveUsersAjax(authToken: string): Promise<any> { private async _getActiveUsersAjax(authToken: string): Promise<any> {
let headers = new Headers(); let headers = new Headers();
headers.append('X-AUTH-TOKEN', authToken); headers.append("X-AUTH-TOKEN", authToken);
let response = await fetch(JsonAPI.ACTIVE_USERS_GET, { let response = await fetch(JsonAPI.ACTIVE_USERS_GET, {
method: 'GET', method: "GET",
headers: headers headers: headers,
}); });
log.debug(response.clone()); log.debug(response.clone());
if (fetchErrorHandler(response.clone(), this._notificationService)) { if (fetchErrorHandler(response.clone(), this._notificationService)) {
@ -106,13 +101,10 @@ export class UserModel implements Subject<ActiveUserViewModel> {
// return data; // return data;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (data != null) { if (data != null) {
resolve(data) resolve(data);
} } else reject("Response data null");
else });
reject('Response data null')
})
} }
private helperMethod() {} private helperMethod() {}
} }

View File

@ -3,25 +3,24 @@ import { NotificationService } from "./NotificationService";
import * as alertify from "alertifyjs"; import * as alertify from "alertifyjs";
import { ActiveUserViewModel } from "../viewmodel/ActiveUserViewModel"; import { ActiveUserViewModel } from "../viewmodel/ActiveUserViewModel";
import log = require("loglevel"); import log = require("loglevel");
import bootbox = require("bootbox") import bootbox = require("bootbox");
import { ChatMessageViewModel } from "../viewmodel/ChatMessageViewModel"; import { ChatMessageViewModel } from "../viewmodel/ChatMessageViewModel";
export class AlertifyNotificationService implements NotificationService { export class AlertifyNotificationService implements NotificationService {
private readonly _alertify = alertify; private readonly _alertify = alertify;
constructor() { constructor() {
this._alertify.set('notifier', 'position', 'top-center'); this._alertify.set("notifier", "position", "top-center");
} }
success(message: string): void { success(message: string): void {
this._alertify.success(message) this._alertify.success(message);
} }
error(message: string): void { error(message: string): void {
this._alertify.error(message); this._alertify.error(message);
} }
errorWithDelay(message: string, delay: number): void { errorWithDelay(message: string, delay: number): void {
const _delay = this._alertify.get('notifier', 'delay'); const _delay = this._alertify.get("notifier", "delay");
this._alertify.set('notifier', 'delay', delay); this._alertify.set("notifier", "delay", delay);
this._alertify.error(message); this._alertify.error(message);
this._alertify.set('notifier', 'delay', _delay); this._alertify.set("notifier", "delay", _delay);
} }
warning(message: string): void { warning(message: string): void {
this._alertify.warning(message); this._alertify.warning(message);
@ -29,101 +28,57 @@ export class AlertifyNotificationService implements NotificationService {
message(message: string): void { message(message: string): void {
this._alertify.message(message); this._alertify.message(message);
} }
passphrasePrompt(vm: ActiveUserViewModel, vms: ActiveUserViewModel[], cb1: (v: ActiveUserViewModel, op: string) => ChatMessageViewModel[], passphrasePrompt(
cb2: (...x: any) => any, cb3: (...x: any) => any): void { vm: ActiveUserViewModel,
vms: ActiveUserViewModel[],
// alertify.myprompt || alertify.dialog('myprompt', function () { cb1: (v: ActiveUserViewModel, op: string) => ChatMessageViewModel[],
cb2: (...x: any) => any,
// // document.getElementById('passphraseFormNew')!.addEventListener('submit', function (e: Event) { cb3: (...x: any) => any
// // e.preventDefault(); ): void {
// // log.debug(this.querySelectorAll('input')) if (!vm.passphrase) {
// // Array.from(this.querySelectorAll('input')).map((el) => {
// // const el2 = el as HTMLInputElement;
// // vm.passphrase = el2.value;
// // vm.unlocked = true;
// // cb1(vm.userName!, vm.passphrase, null, "new");
// // cb2();
// // alertify.myprompt().close();
// // })
// // log.debug(vm)
// // })
// return {
// main: function (content: HTMLElement) {
// log.debug(vm)
// // @ts-ignore
// this.setContent(content);
// },
// setup: function () {
// return {
// focus: {
// // @ts-ignore
// element: function () {
// // @ts-ignore
// return this.elements.body.querySelector(this.get('selector'));
// },
// select: true
// },
// options: {
// title: 'Enter Passphrase',
// basic: true,
// maximizable: false,
// resizable: false,
// padding: false
// }
// };
// },
// settings: {
// // @ts-ignore
// selector: undefined
// },
// }
// })
// alertify.myprompt(document.getElementById('passphraseFormNew')).set('selector', 'input[type="password"]');
if (vm.passphrase == null) {
bootbox.prompt({ bootbox.prompt({
title: "Please enter the passphrase", title: "Please enter the passphrase",
inputType: 'password', inputType: "password",
callback: async function (result) { callback: async function (result) {
if (result) { if (result) {
log.debug(result);
const valid = await cb3(result, vm.userName); const valid = await cb3(result, vm.userName);
if (!valid) { if (!valid) {
bootbox.alert("Some error occured. Please check your password"); bootbox.alert("Some error occured. Please check your password");
log.error("invalid password"); log.error("invalid password");
return; return;
} }
vm.unlocked = true vm.unlocked = true;
vm.passphrase = result; vm.passphrase = result;
const chatMessages: ChatMessageViewModel[] = await cb1(vm, "new"); const chatMessages: ChatMessageViewModel[] = await cb1(vm, "new");
vms.filter(v => v.userName == vm.userName).map(v => { vms
.filter((v) => v.userName == vm.userName)
.map((v) => {
v.passphrase = result; v.passphrase = result;
v.unlocked = true; v.unlocked = true;
if (chatMessages.length != 0) { if (chatMessages.length > 0) {
v.lastMessageTime = new Date(chatMessages[chatMessages.length - 1].messageTime); v.lastMessageTime = new Date(
const lastMessageText = v.lastMessageText = chatMessages[chatMessages.length - 1].message; chatMessages[chatMessages.length - 1].messageTime
);
const lastMessageText = (v.lastMessageText =
chatMessages[chatMessages.length - 1].message);
if (lastMessageText.length > 15) { if (lastMessageText.length > 15) {
v.lastMessageText = chatMessages[chatMessages.length - 1].message.slice(0, 15) + "..." v.lastMessageText =
} chatMessages[chatMessages.length - 1].message.slice(
} 0,
}) 15
// vm.lastMessageTime = new Date(chatMessages[chatMessages.length - 1].messageTime); ) + "...";
cb2(vm, vms);
log.debug(vm)
log.debug(vms)
} }
} }
}); });
// vm.lastMessageTime = new Date(chatMessages[chatMessages.length - 1].messageTime);
cb2(vm, vms);
// log.debug(vm);
// log.debug(vms);
} }
else { },
});
} else {
cb1(vm, "new"); cb1(vm, "new");
} }
} }

View File

@ -1,5 +1,5 @@
import * as DOMPurify from 'dompurify'; import * as DOMPurify from "dompurify";
import * as log from 'loglevel'; import * as log from "loglevel";
import { ChatMessageDTO } from "../dto/ChatMessageDTO"; import { ChatMessageDTO } from "../dto/ChatMessageDTO";
import { MessageCipherDTO } from "../dto/MessageCipherDTO"; import { MessageCipherDTO } from "../dto/MessageCipherDTO";
import { ChatModel } from "../model/ChatModel"; import { ChatModel } from "../model/ChatModel";
@ -10,21 +10,24 @@ import { JsonAPI } from "../singleton/JsonAPI";
import { ChatMessageViewModel } from "../viewmodel/ChatMessageViewModel"; import { ChatMessageViewModel } from "../viewmodel/ChatMessageViewModel";
import { ChatViewDeps } from "./ChatViewDeps"; import { ChatViewDeps } from "./ChatViewDeps";
import { fetchHandler } from "./FetchHandler"; import { fetchHandler } from "./FetchHandler";
import { ObserverData } from '../observe/ObserverData'; import { ObserverData } from "../observe/ObserverData";
import { NotificationService } from '../service/NotificationService'; import { NotificationService } from "../service/NotificationService";
import { UserModel } from '../model/UserModel'; import { UserModel } from "../model/UserModel";
export class ChatView implements Observer<ChatMessageViewModel> { export class ChatView implements Observer<ChatMessageViewModel> {
private readonly _chatModel: ChatModel; private readonly _chatModel: ChatModel;
private readonly _messageContainer: HTMLElement; private readonly _messageContainer: HTMLElement;
private readonly _messageSendTemplate: Handlebars.TemplateDelegate<ChatMessageViewModel>; private readonly _messageSendTemplate: Handlebars.TemplateDelegate<
private readonly _messageReceiveTemplate: Handlebars.TemplateDelegate<ChatMessageViewModel>; ChatMessageViewModel
>;
private readonly _messageReceiveTemplate: Handlebars.TemplateDelegate<
ChatMessageViewModel
>;
private readonly _markdownService: MarkDownService; private readonly _markdownService: MarkDownService;
private readonly _encryptionService: EncryptionService; private readonly _encryptionService: EncryptionService;
private readonly _notificationService: NotificationService; private readonly _notificationService: NotificationService;
private readonly _userModel: UserModel; private readonly _userModel: UserModel;
constructor(deps: ChatViewDeps) { constructor(deps: ChatViewDeps) {
this._messageContainer = deps.messageContainer; this._messageContainer = deps.messageContainer;
this._chatModel = deps.chatModel; this._chatModel = deps.chatModel;
@ -37,8 +40,8 @@ export class ChatView implements Observer<ChatMessageViewModel> {
this._initEventListeners(); this._initEventListeners();
$(document).ready(function () { $(document).ready(function () {
$('#action_menu_btn').click(function () { $("#action_menu_btn").click(function () {
$('.action_menu').toggle(); $(".action_menu").toggle();
}); });
}); });
@ -46,86 +49,67 @@ export class ChatView implements Observer<ChatMessageViewModel> {
} }
update(cd: ObserverData<ChatMessageViewModel>): void { update(cd: ObserverData<ChatMessageViewModel>): void {
log.info('ChatView: updating view'); log.info("ChatView: updating view");
switch (cd.op) { switch (cd.op) {
case "clear": { case "clear":
{
$(this._messageContainer).html(""); $(this._messageContainer).html("");
} break;
case "new": {
const rev: ChatMessageViewModel[] = Object.create(cd.data)
// rev.reverse();
let arr: string[] = [];
rev.forEach((vm: ChatMessageViewModel) => {
const vmTemp: ChatMessageViewModel = { ...vm };
vmTemp.message = this._markdownService.render(vm.message);
/** Very Important!!!
* Sanitizing HTML before displaying on webpage to prevent XSS attacks!!
*/
let rendered;
if (vmTemp.fromUser == JsonAPI.principleName) {
rendered = DOMPurify.sanitize(this._messageSendTemplate(vmTemp));
}
else {
rendered = DOMPurify.sanitize(this._messageReceiveTemplate(vmTemp));
} }
break;
case "new":
{
cd.data.forEach((vm: ChatMessageViewModel) => {
let rendered = this.renderMessage(vm);
$(this._messageContainer).append(rendered); $(this._messageContainer).append(rendered);
}); });
$(this._messageContainer).stop().animate({ $(this._messageContainer)
scrollTop: $(this._messageContainer)[0].scrollHeight .stop()
}, 1500); .animate(
} break; {
case "update": { scrollTop: $(this._messageContainer)[0].scrollHeight,
const rev: ChatMessageViewModel[] = Object.create(cd.data) },
// rev.reverse(); 1500
let arr: string[] = []; );
rev.forEach((vm: ChatMessageViewModel) => {
const vmTemp: ChatMessageViewModel = { ...vm };
vmTemp.message = this._markdownService.render(vm.message);
/** Very Important!!!
* Sanitizing HTML before displaying on webpage to prevent XSS attacks!!
*/
let rendered;
if (vmTemp.fromUser == JsonAPI.principleName) {
rendered = DOMPurify.sanitize(this._messageSendTemplate(vmTemp));
}
else {
rendered = DOMPurify.sanitize(this._messageReceiveTemplate(vmTemp));
} }
break;
case "update":
{
cd.data.forEach((vm: ChatMessageViewModel) => {
let rendered = this.renderMessage(vm);
$(this._messageContainer).append(rendered); $(this._messageContainer).append(rendered);
}); });
if(rev.length > 0) { // if (cd.data.length > 0) {
// $(this._messageContainer).stop().animate({ // this._userModel.notify();
// scrollTop: $(this._messageContainer)[0].scrollHeight // }
// }, 1500);
this._userModel.notify();
} }
} break; break;
default: { case "page":
const rev: ChatMessageViewModel[] = Object.create(cd.data) {
{
const rev: ChatMessageViewModel[] = Object.create(cd.data);
rev.reverse(); rev.reverse();
let arr: string[] = [];
rev.forEach((vm: ChatMessageViewModel) => { rev.forEach((vm: ChatMessageViewModel) => {
const vmTemp: ChatMessageViewModel = { ...vm }; let rendered = this.renderMessage(vm);
vmTemp.message = this._markdownService.render(vm.message);
/** Very Important!!!
* Sanitizing HTML before displaying on webpage to prevent XSS attacks!!
*/
let rendered;
if (vmTemp.fromUser == JsonAPI.principleName) {
rendered = DOMPurify.sanitize(this._messageSendTemplate(vmTemp));
}
else {
rendered = DOMPurify.sanitize(this._messageReceiveTemplate(vmTemp));
}
$(this._messageContainer).prepend(rendered); $(this._messageContainer).prepend(rendered);
}); });
} }
} }
break;
default:
new Error("Invalid option");
}
}
private renderMessage(vm: ChatMessageViewModel): string {
const vmTemp: ChatMessageViewModel = { ...vm };
vmTemp.message = this._markdownService.render(vm.message);
switch (vmTemp.fromUser) {
case JsonAPI.principleName:
return DOMPurify.sanitize(this._messageSendTemplate(vmTemp));
default:
return DOMPurify.sanitize(this._messageReceiveTemplate(vmTemp));
}
} }
private _initEventListeners(): void { private _initEventListeners(): void {
@ -133,16 +117,17 @@ export class ChatView implements Observer<ChatMessageViewModel> {
} }
private _addChatFormEL() { private _addChatFormEL() {
const chatForm = document.getElementById('chatMessageForm') as HTMLSelectElement; const chatForm = document.getElementById(
"chatMessageForm"
) as HTMLSelectElement;
if (chatForm == null) { if (chatForm == null) {
log.error("Chat form is null"); log.error("Chat form is null");
} else {
chatForm.addEventListener("submit", (e) =>
this._createChatMessageDTO(e, chatForm)
);
} }
else {
chatForm.addEventListener('submit', (e) => this._createChatMessageDTO(e, chatForm))
}
} }
private _createChatMessageDTO(e: Event, chatForm: HTMLSelectElement): void { private _createChatMessageDTO(e: Event, chatForm: HTMLSelectElement): void {
@ -150,29 +135,24 @@ export class ChatView implements Observer<ChatMessageViewModel> {
let contactName = JsonAPI.contactName; let contactName = JsonAPI.contactName;
if (contactName == null) {
log.error("Contact name is null");
return;
}
if (!chatForm.checkValidity()) { if (!chatForm.checkValidity()) {
log.error("Form is not valid"); log.error("Form is not valid");
chatForm.classList.add('was-validated'); chatForm.classList.add("was-validated");
return; return;
} }
chatForm.classList.add('was-validated'); chatForm.classList.add("was-validated");
const chatInput = document.getElementById("chatInput") as HTMLInputElement;
const chatInput = document.getElementById('chatInput') as HTMLInputElement; const vm = this._userModel.activeUsersList.find(
const vm = this._userModel.activeUsersList.find(u => u.userName == JsonAPI.contactName); (u) => u.userName == JsonAPI.contactName
);
// new Date(). // new Date().
vm!.lastMessageTime = new Date(); vm!.lastMessageTime = new Date();
const passphrase = vm?.passphrase const passphrase = vm?.passphrase;
if (chatInput.value == '' || chatInput.value == null) { if (chatInput.value == "") {
this._notificationService.error("Please enter a message"); this._notificationService.error("Please enter a message");
log.error("Chat input is null.");
return; return;
} }
@ -183,25 +163,28 @@ export class ChatView implements Observer<ChatMessageViewModel> {
// } // }
const messageContent = chatInput.value; const messageContent = chatInput.value;
vm!.lastMessageText = messageContent; vm!.lastMessageText = messageContent.slice(0, 15) + "...";
const msgTime = new Date(); const msgTime = new Date();
const context: ChatMessageViewModel = { const context: ChatMessageViewModel = {
fromUser: JsonAPI.principleName || "error", fromUser: JsonAPI.principleName,
toUser: "", toUser: "",
message: messageContent, message: messageContent,
messageTime: msgTime messageTime: msgTime,
}; };
this.update({ data: new Array(context), op: "new" }) this.update({ data: new Array(context), op: "new" });
this._userModel.notify(); this._userModel.notify();
let messageCipher: MessageCipherDTO = this._encryptionService.encrypt(passphrase!, messageContent) let messageCipher: MessageCipherDTO = this._encryptionService.encrypt(
passphrase!,
messageContent
);
let chatMessageDTO = { let chatMessageDTO = {
"fromUser": JsonAPI.principleName || "", fromUser: JsonAPI.principleName,
"toUser": contactName, toUser: contactName,
"messageCipher": messageCipher, messageCipher: messageCipher,
messageTime: msgTime messageTime: msgTime,
} };
this._sendMessageAJAX(chatMessageDTO); this._sendMessageAJAX(chatMessageDTO);
} }
@ -210,38 +193,42 @@ export class ChatView implements Observer<ChatMessageViewModel> {
// console.log("Token = " + btoa("hmm" + ":" + "hmm")) // console.log("Token = " + btoa("hmm" + ":" + "hmm"))
// headers.append('Accept','application/json') // headers.append('Accept','application/json')
headers.append('Content-Type', 'application/json'); headers.append("Content-Type", "application/json");
// headers.append('Authorization', basicAuthToken); // headers.append('Authorization', basicAuthToken);
// @ts-ignore // @ts-ignore
headers.append('X-AUTH-TOKEN', JsonAPI.authToken); headers.append("X-AUTH-TOKEN", JsonAPI.authToken);
fetch(JsonAPI.MESSAGE_POST, { fetch(JsonAPI.MESSAGE_POST, {
method: 'POST', method: "POST",
headers: headers, headers: headers,
body: JSON.stringify(chatMessageDTO) body: JSON.stringify(chatMessageDTO),
}) })
.then(response => { .then((response) => {
log.debug(response); log.debug(response);
return response.clone(); return response.clone();
}) })
.then(response => fetchHandler(response, this._notificationService)); .then((response) => fetchHandler(response, this._notificationService));
} }
private _chatMessagePageLoadAjax() { private _chatMessagePageLoadAjax() {
this._messageContainer.addEventListener('scroll', (e) => { this._messageContainer.addEventListener("scroll", (e) => {
if ($(this._messageContainer).scrollTop() == 0 && $(this._messageContainer).html() != "") { if (
let currentMsg = $('.msg:first'); $(this._messageContainer).scrollTop() == 0 &&
log.debug('Reached top') $(this._messageContainer).html() != ""
const vm = this._userModel.activeUsersList.find(u => u.userName == JsonAPI.contactName) ) {
if (JsonAPI.contactName != null) let currentMsg = $(".msg:first");
log.debug("Reached top");
const vm = this._userModel.activeUsersList.find(
(u) => u.userName == JsonAPI.contactName
);
this._chatModel.getMessages(vm!, "page").then(() => { this._chatModel.getMessages(vm!, "page").then(() => {
if (currentMsg != null) { if (currentMsg != null) {
// log.debug(currentMsg.offset()!.top) // log.debug(currentMsg.offset()!.top)
$(this._messageContainer).scrollTop(currentMsg.position().top - $('.msg').position()!.top) $(this._messageContainer).scrollTop(
currentMsg.position().top - $(".msg").position()!.top
);
} }
}); });
} }
}) });
} }
} }

View File

@ -11,8 +11,6 @@ import { JsonAPI } from "../singleton/JsonAPI";
import { NotificationService } from "../service/NotificationService"; import { NotificationService } from "../service/NotificationService";
export class UserView implements Observer<ActiveUserViewModel> { export class UserView implements Observer<ActiveUserViewModel> {
private readonly _model: UserModel; private readonly _model: UserModel;
private readonly _chatModel: ChatModel; private readonly _chatModel: ChatModel;
private readonly _usersListElement: HTMLElement; private readonly _usersListElement: HTMLElement;
@ -20,8 +18,12 @@ export class UserView implements Observer<ActiveUserViewModel> {
private readonly _userSearchButton: HTMLElement; private readonly _userSearchButton: HTMLElement;
private readonly _userSearchCancelButton: HTMLElement; private readonly _userSearchCancelButton: HTMLElement;
private readonly _searchService: SearchService<ActiveUserViewModel>; private readonly _searchService: SearchService<ActiveUserViewModel>;
private readonly _userContactOnlineTemplate: Handlebars.TemplateDelegate<ActiveUserViewModel>; private readonly _userContactOnlineTemplate: Handlebars.TemplateDelegate<
private readonly _userContactOfflineTemplate: Handlebars.TemplateDelegate<ActiveUserViewModel>; ActiveUserViewModel
>;
private readonly _userContactOfflineTemplate: Handlebars.TemplateDelegate<
ActiveUserViewModel
>;
private readonly _notificationService: NotificationService; private readonly _notificationService: NotificationService;
private _newMessagesLoop: any; private _newMessagesLoop: any;
@ -43,8 +45,9 @@ export class UserView implements Observer<ActiveUserViewModel> {
update(d: ObserverData<ActiveUserViewModel>): void { update(d: ObserverData<ActiveUserViewModel>): void {
let html: string = ""; let html: string = "";
d.data.forEach((element: ActiveUserViewModel) => { d.data.forEach((element: ActiveUserViewModel) => {
element.online ? html += this._userContactOnlineTemplate(element) : element.online
html += this._userContactOfflineTemplate(element); ? (html += this._userContactOnlineTemplate(element))
: (html += this._userContactOfflineTemplate(element));
}); });
$(this._usersListElement).html(DOMPurify.sanitize(html)); $(this._usersListElement).html(DOMPurify.sanitize(html));
this._addUserCallBacks(); this._addUserCallBacks();
@ -57,19 +60,19 @@ export class UserView implements Observer<ActiveUserViewModel> {
} }
private _addUserCallBacks(): void { private _addUserCallBacks(): void {
let userBoxes = document.getElementsByClassName('user-box'); let userBoxes = document.getElementsByClassName("user-box");
Array.from(userBoxes).forEach((ub: Element) => Array.from(userBoxes).forEach((ub: Element) =>
ub.addEventListener('click', this._userCallBack.bind(this, ub))) ub.addEventListener("click", this._userCallBack.bind(this, ub))
);
} }
private _userCallBack(el: Element): void { private _userCallBack(el: Element): void {
this._chatModel.clear(); this._chatModel.clear();
clearInterval(this._newMessagesLoop); clearInterval(this._newMessagesLoop);
let current = document.getElementsByClassName('user-box active'); let current = document.getElementsByClassName("user-box active");
let passphrase: string = ''; let passphrase: string = "";
if (current.length > 0) { if (current.length > 0) {
// let passphraseInput = document.getElementById('passphrase') as any; // let passphraseInput = document.getElementById('passphrase') as any;
@ -85,13 +88,12 @@ export class UserView implements Observer<ActiveUserViewModel> {
// return; // return;
// } // }
current[0].className = current[0].className.replace(" active", ""); current[0].className = current[0].className.replace(" active", "");
} }
// Add the active class to the current/clicked button // Add the active class to the current/clicked button
else if (current.length == 0) { else if (current.length == 0) {
let elem = document.getElementById('passphrase-initial') as any; let elem = document.getElementById("passphrase-initial") as any;
if (elem == null) { if (elem == null) {
log.error('passphraseInput element reference is null'); log.error("passphraseInput element reference is null");
return; return;
} }
// passphrase = elem.value; // passphrase = elem.value;
@ -102,48 +104,57 @@ export class UserView implements Observer<ActiveUserViewModel> {
// return; // return;
// } // }
// @ts-ignore: Object is possibly 'null'. // @ts-ignore: Object is possibly 'null'.
document.getElementById('no-user-selected').hidden = true; document.getElementById("no-user-selected").hidden = true;
// @ts-ignore: Object is possibly 'null'. // @ts-ignore: Object is possibly 'null'.
document.getElementById('chat-card').hidden = false; document.getElementById("chat-card").hidden = false;
// @ts-ignore: Object is possibly 'null'. // @ts-ignore: Object is possibly 'null'.
elem.hidden = true; elem.hidden = true;
} }
// console.log(this.getElementsByClassName('to-user-span')); // console.log(this.getElementsByClassName('to-user-span'));
let elem = el.getElementsByClassName('to-user-span')[0] as HTMLElement; let elem = el.getElementsByClassName("to-user-span")[0] as HTMLElement;
let userName = elem.innerText; let userName = elem.innerText;
JsonAPI.contactName = userName; JsonAPI.contactName = userName;
// @ts-ignore: Object is possibly 'null'. // @ts-ignore: Object is possibly 'null'.
document.getElementById('user-name-span').innerText = userName; document.getElementById("user-name-span").innerText = userName;
let vm = this._model.activeUsersList.find(vm => vm.userName === userName); let vm = this._model.activeUsersList.find((vm) => vm.userName === userName);
if (!vm) { if (!vm) {
vm = new ActiveUserViewModel(); vm = new ActiveUserViewModel();
vm.userName = userName; vm.userName = userName;
} }
this._notificationService.passphrasePrompt(vm, this._model.activeUsersList, this._notificationService.passphrasePrompt(
vm,
this._model.activeUsersList,
this._chatModel.getMessages.bind(this._chatModel), this._chatModel.getMessages.bind(this._chatModel),
this._promptHandler.bind(this), this._chatModel.isPassphraseValid.bind(this._chatModel)); this._promptHandler.bind(this),
this._chatModel.isPassphraseValid.bind(this._chatModel)
);
// this._chatModel.getMessages(userName, vm.passphrase, null, "new"); // this._chatModel.getMessages(userName, vm.passphrase, null, "new");
el.className += " active"; el.className += " active";
log.debug("loop", this._newMessagesLoop) log.debug("loop", this._newMessagesLoop);
if (vm.unlocked && vm.lastMessageTime != null) { if (vm.unlocked && vm.lastMessageTime) {
this._newMessagesLoop = setInterval(this._chatModel.getMessages.bind(this._chatModel, this._newMessagesLoop = setInterval(
vm, "update"), 10_000); this._chatModel.getMessages.bind(this._chatModel, vm, "update"),
10_000
);
this._model.notify();
} }
} }
private _promptHandler(vm: ActiveUserViewModel, vms: ActiveUserViewModel[]) { private _promptHandler(vm: ActiveUserViewModel, vms: ActiveUserViewModel[]) {
// vms.filter(v => v.userName == vm.userName).map(v => v.userName = vm.userName) // vms.filter(v => v.userName == vm.userName).map(v => v.userName = vm.userName)
log.debug(vms) // log.debug(vms);
if (vm.lastMessageTime != null) { if (vm.lastMessageTime) {
this._newMessagesLoop = setInterval(this._chatModel.getMessages.bind(this._chatModel, this._newMessagesLoop = setInterval(
vm, "update"), 10_000); this._chatModel.getMessages.bind(this._chatModel, vm, "update"),
} 10_000
);
this._model.notify(); this._model.notify();
} }
}
private _addSearchButtonEL() { private _addSearchButtonEL() {
this._userSearchButton.addEventListener('submit', (e) => { this._userSearchButton.addEventListener("submit", (e) => {
e.preventDefault(); e.preventDefault();
// log.trace(temp); // log.trace(temp);
const searchTerm = this._userSearchInputElement.value; const searchTerm = this._userSearchInputElement.value;
@ -158,27 +169,26 @@ export class UserView implements Observer<ActiveUserViewModel> {
let searchResult = this._searchService.search(list, searchTerm); let searchResult = this._searchService.search(list, searchTerm);
this.update({ data: searchResult, op: "" }); this.update({ data: searchResult, op: "" });
log.debug(searchResult); log.debug(searchResult);
}) });
} }
private _addSearchInputEL() { private _addSearchInputEL() {
this._userSearchInputElement.addEventListener('input', (e) => { this._userSearchInputElement.addEventListener("input", (e) => {
e.preventDefault(); e.preventDefault();
if (this._userSearchInputElement.value.length < 2) { if (this._userSearchInputElement.value.length < 2) {
log.debug("inputted") log.debug("inputted");
this._userSearchCancelButton.hidden = false; this._userSearchCancelButton.hidden = false;
} }
}) });
} }
private _addSearchCancelEL() { private _addSearchCancelEL() {
this._userSearchCancelButton.addEventListener('click', (e) => { this._userSearchCancelButton.addEventListener("click", (e) => {
e.preventDefault(); e.preventDefault();
this._userSearchInputElement.value = ""; this._userSearchInputElement.value = "";
this._userSearchCancelButton.hidden = true; this._userSearchCancelButton.hidden = true;
let list = this._model.activeUsersList; let list = this._model.activeUsersList;
this.update({ data: list, op: "" }) this.update({ data: list, op: "" });
}) });
} }
} }