improve chat

This commit is contained in:
Peter Maquiran
2023-01-09 10:49:58 +01:00
parent 56c1733945
commit a73dde467c
21 changed files with 436 additions and 373 deletions
+181 -242
View File
@@ -23,6 +23,7 @@ import { AttachmentsService } from 'src/app/services/attachments.service';
import { ConnectionStatus, NetworkServiceService} from 'src/app/services/network-service.service';
import { ChatSystemService } from './chat-system.service';
import { ViewedMessageService } from './viewed-message.service'
import * as FIFOProcessQueue from 'fifo-process-queue';
@Injectable({
providedIn: 'root'
@@ -47,9 +48,9 @@ export class RoomService {
message = ''
lastMessageTxt = ''
userThatIsTyping = ''
messagesLocalReference = []
members = []
membersExcludeMe = []
messagesLocalReference: string[] = []
members: chatUser[] = []
membersExcludeMe: chatUser[] = []
u
sessionStore = SessionStore
countDownTime = ''
@@ -186,9 +187,13 @@ export class RoomService {
if(!this.isGroup) {
for(let user of this.ChatSystemService.users) {
if(this.membersExcludeMe[0]._id == user._id) {
return user.status
for (const members of this.membersExcludeMe) {
if(members._id == user._id) {
return user.status
}
}
}
}
@@ -260,71 +265,7 @@ export class RoomService {
"stream-room-messages",
async (IncomingChatMessage:IncomingChatMessage) => {
let IncomingChatMessageArgs = IncomingChatMessage.fields.args[0]
let ChatMessage : ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs)
const allMessageIds = this.messages.map((e)=> e._id);
if(!this.messagesLocalReference.includes(ChatMessage.localReference) && !allMessageIds.includes(ChatMessage?._id)) {
this.messagesLocalReference.push(ChatMessage.localReference);
const message = await this.prepareCreate({message: ChatMessage, save: true});
message.messageSend = true
message.from = 'stream'
message.loadHistory = this.hasLoadHistory
this.lastMessage = message;
this.calDateDuration(ChatMessage._updatedAt);
if (message.t == 'r') {
this.name = message.msg;
}
if(this.isSenderIsNotMe(ChatMessage)) {
this.NativeNotificationService.sendNotificationChat({
message: message.msg,
title: this.name
});
}
if(this.hasLoadHistory == true) {
await message.addMessageDB()
}
if(this.chatOpen == false) {
this.messageUnread = true
}
setTimeout(()=>{
this.scrollDown()
}, 50)
} else {
this.messages.forEach((message, index)=> {
if(message.localReference == ChatMessage.localReference) {
const membersIds = this.membersExcludeMe.map((user)=> user._id)
this.getAllUsers().forEach( async (users) => {
if(membersIds.includes(users._id)) {
if(users.status != 'offline') {
this.messages[index].received.push(users._id)
setTimeout(() => {
message.save()
}, 150)
}
}
});
}
})
}
this.appendReceiveMessage.push(IncomingChatMessage)
}
)
@@ -334,9 +275,7 @@ export class RoomService {
if(message.fields.eventName == this.id+'/'+'typing') {
const args = message.fields.args
if (typeof args[1] != 'object') {
this.userThatIsTyping = this.usernameToDisplayName(args[0])
@@ -350,7 +289,6 @@ export class RoomService {
this.readAllMessage()
} else if(args[0]?.method == 'deleteMessage' || args[1]?.method == 'deleteMessage') {
this.deleteMessage(args[1]?.method?._id)
} else {
@@ -363,6 +301,68 @@ export class RoomService {
})
}
appendReceiveMessage = FIFOProcessQueue(async (IncomingChatMessage:IncomingChatMessage, done) => {
let IncomingChatMessageArgs = IncomingChatMessage.fields.args[0]
let ChatMessage : ChatMessageInterface = this.fix_updatedAt(IncomingChatMessageArgs)
let found = this.findMessageBy_id(ChatMessage._id) ||
this.findMessageBy_localReference(ChatMessage?.localReference)
// || await this.findMessageInDBByData({_id:ChatMessage._id, localReference:ChatMessage.localReference })
if(!found) {
const message = await this.prepareCreate({message: ChatMessage, save: true});
this.registerSendMessage(message)
message.from = 'stream'
message.loadHistory = this.hasLoadHistory
this.lastMessage = message;
this.calDateDuration(ChatMessage._updatedAt);
if (message.t == 'r') {
this.name = message.msg;
}
if(this.isSenderIsNotMe(ChatMessage)) {
this.NativeNotificationService.sendNotificationChat({
message: message.msg,
title: this.name
});
}
if(this.hasLoadHistory == true) {
await message.addMessageDB()
}
if(this.chatOpen == false) {
this.messageUnread = true
}
setTimeout(()=>{
this.scrollDown()
}, 50)
}
setTimeout(() => {
done()
}, 5)
})
getUsersByStatus(status: 'offline' | 'online') {
return this.getAllUsers().filter((user => {
for(const member of this.membersExcludeMe) {
if(user._id == member._id && user.status == status) {
return true
}
}
}))
}
getRoomMembersIds(): string[] {
try {
@@ -528,7 +528,7 @@ export class RoomService {
this.RochetChatConnectorService.deleteMessage(msgId).then(async() => {
message.delateRequest = true
await message.save();
await message.saveChanges();
this.deleteMessage(msgId);
})
@@ -564,8 +564,8 @@ export class RoomService {
this.message= ''
this.messagesLocalReference.push(localReference)
const message: MessageService = await this.prepareCreate({message:offlineChatMessage, save: environment.chatOffline})
this.registerSendMessage(message)
if(this.hasLoadHistory == true) {
await message.addMessageDB()
@@ -574,7 +574,6 @@ export class RoomService {
message.send()
message.from = 'send'
message.loadHistory = this.hasLoadHistory
if (environment.chatOffline) {
@@ -589,6 +588,24 @@ export class RoomService {
}
/**
* Register all send message so that
* the incoming message wont be confuse to
* other user the localReference is the identifier
*/
registerSendMessage(message: MessageService) {
this.messagesLocalReference.push(message.localReference)
}
localReferenceExist(message: MessageService) {
for( const localReference of this.messagesLocalReference) {
if(localReference == message?.localReference) {
return true
}
}
return false
}
sendTyping(text:string = this.message) {
@@ -660,8 +677,11 @@ export class RoomService {
return JSON.parse(str);
}
restoreOnce = false
async restoreMessageFromDB() {
if(environment.chatOffline) {
if(environment.chatOffline && this.restoreOnce == false) {
this.restoreOnce = true
const messages = await MessageModel.filter({rid:this.id}).execute()
@@ -669,31 +689,24 @@ export class RoomService {
const wewMessage = await this.simplePrepareMessage(ChatMessage)
wewMessage.from = 'Offline'
wewMessage.loadHistory = this.hasLoadHistory
if(wewMessage.offline == false) {
const message = await this.prepareMessageCreateIfNotExist_iD({message:ChatMessage})
if(message) {
message.from = 'Offline'
message.loadHistory = this.hasLoadHistory
message?.decryptMessage()
}
const message = await this.prepareCreate({message:ChatMessage})
message.from = 'Offline'
message.loadHistory = this.hasLoadHistory
message?.decryptMessage()
} else {
const offlineMessage = await this.prepareCreate({message:ChatMessage})
const offlineMessage = await this.prepareMessageCreateIfNotExist({message:ChatMessage})
if(offlineMessage) {
offlineMessage.from = 'Offline'
offlineMessage.loadHistory = this.hasLoadHistory
this.messagesLocalReference.push(offlineMessage.localReference)
offlineMessage?.decryptMessage()
offlineMessage.send()
}
offlineMessage.from = 'Offline'
offlineMessage.loadHistory = this.hasLoadHistory
this.registerSendMessage(offlineMessage)
offlineMessage?.decryptMessage()
offlineMessage.send()
// console.log('send offline', ChatMessage)
}
@@ -710,6 +723,7 @@ export class RoomService {
}
// runs onces only
async loadHistory({limit = 1000, forceUpdate = false }) {
if(forceUpdate == false) {
@@ -718,23 +732,27 @@ export class RoomService {
}
}
if(this.restoreFromOffline == false) {
this.restoreFromOffline = true
await this.restoreMessageFromDB()
}
const chatHistory: chatHistory = await this.RochetChatConnectorService.loadHistory(this.id, limit)
if(chatHistory?.result?.messages) {
const messagesId = this.messages.map((message)=> message._id)
const users = this.getUsersByStatus('online')
for(let message of chatHistory.result.messages.reverse()) {
if (!messagesId.includes(message._id)) {
const messagesToSave = await this.prepareMessageCreateIfNotExist_iD({message: message});
if(messagesToSave) {
const messagesToSave = await this.prepareMessageCreateIfNotExist({message: message});
if(messagesToSave != null) {
messagesToSave.received = users.map((user) => user._id)
messagesToSave.addMessageDB()
// console.log('add history', message)
} else {
// console.log('exit')
}
} else {
// console.log('exit')
}
}
@@ -744,28 +762,6 @@ export class RoomService {
}, 50)
this.hasLoadHistory = true
this.messageReorder();
}
}
async messageReorder() {
const reorderMessage: MessageService[] = this.messages.filter((message) =>
message.from == 'send' && !message.loadHistory || message.from == 'stream' && !message.loadHistory
);
let i = 0
for(let message of this.messages) {
if(message.from == 'send' && !message.loadHistory || message.from == 'stream' && !message.loadHistory) {
this.messages.splice(i, 1)
}
i++;
}
for(let message of reorderMessage) {
this.messages.push(message)
message.addMessageDB()
}
}
@@ -774,60 +770,11 @@ export class RoomService {
async readAllMessage() {
const membersIds = this.membersExcludeMe.map((user)=> user._id)
await this.messages.forEach( async (message, index) => {
if(message._id) {
if(message.viewed.length == 0) {
this.messages[index].viewed = membersIds;
this.messages[index].received = membersIds;
await this.messages[index].save()
}
}
})
this.ViewedMessageService.requestReadAll(this)
}
/**
* @description find or create message
* @param message
* @param save
* @returns
*/
async prepareMessage({message, save = true, redefined = false}): Promise<MessageService> {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService)
wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory
let foundIndex;
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == message._id) {
foundIndex = index
return true
} else {
return false
}
})
if(save) {
if (!found) {
this.messages.push(wewMessage)
return wewMessage
}
} else if(foundIndex) {
return this.messages[foundIndex]
} else {
return wewMessage
}
}
async ChatMessageIsPresentInTheView(ChatMessage:ChatMessageInterface) {
let foundIndex;
@@ -849,48 +796,18 @@ export class RoomService {
}
/**
* @description find or create message
* @param message
* @param save
* @returns
*/
async prepareCreate({message, save = true}): Promise<MessageService> {
async prepareCreate({message, save = true}): Promise<MessageService> {
message = this.fix_updatedAt(message)
const wewMessage = new MessageService(this.NfService, this.RochetChatConnectorService, this.ChatMethodsService, this.AESEncrypt, this.AttachmentsService, this.NetworkServiceService, this.ChatSystemService)
wewMessage.setData(message)
wewMessage.loadHistory = this.hasLoadHistory
let found;
if(wewMessage.localReference != null) {
found = this.messages.find((MessageService, index) => {
if ( MessageService.localReference == wewMessage.localReference ) {
return true
} else {
return false
}
})
} else {
found = this.messages.find((MessageService, index) => {
if ( MessageService._id == wewMessage._id) {
return true
} else {
return false
}
})
}
if (!found) {
this.messages.push(wewMessage)
return wewMessage
}
this.messages.push(wewMessage)
return wewMessage
}
@@ -903,40 +820,62 @@ export class RoomService {
return wewMessage
}
private findMessageBy_id (id) {
for( let m of this.messages) {
if(m._id == id) {
return true
}
}
return false
}
private findMessageBy_localReference (localReference) {
for( let m of this.messages) {
if(m.localReference == localReference) {
return true
}
}
return false
}
private async findMessageInDBByLocalReference({localReference}) {
const a = await MessageModel.get({localReference: localReference})
return typeof a.id == 'number'
}
private async findMessageInDBByLocalId({_id}) {
const a = await MessageModel.get({_id: _id})
return typeof a.id == 'number'
}
private async findMessageInDBByData({localReference, _id}) {
// console.log('look')
const a = await MessageModel.filter({localReference: localReference})
if(a.length >= 1) {
// console.log('localReference', localReference)
return true
}
const c = await MessageModel.filter({_id: _id})
if(c.length >= 1) {
// console.log('_id', _id)
return true
}
// console.log('look not found')
return false
}
async prepareMessageCreateIfNotExist({message}) {
message = this.fix_updatedAt(message)
let foundIndex;
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == message._id ||
MessageService.localReference == message.localReference ) {
foundIndex = index
return true
} else {
return false
}
})
if (!found) {
const wewMessage = this.simplePrepareMessage(message)
this.messages.push(wewMessage)
return wewMessage
} else {
return null
}
}
async prepareMessageCreateIfNotExist_iD({message}) {
message = this.fix_updatedAt(message)
const found = this.messages.find((MessageService, index) => {
if (MessageService._id == message._id) {
return true
} else {
return false
}
})
let found = await this.findMessageBy_id(message._id) || this.findMessageBy_localReference(message.localReference)
// || await this.findMessageInDBByData({_id:message._id, localReference:message.localReference })
if (!found) {
const wewMessage = this.simplePrepareMessage(message)