271 lines
8.5 KiB
TypeScript
271 lines
8.5 KiB
TypeScript
import {Component, inject, OnInit, signal} from '@angular/core';
|
|
import {DmStorage, LoadStatus, ServiceManager} from '../../service-manager';
|
|
import {ActivatedRoute} from '@angular/router';
|
|
import {DMService} from '@chatenium/chatenium-sdk/services/dmService';
|
|
import {IndexedDB} from '../../storage/indexed-db';
|
|
import {Navbar} from '../elements/navbar/navbar';
|
|
import {Oimg} from '../elements/oimg/oimg';
|
|
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';
|
|
import {FileDataWithPreview, MessageBox} from '../elements/message-box/message-box';
|
|
import {Messages} from '../elements/messages/messages';
|
|
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
|
|
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
|
|
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel';
|
|
import {FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema';
|
|
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';
|
|
import {MessagesViewModel} from '../elements/messages/messages-viewmodel';
|
|
import {v4 as uuidv4} from 'uuid';
|
|
|
|
@Component({
|
|
selector: 'app-dm',
|
|
imports: [
|
|
Navbar,
|
|
Oimg,
|
|
TuiButton,
|
|
TuiIcon,
|
|
MessageBox,
|
|
Messages
|
|
],
|
|
templateUrl: './dm.html',
|
|
styleUrl: './dm.scss',
|
|
})
|
|
export class Dm implements OnInit {
|
|
serviceManager = inject(ServiceManager)
|
|
route = inject(ActivatedRoute)
|
|
indexedDb = inject(IndexedDB)
|
|
breakpoint = inject(TUI_BREAKPOINT)
|
|
|
|
chatid = ""
|
|
|
|
get store(): DmStorage {
|
|
return this.serviceManager.dmServices()[this.chatid]
|
|
}
|
|
|
|
async sendMessage(message: string, files: FileDataWithPreview[] | null) {
|
|
if (!files && message.trim() == "") return
|
|
|
|
const session = this.serviceManager.currentSession();
|
|
if (session != null) {
|
|
const editedMessage = this.store.messageBox.editingMessage()
|
|
if (editedMessage) {
|
|
const storedMsg = this.store.messages().find(m => m.msgid == editedMessage.messageId)
|
|
const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg))
|
|
if (storedMsg) {
|
|
storedMsg.message = message
|
|
}
|
|
|
|
try {
|
|
await this.store.service.editMessage(editedMessage.messageId, message)
|
|
} catch (e) {
|
|
if (storedMsg) {
|
|
storedMsg.message = originalMessage.message
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
let attachments: Attachment[] = []
|
|
files?.forEach(file => {
|
|
const extraMetaData: Record<string, any> = {}
|
|
extraMetaData["thumbnailMetaData"] = file.videoThumbnail ?? ""
|
|
extraMetaData["progressShown"] = true
|
|
extraMetaData["totalChunks"] = 0
|
|
extraMetaData["uploadedChunks"] = 0
|
|
|
|
attachments.push({
|
|
fileName: file.name,
|
|
fileId: file.fileId,
|
|
type: file.type,
|
|
format: file.extension,
|
|
path: file.blob,
|
|
height: file.height,
|
|
width: file.width,
|
|
extraMetaData: extraMetaData
|
|
})
|
|
})
|
|
|
|
const tempMsgId = uuidv4()
|
|
this.store.messages.update(value => [...value, {
|
|
message: message,
|
|
chatid: this.chatid,
|
|
files: attachments,
|
|
replyTo: "",
|
|
author: session.userData.userid,
|
|
seen: false,
|
|
msgid: tempMsgId,
|
|
forwardedFrom: "",
|
|
isEdited: false,
|
|
sent_at: {T: 0, I: 0},
|
|
replyToId: "",
|
|
forwardedFromName: ""
|
|
}])
|
|
|
|
const respMessage = await this.store.service.sendMessage(tempMsgId, message, null, null, files, <FileUploadProgressListener>{
|
|
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
|
|
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone)
|
|
}
|
|
})
|
|
this.updateTempMessage(tempMsgId, respMessage)
|
|
this.scrollToBottom("smooth")
|
|
}
|
|
}
|
|
|
|
async deleteMessage(messageId: string) {
|
|
const i = this.store.messages().findIndex(m => m.msgid == messageId)
|
|
if (i != -1) {
|
|
const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]))
|
|
this.store.messages().splice(i, 1)
|
|
try {
|
|
await this.store.service.deleteMessages([messageId])
|
|
} catch (e) {
|
|
this.store.messages().splice(i, 0, originalMessage)
|
|
}
|
|
}
|
|
}
|
|
|
|
restoreScrollState(): void {
|
|
setTimeout(() => {
|
|
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
|
|
scrollContainer.scroll({
|
|
top: this.store.messagesVm.scrollBarStatus() == -1 ? scrollContainer.scrollHeight : this.store.messagesVm.scrollBarStatus(),
|
|
left: 0,
|
|
behavior: "instant"
|
|
});
|
|
|
|
if (this.store.messagesVm.scrollBarStatus() == -1) {
|
|
this.store.messagesVm.scrollBarStatus.set(scrollContainer.scrollHeight)
|
|
}
|
|
}, 0)
|
|
}
|
|
|
|
scrollToBottom(anim: 'instant' | 'smooth'): void {
|
|
setTimeout(() => {
|
|
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
|
|
scrollContainer.scroll({
|
|
top: scrollContainer.scrollHeight,
|
|
left: 0,
|
|
behavior: anim
|
|
});
|
|
}, 0)
|
|
}
|
|
|
|
handleMessagesScroll(e: any) {
|
|
this.store.messagesVm.scrollBarStatus.set(e.target.scrollTop)
|
|
}
|
|
|
|
uploadProgressUpdate(tempMsgId: string, fileId: string, allChunks: number, chunksDone: number) {
|
|
console.log(tempMsgId, fileId, allChunks, chunksDone)
|
|
this.store.messages.update(messages =>
|
|
messages.map(m => {
|
|
if (m.msgid !== tempMsgId) return m;
|
|
|
|
return {
|
|
...m,
|
|
files: m.files.map(f => {
|
|
if (f.fileId !== fileId) return f;
|
|
return {
|
|
...f,
|
|
extraMetaData: {
|
|
...f.extraMetaData,
|
|
totalChunks: allChunks,
|
|
uploadedChunks: chunksDone
|
|
}
|
|
};
|
|
})
|
|
};
|
|
})
|
|
);
|
|
}
|
|
|
|
updateTempMessage(tempMsgId: string, message: Message) {
|
|
this.store.messages.update(messages =>
|
|
messages.map(m => {
|
|
if (m.msgid !== tempMsgId) return m;
|
|
|
|
return {
|
|
...m,
|
|
msgid: message.msgid,
|
|
sent_at: message.sent_at,
|
|
files: m.files.map(f => {
|
|
f.extraMetaData["progressShown"] = false
|
|
return f
|
|
})
|
|
};
|
|
})
|
|
);
|
|
}
|
|
|
|
// The chatid parameter ensures isolation
|
|
onWsListen(action: string, message: string, chatid: string) {
|
|
const data = JSON.parse(message);
|
|
if (data.chatid === chatid) {
|
|
const targetStore = this.serviceManager.dmServices()[chatid];
|
|
if (targetStore) {
|
|
switch (action) {
|
|
case "newMessage":
|
|
targetStore.messages.update(messages => [...messages, data]);
|
|
this.scrollToBottom("smooth")
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
ngOnInit() {
|
|
this.route.params.subscribe(async params => {
|
|
const chatid = params['chatid'];
|
|
this.chatid = chatid;
|
|
console.log(`Loading chat ${chatid}...`)
|
|
|
|
const session = this.serviceManager.currentSession();
|
|
const chatData = this.serviceManager.chats().find(c => c.chatid === chatid);
|
|
|
|
if (!session || !chatData) {
|
|
return
|
|
}
|
|
|
|
if (!this.serviceManager.dmServices()[chatid]) {
|
|
const newStore = {
|
|
chatData: signal<Chat>(chatData),
|
|
messages: signal<Message[]>([]),
|
|
messagesStatus: signal<LoadStatus>(LoadStatus.loading),
|
|
messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)),
|
|
messagesVm: new MessagesViewModel(),
|
|
wsListener: (action, data) => this.onWsListen(action, data, chatid),
|
|
} as DmStorage;
|
|
|
|
newStore.service = new DMService(
|
|
session.userData.userid,
|
|
session.token,
|
|
chatid,
|
|
this.indexedDb.getApi(),
|
|
(action, data) => newStore.wsListener(action, data)
|
|
);
|
|
|
|
this.serviceManager.dmServices()[chatid] = newStore;
|
|
|
|
const currentStore = this.serviceManager.dmServices()[chatid];
|
|
try {
|
|
const messagesCache = await currentStore.service.getQuick();
|
|
currentStore.messages.set(messagesCache);
|
|
this.store.messagesStatus.set(LoadStatus.updating)
|
|
this.restoreScrollState()
|
|
} catch (e) {
|
|
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
|
|
}
|
|
const messages = await currentStore.service.get();
|
|
currentStore.messages.set(messages);
|
|
this.store.messagesStatus.set(LoadStatus.loaded)
|
|
this.restoreScrollState()
|
|
|
|
await currentStore.service.joinWebSocketRoom();
|
|
} else {
|
|
this.restoreScrollState()
|
|
}
|
|
});
|
|
}
|
|
|
|
protected readonly LoadStatus = LoadStatus;
|
|
}
|